diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml index aacfe53a1be1f..9bb88da3ae438 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml @@ -50,6 +50,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/AppPlatformManager.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/AppPlatformManager.java index 5ab8910cf5541..d489bcf74ce8e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/AppPlatformManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/AppPlatformManager.java @@ -21,6 +21,7 @@ public final class AppPlatformManager extends Manager { // Collections private SpringServices springServices; + /** * Get a Configurable instance that can be used to create AppPlatformManager with optional configuration. * @@ -76,11 +77,8 @@ public AppPlatformManager authenticate(TokenCredential credential, AzureProfile } private AppPlatformManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new AppPlatformManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new AppPlatformManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/CustomizedAcceleratorsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/CustomizedAcceleratorsClientImpl.java index 1f4e6dc6744ea..7635ef51cdb99 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/CustomizedAcceleratorsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/CustomizedAcceleratorsClientImpl.java @@ -690,7 +690,7 @@ public Mono createOrUpdateAsync(String resou CustomizedAcceleratorResourceInner customizedAcceleratorResource) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, applicationAcceleratorName, customizedAcceleratorName, customizedAcceleratorResource).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -714,7 +714,7 @@ private Mono createOrUpdateAsync(String reso CustomizedAcceleratorResourceInner customizedAcceleratorResource, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, applicationAcceleratorName, customizedAcceleratorName, customizedAcceleratorResource, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentImpl.java index 298a07e454a28..e9cae49e60216 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentImpl.java @@ -59,9 +59,8 @@ public class SpringAppDeploymentImpl extends ExternalChildResourceImpl - implements SpringAppDeployment, - SpringAppDeployment.Definition, - SpringAppDeployment.Update { + implements SpringAppDeployment, SpringAppDeployment.Definition, + SpringAppDeployment.Update { private static final Duration MAX_BUILD_TIMEOUT = Duration.ofHours(1); private BuildServiceTask buildServiceTask; private FunctionalTaskItem setActiveTask = null; @@ -117,9 +116,9 @@ public void start() { @Override public Mono startAsync() { - return manager().serviceClient().getDeployments().startAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getDeployments() + .startAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override @@ -129,9 +128,9 @@ public void stop() { @Override public Mono stopAsync() { - return manager().serviceClient().getDeployments().stopAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getDeployments() + .stopAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override @@ -141,9 +140,9 @@ public void restart() { @Override public Mono restartAsync() { - return manager().serviceClient().getDeployments().restartAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getDeployments() + .restartAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override @@ -153,15 +152,17 @@ public String getLogFileUrl() { @Override public Mono getLogFileUrlAsync() { - return manager().serviceClient().getDeployments().getLogFileUrlAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ) + return manager().serviceClient() + .getDeployments() + .getLogFileUrlAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name()) .map(LogFileUrlResponseInner::url); } @Override public List configFilePatterns() { - Map> addonConfigs = this.innerModel().properties().deploymentSettings().addonConfigs(); + Map> addonConfigs + = this.innerModel().properties().deploymentSettings().addonConfigs(); if (addonConfigs == null) { return Collections.emptyList(); } @@ -293,22 +294,18 @@ public SpringAppDeploymentImpl withJarFile(File jar) { return withJarFile(jar, null); } else { ensureSource(UserSourceType.JAR); - this.addDependency( - context -> parent().getResourceUploadUrlAsync() - .flatMap(option -> { - UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); - uploadedUserSourceInfo.withRelativePath(option.relativePath()); - return uploadToStorageAsync(jar, option) - .then(context.voidMono()); - }) - ); + this.addDependency(context -> parent().getResourceUploadUrlAsync().flatMap(option -> { + UploadedUserSourceInfo uploadedUserSourceInfo + = (UploadedUserSourceInfo) innerModel().properties().source(); + uploadedUserSourceInfo.withRelativePath(option.relativePath()); + return uploadToStorageAsync(jar, option).then(context.voidMono()); + })); return this; } } private ShareFileAsyncClient createShareFileAsyncClient(ResourceUploadDefinition option) { - return new ShareFileClientBuilder() - .endpoint(option.uploadUrl()) + return new ShareFileClientBuilder().endpoint(option.uploadUrl()) .httpClient(manager().httpPipeline().getHttpClient()) .buildFileAsyncClient(); } @@ -385,15 +382,12 @@ public SpringAppDeploymentImpl withSourceCodeTarGzFile(File sourceCodeTarGz, Lis this.buildServiceTask = new BuildServiceTask(sourceCodeTarGz, configFilePatterns, true); } else { ensureSource(UserSourceType.SOURCE); - this.addDependency( - context -> parent().getResourceUploadUrlAsync() - .flatMap(option -> { - UploadedUserSourceInfo uploadedUserSourceInfo = (UploadedUserSourceInfo) innerModel().properties().source(); - uploadedUserSourceInfo.withRelativePath(option.relativePath()); - return uploadToStorageAsync(sourceCodeTarGz, option) - .then(context.voidMono()); - }) - ); + this.addDependency(context -> parent().getResourceUploadUrlAsync().flatMap(option -> { + UploadedUserSourceInfo uploadedUserSourceInfo + = (UploadedUserSourceInfo) innerModel().properties().source(); + uploadedUserSourceInfo.withRelativePath(option.relativePath()); + return uploadToStorageAsync(sourceCodeTarGz, option).then(context.voidMono()); + })); } return this; } @@ -407,7 +401,8 @@ public SpringAppDeploymentImpl withTargetModule(String moduleName) { ensureSource(UserSourceType.SOURCE); UserSourceInfo userSourceInfo = innerModel().properties().source(); if (userSourceInfo instanceof SourceUploadedUserSourceInfo) { - SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo = (SourceUploadedUserSourceInfo) userSourceInfo; + SourceUploadedUserSourceInfo sourceUploadedUserSourceInfo + = (SourceUploadedUserSourceInfo) userSourceInfo; sourceUploadedUserSourceInfo.withArtifactSelector(moduleName); } } @@ -523,14 +518,12 @@ public SpringAppDeploymentImpl withVersionName(String versionName) { @Override public SpringAppDeploymentImpl withActivation() { - this.setActiveTask = context -> - manager().serviceClient().getApps() - .setActiveDeploymentsAsync( - parent().parent().resourceGroupName(), - parent().parent().name(), // service name - parent().name(), // app name - new ActiveDeploymentCollection().withActiveDeploymentNames(Collections.singletonList(name()))) - .then(context.voidMono()); + this.setActiveTask = context -> manager().serviceClient() + .getApps() + .setActiveDeploymentsAsync(parent().parent().resourceGroupName(), parent().parent().name(), // service name + parent().name(), // app name + new ActiveDeploymentCollection().withActiveDeploymentNames(Collections.singletonList(name()))) + .then(context.voidMono()); return this; } @@ -540,8 +533,7 @@ public SpringAppDeploymentImpl withConfigFilePatterns(List configFilePat Map> addonConfigs = innerModel().properties().deploymentSettings().addonConfigs(); addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, s -> { Map config = new HashMap<>(); - config.put( - Constants.CONFIG_FILE_PATTERNS_KEY, + config.put(Constants.CONFIG_FILE_PATTERNS_KEY, CoreUtils.isNullOrEmpty(configFilePatterns) ? "" : String.join(",", configFilePatterns)); return config; }); @@ -563,10 +555,10 @@ public void beforeGroupCreateOrUpdate() { @Override public Mono createResourceAsync() { - return manager().serviceClient().getDeployments().createOrUpdateAsync( - parent().parent().resourceGroupName(), parent().parent().name(), - parent().name(), name(), innerModel() - ) + return manager().serviceClient() + .getDeployments() + .createOrUpdateAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -575,10 +567,10 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return manager().serviceClient().getDeployments().updateAsync( - parent().parent().resourceGroupName(), parent().parent().name(), - parent().name(), name(), innerModel() - ) + return manager().serviceClient() + .getDeployments() + .updateAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), + innerModel()) .map(inner -> { setInner(inner); return this; @@ -587,16 +579,16 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getDeployments().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getDeployments() + .deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getDeployments().getAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getDeployments() + .getAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override @@ -646,26 +638,25 @@ private class BuildServiceTask implements FunctionalTaskItem { @Override public Mono 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())); + .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 uploadAndBuildAsync(File source, ResourceUploadDefinition option) { - return uploadToStorageAsync(source, option) - .then(enqueueBuildAsync(option)) - .flatMap(waitForBuildAsync()); + return uploadToStorageAsync(source, option).then(enqueueBuildAsync(option)).flatMap(waitForBuildAsync()); } private Mono 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)) + .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()); // source code if (this.sourceCodeTarGz) { @@ -676,14 +667,12 @@ private Mono enqueueBuildAsync(ResourceUploadDefinition option) { buildEnv.put("BP_MAVEN_BUILT_MODULE", module); } } - return manager().serviceClient().getBuildServices() + return manager().serviceClient() + .getBuildServices() // This method enqueues the build request, response with provision state "Succeeded" only means the build is enqueued. // Attempting to continue deploying without waiting for the build to complete will result in failure. - .createOrUpdateBuildAsync( - service().resourceGroupName(), - service().name(), - Constants.DEFAULT_TANZU_COMPONENT_NAME, - app().name(), + .createOrUpdateBuildAsync(service().resourceGroupName(), service().name(), + Constants.DEFAULT_TANZU_COMPONENT_NAME, app().name(), new BuildInner().withProperties(buildProperties)) .map(inner -> inner.properties().triggeredBuildResult().id()); } @@ -691,38 +680,34 @@ private Mono enqueueBuildAsync(ResourceUploadDefinition option) { private Function> 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()))); - } + 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 { - return Mono.error(new ManagementException(String.format("Build timeout for file: %s, buildId: %s", - file.getName(), buildId), null)); + 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()))); } - }).repeatWhenEmpty(longFlux -> - longFlux - .flatMap( - index -> { - pollCount.set(index); - return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollDuration)); - })); + } 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") @@ -754,7 +739,8 @@ public HttpHeaders getHeaders() { @Override public Flux getBody() { try { - return Flux.just(ByteBuffer.wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); + return Flux.just(ByteBuffer + .wrap(serializerAdapter.serializeToBytes(response.getValue(), SerializerEncoding.JSON))); } catch (IOException e) { return Flux.empty(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentsImpl.java index 6eab9c12bfb6c..08c3b739a8f66 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDeploymentsImpl.java @@ -16,9 +16,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringAppDeploymentsImpl - extends ExternalChildResourcesNonCachedImpl< - SpringAppDeploymentImpl, SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp> +public class SpringAppDeploymentsImpl extends + ExternalChildResourcesNonCachedImpl implements SpringAppDeployments { SpringAppDeploymentsImpl(SpringAppImpl parent) { @@ -78,8 +77,8 @@ public void deleteByName(String name) { @Override public Mono deleteByNameAsync(String name) { - return inner().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name); + return inner().deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name); } @Override @@ -89,7 +88,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), + return PagedConverter.mapPage( + inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), this::wrapModel); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainImpl.java index 7ced6ee318704..f225c5141e67d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainImpl.java @@ -20,9 +20,10 @@ public class SpringAppDomainImpl @Override public Mono createResourceAsync() { - return manager().serviceClient().getCustomDomains().createOrUpdateAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() - ) + return manager().serviceClient() + .getCustomDomains() + .createOrUpdateAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -36,16 +37,16 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getBindings().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getBindings() + .deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getCustomDomains().getAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getCustomDomains() + .getAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainsImpl.java index 1a77df6e72594..c524b4e389330 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppDomainsImpl.java @@ -19,9 +19,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringAppDomainsImpl - extends ExternalChildResourcesNonCachedImpl< - SpringAppDomainImpl, SpringAppDomain, CustomDomainResourceInner, SpringAppImpl, SpringApp> +public class SpringAppDomainsImpl extends + ExternalChildResourcesNonCachedImpl implements SpringAppDomains { SpringAppDomainsImpl(SpringAppImpl parent) { super(parent, parent.taskGroup(), "SpringAppDomain"); @@ -79,8 +78,8 @@ public void deleteByName(String name) { @Override public Mono deleteByNameAsync(String name) { - return inner().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name); + return inner().deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name); } @Override @@ -90,7 +89,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), + return PagedConverter.mapPage( + inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), this::wrapModel); } @@ -105,8 +105,10 @@ public CustomDomainValidateResult validate(String domain) { @Override public Mono validateAsync(String domain) { - return manager().serviceClient().getApps().validateDomainAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), new CustomDomainValidatePayload().withName(domain)); + return manager().serviceClient() + .getApps() + .validateDomainAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + new CustomDomainValidatePayload().withName(domain)); } SpringAppDomain prepareCreateOrUpdate(String name, CustomDomainProperties properties) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppImpl.java index 5e756eba9cefc..e3166835e569c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppImpl.java @@ -102,7 +102,8 @@ public ManagedIdentityProperties identity() { @Override public String activeDeploymentName() { // get the first active deployment - Optional deployment = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); + Optional deployment + = deployments.list().stream().filter(SpringAppDeployment::isActive).findFirst(); return deployment.map(SpringAppDeployment::appName).orElse(null); } @@ -134,8 +135,9 @@ public SpringAppDomains customDomains() { @Override public Mono getResourceUploadUrlAsync() { - return manager().serviceClient().getApps().getResourceUploadUrlAsync( - parent().resourceGroupName(), parent().name(), name()); + return manager().serviceClient() + .getApps() + .getResourceUploadUrlAsync(parent().resourceGroupName(), parent().name(), name()); } @Override @@ -160,7 +162,9 @@ public boolean hasConfigurationServiceBinding() { return false; } return addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) != null - && configurationService.id().equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY).get(Constants.BINDING_RESOURCE_ID)); + && configurationService.id() + .equalsIgnoreCase((String) addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY) + .get(Constants.BINDING_RESOURCE_ID)); } @Override @@ -174,7 +178,9 @@ public boolean hasServiceRegistryBinding() { return false; } return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null - && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); + && serviceRegistry.id() + .equalsIgnoreCase( + (String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID)); } @Override @@ -226,16 +232,16 @@ public SpringAppImpl withoutHttpsOnly() { @Override public SpringAppImpl withTemporaryDisk(int sizeInGB, String mountPath) { ensureProperty(); - innerModel().properties().withTemporaryDisk( - new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); + innerModel().properties() + .withTemporaryDisk(new TemporaryDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @Override public SpringAppImpl withPersistentDisk(int sizeInGB, String mountPath) { ensureProperty(); - innerModel().properties().withPersistentDisk( - new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); + innerModel().properties() + .withPersistentDisk(new PersistentDisk().withSizeInGB(sizeInGB).withMountPath(mountPath)); return this; } @@ -244,10 +250,11 @@ public SpringAppImpl withActiveDeployment(String name) { if (CoreUtils.isNullOrEmpty(name)) { return this; } - this.setActiveDeploymentTask = - context -> manager().serviceClient().getApps() - .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) - .then(context.voidMono()); + this.setActiveDeploymentTask = context -> manager().serviceClient() + .getApps() + .setActiveDeploymentsAsync(parent().resourceGroupName(), parent().name(), name(), + new ActiveDeploymentCollection().withActiveDeploymentNames(Arrays.asList(name))) + .then(context.voidMono()); return this; } @@ -264,8 +271,9 @@ public Mono createResourceAsync() { if (springAppDeploymentToCreate == null) { withDefaultActiveDeployment(); } - return manager().serviceClient().getApps().createOrUpdateAsync( - parent().resourceGroupName(), parent().name(), name(), innerModel()) + return manager().serviceClient() + .getApps() + .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -276,8 +284,9 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return manager().serviceClient().getApps().updateAsync( - parent().resourceGroupName(), parent().name(), name(), innerModel()) + return manager().serviceClient() + .getApps() + .updateAsync(parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -332,8 +341,7 @@ public SpringAppImpl withDefaultActiveDeployment() { @Override @SuppressWarnings("unchecked") - public > + public > SpringAppDeployment.DefinitionStages.Blank defineActiveDeployment(String name) { return (SpringAppDeployment.DefinitionStages.Blank) deployments.define(name).withActivation(); } @@ -353,7 +361,8 @@ public SpringAppImpl withConfigurationServiceBinding() { } SpringConfigurationService configurationService = parent().getDefaultConfigurationService(); if (configurationService != null) { - Map configurationServiceConfigs = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); + Map configurationServiceConfigs + = addonConfigs.computeIfAbsent(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY, k -> new HashMap<>()); configurationServiceConfigs.put(Constants.BINDING_RESOURCE_ID, configurationService.id()); } return this; @@ -368,7 +377,8 @@ public SpringAppImpl withoutConfigurationServiceBinding() { if (addonConfigs == null) { return this; } - Map configurationServiceConfigs = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); + Map configurationServiceConfigs + = addonConfigs.get(Constants.APPLICATION_CONFIGURATION_SERVICE_KEY); if (configurationServiceConfigs == null) { return this; } @@ -386,7 +396,8 @@ public SpringAppImpl withServiceRegistryBinding() { } SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry(); if (serviceRegistry != null) { - Map serviceRegistryConfigs = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); + Map serviceRegistryConfigs + = addonConfigs.computeIfAbsent(Constants.SERVICE_REGISTRY_KEY, k -> new HashMap<>()); serviceRegistryConfigs.put(Constants.BINDING_RESOURCE_ID, serviceRegistry.id()); } return this; diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingImpl.java index 94f6cd2c438a8..cc37f227b1ee8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingImpl.java @@ -20,9 +20,10 @@ public class SpringAppServiceBindingImpl @Override public Mono createResourceAsync() { - return manager().serviceClient().getBindings().createOrUpdateAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name(), innerModel() - ) + return manager().serviceClient() + .getBindings() + .createOrUpdateAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -36,16 +37,16 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getBindings().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getBindings() + .deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getBindings().getAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name() - ); + return manager().serviceClient() + .getBindings() + .getAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingsImpl.java index 3b8eaed54c4ae..c6b40edab5ec0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppServiceBindingsImpl.java @@ -17,9 +17,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringAppServiceBindingsImpl - extends ExternalChildResourcesNonCachedImpl< - SpringAppServiceBindingImpl, SpringAppServiceBinding, BindingResourceInner, SpringAppImpl, SpringApp> +public class SpringAppServiceBindingsImpl extends + ExternalChildResourcesNonCachedImpl implements SpringAppServiceBindings { SpringAppServiceBindingsImpl(SpringAppImpl parent) { super(parent, parent.taskGroup(), "SpringAppServiceBinding"); @@ -77,8 +76,8 @@ public void deleteByName(String name) { @Override public Mono deleteByNameAsync(String name) { - return inner().deleteAsync( - parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), name); + return inner().deleteAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name(), + name); } @Override @@ -88,7 +87,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), + return PagedConverter.mapPage( + inner().listAsync(parent().parent().resourceGroupName(), parent().parent().name(), parent().name()), this::wrapModel); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppsImpl.java index 49ecea64c7c3e..18b0f72e201e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringAppsImpl.java @@ -16,9 +16,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringAppsImpl - extends ExternalChildResourcesNonCachedImpl< - SpringAppImpl, SpringApp, AppResourceInner, SpringServiceImpl, SpringService> +public class SpringAppsImpl extends + ExternalChildResourcesNonCachedImpl implements SpringApps { SpringAppsImpl(SpringServiceImpl parent) { @@ -42,8 +41,7 @@ public SpringApp getByName(String name) { @Override public Mono getByNameAsync(String name) { - return inner().getAsync(parent().resourceGroupName(), parent().name(), name) - .map(this::wrapModel); + return inner().getAsync(parent().resourceGroupName(), parent().name(), name).map(this::wrapModel); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServiceImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServiceImpl.java index 29cb60bfe15fb..276ee67a99f29 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServiceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServiceImpl.java @@ -18,10 +18,11 @@ import java.util.Optional; import java.util.stream.Collectors; -public class SpringConfigurationServiceImpl - extends ExternalChildResourceImpl +public class SpringConfigurationServiceImpl extends + ExternalChildResourceImpl implements SpringConfigurationService { - protected SpringConfigurationServiceImpl(String name, SpringServiceImpl parent, ConfigurationServiceResourceInner innerObject) { + protected SpringConfigurationServiceImpl(String name, SpringServiceImpl parent, + ConfigurationServiceResourceInner innerObject) { super(name, parent, innerObject); } @@ -37,22 +38,16 @@ public Double memory() { @Override public String gitUri() { - return findDefaultRepository() - .map(ConfigurationServiceGitRepository::uri) - .orElse(null); + return findDefaultRepository().map(ConfigurationServiceGitRepository::uri).orElse(null); } @Override public List filePatterns() { - return findDefaultRepository() - .map(ConfigurationServiceGitRepository::patterns) - .orElse(Collections.emptyList()); + return findDefaultRepository().map(ConfigurationServiceGitRepository::patterns).orElse(Collections.emptyList()); } public String branch() { - return findDefaultRepository() - .map(ConfigurationServiceGitRepository::label) - .orElse(null); + return findDefaultRepository().map(ConfigurationServiceGitRepository::label).orElse(null); } @Override @@ -66,7 +61,11 @@ private Optional findDefaultRepository() { @Override public List getAppBindings() { - return parent().apps().list().stream().filter(SpringApp::hasConfigurationServiceBinding).collect(Collectors.toList()); + return parent().apps() + .list() + .stream() + .filter(SpringApp::hasConfigurationServiceBinding) + .collect(Collectors.toList()); } private Optional findRepository(String name) { @@ -75,10 +74,7 @@ private Optional findRepository(String name) } ConfigurationServiceGitProperty property = innerModel().properties().settings().gitProperty(); if (property != null && property.repositories() != null) { - return property.repositories() - .stream() - .filter(repository -> name.equals(repository.name())) - .findFirst(); + return property.repositories().stream().filter(repository -> name.equals(repository.name())).findFirst(); } else { return Optional.empty(); } @@ -91,7 +87,8 @@ public String id() { @Override public Mono createResourceAsync() { - return manager().serviceClient().getConfigurationServices() + return manager().serviceClient() + .getConfigurationServices() .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); @@ -106,12 +103,16 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getConfigurationServices().deleteAsync(parent().resourceGroupName(), parent().name(), name()); + return manager().serviceClient() + .getConfigurationServices() + .deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getConfigurationServices().getAsync(parent().resourceGroupName(), parent().name(), name()); + return manager().serviceClient() + .getConfigurationServices() + .getAsync(parent().resourceGroupName(), parent().name(), name()); } public AppPlatformManager manager() { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServicesImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServicesImpl.java index 902c85580a1a0..c36e16421b05d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServicesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringConfigurationServicesImpl.java @@ -13,9 +13,8 @@ import com.azure.resourcemanager.appplatform.models.SpringService; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.ExternalChildResourcesNonCachedImpl; -public class SpringConfigurationServicesImpl - extends ExternalChildResourcesNonCachedImpl - +public class SpringConfigurationServicesImpl extends + ExternalChildResourcesNonCachedImpl implements SpringConfigurationServices { public SpringConfigurationServicesImpl(SpringServiceImpl parentImpl) { @@ -23,19 +22,9 @@ public SpringConfigurationServicesImpl(SpringServiceImpl parentImpl) { } void prepareCreateOrUpdate(ConfigurationServiceGitProperty property) { - prepareInlineDefine( - new SpringConfigurationServiceImpl( - Constants.DEFAULT_TANZU_COMPONENT_NAME, - parent(), - new ConfigurationServiceResourceInner() - .withProperties( - new ConfigurationServiceProperties() - .withSettings( - new ConfigurationServiceSettings() - .withGitProperty(property)) - ) - ) - ); + prepareInlineDefine(new SpringConfigurationServiceImpl(Constants.DEFAULT_TANZU_COMPONENT_NAME, parent(), + new ConfigurationServiceResourceInner().withProperties(new ConfigurationServiceProperties() + .withSettings(new ConfigurationServiceSettings().withGitProperty(property))))); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificateImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificateImpl.java index 34f55a063b269..2e283f5a67171 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificateImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificateImpl.java @@ -11,9 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.ExternalChildResourceImpl; import reactor.core.publisher.Mono; -public class SpringServiceCertificateImpl - extends ExternalChildResourceImpl< - SpringServiceCertificate, CertificateResourceInner, SpringServiceImpl, SpringService> +public class SpringServiceCertificateImpl extends + ExternalChildResourceImpl implements SpringServiceCertificate { SpringServiceCertificateImpl(String name, SpringServiceImpl parent, CertificateResourceInner innerObject) { super(name, parent, innerObject); @@ -21,8 +20,9 @@ public class SpringServiceCertificateImpl @Override public Mono createResourceAsync() { - return manager().serviceClient().getCertificates().createOrUpdateAsync( - parent().resourceGroupName(), parent().name(), name(), innerModel()) + return manager().serviceClient() + .getCertificates() + .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), name(), innerModel()) .map(inner -> { setInner(inner); return this; @@ -36,13 +36,15 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getCertificates() + return manager().serviceClient() + .getCertificates() .deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getCertificates() + return manager().serviceClient() + .getCertificates() .getAsync(parent().resourceGroupName(), parent().name(), name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificatesImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificatesImpl.java index 622170d0d61da..1d42cf0a81e88 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificatesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceCertificatesImpl.java @@ -17,9 +17,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringServiceCertificatesImpl - extends ExternalChildResourcesNonCachedImpl< - SpringServiceCertificateImpl, SpringServiceCertificate, CertificateResourceInner, SpringServiceImpl, SpringService> +public class SpringServiceCertificatesImpl extends + ExternalChildResourcesNonCachedImpl implements SpringServiceCertificates { SpringServiceCertificatesImpl(SpringServiceImpl parent) { super(parent, parent.taskGroup(), "SpringServiceCertificate"); @@ -42,8 +41,7 @@ public SpringServiceCertificate getByName(String name) { @Override public Mono getByNameAsync(String name) { - return inner().getAsync(parent().resourceGroupName(), parent().name(), name) - .map(this::wrapModel); + return inner().getAsync(parent().resourceGroupName(), parent().name(), name).map(this::wrapModel); } SpringServiceCertificateImpl wrapModel(CertificateResourceInner inner) { @@ -87,7 +85,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(inner().listAsync(parent().resourceGroupName(), parent().name()), this::wrapModel); + return PagedConverter.mapPage(inner().listAsync(parent().resourceGroupName(), parent().name()), + this::wrapModel); } public CertificatesClient inner() { @@ -95,9 +94,8 @@ public CertificatesClient inner() { } SpringServiceCertificate prepareCreateOrUpdate(String name, CertificateProperties properties) { - return prepareInlineDefine( - new SpringServiceCertificateImpl( - name, parent(), new CertificateResourceInner().withProperties(properties))); + return prepareInlineDefine(new SpringServiceCertificateImpl(name, parent(), + new CertificateResourceInner().withProperties(properties))); } void prepareDelete(String name) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceImpl.java index c194f97958669..655a6cd528eab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceImpl.java @@ -86,7 +86,9 @@ public MonitoringSettingProperties getMonitoringSetting() { @Override public Mono getMonitoringSettingAsync() { - return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) + return manager().serviceClient() + .getMonitoringSettings() + .getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @@ -97,7 +99,9 @@ public ConfigServerProperties getServerProperties() { @Override public Mono getServerPropertiesAsync() { - return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) + return manager().serviceClient() + .getConfigServers() + .getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @@ -118,7 +122,10 @@ public TestKeys regenerateTestKeys(TestKeyType keyType) { @Override public Mono regenerateTestKeysAsync(TestKeyType keyType) { - return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); + return manager().serviceClient() + .getServices() + .regenerateTestKeyAsync(resourceGroupName(), name(), + new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override @@ -143,7 +150,9 @@ public Mono enableTestEndpointAsync() { @Override public SpringConfigurationService getDefaultConfigurationService() { - return manager().serviceClient().getConfigurationServices().list(resourceGroupName(), name()) + return manager().serviceClient() + .getConfigurationServices() + .list(resourceGroupName(), name()) .stream() .filter(inner -> Objects.equals(inner.name(), Constants.DEFAULT_TANZU_COMPONENT_NAME)) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) @@ -153,7 +162,9 @@ public SpringConfigurationService getDefaultConfigurationService() { @Override public SpringServiceRegistry getDefaultServiceRegistry() { - return manager().serviceClient().getServiceRegistries().list(resourceGroupName(), name()) + return manager().serviceClient() + .getServiceRegistries() + .list(resourceGroupName(), name()) .stream() .filter(inner -> Objects.equals(inner.name(), Constants.DEFAULT_TANZU_COMPONENT_NAME)) .map(inner -> new SpringServiceRegistryImpl(inner.name(), this, inner)) @@ -194,10 +205,11 @@ public SpringServiceImpl withEnterpriseTierSku() { @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { - monitoringSettingTask = - context -> manager().serviceClient().getMonitoringSettings() - .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( - new MonitoringSettingProperties() + monitoringSettingTask + = context -> manager().serviceClient() + .getMonitoringSettings() + .updatePatchAsync(resourceGroupName(), name(), + new MonitoringSettingResourceInner().withProperties(new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); @@ -206,56 +218,46 @@ public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { @Override public SpringServiceImpl withoutTracing() { - monitoringSettingTask = - context -> manager().serviceClient().getMonitoringSettings() - .updatePatchAsync( - resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( - new MonitoringSettingProperties().withTraceEnabled(false) - )) - .then(context.voidMono()); + monitoringSettingTask = context -> manager().serviceClient() + .getMonitoringSettings() + .updatePatchAsync(resourceGroupName(), name(), + new MonitoringSettingResourceInner() + .withProperties(new MonitoringSettingProperties().withTraceEnabled(false))) + .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { - configServerTask = - context -> manager().serviceClient().getConfigServers() - .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( - new ConfigServerProperties() - .withConfigServer(new ConfigServerSettings().withGitProperty( - new ConfigServerGitProperty().withUri(uri) - )) - )) - .then(context.voidMono()); + configServerTask = context -> manager().serviceClient() + .getConfigServers() + .updatePatchAsync(resourceGroupName(), name(), + new ConfigServerResourceInner().withProperties(new ConfigServerProperties().withConfigServer( + new ConfigServerSettings().withGitProperty(new ConfigServerGitProperty().withUri(uri))))) + .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { - configServerTask = - context -> manager().serviceClient().getConfigServers() - .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( - new ConfigServerProperties() - .withConfigServer(new ConfigServerSettings().withGitProperty( - new ConfigServerGitProperty() - .withUri(uri) - .withUsername(username) - .withPassword(password) - )) - )) - .then(context.voidMono()); + configServerTask = context -> manager().serviceClient() + .getConfigServers() + .updatePatchAsync(resourceGroupName(), name(), + new ConfigServerResourceInner().withProperties( + new ConfigServerProperties().withConfigServer(new ConfigServerSettings().withGitProperty( + new ConfigServerGitProperty().withUri(uri).withUsername(username).withPassword(password))))) + .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { - configServerTask = - context -> manager().serviceClient().getConfigServers() - .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( - new ConfigServerProperties() - .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) - )) - .then(context.voidMono()); + configServerTask = context -> manager().serviceClient() + .getConfigServers() + .updatePatchAsync(resourceGroupName(), name(), + new ConfigServerResourceInner().withProperties(new ConfigServerProperties() + .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)))) + .then(context.voidMono()); return this; } @@ -289,55 +291,49 @@ public void beforeGroupCreateOrUpdate() { public Mono createResourceAsync() { Mono createOrUpdate; if (isInCreateMode()) { - createOrUpdate = manager().serviceClient().getServices() + createOrUpdate = manager().serviceClient() + .getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate // initialize build service agent pool - .flatMap(inner -> - manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( - resourceGroupName(), - name(), - Constants.DEFAULT_TANZU_COMPONENT_NAME, + .flatMap(inner -> manager().serviceClient() + .getBuildServiceAgentPools() + .updatePutAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() - .withProperties( - new BuildServiceAgentPoolProperties() - .withPoolSize( - new BuildServiceAgentPoolSizeProperties() - .withName("S1"))) // S1, S2, S3, S4, S5. - ).then(Mono.just(inner))); + .withProperties(new BuildServiceAgentPoolProperties() + .withPoolSize(new BuildServiceAgentPoolSizeProperties().withName("S1"))) // S1, S2, S3, S4, S5. + ) + .then(Mono.just(inner))); } } else if (updated) { - createOrUpdate = manager().serviceClient().getServices().updateAsync( - resourceGroupName(), name(), patchToUpdate); + createOrUpdate + = manager().serviceClient().getServices().updateAsync(resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } - return createOrUpdate - .map(inner -> { - this.setInner(inner); - return this; - }); + return createOrUpdate.map(inner -> { + this.setInner(inner); + return this; + }); } @Override public Mono afterPostRunAsync(boolean isGroupFaulted) { - return Mono - .just(true) - .map( - ignored -> { - clearCache(); - return ignored; - }) - .then(); + return Mono.just(true).map(ignored -> { + clearCache(); + return ignored; + }).then(); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) + return manager().serviceClient() + .getServices() + .getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; @@ -346,23 +342,18 @@ protected Mono getInnerAsync() { @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { - certificates.prepareCreateOrUpdate( - name, - new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) - ); + certificates.prepareCreateOrUpdate(name, + new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault)); return this; } @Override - public SpringServiceImpl withCertificate(String name, String keyVaultUri, - String certNameInKeyVault, String certVersion) { - certificates.prepareCreateOrUpdate( - name, - new KeyVaultCertificateProperties() - .withVaultUri(keyVaultUri) + public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, + String certVersion) { + certificates.prepareCreateOrUpdate(name, + new KeyVaultCertificateProperties().withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) - .withCertVersion(certVersion) - ); + .withCertVersion(certVersion)); return this; } @@ -382,12 +373,10 @@ public SpringServiceImpl withGitRepository(String name, String uri, String branc if (CoreUtils.isNullOrEmpty(name)) { return this; } - this.configurationServiceConfig.addRepository( - new ConfigurationServiceGitRepository() - .withName(name) - .withUri(uri) - .withPatterns(filePatterns) - .withLabel(branch)); + this.configurationServiceConfig.addRepository(new ConfigurationServiceGitRepository().withName(name) + .withUri(uri) + .withPatterns(filePatterns) + .withLabel(branch)); return this; } @@ -416,7 +405,8 @@ public SpringServiceImpl withoutGitRepositories() { private void prepareCreateOrUpdateConfigurationService() { List repositories = this.configurationServiceConfig.mergeRepositories(); - this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); + this.configurationServices + .prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private void prepareCreateServiceRegistry() { @@ -485,12 +475,17 @@ public List mergeRepositories() { // get existing git repositories SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { - List repositoryList = - configurationService.innerModel().properties().settings() == null + List repositoryList + = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() - : configurationService.innerModel().properties().settings().gitProperty().repositories(); + : configurationService.innerModel() + .properties() + .settings() + .gitProperty() + .repositories(); if (repositoryList != null) { - repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); + repositoryList + .forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistriesImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistriesImpl.java index e6c76809f7a46..924a6e1cf64d7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistriesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistriesImpl.java @@ -8,19 +8,14 @@ import com.azure.resourcemanager.appplatform.models.SpringServiceRegistry; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.ExternalChildResourcesNonCachedImpl; -public class SpringServiceRegistriesImpl - extends ExternalChildResourcesNonCachedImpl< - SpringServiceRegistryImpl, SpringServiceRegistry, ServiceRegistryResourceInner, SpringServiceImpl, SpringService - > { +public class SpringServiceRegistriesImpl extends + ExternalChildResourcesNonCachedImpl { public SpringServiceRegistriesImpl(SpringServiceImpl parentImpl) { super(parentImpl, parentImpl.taskGroup(), "SpringServiceRegistry"); } public void prepareCreate() { - prepareInlineDefine(new SpringServiceRegistryImpl( - Constants.DEFAULT_TANZU_COMPONENT_NAME, - getParent(), - new ServiceRegistryResourceInner() - )); + prepareInlineDefine(new SpringServiceRegistryImpl(Constants.DEFAULT_TANZU_COMPONENT_NAME, getParent(), + new ServiceRegistryResourceInner())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistryImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistryImpl.java index 85814d4d59f92..423520c9d0d9d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistryImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServiceRegistryImpl.java @@ -14,11 +14,12 @@ import java.util.List; import java.util.stream.Collectors; -public class SpringServiceRegistryImpl - extends ExternalChildResourceImpl +public class SpringServiceRegistryImpl extends + ExternalChildResourceImpl implements SpringServiceRegistry { - protected SpringServiceRegistryImpl(String name, SpringServiceImpl parent, ServiceRegistryResourceInner innerObject) { + protected SpringServiceRegistryImpl(String name, SpringServiceImpl parent, + ServiceRegistryResourceInner innerObject) { super(name, parent, innerObject); } @@ -34,7 +35,8 @@ public Double memory() { @Override public List getAppBindings() { - return parent().apps().list() + return parent().apps() + .list() .stream() .filter(SpringApp::hasServiceRegistryBinding) .collect(Collectors.toList()); @@ -47,7 +49,8 @@ public String id() { @Override public Mono createResourceAsync() { - return manager().serviceClient().getServiceRegistries() + return manager().serviceClient() + .getServiceRegistries() .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), name()) .map(inner -> { setInner(inner); @@ -62,12 +65,16 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return manager().serviceClient().getServiceRegistries().deleteAsync(parent().resourceGroupName(), parent().name(), name()); + return manager().serviceClient() + .getServiceRegistries() + .deleteAsync(parent().resourceGroupName(), parent().name(), name()); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getServiceRegistries().getAsync(parent().resourceGroupName(), parent().name(), name()); + return manager().serviceClient() + .getServiceRegistries() + .getAsync(parent().resourceGroupName(), parent().name(), name()); } private AppPlatformManager manager() { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServicesImpl.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServicesImpl.java index e75ffea61eb42..848cb9981786d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServicesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/SpringServicesImpl.java @@ -19,9 +19,8 @@ import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; -public class SpringServicesImpl - extends GroupableResourcesImpl< - SpringService, SpringServiceImpl, ServiceResourceInner, ServicesClient, AppPlatformManager> +public class SpringServicesImpl extends + GroupableResourcesImpl implements SpringServices { private static final String SPRING_TYPE = "Microsoft.AppPlatform/Spring"; @@ -56,8 +55,8 @@ public NameAvailability checkNameAvailability(String name, Region region) { @Override public Mono checkNameAvailabilityAsync(String name, Region region) { - return inner().checkNameAvailabilityAsync( - region.toString(), new NameAvailabilityParameters().withName(name).withType(SPRING_TYPE)); + return inner().checkNameAvailabilityAsync(region.toString(), + new NameAvailabilityParameters().withName(name).withType(SPRING_TYPE)); } @Override @@ -78,8 +77,8 @@ public PagedIterable listByResourceGroup(String resourceGroupName @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return PagedConverter.mapPage(inner().listByResourceGroupAsync(resourceGroupName), this::wrapModel); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/Utils.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/Utils.java index c2a8328be9a04..3a22b85238bd0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/Utils.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/Utils.java @@ -103,10 +103,8 @@ private static class CpuMatcher { static CpuMatcher create(String cpu) { Matcher integerMatcher = CPU_INTEGER.matcher(cpu); Matcher fractionMatcher = CPU_FRACTION.matcher(cpu); - return new CpuMatcher( - integerMatcher.matches() ? integerMatcher : null, - fractionMatcher.matches() ? fractionMatcher : null - ); + return new CpuMatcher(integerMatcher.matches() ? integerMatcher : null, + fractionMatcher.matches() ? fractionMatcher : null); } boolean noMatch() { @@ -136,10 +134,7 @@ private static class MemoryMatcher { static MemoryMatcher create(String memory) { Matcher gbMatcher = MEMORY_GB.matcher(memory); Matcher mbMatcher = MEMORY_MB.matcher(memory); - return new MemoryMatcher( - gbMatcher.matches() ? gbMatcher : null, - mbMatcher.matches() ? mbMatcher : null - ); + return new MemoryMatcher(gbMatcher.matches() ? gbMatcher : null, mbMatcher.matches() ? mbMatcher : null); } boolean noMatch() { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApp.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApp.java index f3bbb1f2f2ef7..c7537ae98a990 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApp.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApp.java @@ -14,10 +14,8 @@ /** An immutable client-side representation of an Azure Spring App. */ @Fluent -public interface SpringApp - extends ExternalChildResource, - HasInnerModel, - Updatable { +public interface SpringApp extends ExternalChildResource, HasInnerModel, + Updatable { /** @return whether the app exposes public endpoint */ boolean isPublic(); @@ -79,14 +77,14 @@ public interface SpringApp boolean hasServiceRegistryBinding(); /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithCreate { } + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate { + } /** Grouping of all the spring app definition stages. */ interface DefinitionStages { /** The first stage of the spring app definition. */ - interface Blank extends WithDeployment { } + interface Blank extends WithDeployment { + } /** * The stage of a spring app definition allowing to specify an active deployment. @@ -104,8 +102,7 @@ interface WithDeployment { * @param derived type of {@link SpringAppDeployment.DefinitionStages.WithAttach} * @return the first stage of spring app deployment definition */ - > + > SpringAppDeployment.DefinitionStages.Blank defineActiveDeployment(String name); } @@ -221,25 +218,17 @@ interface WithServiceRegistryBinding { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithEndpoint, - DefinitionStages.WithDisk, - DefinitionStages.WithDeployment, - DefinitionStages.WithServiceBinding, - DefinitionStages.WithConfigurationServiceBinding, - DefinitionStages.WithServiceRegistryBinding { } + interface WithCreate extends Creatable, DefinitionStages.WithEndpoint, DefinitionStages.WithDisk, + DefinitionStages.WithDeployment, DefinitionStages.WithServiceBinding, + DefinitionStages.WithConfigurationServiceBinding, DefinitionStages.WithServiceRegistryBinding { + } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithEndpoint, - UpdateStages.WithDisk, - UpdateStages.WithDeployment, - UpdateStages.WithServiceBinding, - UpdateStages.WithConfigurationServiceBinding, - UpdateStages.WithServiceRegistryBinding { } + interface Update extends Appliable, UpdateStages.WithEndpoint, UpdateStages.WithDisk, + UpdateStages.WithDeployment, UpdateStages.WithServiceBinding, UpdateStages.WithConfigurationServiceBinding, + UpdateStages.WithServiceRegistryBinding { + } /** Grouping of spring app update stages. */ interface UpdateStages { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployment.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployment.java index fe2315e8621db..f5ae48e015c3c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployment.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployment.java @@ -18,10 +18,8 @@ /** An immutable client-side representation of an Azure Spring App Deployment. */ @Fluent -public interface SpringAppDeployment - extends ExternalChildResource, - HasInnerModel, - Updatable { +public interface SpringAppDeployment extends ExternalChildResource, + HasInnerModel, Updatable { /** @return the app name of the deployment */ String appName(); @@ -91,17 +89,15 @@ public interface SpringAppDeployment * @param The return type of final stage, * usually {@link DefinitionStages.WithCreate} or {@link DefinitionStages.WithAttach} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithSource, - DefinitionStages.WithModule, - DefinitionStages.WithCreate, - DefinitionStages.WithAttach { } + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithSource, + DefinitionStages.WithModule, DefinitionStages.WithCreate, DefinitionStages.WithAttach { + } /** Grouping of all the deployment definition stages. */ interface DefinitionStages { /** The first stage of the deployment definition. */ - interface Blank extends WithSource { } + interface Blank extends WithSource { + } /** The stage of a deployment definition allowing to specify the source code or package. */ interface WithSource { @@ -261,24 +257,22 @@ interface WithSettings { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface Final - extends WithSettings { } + interface Final extends WithSettings { + } /** The final stage of the definition allowing to create a deployment */ - interface WithCreate - extends Creatable, Final { } + interface WithCreate extends Creatable, Final { + } /** The final stage of the definition allowing to attach a deployment to its parent */ - interface WithAttach - extends Attachable, Final { } + interface WithAttach extends Attachable, Final { + } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithSource, - UpdateStages.WithModule, - UpdateStages.WithSettings { } + interface Update extends Appliable, UpdateStages.WithSource, UpdateStages.WithModule, + UpdateStages.WithSettings { + } /** Grouping of deployment update stages. */ interface UpdateStages { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployments.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployments.java index f4b6289093a17..0a4f1403e3012 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployments.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDeployments.java @@ -16,13 +16,8 @@ /** Entry point for Spring App Deployments API. */ @Fluent -public interface SpringAppDeployments - extends HasManager, - HasParent, - SupportsCreating>, - SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsDeletingById, +public interface SpringAppDeployments extends HasManager, HasParent, + SupportsCreating>, SupportsGettingById, + SupportsGettingByName, SupportsListing, SupportsDeletingById, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomain.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomain.java index 60305a424a0aa..04f7d4c20fa8b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomain.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomain.java @@ -9,8 +9,7 @@ /** An immutable client-side representation of an Azure Spring App Custom Domain. */ public interface SpringAppDomain - extends ExternalChildResource, - HasInnerModel { + extends ExternalChildResource, HasInnerModel { /** @return the properties of the spring app custom domain */ CustomDomainProperties properties(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomains.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomains.java index 6a10589193e88..53782a2e59c42 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomains.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppDomains.java @@ -16,14 +16,9 @@ /** Entry point for Spring App Custom Domains API. */ @Fluent -public interface SpringAppDomains - extends HasManager, - HasParent, - SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsDeletingById, - SupportsDeletingByName { +public interface SpringAppDomains extends HasManager, HasParent, + SupportsGettingById, SupportsGettingByName, SupportsListing, + SupportsDeletingById, SupportsDeletingByName { /** * Checks the domain is validate for the app or not. * diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBinding.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBinding.java index 19629236c3cc9..be9e59754c4d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBinding.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBinding.java @@ -9,8 +9,7 @@ /** An immutable client-side representation of an Azure Spring App Service Binding. */ public interface SpringAppServiceBinding - extends ExternalChildResource, - HasInnerModel { + extends ExternalChildResource, HasInnerModel { /** @return the properties of the service binding */ BindingResourceProperties properties(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBindings.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBindings.java index 532f06769b965..5730eb243d4d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBindings.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringAppServiceBindings.java @@ -15,12 +15,7 @@ /** Entry point for Spring App Service Bindings API. */ @Fluent -public interface SpringAppServiceBindings - extends HasManager, - HasParent, - SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsDeletingById, - SupportsDeletingByName { +public interface SpringAppServiceBindings extends HasManager, HasParent, + SupportsGettingById, SupportsGettingByName, + SupportsListing, SupportsDeletingById, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApps.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApps.java index a94fc92ef6c01..174fbb98210fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApps.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringApps.java @@ -16,13 +16,7 @@ /** Entry point for Spring Apps API. */ @Fluent -public interface SpringApps - extends HasManager, - HasParent, - SupportsCreating, - SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsDeletingById, - SupportsDeletingByName { +public interface SpringApps extends HasManager, HasParent, + SupportsCreating, SupportsGettingById, + SupportsGettingByName, SupportsListing, SupportsDeletingById, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationService.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationService.java index b2bfed0f61dd2..74f0a24265153 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationService.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationService.java @@ -15,9 +15,8 @@ * An immutable client-side representation of an Azure Spring Cloud Configuration Service. */ @Fluent -public interface SpringConfigurationService - extends ExternalChildResource, - HasInnerModel { +public interface SpringConfigurationService extends ExternalChildResource, + HasInnerModel { /** @return cpu for the Configuration Service */ Double cpu(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationServices.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationServices.java index bc89fdf869f09..0265fb1cdd33d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationServices.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringConfigurationServices.java @@ -13,7 +13,5 @@ * Entry point for Tanzu Configuration Service API. */ @Fluent -public interface SpringConfigurationServices - extends HasManager, - HasParent { +public interface SpringConfigurationServices extends HasManager, HasParent { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringService.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringService.java index 24a6143bf66c4..95479bb1a9c4e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringService.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringService.java @@ -18,10 +18,8 @@ /** An immutable client-side representation of an Azure Spring Service. */ @Fluent -public interface SpringService - extends GroupableResource, - Refreshable, - Updatable { +public interface SpringService extends GroupableResource, + Refreshable, Updatable { /** @return Sku of the service */ Sku sku(); @@ -100,19 +98,19 @@ public interface SpringService SpringServiceRegistry getDefaultServiceRegistry(); /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.WithEnterpriseTierCreate { } + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.WithEnterpriseTierCreate { + } /** Grouping of all the spring service definition stages. */ interface DefinitionStages { /** The first stage of the spring service definition. */ - interface Blank extends GroupableResource.DefinitionWithRegion { } + interface Blank extends GroupableResource.DefinitionWithRegion { + } /** The stage of a spring service definition allowing to specify the resource group. */ - interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { } + interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { + } /** * The stage of a spring service definition allowing to specify sku. @@ -214,7 +212,8 @@ interface WithConfigurationService { * @param filePatterns patterns for configuration files to be selected from the git repository * @return the next stage of spring service definition */ - WithEnterpriseTierCreate withGitRepository(String name, String uri, String branch, List filePatterns); + WithEnterpriseTierCreate withGitRepository(String name, String uri, String branch, + List filePatterns); /** * Specifies complete git repository configuration for the spring service. @@ -251,35 +250,23 @@ interface WithCertificate { * The stage of the definition which contains all the minimum required inputs for the resource of enterprise tier to be created, * but also allows for any other optional settings to be specified. */ - interface WithEnterpriseTierCreate - extends Creatable, - Resource.DefinitionWithTags, - WithSku, - WithTracing, - WithConfigurationService, - WithCertificate { } + interface WithEnterpriseTierCreate extends Creatable, Resource.DefinitionWithTags, + WithSku, WithTracing, WithConfigurationService, WithCertificate { + } /** * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithSku, - WithTracing, - WithConfiguration, - WithCertificate { } + interface WithCreate extends Creatable, Resource.DefinitionWithTags, WithSku, + WithTracing, WithConfiguration, WithCertificate { + } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithTracing, - UpdateStages.WithConfiguration, - UpdateStages.WithCertificate { } + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithTracing, UpdateStages.WithConfiguration, UpdateStages.WithCertificate { + } /** Grouping of spring service update stages. */ interface UpdateStages { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificate.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificate.java index 8be7ccedba1cf..5562ccff74a7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificate.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificate.java @@ -9,8 +9,7 @@ /** An immutable client-side representation of an Azure Spring Service Certificate. */ public interface SpringServiceCertificate - extends ExternalChildResource, - HasInnerModel { + extends ExternalChildResource, HasInnerModel { /** @return the properties of the service binding */ CertificateProperties properties(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificates.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificates.java index c91a43dfb32f2..38d7d822e6357 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificates.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceCertificates.java @@ -15,12 +15,7 @@ /** Entry point for Spring Service Certificates API. */ @Fluent -public interface SpringServiceCertificates - extends HasManager, - HasParent, - SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsDeletingById, - SupportsDeletingByName { +public interface SpringServiceCertificates extends HasManager, HasParent, + SupportsGettingById, SupportsGettingByName, + SupportsListing, SupportsDeletingById, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceRegistry.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceRegistry.java index 500b0e1234f71..0d4fd7f704635 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServiceRegistry.java @@ -13,8 +13,7 @@ /** An immutable client-side representation of an Azure Spring Service Registry. */ @Fluent public interface SpringServiceRegistry - extends ExternalChildResource, - HasInnerModel { + extends ExternalChildResource, HasInnerModel { /** @return cpu for the Service Registry */ Double cpu(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServices.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServices.java index 580828524d6c0..cdc517310128c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServices.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/models/SpringServices.java @@ -21,14 +21,9 @@ /** Entry point for Spring Service management API. */ @Fluent public interface SpringServices - extends HasManager, - SupportsCreating, - SupportsGettingById, - SupportsGettingByResourceGroup, - SupportsListing, - SupportsListingByResourceGroup, - SupportsDeletingById, - SupportsDeletingByResourceGroup { + extends HasManager, SupportsCreating, + SupportsGettingById, SupportsGettingByResourceGroup, SupportsListing, + SupportsListingByResourceGroup, SupportsDeletingById, SupportsDeletingByResourceGroup { /** * Checks the name of the service is available in specific region or not. * diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java index 812417c877c25..4db28c98010b9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java @@ -44,21 +44,10 @@ public class AppPlatformTest extends ResourceManagerTestProxyTestBase { protected String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -75,7 +64,8 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile protected void cleanUpResources() { try { appPlatformManager.resourceManager().resourceGroups().beginDeleteByName(rgName); - } catch (Exception e) { } + } catch (Exception e) { + } } protected boolean checkRedirect(String url) throws IOException { @@ -123,19 +113,17 @@ protected boolean requestSuccess(String url) throws Exception { } protected void allowAllSSL() throws NoSuchAlgorithmException, KeyManagementException { - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } - }; + } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/EnterpriseTierTest.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/EnterpriseTierTest.java index e110c0332ca7a..59be2617287fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/EnterpriseTierTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/EnterpriseTierTest.java @@ -40,12 +40,11 @@ public void canCRUDService() { Assertions.assertEquals(springService.getDefaultConfigurationService().gitUri(), GIT_CONFIG_URI); Assertions.assertEquals(springService.getDefaultConfigurationService().filePatterns(), filePatterns); Assertions.assertNotNull(springService.getDefaultConfigurationService().getGitRepository("config1")); - BuildServiceInner buildServiceInner = appPlatformManager.serviceClient().getBuildServices().getBuildService(rgName, serviceName, "default"); + BuildServiceInner buildServiceInner + = appPlatformManager.serviceClient().getBuildServices().getBuildService(rgName, serviceName, "default"); Assertions.assertNotNull(buildServiceInner); - springService.update() - .withoutGitRepository("config1") - .apply(); + springService.update().withoutGitRepository("config1").apply(); // default is not cleared Assertions.assertNotNull(springService.getDefaultConfigurationService().gitUri()); @@ -54,21 +53,17 @@ public void canCRUDService() { springService.update() .withGitRepositoryConfig(new ConfigurationServiceGitProperty() - .withRepositories(Arrays.asList(new ConfigurationServiceGitRepository() - .withName("config2") + .withRepositories(Arrays.asList(new ConfigurationServiceGitRepository().withName("config2") .withLabel("master") .withPatterns(filePatterns) - .withUri(GIT_CONFIG_URI) - ))) + .withUri(GIT_CONFIG_URI)))) .apply(); // default is overridden Assertions.assertNull(springService.getDefaultConfigurationService().gitUri()); Assertions.assertNotNull(springService.getDefaultConfigurationService().getGitRepository("config2")); - springService.update() - .withoutGitRepositories() - .apply(); + springService.update().withoutGitRepositories().apply(); // config2 is cleared Assertions.assertNull(springService.getDefaultConfigurationService().getGitRepository("config2")); @@ -83,9 +78,7 @@ public void canCRUDService() { .create(); Assertions.assertNull(springService2.getDefaultConfigurationService()); - springService2.update() - .withGitRepository("config2", GIT_CONFIG_URI, "master", filePatterns) - .apply(); + springService2.update().withGitRepository("config2", GIT_CONFIG_URI, "master", filePatterns).apply(); Assertions.assertNotNull(springService2.getDefaultConfigurationService()); Assertions.assertNotNull(springService2.getDefaultConfigurationService().getGitRepository("config2")); @@ -123,8 +116,14 @@ public void canCRUDApp() { // skip in playback, as "hasConfigurationServiceBinding" involve resource ID check Assertions.assertTrue(app.hasConfigurationServiceBinding()); Assertions.assertTrue(app.hasServiceRegistryBinding()); - Assertions.assertTrue(springService.getDefaultConfigurationService().getAppBindings().stream().anyMatch(SpringApp::hasConfigurationServiceBinding)); - Assertions.assertTrue(springService.getDefaultServiceRegistry().getAppBindings().stream().anyMatch(SpringApp::hasServiceRegistryBinding)); + Assertions.assertTrue(springService.getDefaultConfigurationService() + .getAppBindings() + .stream() + .anyMatch(SpringApp::hasConfigurationServiceBinding)); + Assertions.assertTrue(springService.getDefaultServiceRegistry() + .getAppBindings() + .stream() + .anyMatch(SpringApp::hasServiceRegistryBinding)); } app.update() @@ -139,8 +138,14 @@ public void canCRUDApp() { if (!isPlaybackMode()) { Assertions.assertFalse(app.hasConfigurationServiceBinding()); Assertions.assertFalse(app.hasServiceRegistryBinding()); - Assertions.assertFalse(springService.getDefaultConfigurationService().getAppBindings().stream().anyMatch(SpringApp::hasConfigurationServiceBinding)); - Assertions.assertFalse(springService.getDefaultServiceRegistry().getAppBindings().stream().anyMatch(SpringApp::hasServiceRegistryBinding)); + Assertions.assertFalse(springService.getDefaultConfigurationService() + .getAppBindings() + .stream() + .anyMatch(SpringApp::hasConfigurationServiceBinding)); + Assertions.assertFalse(springService.getDefaultServiceRegistry() + .getAppBindings() + .stream() + .anyMatch(SpringApp::hasServiceRegistryBinding)); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudLiveOnlyTest.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudLiveOnlyTest.java index 33326cf2d0e60..8bc2105182d58 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudLiveOnlyTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudLiveOnlyTest.java @@ -50,11 +50,16 @@ public class SpringCloudLiveOnlyTest extends AppPlatformTest { private static final String PIGGYMETRICS_CONFIG_URL = "https://github.com/Azure-Samples/piggymetrics-config"; - private static final String GATEWAY_JAR_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/gateway.jar"; - private static final String PIGGYMETRICS_TAR_GZ_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; - private static final String PETCLINIC_CONFIG_URL = "https://github.com/XiaofeiCao/spring-petclinic-microservices-config"; - private static final String PETCLINIC_GATEWAY_JAR_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/tree/master/spring-cloud/api-gateway.jar"; - private static final String PETCLINIC_TAR_GZ_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/tree/master/spring-cloud/petclinic.tar.gz"; + private static final String GATEWAY_JAR_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/gateway.jar"; + private static final String PIGGYMETRICS_TAR_GZ_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; + private static final String PETCLINIC_CONFIG_URL + = "https://github.com/XiaofeiCao/spring-petclinic-microservices-config"; + private static final String PETCLINIC_GATEWAY_JAR_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/tree/master/spring-cloud/api-gateway.jar"; + private static final String PETCLINIC_TAR_GZ_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/tree/master/spring-cloud/petclinic.tar.gz"; private static final String SPRING_CLOUD_SERVICE_OBJECT_ID = "938df8e2-2b9d-40b1-940c-c75c33494239"; @@ -69,14 +74,16 @@ public void canCRUDDeployment() throws Exception { String deploymentName1 = generateRandomResourceName("deploy", 15); Region region = Region.US_EAST; - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); File jarFile = downloadFile(GATEWAY_JAR_URL); - SpringApp app = service.apps().define(appName) + SpringApp app = service.apps() + .define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) @@ -100,12 +107,13 @@ public void canCRUDDeployment() throws Exception { Assertions.assertEquals("2", deployment.settings().resourceRequests().cpu()); Assertions.assertEquals("4Gi", deployment.settings().resourceRequests().memory()); -// Assertions.assertEquals(RuntimeVersion.JAVA_11, deployment.settings().runtimeVersion()); + // Assertions.assertEquals(RuntimeVersion.JAVA_11, deployment.settings().runtimeVersion()); Assertions.assertEquals(2, deployment.instances().size()); File gzFile = downloadFile(PIGGYMETRICS_TAR_GZ_URL); - deployment = app.deployments().define(deploymentName1) + deployment = app.deployments() + .define(deploymentName1) .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .withActivation() @@ -118,9 +126,7 @@ public void canCRUDDeployment() throws Exception { Assertions.assertTrue(requestSuccess(app.url())); - app.update() - .withoutDefaultPublicEndpoint() - .apply(); + app.update().withoutDefaultPublicEndpoint().apply(); Assertions.assertFalse(app.isPublic()); app.deployments().deleteByName(deploymentName); @@ -140,75 +146,72 @@ public void canCreateCustomDomainWithSsl() throws Exception { allowAllSSL(); String cerPassword = password(); - String resourcePath = Paths.get(this.getClass().getResource("/junit-platform.properties").toURI()).getParent().toString(); + String resourcePath + = Paths.get(this.getClass().getResource("/junit-platform.properties").toURI()).getParent().toString(); String cerPath = resourcePath + domainName + ".cer"; String pfxPath = resourcePath + domainName + ".pfx"; createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); - appPlatformManager.resourceManager().resourceGroups().define(rgName) - .withRegion(region) - .create(); + appPlatformManager.resourceManager().resourceGroups().define(rgName).withRegion(region).create(); // create custom domain and certificate - DnsZone dnsZone = dnsZoneManager.zones().define(domainName) - .withExistingResourceGroup(rgName) - .create(); + DnsZone dnsZone = dnsZoneManager.zones().define(domainName).withExistingResourceGroup(rgName).create(); - AppServiceDomain domain = appServiceManager.domains().define(domainName) + AppServiceDomain domain = appServiceManager.domains() + .define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .withExistingDnsZone(dnsZone) .create(); - Vault vault = keyVaultManager.vaults().define(vaultName) + Vault vault = keyVaultManager.vaults() + .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowSecretAllPermissions() - .allowCertificateAllPermissions() - .attach() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowSecretAllPermissions() + .allowCertificateAllPermissions() + .attach() .defineAccessPolicy() - .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) - .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) - .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) - .attach() + .forObjectId(SPRING_CLOUD_SERVICE_OBJECT_ID) + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) + .attach() .create(); // upload certificate - CertificateClient certificateClient = new CertificateClientBuilder() - .vaultUrl(vault.vaultUri()) + CertificateClient certificateClient = new CertificateClientBuilder().vaultUrl(vault.vaultUri()) .pipeline(appPlatformManager.httpPipeline()) .buildClient(); certificateClient.importCertificate( - new ImportCertificateOptions(certName, certificate) - .setPassword(cerPassword) - .setEnabled(true) - ); + new ImportCertificateOptions(certName, certificate).setPassword(cerPassword).setEnabled(true)); // get thumbprint KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); - String thumbprint = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); + String thumbprint + = printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .withCertificate("test", vault.vaultUri(), certName) @@ -217,10 +220,7 @@ public void canCreateCustomDomainWithSsl() throws Exception { service.apps().define(appName).withDefaultActiveDeployment().withDefaultPublicEndpoint().create(); SpringApp app = service.apps().getByName(appName); - dnsZone.update() - .withCNameRecordSet("www", app.fqdn()) - .withCNameRecordSet("ssl", app.fqdn()) - .apply(); + dnsZone.update().withCNameRecordSet("www", app.fqdn()).withCNameRecordSet("ssl", app.fqdn()).apply(); app.update() .withoutDefaultPublicEndpoint() @@ -232,10 +232,7 @@ public void canCreateCustomDomainWithSsl() throws Exception { Assertions.assertTrue(requestSuccess(String.format("http://www.%s", domainName))); Assertions.assertTrue(requestSuccess(String.format("https://ssl.%s", domainName))); - app.update() - .withHttpsOnly() - .withoutCustomDomain(String.format("www.%s", domainName)) - .apply(); + app.update().withHttpsOnly().withoutCustomDomain(String.format("www.%s", domainName)).apply(); Assertions.assertTrue(checkRedirect(String.format("http://ssl.%s", domainName))); } @@ -249,7 +246,8 @@ public void canCRUDEnterpriseTierDeployment() throws Exception { String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withEnterpriseTierSku() @@ -259,7 +257,8 @@ public void canCRUDEnterpriseTierDeployment() throws Exception { List apiGatewayConfigFilePatterns = Arrays.asList("api-gateway"); String appName = "api-gateway"; - SpringApp gatewayApp = service.apps().define(appName) + SpringApp gatewayApp = service.apps() + .define(appName) .defineActiveDeployment(deploymentName) .withJarFile(jarFile) .withInstance(2) @@ -278,13 +277,9 @@ public void canCRUDEnterpriseTierDeployment() throws Exception { Assertions.assertEquals(jvmOptions, "-DskipTests=true"); List configFilePatterns = Arrays.asList("api-gateway", "customers-service"); - service.update() - .withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns) - .apply(); + service.update().withDefaultGitRepository(PETCLINIC_CONFIG_URL, "master", configFilePatterns).apply(); - deployment.update() - .withConfigFilePatterns(apiGatewayConfigFilePatterns) - .apply(); + deployment.update().withConfigFilePatterns(apiGatewayConfigFilePatterns).apply(); deployment.refresh(); Assertions.assertFalse(CoreUtils.isNullOrEmpty(deployment.configFilePatterns())); @@ -296,7 +291,8 @@ public void canCRUDEnterpriseTierDeployment() throws Exception { String appName2 = "customers-service"; String customerServiceModule = "spring-petclinic-customers-service"; List customerServiceConfigFilePatterns = Arrays.asList("customers-service"); - SpringApp customerServiceApp = service.apps().define(appName2) + SpringApp customerServiceApp = service.apps() + .define(appName2) .defineActiveDeployment(deploymentName) .withSourceCodeTarGzFile(tarGzFile, customerServiceConfigFilePatterns) .withTargetModule(customerServiceModule) @@ -320,7 +316,7 @@ private File downloadFile(String remoteFileUrl) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); - OutputStream outputStream = new FileOutputStream(downloaded)) { + OutputStream outputStream = new FileOutputStream(downloaded)) { IOUtils.copy(inputStream, outputStream); } finally { connection.disconnect(); @@ -332,7 +328,8 @@ private File downloadFile(String remoteFileUrl) throws Exception { private void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); - try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { + try (TarArchiveInputStream inputStream + = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { @@ -367,8 +364,8 @@ private byte[] readAllBytes(InputStream inputStream) throws IOException { } } - public static void createCertificate(String certPath, String pfxPath, - String alias, String password, String cnName, String dnsName) throws IOException { + public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, + String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } @@ -389,10 +386,29 @@ public static void createCertificate(String certPath, String pfxPath, } // Create Pfx file - String[] commandArgs = {command, "-genkey", "-alias", alias, - "-keystore", pfxPath, "-storepass", password, "-validity", - validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, - "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; + String[] commandArgs = { + command, + "-genkey", + "-alias", + alias, + "-keystore", + pfxPath, + "-storepass", + password, + "-validity", + validityInDays, + "-keyalg", + keyAlg, + "-sigalg", + sigAlg, + "-keysize", + keySize, + "-storetype", + storeType, + "-dname", + "CN=" + cnName, + "-ext", + "EKU=1.3.6.1.5.5.7.3.1" }; if (dnsName != null) { List args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); @@ -404,9 +420,20 @@ public static void createCertificate(String certPath, String pfxPath, // Create cer file i.e. extract public key from pfx File pfxFile = new File(pfxPath); if (pfxFile.exists()) { - String[] certCommandArgs = {command, "-export", "-alias", alias, - "-storetype", storeType, "-keystore", pfxPath, - "-storepass", password, "-rfc", "-file", certPath}; + String[] certCommandArgs = { + command, + "-export", + "-alias", + alias, + "-storetype", + storeType, + "-keystore", + pfxPath, + "-storepass", + password, + "-rfc", + "-file", + certPath }; // output of keytool export command is going to error stream // although command is // executed successfully, hence ignoring error stream in this case @@ -415,28 +442,22 @@ public static void createCertificate(String certPath, String pfxPath, // Check if file got created or not File cerFile = new File(pfxPath); if (!cerFile.exists()) { - throw new IOException( - "Error occurred while creating certificate" - + String.join(" ", certCommandArgs)); + throw new IOException("Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { - throw new IOException("Error occurred while creating certificates" - + String.join(" ", commandArgs)); + throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } - public static String cmdInvocation(String[] command, - boolean ignoreErrorStream) throws IOException { + public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); - try ( - InputStream inputStream = process.getInputStream(); + try (InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); - ) { + BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8));) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudTest.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudTest.java index 0340f26cb3c55..55b532a20e046 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/SpringCloudTest.java @@ -22,9 +22,11 @@ public void canCRUDServie() { String serviceName = generateRandomResourceName("springsvc", 15); Region region = Region.US_EAST; - Assertions.assertTrue(appPlatformManager.springServices().checkNameAvailability(serviceName, region).nameAvailable()); + Assertions + .assertTrue(appPlatformManager.springServices().checkNameAvailability(serviceName, region).nameAvailable()); - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .withSku("B0") @@ -32,12 +34,10 @@ public void canCRUDServie() { .create(); Assertions.assertEquals("B0", service.sku().name()); - Assertions.assertEquals(PIGGYMETRICS_CONFIG_URL, service.getServerProperties().configServer().gitProperty().uri()); + Assertions.assertEquals(PIGGYMETRICS_CONFIG_URL, + service.getServerProperties().configServer().gitProperty().uri()); - service.update() - .withSku("S0", 2) - .withoutGitConfig() - .apply(); + service.update().withSku("S0", 2).withoutGitConfig().apply(); Assertions.assertEquals("S0", service.sku().name()); @@ -48,13 +48,16 @@ public void canCRUDServie() { || serverProperties.configServer().gitProperty().uri() == null || serverProperties.configServer().gitProperty().uri().isEmpty()); - Assertions.assertEquals(1, appPlatformManager.springServices().list().stream().filter(s -> s.name().equals(serviceName)).count()); + Assertions.assertEquals(1, + appPlatformManager.springServices().list().stream().filter(s -> s.name().equals(serviceName)).count()); appPlatformManager.springServices().deleteById(service.id()); Assertions.assertEquals(404, - appPlatformManager.springServices().getByIdAsync(service.id()).map(o -> 200) - .onErrorResume(e -> - Mono.just(e instanceof ManagementException ? ((ManagementException) e).getResponse().getStatusCode() : 400)) + appPlatformManager.springServices() + .getByIdAsync(service.id()) + .map(o -> 200) + .onErrorResume(e -> Mono.just( + e instanceof ManagementException ? ((ManagementException) e).getResponse().getStatusCode() : 400)) .block()); } @@ -64,12 +67,14 @@ public void canCRUDApp() throws Exception { String appName = "gateway"; Region region = Region.US_EAST; - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); - SpringApp app = service.apps().define(appName) + SpringApp app = service.apps() + .define(appName) .withDefaultActiveDeployment() .withDefaultPublicEndpoint() .withHttpsOnly() @@ -88,13 +93,10 @@ public void canCRUDApp() throws Exception { if (!isPlaybackMode()) { allowAllSSL(); -// Assertions.assertTrue(requestSuccess(app.url())); + // Assertions.assertTrue(requestSuccess(app.url())); } - app.update() - .withoutDefaultPublicEndpoint() - .withoutHttpsOnly() - .apply(); + app.update().withoutDefaultPublicEndpoint().withoutHttpsOnly().apply(); Assertions.assertFalse(app.isPublic()); Assertions.assertFalse(app.isHttpsOnly()); @@ -103,10 +105,12 @@ public void canCRUDApp() throws Exception { service.apps().deleteById(app.id()); Assertions.assertEquals(404, - service.apps().getByIdAsync(app.id()).map(o -> 200) - .onErrorResume( - e -> Mono.just((e instanceof ManagementException) ? ((ManagementException) e).getResponse().getStatusCode() : 400) - ).block()); + service.apps() + .getByIdAsync(app.id()) + .map(o -> 200) + .onErrorResume(e -> Mono.just( + (e instanceof ManagementException) ? ((ManagementException) e).getResponse().getStatusCode() : 400)) + .block()); } @Test @@ -116,14 +120,16 @@ public void canSetActiveDeployment() { String deploymentName = generateRandomResourceName("dp", 15); Region region = Region.US_EAST; - SpringService service = appPlatformManager.springServices().define(serviceName) + SpringService service = appPlatformManager.springServices() + .define(serviceName) .withRegion(region) .withNewResourceGroup(rgName) .create(); // -------------------------------- // create app with default active deployment - SpringApp app = service.apps().define(appName) + SpringApp app = service.apps() + .define(appName) .withDefaultActiveDeployment() .withDefaultPublicEndpoint() .withHttpsOnly() @@ -149,9 +155,7 @@ public void canSetActiveDeployment() { // -------------------------------- // set active deployment back to the default one - app.update() - .withActiveDeployment("default") - .apply(); + app.update().withActiveDeployment("default").apply(); Assertions.assertEquals(1, app.deployments().list().stream().filter(SpringAppDeployment::isActive).count()); deployment = app.getActiveDeployment(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml index 83c6e8b7165f3..6c3c7da39147a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml @@ -52,6 +52,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/AppServiceManager.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/AppServiceManager.java index e8b1e513ebe71..09d6391c75ada 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/AppServiceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/AppServiceManager.java @@ -101,11 +101,8 @@ public AppServiceManager authenticate(TokenCredential credential, AzureProfile p } private AppServiceManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new WebSiteManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new WebSiteManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); @@ -174,6 +171,7 @@ public AppServiceDomains domains() { } return appServiceDomains; } + /** @return the web app management API entry point */ public FunctionApps functionApps() { if (functionApps == null) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceBaseImpl.java index fc5c72c0fc758..3688a8d5e0b8c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceBaseImpl.java @@ -58,25 +58,14 @@ * @param the definition stage that derives from Creatable * @param The definition stage that derives from Appliable */ -abstract class AppServiceBaseImpl< - FluentT extends WebAppBase, - FluentImplT extends AppServiceBaseImpl, - FluentWithCreateT, - FluentUpdateT> - extends WebAppBaseImpl - implements - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, - SupportsUpdatingPrivateEndpointConnection { +abstract class AppServiceBaseImpl, FluentWithCreateT, FluentUpdateT> + extends WebAppBaseImpl implements SupportsListingPrivateLinkResource, + SupportsListingPrivateEndpointConnection, SupportsUpdatingPrivateEndpointConnection { private final ClientLogger logger = new ClientLogger(getClass()); - AppServiceBaseImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - AppServiceManager manager) { + AppServiceBaseImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); } @@ -102,8 +91,7 @@ Mono getConfigInner() { @Override Mono createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) { - return this - .manager() + return this.manager() .serviceClient() .getWebApps() .createOrUpdateConfigurationAsync(resourceGroupName(), name(), siteConfig); @@ -111,7 +99,9 @@ Mono createOrUpdateSiteConfig(SiteConfigResourceInner s @Override Mono deleteHostnameBinding(String hostname) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .deleteHostnameBindingAsync(resourceGroupName(), name(), hostname); } @@ -122,7 +112,9 @@ Mono listAppSettings() { @Override Mono updateAppSettings(StringDictionaryInner inner) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .updateApplicationSettingsAsync(resourceGroupName(), name(), inner); } @@ -133,7 +125,9 @@ Mono listConnectionStrings() { @Override Mono updateConnectionStrings(ConnectionStringDictionaryInner inner) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .updateConnectionStringsAsync(resourceGroupName(), name(), inner); } @@ -144,13 +138,17 @@ Mono listSlotConfigurations() { @Override Mono updateSlotConfigurations(SlotConfigNamesResourceInner inner) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .updateSlotConfigurationNamesAsync(resourceGroupName(), name(), inner); } @Override Mono createOrUpdateSourceControl(SiteSourceControlInner inner) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .createOrUpdateSourceControlAsync(resourceGroupName(), name(), inner); } @@ -177,25 +175,13 @@ public Map getHostnameBindings() { @Override @SuppressWarnings("unchecked") public Mono> getHostnameBindingsAsync() { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getWebApps() - .listHostnameBindingsAsync(resourceGroupName(), name()), - hostNameBindingInner -> - new HostnameBindingImpl<>(hostNameBindingInner, (FluentImplT) AppServiceBaseImpl.this)) + return PagedConverter + .mapPage(this.manager().serviceClient().getWebApps().listHostnameBindingsAsync(resourceGroupName(), name()), + hostNameBindingInner -> new HostnameBindingImpl<>(hostNameBindingInner, + (FluentImplT) AppServiceBaseImpl.this)) .collectList() - .map( - hostNameBindings -> - Collections - .unmodifiableMap( - hostNameBindings - .stream() - .collect( - Collectors - .toMap( - binding -> binding.name().replace(name() + "/", ""), - Function.identity())))); + .map(hostNameBindings -> Collections.unmodifiableMap(hostNameBindings.stream() + .collect(Collectors.toMap(binding -> binding.name().replace(name() + "/", ""), Function.identity())))); } @Override @@ -204,8 +190,7 @@ public PublishingProfile getPublishingProfile() { } public Mono getPublishingProfileAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .listPublishingProfileXmlWithSecretsAsync(resourceGroupName(), name(), new CsmPublishingProfileOptions()) .map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this)); @@ -218,18 +203,17 @@ public WebAppSourceControl getSourceControl() { @Override public Mono getSourceControlAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .getSourceControlAsync(resourceGroupName(), name()) - .map( - siteSourceControlInner -> - new WebAppSourceControlImpl<>(siteSourceControlInner, AppServiceBaseImpl.this)); + .map(siteSourceControlInner -> new WebAppSourceControlImpl<>(siteSourceControlInner, + AppServiceBaseImpl.this)); } @Override Mono createMSDeploy(MSDeploy msDeployInner) { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .createMSDeployOperationAsync(resourceGroupName(), name(), msDeployInner); } @@ -241,12 +225,11 @@ public void verifyDomainOwnership(String certificateOrderName, String domainVeri @Override public Mono verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) { IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken); - return this - .manager() + return this.manager() .serviceClient() .getWebApps() - .createOrUpdateDomainOwnershipIdentifierAsync( - resourceGroupName(), name(), certificateOrderName, identifierInner) + .createOrUpdateDomainOwnershipIdentifierAsync(resourceGroupName(), name(), certificateOrderName, + identifierInner) .then(Mono.empty()); } @@ -257,8 +240,7 @@ public void start() { @Override public Mono startAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .startAsync(resourceGroupName(), name()) .then(refreshAsync()) @@ -272,8 +254,7 @@ public void stop() { @Override public Mono stopAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .stopAsync(resourceGroupName(), name()) .then(refreshAsync()) @@ -287,8 +268,7 @@ public void restart() { @Override public Mono restartAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .restartAsync(resourceGroupName(), name()) .then(refreshAsync()) @@ -302,8 +282,7 @@ public void swap(String slotName) { @Override public Mono swapAsync(String slotName) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .swapSlotWithProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) @@ -317,8 +296,7 @@ public void applySlotConfigurations(String slotName) { @Override public Mono applySlotConfigurationsAsync(String slotName) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .applySlotConfigToProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) @@ -332,8 +310,7 @@ public void resetSlotConfigurations() { @Override public Mono resetSlotConfigurationsAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .resetProductionSlotConfigAsync(resourceGroupName(), name()) .then(refreshAsync()) @@ -347,7 +324,9 @@ public byte[] getContainerLogs() { @Override public Mono getContainerLogsAsync() { - return manager().serviceClient().getWebApps().getWebSiteContainerLogsAsync(resourceGroupName(), name()) + return manager().serviceClient() + .getWebApps() + .getWebSiteContainerLogsAsync(resourceGroupName(), name()) .map(BinaryData::toBytes); } @@ -358,14 +337,15 @@ public byte[] getContainerLogsZip() { @Override public Mono getContainerLogsZipAsync() { - return manager().serviceClient().getWebApps().getContainerLogsZipAsync(resourceGroupName(), name()) + return manager().serviceClient() + .getWebApps() + .getContainerLogsZipAsync(resourceGroupName(), name()) .map(BinaryData::toBytes); } @Override Mono updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateDiagnosticLogsConfigAsync(resourceGroupName(), name(), siteLogsConfigInner); } @@ -376,8 +356,9 @@ private AppServicePlanImpl newDefaultAppServicePlan() { } private AppServicePlanImpl newDefaultAppServicePlan(String appServicePlanName) { - AppServicePlanImpl appServicePlan = - (AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)).withRegion(regionName()); + AppServicePlanImpl appServicePlan + = (AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)) + .withRegion(regionName()); if (super.creatableGroup != null && isInCreateMode()) { appServicePlan = appServicePlan.withNewResourceGroup(super.creatableGroup); } else { @@ -399,12 +380,10 @@ FluentImplT withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier p newDefaultAppServicePlan().withOperatingSystem(operatingSystem).withPricingTier(pricingTier)); } - FluentImplT withNewAppServicePlan( - String appServicePlanName, OperatingSystem operatingSystem, PricingTier pricingTier) { - return withNewAppServicePlan( - newDefaultAppServicePlan(appServicePlanName) - .withOperatingSystem(operatingSystem) - .withPricingTier(pricingTier)); + FluentImplT withNewAppServicePlan(String appServicePlanName, OperatingSystem operatingSystem, + PricingTier pricingTier) { + return withNewAppServicePlan(newDefaultAppServicePlan(appServicePlanName).withOperatingSystem(operatingSystem) + .withPricingTier(pricingTier)); } public FluentImplT withNewAppServicePlan(PricingTier pricingTier) { @@ -417,15 +396,8 @@ public FluentImplT withNewAppServicePlan(String appServicePlanName, PricingTier public FluentImplT withNewAppServicePlan(Creatable appServicePlanCreatable) { this.addDependency(appServicePlanCreatable); - String id = - ResourceUtils - .constructResourceId( - this.manager().subscriptionId(), - resourceGroupName(), - "Microsoft.Web", - "serverFarms", - appServicePlanCreatable.name(), - ""); + String id = ResourceUtils.constructResourceId(this.manager().subscriptionId(), resourceGroupName(), + "Microsoft.Web", "serverFarms", appServicePlanCreatable.name(), ""); innerModel().withServerFarmId(id); if (appServicePlanCreatable instanceof AppServicePlanImpl) { return withOperatingSystem(((AppServicePlanImpl) appServicePlanCreatable).operatingSystem()); @@ -506,11 +478,12 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - Mono>> retList = this.manager().serviceClient().getWebApps() + Mono>> retList = this.manager() + .serviceClient() + .getWebApps() .getPrivateLinkResourcesWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(PrivateLinkResourceImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue().value().stream().map(PrivateLinkResourceImpl::new).collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -522,8 +495,11 @@ public PagedIterable listPrivateEndpointConnections() @Override public PagedFlux listPrivateEndpointConnectionsAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getWebApps() - .getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()), + return PagedConverter.mapPage( + this.manager() + .serviceClient() + .getWebApps() + .getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @@ -534,13 +510,14 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new RemotePrivateEndpointConnectionArmResourceInner().withPrivateLinkServiceConnectionState( - new PrivateLinkConnectionState() - .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString()) - )) + new RemotePrivateEndpointConnectionArmResourceInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString()))) .then(); } @@ -551,13 +528,14 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new RemotePrivateEndpointConnectionArmResourceInner().withPrivateLinkServiceConnectionState( - new PrivateLinkConnectionState() - .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString()) - )) + new RemotePrivateEndpointConnectionArmResourceInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString()))) .then(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateImpl.java index 4860a6185da7a..3a860e264e99f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateImpl.java @@ -118,31 +118,21 @@ protected Mono getInnerAsync() { public Mono createResourceAsync() { Mono pfxBytes = Mono.empty(); if (pfxFileUrl != null) { - pfxBytes = - Utils - .downloadFileAsync(pfxFileUrl, this.manager().httpPipeline()) - .map( - bytes -> { - innerModel().withPfxBlob(bytes); - return null; - }); + pfxBytes = Utils.downloadFileAsync(pfxFileUrl, this.manager().httpPipeline()).map(bytes -> { + innerModel().withPfxBlob(bytes); + return null; + }); } Mono keyVaultBinding = Mono.empty(); if (certificateOrder != null) { - keyVaultBinding = - certificateOrder - .getKeyVaultBindingAsync() - .map( - keyVaultBinding1 -> { - innerModel() - .withKeyVaultId(keyVaultBinding1.keyVaultId()) - .withKeyVaultSecretName(keyVaultBinding1.keyVaultSecretName()); - return null; - }); + keyVaultBinding = certificateOrder.getKeyVaultBindingAsync().map(keyVaultBinding1 -> { + innerModel().withKeyVaultId(keyVaultBinding1.keyVaultId()) + .withKeyVaultSecretName(keyVaultBinding1.keyVaultSecretName()); + return null; + }); } final CertificatesClient client = this.manager().serviceClient().getCertificates(); - return pfxBytes - .then(keyVaultBinding) + return pfxBytes.then(keyVaultBinding) .then(client.createOrUpdateAsync(resourceGroupName(), name(), innerModel())) .map(innerToFluentMap(this)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateKeyVaultBindingImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateKeyVaultBindingImpl.java index 22824a7561876..c701de2640004 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateKeyVaultBindingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateKeyVaultBindingImpl.java @@ -13,19 +13,14 @@ import reactor.core.publisher.Mono; /** The implementation for {@link AppServicePlan}. */ -class AppServiceCertificateKeyVaultBindingImpl - extends IndependentChildResourceImpl< - AppServiceCertificateKeyVaultBinding, - AppServiceCertificateOrder, - AppServiceCertificateResourceInner, - AppServiceCertificateKeyVaultBindingImpl, - AppServiceManager> +class AppServiceCertificateKeyVaultBindingImpl extends + IndependentChildResourceImpl implements AppServiceCertificateKeyVaultBinding { private final AppServiceCertificateOrderImpl parent; - AppServiceCertificateKeyVaultBindingImpl( - AppServiceCertificateResourceInner innerObject, AppServiceCertificateOrderImpl parent) { + AppServiceCertificateKeyVaultBindingImpl(AppServiceCertificateResourceInner innerObject, + AppServiceCertificateOrderImpl parent) { super(innerObject.name(), innerObject, (parent != null) ? parent.manager() : null); this.parent = parent; } @@ -38,16 +33,14 @@ public String id() { @Override public Mono createChildResourceAsync() { final AppServiceCertificateKeyVaultBinding self = this; - return parent - .manager() + return parent.manager() .serviceClient() .getAppServiceCertificateOrders() .createOrUpdateCertificateAsync(parent.resourceGroupName(), parent.name(), name(), innerModel()) - .map( - appServiceCertificateInner -> { - setInner(appServiceCertificateInner); - return self; - }); + .map(appServiceCertificateInner -> { + setInner(appServiceCertificateInner); + return self; + }); } @Override @@ -67,8 +60,7 @@ public KeyVaultSecretStatus provisioningState() { @Override protected Mono getInnerAsync() { - return parent - .manager() + return parent.manager() .serviceClient() .getAppServiceCertificateOrders() .getCertificateAsync(parent.resourceGroupName(), parent.name(), name()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrderImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrderImpl.java index 5fc13f5a9087e..d722444c6a355 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrderImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrderImpl.java @@ -24,9 +24,8 @@ import java.time.OffsetDateTime; /** The implementation for {@link AppServicePlan}. */ -class AppServiceCertificateOrderImpl - extends GroupableResourceImpl< - AppServiceCertificateOrder, AppServiceCertificateOrderInner, AppServiceCertificateOrderImpl, AppServiceManager> +class AppServiceCertificateOrderImpl extends + GroupableResourceImpl implements AppServiceCertificateOrder, AppServiceCertificateOrder.Definition, AppServiceCertificateOrder.Update { private WebAppBase domainVerifyWebApp; @@ -40,8 +39,7 @@ class AppServiceCertificateOrderImpl @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAppServiceCertificateOrders() .getByResourceGroupAsync(resourceGroupName(), name()); @@ -54,8 +52,7 @@ public AppServiceCertificateKeyVaultBinding getKeyVaultBinding() { @Override public Mono getKeyVaultBindingAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAppServiceCertificateOrders() .listCertificatesAsync(resourceGroupName(), name()) @@ -156,14 +153,12 @@ public Mono createKeyVaultBindingAsync(Str certInner.withLocation(vault.regionName()); certInner.withKeyVaultId(vault.id()); certInner.withKeyVaultSecretName(certificateName); - return this - .manager() + return this.manager() .serviceClient() .getAppServiceCertificateOrders() .createOrUpdateCertificateAsync(resourceGroupName(), name(), certificateName, certInner) - .map( - appServiceCertificateInner -> - new AppServiceCertificateKeyVaultBindingImpl(appServiceCertificateInner, this)); + .map(appServiceCertificateInner -> new AppServiceCertificateKeyVaultBindingImpl(appServiceCertificateInner, + this)); } @Override @@ -192,29 +187,22 @@ public AppServiceCertificateOrderImpl withValidYears(int years) { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAppServiceCertificateOrders() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) .map(innerToFluentMap(this)) - .then( - Mono - .defer( - () -> { - if (domainVerifyWebApp != null) { - return domainVerifyWebApp.verifyDomainOwnershipAsync(name(), domainVerificationToken()); - } else if (domainVerifyDomain != null) { - return domainVerifyDomain.verifyDomainOwnershipAsync(name(), domainVerificationToken()); - } else { - return Mono - .error( - new IllegalArgumentException( - "Please specify a non-null web app or domain to verify the domain" - + " ownership for hostname " - + distinguishedName())); - } - })) + .then(Mono.defer(() -> { + if (domainVerifyWebApp != null) { + return domainVerifyWebApp.verifyDomainOwnershipAsync(name(), domainVerificationToken()); + } else if (domainVerifyDomain != null) { + return domainVerifyDomain.verifyDomainOwnershipAsync(name(), domainVerificationToken()); + } else { + return Mono.error( + new IllegalArgumentException("Please specify a non-null web app or domain to verify the domain" + + " ownership for hostname " + distinguishedName())); + } + })) .then(bindingVault.flatMap(vault -> createKeyVaultBindingAsync(name(), vault))) .then(Mono.just(this)); } @@ -245,22 +233,20 @@ public AppServiceCertificateOrderImpl withExistingKeyVault(Vault vault) { @Override public AppServiceCertificateOrderImpl withNewKeyVault(String vaultName, Region region) { - this.bindingVault = - myManager - .keyVaultManager() - .vaults() - .define(vaultName) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName()) - .defineAccessPolicy() - .forServicePrincipal("f3c21649-0979-4721-ac85-b0216b2cf413") - .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.SET, SecretPermissions.DELETE) - .attach() - .defineAccessPolicy() - .forServicePrincipal("abfa0a7c-a6b6-4736-8310-5855508787cd") - .allowSecretPermissions(SecretPermissions.GET) - .attach() - .createAsync(); + this.bindingVault = myManager.keyVaultManager() + .vaults() + .define(vaultName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName()) + .defineAccessPolicy() + .forServicePrincipal("f3c21649-0979-4721-ac85-b0216b2cf413") + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.SET, SecretPermissions.DELETE) + .attach() + .defineAccessPolicy() + .forServicePrincipal("abfa0a7c-a6b6-4736-8310-5855508787cd") + .allowSecretPermissions(SecretPermissions.GET) + .attach() + .createAsync(); return this; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrdersImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrdersImpl.java index 1a3aeaecad641..06058f6c1762b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrdersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrdersImpl.java @@ -12,13 +12,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** The implementation for {@link AppServicePlans}. */ -public class AppServiceCertificateOrdersImpl - extends TopLevelModifiableResourcesImpl< - AppServiceCertificateOrder, - AppServiceCertificateOrderImpl, - AppServiceCertificateOrderInner, - AppServiceCertificateOrdersClient, - AppServiceManager> +public class AppServiceCertificateOrdersImpl extends + TopLevelModifiableResourcesImpl implements AppServiceCertificateOrders { public AppServiceCertificateOrdersImpl(AppServiceManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificatesImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificatesImpl.java index 4c2ea84165e52..153eaebd336b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificatesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificatesImpl.java @@ -15,9 +15,8 @@ import reactor.core.publisher.Mono; /** The implementation for AppServiceCertificates. */ -public class AppServiceCertificatesImpl - extends GroupableResourcesImpl< - AppServiceCertificate, AppServiceCertificateImpl, CertificateInner, CertificatesClient, AppServiceManager> +public class AppServiceCertificatesImpl extends + GroupableResourcesImpl implements AppServiceCertificates { public AppServiceCertificatesImpl(AppServiceManager manager) { @@ -42,8 +41,8 @@ public PagedIterable listByResourceGroup(String resourceG @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainImpl.java index 965d7abc1cd62..6245d3bf87653 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainImpl.java @@ -43,8 +43,9 @@ class AppServiceDomainImpl super(name, innerObject, manager); innerModel().withLocation("global"); if (innerModel().managedHostNames() != null) { - this.hostNameMap = - innerModel().managedHostNames().stream().collect(Collectors.toMap(Hostname::name, Function.identity())); + this.hostNameMap = innerModel().managedHostNames() + .stream() + .collect(Collectors.toMap(Hostname::name, Function.identity())); } } @@ -58,6 +59,7 @@ public Mono createAsync() { } return super.createAsync(); } + @Override public Mono createResourceAsync() { if (this.dnsZoneCreatable != null) { @@ -68,8 +70,7 @@ public Mono createResourceAsync() { String[] domainParts = this.name().split("\\."); String topLevel = domainParts[domainParts.length - 1]; final DomainsClient client = this.manager().serviceClient().getDomains(); - return this - .manager() + return this.manager() .serviceClient() .getTopLevelDomains() .listAgreementsAsync(topLevel, new TopLevelDomainAgreementOption()) @@ -77,20 +78,16 @@ public Mono createResourceAsync() { .map(TldLegalAgreementInner::agreementKey) .collectList() // Step 2: Create domain - .flatMap( - keys -> { - try { - innerModel() - .withConsent( - new DomainPurchaseConsent() - .withAgreedAt(OffsetDateTime.now()) - .withAgreedBy(Inet4Address.getLocalHost().getHostAddress()) - .withAgreementKeys(keys)); - } catch (UnknownHostException e) { - return Mono.error(e); - } - return client.createOrUpdateAsync(resourceGroupName(), name(), innerModel()); - }) + .flatMap(keys -> { + try { + innerModel().withConsent(new DomainPurchaseConsent().withAgreedAt(OffsetDateTime.now()) + .withAgreedBy(Inet4Address.getLocalHost().getHostAddress()) + .withAgreementKeys(keys)); + } catch (UnknownHostException e) { + return Mono.error(e); + } + return client.createOrUpdateAsync(resourceGroupName(), name(), innerModel()); + }) .map(innerToFluentMap(this)) .doOnSuccess(ignored -> dnsZoneCreatable = null); } @@ -190,10 +187,9 @@ public void verifyDomainOwnership(String certificateOrderName, String domainVeri @Override public Mono verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) { - DomainOwnershipIdentifierInner identifierInner = - new DomainOwnershipIdentifierInner().withOwnershipId(domainVerificationToken); - return this - .manager() + DomainOwnershipIdentifierInner identifierInner + = new DomainOwnershipIdentifierInner().withOwnershipId(domainVerificationToken); + return this.manager() .serviceClient() .getDomains() .createOrUpdateOwnershipIdentifierAsync(resourceGroupName(), name(), certificateOrderName, identifierInner) @@ -248,12 +244,14 @@ public AppServiceDomainImpl withAutoRenewEnabled(boolean autoRenew) { public AppServiceDomainImpl withNewDnsZone(String dnsZoneName) { Creatable dnsZone; if (creatableGroup != null && isInCreateMode()) { - dnsZone = manager().dnsZoneManager().zones() + dnsZone = manager().dnsZoneManager() + .zones() .define(dnsZoneName) .withNewResourceGroup(creatableGroup) .withETagCheck(); } else { - dnsZone = manager().dnsZoneManager().zones() + dnsZone = manager().dnsZoneManager() + .zones() .define(dnsZoneName) .withExistingResourceGroup(resourceGroupName()) .withETagCheck(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainsImpl.java index 4a44c762a5cb8..f23081f82e296 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceDomainsImpl.java @@ -15,9 +15,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for AppServiceDomains. */ -public class AppServiceDomainsImpl - extends TopLevelModifiableResourcesImpl< - AppServiceDomain, AppServiceDomainImpl, DomainInner, DomainsClient, AppServiceManager> +public class AppServiceDomainsImpl extends + TopLevelModifiableResourcesImpl implements AppServiceDomains { public AppServiceDomainsImpl(AppServiceManager manager) { @@ -44,11 +43,9 @@ public AppServiceDomainImpl define(String name) { @Override public PagedIterable listAgreements(String topLevelExtension) { - return PagedConverter.mapPage(this - .manager() + return PagedConverter.mapPage(this.manager() .serviceClient() .getTopLevelDomains() - .listAgreements(topLevelExtension, new TopLevelDomainAgreementOption()), - DomainLegalAgreementImpl::new); + .listAgreements(topLevelExtension, new TopLevelDomainAgreementOption()), DomainLegalAgreementImpl::new); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceEnvironmentsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceEnvironmentsClientImpl.java index 957320e8f40d5..417cc4bac6763 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceEnvironmentsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceEnvironmentsClientImpl.java @@ -5882,7 +5882,7 @@ public Mono approveOrRejectPriv RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -5906,7 +5906,7 @@ private Mono approveOrRejectPri RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper, Context context) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlanImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlanImpl.java index eae2e2fe41baf..1e3861c76cb7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlanImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlanImpl.java @@ -26,8 +26,7 @@ class AppServicePlanImpl @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAppServicePlans() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlansImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlansImpl.java index e410dde608657..07db40942c9f4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlansImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServicePlansImpl.java @@ -12,9 +12,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** The implementation for AppServicePlans. */ -public class AppServicePlansImpl - extends TopLevelModifiableResourcesImpl< - AppServicePlan, AppServicePlanImpl, AppServicePlanInner, AppServicePlansClient, AppServiceManager> +public class AppServicePlansImpl extends + TopLevelModifiableResourcesImpl implements AppServicePlans { public AppServicePlansImpl(AppServiceManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotBaseImpl.java index 6b0cbc1e99985..d7bf549f16173 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotBaseImpl.java @@ -35,24 +35,15 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for DeploymentSlot. */ -abstract class DeploymentSlotBaseImpl< - FluentT extends WebAppBase, - FluentImplT extends DeploymentSlotBaseImpl, - ParentImplT extends AppServiceBaseImpl, - FluentWithCreateT, - FluentUpdateT> +abstract class DeploymentSlotBaseImpl, ParentImplT extends AppServiceBaseImpl, FluentWithCreateT, FluentUpdateT> extends WebAppBaseImpl implements DeploymentSlotBase, DeploymentSlotBase.Update { private final ParentImplT parent; private final String name; WebAppBase configurationSource; - DeploymentSlotBaseImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - final ParentImplT parent) { + DeploymentSlotBaseImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, final ParentImplT parent) { super(name.replaceAll(".*/", ""), innerObject, siteConfig, logConfig, parent.manager()); this.name = name.replaceAll(".*/", ""); this.parent = parent; @@ -73,26 +64,17 @@ public Map getHostnameBindings() { @Override @SuppressWarnings("unchecked") public Mono> getHostnameBindingsAsync() { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getWebApps() - .listHostnameBindingsSlotAsync(resourceGroupName(), parent().name(), name()), - hostNameBindingInner -> - new HostnameBindingImpl( - hostNameBindingInner, (FluentImplT) DeploymentSlotBaseImpl.this)) + return PagedConverter + .mapPage( + this.manager() + .serviceClient() + .getWebApps() + .listHostnameBindingsSlotAsync(resourceGroupName(), parent().name(), name()), + hostNameBindingInner -> new HostnameBindingImpl(hostNameBindingInner, + (FluentImplT) DeploymentSlotBaseImpl.this)) .collectList() - .map( - hostNameBindings -> - Collections - .unmodifiableMap( - hostNameBindings - .stream() - .collect( - Collectors - .toMap( - binding -> binding.name().replace(name() + "/", ""), - Function.identity())))); + .map(hostNameBindings -> Collections.unmodifiableMap(hostNameBindings.stream() + .collect(Collectors.toMap(binding -> binding.name().replace(name() + "/", ""), Function.identity())))); } @Override @@ -101,11 +83,10 @@ public PublishingProfile getPublishingProfile() { } public Mono getPublishingProfileAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() - .listPublishingProfileXmlWithSecretsSlotAsync( - resourceGroupName(), this.parent().name(), name(), new CsmPublishingProfileOptions()) + .listPublishingProfileXmlWithSecretsSlotAsync(resourceGroupName(), this.parent().name(), name(), + new CsmPublishingProfileOptions()) .map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this)); } @@ -116,8 +97,7 @@ public void start() { @Override public Mono startAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .startSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) @@ -131,8 +111,7 @@ public void stop() { @Override public Mono stopAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .stopSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) @@ -146,8 +125,7 @@ public void restart() { @Override public Mono restartAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .restartSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) @@ -168,57 +146,41 @@ public FluentImplT withConfigurationFromDeploymentSlot(FluentT slot) { } Mono submitAppSettings() { - return Mono - .justOrEmpty(configurationSource) - .flatMap( - webAppBase -> { - if (!isInCreateMode()) { - return DeploymentSlotBaseImpl.super.submitAppSettings(); + return Mono.justOrEmpty(configurationSource).flatMap(webAppBase -> { + if (!isInCreateMode()) { + return DeploymentSlotBaseImpl.super.submitAppSettings(); + } + return webAppBase.getAppSettingsAsync().flatMap(stringAppSettingMap -> { + for (AppSetting appSetting : stringAppSettingMap.values()) { + if (appSetting.sticky()) { + withStickyAppSetting(appSetting.key(), appSetting.value()); + } else { + withAppSetting(appSetting.key(), appSetting.value()); } - return webAppBase - .getAppSettingsAsync() - .flatMap( - stringAppSettingMap -> { - for (AppSetting appSetting : stringAppSettingMap.values()) { - if (appSetting.sticky()) { - withStickyAppSetting(appSetting.key(), appSetting.value()); - } else { - withAppSetting(appSetting.key(), appSetting.value()); - } - } - return DeploymentSlotBaseImpl.super.submitAppSettings(); - }); - }) - .switchIfEmpty(DeploymentSlotBaseImpl.super.submitAppSettings()); + } + return DeploymentSlotBaseImpl.super.submitAppSettings(); + }); + }).switchIfEmpty(DeploymentSlotBaseImpl.super.submitAppSettings()); } Mono submitConnectionStrings() { - return Mono - .justOrEmpty(configurationSource) - .flatMap( - webAppBase -> { - if (!isInCreateMode()) { - return DeploymentSlotBaseImpl.super.submitConnectionStrings(); + return Mono.justOrEmpty(configurationSource).flatMap(webAppBase -> { + if (!isInCreateMode()) { + return DeploymentSlotBaseImpl.super.submitConnectionStrings(); + } + return webAppBase.getConnectionStringsAsync().flatMap(stringConnectionStringMap -> { + for (ConnectionString connectionString : stringConnectionStringMap.values()) { + if (connectionString.sticky()) { + withStickyConnectionString(connectionString.name(), connectionString.value(), + connectionString.type()); + } else { + withConnectionString(connectionString.name(), connectionString.value(), + connectionString.type()); } - return webAppBase - .getConnectionStringsAsync() - .flatMap( - stringConnectionStringMap -> { - for (ConnectionString connectionString : stringConnectionStringMap.values()) { - if (connectionString.sticky()) { - withStickyConnectionString( - connectionString.name(), connectionString.value(), - connectionString.type()); - } else { - withConnectionString( - connectionString.name(), connectionString.value(), - connectionString.type()); - } - } - return DeploymentSlotBaseImpl.super.submitConnectionStrings(); - }); - }) - .switchIfEmpty(DeploymentSlotBaseImpl.super.submitConnectionStrings()); + } + return DeploymentSlotBaseImpl.super.submitConnectionStrings(); + }); + }).switchIfEmpty(DeploymentSlotBaseImpl.super.submitConnectionStrings()); } public ParentImplT parent() { @@ -227,16 +189,14 @@ public ParentImplT parent() { @Override Mono createOrUpdateInner(SiteInner site) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .createOrUpdateSlotAsync(resourceGroupName(), this.parent().name(), name(), site); } @Override Mono updateInner(SitePatchResourceInner siteUpdate) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateSlotAsync(resourceGroupName(), this.parent().name(), name(), siteUpdate); } @@ -248,74 +208,70 @@ Mono getInner() { @Override Mono getConfigInner() { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .getConfigurationSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .createOrUpdateConfigurationSlotAsync(resourceGroupName(), this.parent().name(), name(), siteConfig); } @Override Mono deleteHostnameBinding(String hostname) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .deleteHostnameBindingSlotAsync(resourceGroupName(), parent().name(), name(), hostname); } @Override Mono listAppSettings() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .listApplicationSettingsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono updateAppSettings(StringDictionaryInner inner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateApplicationSettingsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono listConnectionStrings() { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .listConnectionStringsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono updateConnectionStrings(ConnectionStringDictionaryInner inner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateConnectionStringsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono listSlotConfigurations() { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .listSlotConfigurationNamesAsync(resourceGroupName(), parent().name()); } @Override Mono updateSlotConfigurations(SlotConfigNamesResourceInner inner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateSlotConfigurationNamesAsync(resourceGroupName(), parent().name(), inner); } @Override Mono createOrUpdateSourceControl(SiteSourceControlInner inner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .createOrUpdateSourceControlSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @@ -327,11 +283,10 @@ public void swap(String slotName) { @Override public Mono swapAsync(String slotName) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() - .swapSlotAsync( - resourceGroupName(), this.parent().name(), name(), new CsmSlotEntity().withTargetSlot(slotName)) + .swapSlotAsync(resourceGroupName(), this.parent().name(), name(), + new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) .then(Mono.empty()); } @@ -343,11 +298,10 @@ public void applySlotConfigurations(String slotName) { @Override public Mono applySlotConfigurationsAsync(String slotName) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() - .applySlotConfigurationSlotAsync( - resourceGroupName(), this.parent().name(), name(), new CsmSlotEntity().withTargetSlot(slotName)) + .applySlotConfigurationSlotAsync(resourceGroupName(), this.parent().name(), name(), + new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) .then(Mono.empty()); } @@ -359,8 +313,7 @@ public void resetSlotConfigurations() { @Override public Mono resetSlotConfigurationsAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .resetSlotConfigurationSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) @@ -369,8 +322,7 @@ public Mono resetSlotConfigurationsAsync() { @Override Mono deleteSourceControl() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .deleteSourceControlSlotAsync(resourceGroupName(), parent().name(), name()) .then(refreshAsync()) @@ -379,22 +331,21 @@ Mono deleteSourceControl() { @Override Mono updateAuthentication(SiteAuthSettingsInner inner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateAuthSettingsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono getAuthentication() { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .getAuthSettingsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono createMSDeploy(MSDeploy msDeployInner) { - return parent() - .manager() + return parent().manager() .serviceClient() .getWebApps() .createMSDeployOperationAsync(parent().resourceGroupName(), parent().name(), msDeployInner); @@ -407,13 +358,11 @@ public WebAppSourceControl getSourceControl() { @Override public Mono getSourceControlAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .getSourceControlSlotAsync(resourceGroupName(), parent().name(), name()) - .map( - siteSourceControlInner -> - new WebAppSourceControlImpl<>(siteSourceControlInner, DeploymentSlotBaseImpl.this)); + .map(siteSourceControlInner -> new WebAppSourceControlImpl<>(siteSourceControlInner, + DeploymentSlotBaseImpl.this)); } @Override @@ -423,8 +372,7 @@ public byte[] getContainerLogs() { @Override public Mono getContainerLogsAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .getWebSiteContainerLogsSlotAsync(resourceGroupName(), parent().name(), name()) .map(BinaryData::toBytes); @@ -437,15 +385,15 @@ public byte[] getContainerLogsZip() { @Override public Mono getContainerLogsZipAsync() { - return manager().serviceClient().getWebApps() + return manager().serviceClient() + .getWebApps() .getContainerLogsZipSlotAsync(resourceGroupName(), parent().name(), name()) .map(BinaryData::toBytes); } @Override Mono updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .updateDiagnosticLogsConfigSlotAsync(resourceGroupName(), parent().name(), name(), siteLogsConfigInner); } @@ -458,11 +406,10 @@ public void verifyDomainOwnership(String certificateOrderName, String domainVeri @Override public Mono verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) { IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken); - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() - .createOrUpdateDomainOwnershipIdentifierSlotAsync( - resourceGroupName(), parent().name(), name(), certificateOrderName, identifierInner) + .createOrUpdateDomainOwnershipIdentifierSlotAsync(resourceGroupName(), parent().name(), name(), + certificateOrderName, identifierInner) .then(Mono.empty()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotImpl.java index 7f06d8e0055f5..4c0856f576561 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotImpl.java @@ -26,21 +26,12 @@ import java.util.Objects; /** The implementation for DeploymentSlot. */ -class DeploymentSlotImpl - extends DeploymentSlotBaseImpl< - DeploymentSlot, - DeploymentSlotImpl, - WebAppImpl, - DeploymentSlot.DefinitionStages.WithCreate, - DeploymentSlotBase.Update> +class DeploymentSlotImpl extends + DeploymentSlotBaseImpl> implements DeploymentSlot, DeploymentSlot.Definition { - DeploymentSlotImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - WebAppImpl parent) { + DeploymentSlotImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, WebAppImpl parent) { super(name, innerObject, siteConfig, logConfig, parent); } @@ -147,8 +138,8 @@ public Mono deployAsync(DeployType type, File file, DeployOptions deployOp deployOptions = new DeployOptions(); } try { - return kuduClient.deployAsync(type, file, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment()); + return kuduClient.deployAsync(type, file, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment()); } catch (IOException e) { return Mono.error(e); } @@ -176,8 +167,8 @@ public Mono deployAsync(DeployType type, InputStream file, long length, De if (deployOptions == null) { deployOptions = new DeployOptions(); } - return kuduClient.deployAsync(type, file, length, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment()); + return kuduClient.deployAsync(type, file, length, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment()); } @Override @@ -193,9 +184,8 @@ public Mono pushDeployAsync(DeployType type, File file, De deployOptions = new DeployOptions(); } try { - return kuduClient.pushDeployAsync(type, file, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment(), - deployOptions.trackDeployment()); + return kuduClient.pushDeployAsync(type, file, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment(), deployOptions.trackDeployment()); } catch (IOException e) { return Mono.error(e); } @@ -210,20 +200,23 @@ public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { public Mono getDeploymentStatusAsync(String deploymentId) { // "GET" LRO is not supported in azure-core SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - return this.manager().serviceClient().getWebApps() - .getSlotSiteDeploymentStatusSlotWithResponseAsync(this.resourceGroupName(), this.parent().name(), this.name(), deploymentId) + return this.manager() + .serviceClient() + .getWebApps() + .getSlotSiteDeploymentStatusSlotWithResponseAsync(this.resourceGroupName(), this.parent().name(), + this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); - return response.getBodyAsString() - .flatMap(bodyString -> { - CsmDeploymentStatus status; - try { - status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); - } catch (IOException e) { - return Mono.error(new ManagementException("Deserialize failed for response body.", response)); - } - return Mono.justOrEmpty(status); - }).doFinally(ignored -> response.close()); + return response.getBodyAsString().flatMap(bodyString -> { + CsmDeploymentStatus status; + try { + status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, + SerializerEncoding.JSON); + } catch (IOException e) { + return Mono.error(new ManagementException("Deserialize failed for response body.", response)); + } + return Mono.justOrEmpty(status); + }).doFinally(ignored -> response.close()); }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotsImpl.java index be6667dfebfe3..70a9196405dc3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotsImpl.java @@ -19,9 +19,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation DeploymentSlots. */ -class DeploymentSlotsImpl - extends IndependentChildResourcesImpl< - DeploymentSlot, DeploymentSlotImpl, SiteInner, WebAppsClient, AppServiceManager, WebApp> +class DeploymentSlotsImpl extends + IndependentChildResourcesImpl implements DeploymentSlots { private final WebAppImpl parent; @@ -34,8 +33,7 @@ class DeploymentSlotsImpl @Override protected DeploymentSlotImpl wrapModel(String name) { - return new DeploymentSlotImpl(name, new SiteInner(), null, null, parent) - .withRegion(parent.regionName()) + return new DeploymentSlotImpl(name, new SiteInner(), null, null, parent).withRegion(parent.regionName()) .withExistingResourceGroup(parent.resourceGroupName()); } @@ -50,20 +48,15 @@ public DeploymentSlotImpl define(String name) { } @Override - public Mono getByParentAsync( - final String resourceGroup, final String parentName, final String name) { - return innerCollection - .getSlotAsync(resourceGroup, parentName, name) - .flatMap( - siteInner -> - Mono - .zip( - innerCollection.getConfigurationSlotAsync(resourceGroup, parentName, - name.replaceAll(".*/", "")), - innerCollection.getDiagnosticLogsConfigurationSlotAsync(resourceGroup, parentName, - name.replaceAll(".*/", "")), - (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> - wrapModel(siteInner, siteConfigResourceInner, logsConfigInner))); + public Mono getByParentAsync(final String resourceGroup, final String parentName, + final String name) { + return innerCollection.getSlotAsync(resourceGroup, parentName, name) + .flatMap(siteInner -> Mono.zip( + innerCollection.getConfigurationSlotAsync(resourceGroup, parentName, name.replaceAll(".*/", "")), + innerCollection.getDiagnosticLogsConfigurationSlotAsync(resourceGroup, parentName, + name.replaceAll(".*/", "")), + (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> wrapModel( + siteInner, siteConfigResourceInner, logsConfigInner))); } @Override @@ -112,8 +105,8 @@ public PagedFlux listAsync() { inner -> new WebDeploymentSlotBasicImpl(inner, parent)); } - private DeploymentSlotImpl wrapModel( - SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) { + private DeploymentSlotImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig) { if (inner == null) { return null; } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppBasicImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppBasicImpl.java index 655c2185d370d..0cd25bc66f412 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppBasicImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppBasicImpl.java @@ -26,8 +26,7 @@ public FunctionApp refresh() { @Override public Mono refreshAsync() { - return this.manager().functionApps().getByIdAsync(this.id()) - .doOnNext(site -> this.setInner(site.innerModel())); + return this.manager().functionApps().getByIdAsync(this.id()).doOnNext(site -> this.setInner(site.innerModel())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppImpl.java index e30235706df95..7bfc5604a37e3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppImpl.java @@ -80,19 +80,15 @@ import java.util.stream.Collectors; /** The implementation for FunctionApp. */ -class FunctionAppImpl - extends AppServiceBaseImpl< - FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update> - implements FunctionApp, - FunctionApp.Definition, - FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, - FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, - FunctionApp.Update { +class FunctionAppImpl extends + AppServiceBaseImpl + implements FunctionApp, FunctionApp.Definition, FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, + FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, FunctionApp.Update { private static final ClientLogger LOGGER = new ClientLogger(FunctionAppImpl.class); - private static final String SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING = - "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; + private static final String SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING + = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String SETTING_WEBSITE_CONTENTSHARE = "WEBSITE_CONTENTSHARE"; private static final String SETTING_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String SETTING_WEB_JOBS_DASHBOARD = "AzureWebJobsDashboard"; @@ -107,12 +103,8 @@ class FunctionAppImpl private Boolean appServicePlanIsFlexConsumption; - FunctionAppImpl( - final String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - AppServiceManager manager) { + FunctionAppImpl(final String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); if (!isInCreateMode()) { initializeFunctionService(); @@ -142,14 +134,12 @@ private void initializeFunctionService() { } } policies.add(new FunctionAuthenticationPolicy(this)); - HttpPipeline httpPipeline = new HttpPipelineBuilder() - .policies(policies.toArray(new HttpPipelinePolicy[0])) + HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(manager().httpPipeline().getHttpClient()) .build(); functionServiceHost = baseUrl; - functionService = - RestProxy.create(FunctionService.class, httpPipeline, - SerializerFactory.createDefaultManagementSerializerAdapter()); + functionService = RestProxy.create(FunctionService.class, httpPipeline, + SerializerFactory.createDefaultManagementSerializerAdapter()); } } @@ -173,8 +163,8 @@ public FunctionAppImpl withNewConsumptionPlan() { @Override public FunctionAppImpl withNewConsumptionPlan(String appServicePlanName) { - return withNewAppServicePlan( - appServicePlanName, OperatingSystem.WINDOWS, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); + return withNewAppServicePlan(appServicePlanName, OperatingSystem.WINDOWS, + new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override @@ -218,44 +208,38 @@ Mono submitAppSettings() { if (storageAccountToSet == null) { return super.submitAppSettings(); } else { - return storageAccountToSet - .getKeysAsync() - .flatMap(storageAccountKeys -> { - StorageAccountKey key = storageAccountKeys.get(0); - String connectionString = ResourceManagerUtils - .getStorageConnectionString(storageAccountToSet.name(), key.value(), - manager().environment()); - addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); - if (!isFunctionAppOnACA()) { - // Function App on ACA only supports Application Insights as log option. - // https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#azurewebjobsdashboard - addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); - return this.manager().appServicePlans().getByIdAsync(this.appServicePlanId()) - .flatMap(appServicePlan -> { - if (appServicePlan == null - || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier())) { - - addAppSettingIfNotModified( - SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, connectionString); - addAppSettingIfNotModified( - SETTING_WEBSITE_CONTENTSHARE, - this.manager().resourceManager().internalContext() - .randomResourceName(name(), 32)); - } - return FunctionAppImpl.super.submitAppSettings(); - }); - } else { - return FunctionAppImpl.super.submitAppSettings(); - } - }).then( - Mono - .fromCallable( - () -> { - currentStorageAccount = storageAccountToSet; - storageAccountToSet = null; - storageAccountCreatable = null; - return this; - })); + return storageAccountToSet.getKeysAsync().flatMap(storageAccountKeys -> { + StorageAccountKey key = storageAccountKeys.get(0); + String connectionString = ResourceManagerUtils.getStorageConnectionString(storageAccountToSet.name(), + key.value(), manager().environment()); + addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); + if (!isFunctionAppOnACA()) { + // Function App on ACA only supports Application Insights as log option. + // https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#azurewebjobsdashboard + addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); + return this.manager() + .appServicePlans() + .getByIdAsync(this.appServicePlanId()) + .flatMap(appServicePlan -> { + if (appServicePlan == null + || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier())) { + + addAppSettingIfNotModified(SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, + connectionString); + addAppSettingIfNotModified(SETTING_WEBSITE_CONTENTSHARE, + this.manager().resourceManager().internalContext().randomResourceName(name(), 32)); + } + return FunctionAppImpl.super.submitAppSettings(); + }); + } else { + return FunctionAppImpl.super.submitAppSettings(); + } + }).then(Mono.fromCallable(() -> { + currentStorageAccount = storageAccountToSet; + storageAccountToSet = null; + storageAccountCreatable = null; + return this; + })); } } @@ -267,7 +251,8 @@ public OperatingSystem operatingSystem() { return OperatingSystem.LINUX; } return (innerModel().reserved() == null || !innerModel().reserved()) - ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; + ? OperatingSystem.WINDOWS + : OperatingSystem.LINUX; } private void addAppSettingIfNotModified(String key, String value) { @@ -296,8 +281,8 @@ FunctionAppImpl withNewAppServicePlan(OperatingSystem operatingSystem, PricingTi } @Override - FunctionAppImpl withNewAppServicePlan( - String appServicePlan, OperatingSystem operatingSystem, PricingTier pricingTier) { + FunctionAppImpl withNewAppServicePlan(String appServicePlan, OperatingSystem operatingSystem, + PricingTier pricingTier) { return super.withNewAppServicePlan(appServicePlan, operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier); } @@ -324,20 +309,16 @@ private FunctionAppImpl autoSetAlwaysOn(PricingTier pricingTier) { @Override public FunctionAppImpl withNewStorageAccount(String name, StorageAccountSkuType sku) { - StorageAccount.DefinitionStages.WithGroup storageDefine = - manager().storageManager().storageAccounts().define(name).withRegion(regionName()); + StorageAccount.DefinitionStages.WithGroup storageDefine + = manager().storageManager().storageAccounts().define(name).withRegion(regionName()); if (super.creatableGroup != null && isInCreateMode()) { - storageAccountCreatable = - storageDefine - .withNewResourceGroup(super.creatableGroup) - .withGeneralPurposeAccountKindV2() - .withSku(sku); + storageAccountCreatable = storageDefine.withNewResourceGroup(super.creatableGroup) + .withGeneralPurposeAccountKindV2() + .withSku(sku); } else { - storageAccountCreatable = - storageDefine - .withExistingResourceGroup(resourceGroupName()) - .withGeneralPurposeAccountKindV2() - .withSku(sku); + storageAccountCreatable = storageDefine.withExistingResourceGroup(resourceGroupName()) + .withGeneralPurposeAccountKindV2() + .withSku(sku); } this.addDependency(storageAccountCreatable); return this; @@ -374,8 +355,8 @@ public FunctionAppImpl withNewLinuxConsumptionPlan() { @Override public FunctionAppImpl withNewLinuxConsumptionPlan(String appServicePlanName) { - return withNewAppServicePlan( - appServicePlanName, OperatingSystem.LINUX, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); + return withNewAppServicePlan(appServicePlanName, OperatingSystem.LINUX, + new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override @@ -479,7 +460,10 @@ public String getMasterKey() { @Override public Mono getMasterKeyAsync() { - return this.manager().serviceClient().getWebApps().listHostKeysAsync(resourceGroupName(), name()) + return this.manager() + .serviceClient() + .getWebApps() + .listHostKeysAsync(resourceGroupName(), name()) .map(HostKeysInner::masterKey); } @@ -495,18 +479,15 @@ public Map listFunctionKeys(String functionName) { @Override public Mono> listFunctionKeysAsync(final String functionName) { - return functionService - .listFunctionKeys(functionServiceHost, functionName) - .map( - result -> { - Map keys = new HashMap<>(); - if (result.keys != null) { - for (NameValuePair pair : result.keys) { - keys.put(pair.name(), pair.value()); - } - } - return keys; - }); + return functionService.listFunctionKeys(functionServiceHost, functionName).map(result -> { + Map keys = new HashMap<>(); + if (result.keys != null) { + for (NameValuePair pair : result.keys) { + keys.put(pair.name(), pair.value()); + } + } + return keys; + }); } @Override @@ -517,12 +498,8 @@ public NameValuePair addFunctionKey(String functionName, String keyName, String @Override public Mono addFunctionKeyAsync(String functionName, String keyName, String keyValue) { if (keyValue != null) { - return functionService - .addFunctionKey( - functionServiceHost, - functionName, - keyName, - new NameValuePair().withName(keyName).withValue(keyValue)); + return functionService.addFunctionKey(functionServiceHost, functionName, keyName, + new NameValuePair().withName(keyName).withValue(keyValue)); } else { return functionService.generateFunctionKey(functionServiceHost, functionName, keyName); } @@ -555,19 +532,17 @@ public void syncTriggers() { @Override public Mono syncTriggersAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getWebApps() .syncFunctionTriggersAsync(resourceGroupName(), name()) - .onErrorResume( - throwable -> { - if (throwable instanceof ManagementException - && ((ManagementException) throwable).getResponse().getStatusCode() == 200) { - return Mono.empty(); - } else { - return Mono.error(throwable); - } - }); + .onErrorResume(throwable -> { + if (throwable instanceof ManagementException + && ((ManagementException) throwable).getResponse().getStatusCode() == 200) { + return Mono.empty(); + } else { + return Mono.error(throwable); + } + }); } @Override @@ -593,40 +568,35 @@ public Integer minReplicas() { @Override public Flux streamApplicationLogsAsync() { - return functionService - .ping(functionServiceHost) + return functionService.ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamApplicationLogsAsync()); } @Override public Flux streamHttpLogsAsync() { - return functionService - .ping(functionServiceHost) + return functionService.ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamHttpLogsAsync()); } @Override public Flux streamTraceLogsAsync() { - return functionService - .ping(functionServiceHost) + return functionService.ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamTraceLogsAsync()); } @Override public Flux streamDeploymentLogsAsync() { - return functionService - .ping(functionServiceHost) + return functionService.ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamDeploymentLogsAsync()); } @Override public Flux streamAllLogsAsync() { - return functionService - .ping(functionServiceHost) + return functionService.ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamAllLogsAsync()); } @@ -671,13 +641,15 @@ private void adaptForFunctionAppOnACA() { siteConfigInner.withLinuxFxVersion(this.siteConfig.linuxFxVersion()); siteConfigInner.withMinimumElasticInstanceCount(this.siteConfig.minimumElasticInstanceCount()); siteConfigInner.withFunctionAppScaleLimit(this.siteConfig.functionAppScaleLimit()); - siteConfigInner.withAppSettings(this.siteConfig.appSettings() == null ? new ArrayList<>() : this.siteConfig.appSettings()); + siteConfigInner.withAppSettings( + this.siteConfig.appSettings() == null ? new ArrayList<>() : this.siteConfig.appSettings()); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { for (String settingToRemove : appSettingsToRemove) { siteConfigInner.appSettings().removeIf(kvPair -> Objects.equals(settingToRemove, kvPair.name())); } for (Map.Entry entry : appSettingsToAdd.entrySet()) { - siteConfigInner.appSettings().add(new NameValuePair().withName(entry.getKey()).withValue(entry.getValue())); + siteConfigInner.appSettings() + .add(new NameValuePair().withName(entry.getKey()).withValue(entry.getValue())); } } this.innerModel().withSiteConfig(siteConfigInner); @@ -692,8 +664,7 @@ public Mono createAsync() { } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( - this.manager().resourceManager().internalContext() - .randomResourceName(getStorageAccountName(), 20), + this.manager().resourceManager().internalContext().randomResourceName(getStorageAccountName(), 20), StorageAccountSkuType.STANDARD_LRS); } } @@ -742,22 +713,11 @@ public FunctionAppImpl withMinReplicas(int minReplicas) { public Mono> getAppSettingsAsync() { if (isFunctionAppOnACA()) { // current function app on ACA doesn't support deployment slot, so appSettings sticky is false - return listAppSettings() - .map( - appSettingsInner -> - appSettingsInner - .properties() - .entrySet() - .stream() - .collect( - Collectors - .toMap( - Map.Entry::getKey, - entry -> - new AppSettingImpl( - entry.getKey(), - entry.getValue(), - false)))); + return listAppSettings().map(appSettingsInner -> appSettingsInner.properties() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> new AppSettingImpl(entry.getKey(), entry.getValue(), false)))); } else { return super.getAppSettingsAsync(); } @@ -834,7 +794,8 @@ public void deploy(DeployType type, File file, DeployOptions deployOptions) { @Override public Mono deployAsync(DeployType type, File file, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, null) - .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); + .flatMap( + result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override @@ -855,7 +816,8 @@ public void deploy(DeployType type, InputStream file, long length, DeployOptions @Override public Mono deployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, length, null) - .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); + .flatMap( + result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override @@ -888,7 +850,7 @@ public Mono pushDeployAsync(DeployType type, File file, De } private Mono pushDeployAsync(DeployType type, InputStream file, long length, - DeployOptions deployOptions) { + DeployOptions deployOptions) { // deployOptions is ignored if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); @@ -910,13 +872,12 @@ private Mono pushDeployAsync(DeployType type, InputStream private Mono getAppServicePlanIsFlexConsumptionMono() { Mono updateAppServicePlan = Mono.justOrEmpty(appServicePlanIsFlexConsumption); if (appServicePlanIsFlexConsumption == null) { - updateAppServicePlan = Mono.defer( - () -> manager().appServicePlans() - .getByIdAsync(this.appServicePlanId()) - .map(appServicePlan -> { - appServicePlanIsFlexConsumption = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); - return appServicePlanIsFlexConsumption; - })); + updateAppServicePlan = Mono + .defer(() -> manager().appServicePlans().getByIdAsync(this.appServicePlanId()).map(appServicePlan -> { + appServicePlanIsFlexConsumption + = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); + return appServicePlanIsFlexConsumption; + })); } return updateAppServicePlan; } @@ -930,83 +891,59 @@ public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { public Mono getDeploymentStatusAsync(String deploymentId) { // "GET" LRO is not supported in azure-core SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .getProductionSiteDeploymentStatusWithResponseAsync(this.resourceGroupName(), this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); - return response.getBodyAsString() - .flatMap(bodyString -> { - CsmDeploymentStatus status; - try { - status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); - } catch (IOException e) { - return Mono.error(new ManagementException("Deserialize failed for response body.", response)); - } - return Mono.justOrEmpty(status); - }).doFinally(ignored -> response.close()); + return response.getBodyAsString().flatMap(bodyString -> { + CsmDeploymentStatus status; + try { + status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, + SerializerEncoding.JSON); + } catch (IOException e) { + return Mono.error(new ManagementException("Deserialize failed for response body.", response)); + } + return Mono.justOrEmpty(status); + }).doFinally(ignored -> response.close()); }); } @Host("{$host}") @ServiceInterface(name = "FunctionService") private interface FunctionService { - @Headers({ - "Accept: application/json", - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Get("admin/functions/{name}/keys") - Mono listFunctionKeys( - @HostParam("$host") String host, @PathParam("name") String functionName); + Mono listFunctionKeys(@HostParam("$host") String host, + @PathParam("name") String functionName); - @Headers({ - "Accept: application/json", - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Put("admin/functions/{name}/keys/{keyName}") - Mono addFunctionKey( - @HostParam("$host") String host, - @PathParam("name") String functionName, - @PathParam("keyName") String keyName, - @BodyParam("application/json") NameValuePair key); - - @Headers({ - "Accept: application/json", - "Content-Type: application/json; charset=utf-8" - }) + Mono addFunctionKey(@HostParam("$host") String host, @PathParam("name") String functionName, + @PathParam("keyName") String keyName, @BodyParam("application/json") NameValuePair key); + + @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}/keys/{keyName}") - Mono generateFunctionKey( - @HostParam("$host") String host, - @PathParam("name") String functionName, + Mono generateFunctionKey(@HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); - @Headers({ - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Content-Type: application/json; charset=utf-8" }) @Delete("admin/functions/{name}/keys/{keyName}") - Mono deleteFunctionKey( - @HostParam("$host") String host, - @PathParam("name") String functionName, + Mono deleteFunctionKey(@HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); - @Headers({ - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/host/ping") Mono ping(@HostParam("$host") String host); - @Headers({ - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Content-Type: application/json; charset=utf-8" }) @Get("admin/host/status") Mono getHostStatus(@HostParam("$host") String host); - @Headers({ - "Content-Type: application/json; charset=utf-8" - }) + @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}") - Mono triggerFunction( - @HostParam("$host") String host, - @PathParam("name") String functionName, + Mono triggerFunction(@HostParam("$host") String host, @PathParam("name") String functionName, @BodyParam("application/json") Object payload); } @@ -1015,10 +952,7 @@ private static class FunctionKeyListResult implements JsonSerializable keys = reader.readArray(reader1 -> - reader1.readObject(NameValuePair::fromJson)); + List keys + = reader.readArray(reader1 -> reader1.readObject(NameValuePair::fromJson)); result.keys = keys; } else { reader.skipChildren(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppsImpl.java index e64064ce15ee1..777cbd83fc7f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppsImpl.java @@ -45,29 +45,25 @@ public FunctionApp getByResourceGroup(String groupName, String name) { @Override public Mono getByResourceGroupAsync(final String resourceGroupName, final String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this - .getInnerAsync(resourceGroupName, name) - .flatMap( - siteInner -> { - if (FunctionAppImpl.isFunctionAppOnACA(siteInner)) { - // Function App on ACA only supports Application Insights as log option. - return this.inner().getConfigurationAsync(resourceGroupName, name) - .map(siteConfigResourceInner -> wrapModel(siteInner, siteConfigResourceInner, null)); - } else { - return Mono.zip( - this.inner().getConfigurationAsync(resourceGroupName, name), - this.inner().getDiagnosticLogsConfigurationAsync(resourceGroupName, name), - (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> - wrapModel(siteInner, siteConfigResourceInner, logsConfigInner)); - } - }); + return this.getInnerAsync(resourceGroupName, name).flatMap(siteInner -> { + if (FunctionAppImpl.isFunctionAppOnACA(siteInner)) { + // Function App on ACA only supports Application Insights as log option. + return this.inner() + .getConfigurationAsync(resourceGroupName, name) + .map(siteConfigResourceInner -> wrapModel(siteInner, siteConfigResourceInner, null)); + } else { + return Mono.zip(this.inner().getConfigurationAsync(resourceGroupName, name), + this.inner().getDiagnosticLogsConfigurationAsync(resourceGroupName, name), + (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> wrapModel( + siteInner, siteConfigResourceInner, logsConfigInner)); + } + }); } @Override @@ -77,11 +73,8 @@ protected Mono getInnerAsync(String resourceGroupName, String name) { @Override public PagedIterable listFunctions(String resourceGroupName, String name) { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getWebApps() - .listFunctions(resourceGroupName, name), + return PagedConverter.mapPage( + this.manager().serviceClient().getWebApps().listFunctions(resourceGroupName, name), FunctionEnvelopeImpl::new); } @@ -103,8 +96,8 @@ protected FunctionAppImpl wrapModel(SiteInner inner) { return wrapModel(inner, null, null); } - private FunctionAppImpl wrapModel( - SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) { + private FunctionAppImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig) { if (inner == null) { return null; } @@ -119,12 +112,11 @@ public FunctionAppImpl define(String name) { @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } return this.inner().deleteAsync(resourceGroupName, name); } @@ -159,8 +151,8 @@ public PagedIterable listByResourceGroup(String resourceGroupN @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return PagedConverter.flatMapPage(inner().listByResourceGroupAsync(resourceGroupName), inner -> isFunctionApp(inner) ? Mono.just(new FunctionAppBasicImpl(inner, this.manager())) : Mono.empty()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotBasicImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotBasicImpl.java index a3a6d28af8487..88b0c3aeac882 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotBasicImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotBasicImpl.java @@ -32,7 +32,9 @@ public FunctionDeploymentSlot refresh() { @Override public Mono refreshAsync() { - return this.parent().deploymentSlots().getByIdAsync(this.id()) + return this.parent() + .deploymentSlots() + .getByIdAsync(this.id()) .doOnNext(site -> this.setInner(site.innerModel())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotImpl.java index 543f13f5c4f9e..035d0e70c2c2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotImpl.java @@ -28,25 +28,16 @@ import reactor.core.publisher.Mono; /** The implementation for FunctionDeploymentSlot. */ -class FunctionDeploymentSlotImpl - extends DeploymentSlotBaseImpl< - FunctionDeploymentSlot, - FunctionDeploymentSlotImpl, - FunctionAppImpl, - FunctionDeploymentSlot.DefinitionStages.WithCreate, - DeploymentSlotBase> +class FunctionDeploymentSlotImpl extends + DeploymentSlotBaseImpl> implements FunctionDeploymentSlot, FunctionDeploymentSlot.Definition { private static final ClientLogger LOGGER = new ClientLogger(FunctionDeploymentSlotImpl.class); private Boolean appServicePlanIsFlexConsumption; - FunctionDeploymentSlotImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - FunctionAppImpl parent) { + FunctionDeploymentSlotImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, FunctionAppImpl parent) { super(name, innerObject, siteConfig, logConfig, parent); } @@ -104,8 +95,11 @@ public String getMasterKey() { @Override public Mono getMasterKeyAsync() { - return this.manager().serviceClient().getWebApps().listHostKeysSlotAsync( - this.resourceGroupName(), this.parent().name(), this.name()).map(HostKeysInner::masterKey); + return this.manager() + .serviceClient() + .getWebApps() + .listHostKeysSlotAsync(this.resourceGroupName(), this.parent().name(), this.name()) + .map(HostKeysInner::masterKey); } @Override @@ -126,7 +120,8 @@ public void deploy(DeployType type, File file, DeployOptions deployOptions) { @Override public Mono deployAsync(DeployType type, File file, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, null) - .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); + .flatMap( + result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override @@ -147,7 +142,8 @@ public void deploy(DeployType type, InputStream file, long length, DeployOptions @Override public Mono deployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, length, null) - .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); + .flatMap( + result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override @@ -168,8 +164,7 @@ public Mono pushDeployAsync(DeployType type, File file, De if (appServiceIsFlexConsumptionPlan) { return kuduClient.pushDeployFlexConsumptionAsync(file); } else { - return kuduClient.pushZipDeployAsync(file) - .then(Mono.just(new KuduDeploymentResult("latest"))); + return kuduClient.pushZipDeployAsync(file).then(Mono.just(new KuduDeploymentResult("latest"))); } } catch (IOException e) { return Mono.error(e); @@ -178,7 +173,7 @@ public Mono pushDeployAsync(DeployType type, File file, De } private Mono pushDeployAsync(DeployType type, InputStream file, long length, - DeployOptions deployOptions) { + DeployOptions deployOptions) { // deployOptions is ignored if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); @@ -200,13 +195,12 @@ private Mono pushDeployAsync(DeployType type, InputStream private Mono getAppServicePlanIsFlexConsumptionMono() { Mono updateAppServicePlan = Mono.justOrEmpty(appServicePlanIsFlexConsumption); if (appServicePlanIsFlexConsumption == null) { - updateAppServicePlan = Mono.defer( - () -> manager().appServicePlans() - .getByIdAsync(this.appServicePlanId()) - .map(appServicePlan -> { - appServicePlanIsFlexConsumption = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); - return appServicePlanIsFlexConsumption; - })); + updateAppServicePlan = Mono + .defer(() -> manager().appServicePlans().getByIdAsync(this.appServicePlanId()).map(appServicePlan -> { + appServicePlanIsFlexConsumption + = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); + return appServicePlanIsFlexConsumption; + })); } return updateAppServicePlan; } @@ -220,20 +214,23 @@ public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { public Mono getDeploymentStatusAsync(String deploymentId) { // "GET" LRO is not supported in azure-core SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - return this.manager().serviceClient().getWebApps() - .getSlotSiteDeploymentStatusSlotWithResponseAsync(this.resourceGroupName(), this.parent().name(), this.name(), deploymentId) + return this.manager() + .serviceClient() + .getWebApps() + .getSlotSiteDeploymentStatusSlotWithResponseAsync(this.resourceGroupName(), this.parent().name(), + this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); - return response.getBodyAsString() - .flatMap(bodyString -> { - CsmDeploymentStatus status; - try { - status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); - } catch (IOException e) { - return Mono.error(new ManagementException("Deserialize failed for response body.", response)); - } - return Mono.justOrEmpty(status); - }).doFinally(ignored -> response.close()); + return response.getBodyAsString().flatMap(bodyString -> { + CsmDeploymentStatus status; + try { + status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, + SerializerEncoding.JSON); + } catch (IOException e) { + return Mono.error(new ManagementException("Deserialize failed for response body.", response)); + } + return Mono.justOrEmpty(status); + }).doFinally(ignored -> response.close()); }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotsImpl.java index 4775d111a5786..3465bc171ebf0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionDeploymentSlotsImpl.java @@ -19,9 +19,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation DeploymentSlots. */ -class FunctionDeploymentSlotsImpl - extends IndependentChildResourcesImpl< - FunctionDeploymentSlot, FunctionDeploymentSlotImpl, SiteInner, WebAppsClient, AppServiceManager, FunctionApp> +class FunctionDeploymentSlotsImpl extends + IndependentChildResourcesImpl implements FunctionDeploymentSlots { private final FunctionAppImpl parent; @@ -34,8 +33,7 @@ class FunctionDeploymentSlotsImpl @Override protected FunctionDeploymentSlotImpl wrapModel(String name) { - return new FunctionDeploymentSlotImpl(name, new SiteInner(), null, null, parent) - .withRegion(parent.regionName()) + return new FunctionDeploymentSlotImpl(name, new SiteInner(), null, null, parent).withRegion(parent.regionName()) .withExistingResourceGroup(parent.resourceGroupName()); } @@ -53,20 +51,15 @@ public FunctionDeploymentSlotImpl define(String name) { } @Override - public Mono getByParentAsync( - final String resourceGroup, final String parentName, final String name) { - return innerCollection - .getSlotAsync(resourceGroup, parentName, name) - .flatMap( - siteInner -> - Mono - .zip( - innerCollection.getConfigurationSlotAsync(resourceGroup, parentName, - name.replaceAll(".*/", "")), - innerCollection.getDiagnosticLogsConfigurationSlotAsync(resourceGroup, parentName, - name.replaceAll(".*/", "")), - (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> - wrapModel(siteInner, siteConfigResourceInner, logsConfigInner))); + public Mono getByParentAsync(final String resourceGroup, final String parentName, + final String name) { + return innerCollection.getSlotAsync(resourceGroup, parentName, name) + .flatMap(siteInner -> Mono.zip( + innerCollection.getConfigurationSlotAsync(resourceGroup, parentName, name.replaceAll(".*/", "")), + innerCollection.getDiagnosticLogsConfigurationSlotAsync(resourceGroup, parentName, + name.replaceAll(".*/", "")), + (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> wrapModel( + siteInner, siteConfigResourceInner, logsConfigInner))); } @Override @@ -115,8 +108,8 @@ public PagedFlux listAsync() { inner -> new FunctionDeploymentSlotBasicImpl(inner, parent)); } - private FunctionDeploymentSlotImpl wrapModel( - SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) { + private FunctionDeploymentSlotImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig) { if (inner == null) { return null; } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameBindingImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameBindingImpl.java index 990991166cc66..64b160c8c7a43 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameBindingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameBindingImpl.java @@ -31,11 +31,9 @@ * @param the fluent implementation of the parent web app */ class HostnameBindingImpl> - extends IndexableWrapperImpl - implements Creatable, - HostnameBinding, - HostnameBinding.Definition>, - HostnameBinding.UpdateDefinition> { + extends IndexableWrapperImpl implements Creatable, HostnameBinding, + HostnameBinding.Definition>, + HostnameBinding.UpdateDefinition> { private final ClientLogger logger = new ClientLogger(getClass()); @@ -114,8 +112,8 @@ public FluentImplT attach() { } @Override - public HostnameBindingImpl withDnsRecordType( - CustomHostnameDnsRecordType hostnameDnsRecordType) { + public HostnameBindingImpl + withDnsRecordType(CustomHostnameDnsRecordType hostnameDnsRecordType) { Pattern pattern = Pattern.compile("([.\\w-]+|\\*)\\.([\\w-]+\\.\\w+)"); Matcher matcher = pattern.matcher(name); if (hostnameDnsRecordType == CustomHostnameDnsRecordType.CNAME && !matcher.matches()) { @@ -138,33 +136,24 @@ public Mono refreshAsync() { Mono observable = null; if (parent instanceof DeploymentSlot) { - observable = - this - .parent() - .manager() - .serviceClient() - .getWebApps() - .getHostnameBindingSlotAsync( - parent().resourceGroupName(), - ((DeploymentSlot) parent).parent().name(), - parent().name(), - name()); + observable = this.parent() + .manager() + .serviceClient() + .getWebApps() + .getHostnameBindingSlotAsync(parent().resourceGroupName(), ((DeploymentSlot) parent).parent().name(), + parent().name(), name()); } else { - observable = - this - .parent() - .manager() - .serviceClient() - .getWebApps() - .getHostnameBindingAsync(parent().resourceGroupName(), parent().name(), name()); + observable = this.parent() + .manager() + .serviceClient() + .getWebApps() + .getHostnameBindingAsync(parent().resourceGroupName(), parent().name(), name()); } - return observable - .map( - hostnameBindingInner -> { - self.setInner(hostnameBindingInner); - return self; - }); + return observable.map(hostnameBindingInner -> { + self.setInner(hostnameBindingInner); + return self; + }); } @Override @@ -185,39 +174,29 @@ public HostnameBinding create(Context context) { @Override public Mono createAsync(Context context) { final HostnameBinding self = this; - Function mapper = - hostnameBindingInner -> { - setInner(hostnameBindingInner); - return self; - }; + Function mapper = hostnameBindingInner -> { + setInner(hostnameBindingInner); + return self; + }; Mono hostnameBindingObservable; if (parent instanceof DeploymentSlot) { - hostnameBindingObservable = - this - .parent() - .manager() - .serviceClient() - .getWebApps() - .createOrUpdateHostnameBindingSlotAsync( - parent().resourceGroupName(), - ((DeploymentSlot) parent).parent().name(), - name, - parent().name(), - innerModel()) - .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map(mapper); + hostnameBindingObservable = this.parent() + .manager() + .serviceClient() + .getWebApps() + .createOrUpdateHostnameBindingSlotAsync(parent().resourceGroupName(), + ((DeploymentSlot) parent).parent().name(), name, parent().name(), innerModel()) + .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) + .map(mapper); } else { - hostnameBindingObservable = - this - .parent() - .manager() - .serviceClient() - .getWebApps() - .createOrUpdateHostnameBindingAsync( - parent().resourceGroupName(), parent().name(), name, innerModel()) - .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map(mapper); + hostnameBindingObservable = this.parent() + .manager() + .serviceClient() + .getWebApps() + .createOrUpdateHostnameBindingAsync(parent().resourceGroupName(), parent().name(), name, innerModel()) + .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) + .map(mapper); } return hostnameBindingObservable; diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameSslBindingImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameSslBindingImpl.java index 620cb181373c9..165cf98014217 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameSslBindingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/HostnameSslBindingImpl.java @@ -34,9 +34,8 @@ */ class HostnameSslBindingImpl> extends IndexableWrapperImpl - implements HostnameSslBinding, - HostnameSslBinding.Definition>, - HostnameSslBinding.UpdateDefinition> { + implements HostnameSslBinding, HostnameSslBinding.Definition>, + HostnameSslBinding.UpdateDefinition> { private final ClientLogger logger = new ClientLogger(getClass()); @@ -77,82 +76,72 @@ public FluentImplT attach() { } @Override - public HostnameSslBindingImpl withPfxCertificateToUpload( - final File pfxFile, final String password) { + public HostnameSslBindingImpl withPfxCertificateToUpload(final File pfxFile, + final String password) { String thumbprint = getCertificateThumbprint(pfxFile.getPath(), password); - newCertificate = - this - .parent() - .manager() - .certificates() - .define(getCertificateUniqueName(thumbprint, parent().region())) - .withRegion(parent().region()) - .withExistingResourceGroup(parent().resourceGroupName()) - .withPfxFile(pfxFile) - .withPfxPassword(password) - .createAsync(); + newCertificate = this.parent() + .manager() + .certificates() + .define(getCertificateUniqueName(thumbprint, parent().region())) + .withRegion(parent().region()) + .withExistingResourceGroup(parent().resourceGroupName()) + .withPfxFile(pfxFile) + .withPfxPassword(password) + .createAsync(); return this; } @Override - public HostnameSslBindingImpl withExistingCertificate( - final String certificateNameOrThumbprint) { - newCertificate = - this - .parent() - .manager() - .certificates() - .listByResourceGroupAsync(parent().resourceGroupName()) - .collectList() - .map( - appServiceCertificates -> { - for (AppServiceCertificate certificate : appServiceCertificates) { - if (certificate.name().equals(certificateNameOrThumbprint) - || certificate.thumbprint().equalsIgnoreCase(certificateNameOrThumbprint)) { - return certificate; - } - } - return null; - }) - .map( - appServiceCertificate -> { - if (appServiceCertificate != null) { - withCertificateThumbprint(certificateNameOrThumbprint); - } - return appServiceCertificate; - }); + public HostnameSslBindingImpl + withExistingCertificate(final String certificateNameOrThumbprint) { + newCertificate = this.parent() + .manager() + .certificates() + .listByResourceGroupAsync(parent().resourceGroupName()) + .collectList() + .map(appServiceCertificates -> { + for (AppServiceCertificate certificate : appServiceCertificates) { + if (certificate.name().equals(certificateNameOrThumbprint) + || certificate.thumbprint().equalsIgnoreCase(certificateNameOrThumbprint)) { + return certificate; + } + } + return null; + }) + .map(appServiceCertificate -> { + if (appServiceCertificate != null) { + withCertificateThumbprint(certificateNameOrThumbprint); + } + return appServiceCertificate; + }); return this; } @Override - public HostnameSslBindingImpl withNewStandardSslCertificateOrder( - final String certificateOrderName) { - this.certificateInDefinition = - this - .parent() - .manager() - .certificateOrders() - .define(certificateOrderName) - .withExistingResourceGroup(parent().resourceGroupName()) - .withHostName(name()) - .withStandardSku() - .withWebAppVerification(parent()); + public HostnameSslBindingImpl + withNewStandardSslCertificateOrder(final String certificateOrderName) { + this.certificateInDefinition = this.parent() + .manager() + .certificateOrders() + .define(certificateOrderName) + .withExistingResourceGroup(parent().resourceGroupName()) + .withHostName(name()) + .withStandardSku() + .withWebAppVerification(parent()); return this; } @Override - public HostnameSslBindingImpl withExistingAppServiceCertificateOrder( - final AppServiceCertificateOrder certificateOrder) { - newCertificate = - this - .parent() - .manager() - .certificates() - .define(getCertificateUniqueName(certificateOrder.signedCertificate().thumbprint(), parent().region())) - .withRegion(parent().region()) - .withExistingResourceGroup(parent().resourceGroupName()) - .withExistingCertificateOrder(certificateOrder) - .createAsync(); + public HostnameSslBindingImpl + withExistingAppServiceCertificateOrder(final AppServiceCertificateOrder certificateOrder) { + newCertificate = this.parent() + .manager() + .certificates() + .define(getCertificateUniqueName(certificateOrder.signedCertificate().thumbprint(), parent().region())) + .withRegion(parent().region()) + .withExistingResourceGroup(parent().resourceGroupName()) + .withExistingCertificateOrder(certificateOrder) + .createAsync(); return this; } @@ -174,13 +163,11 @@ public HostnameSslBindingImpl withIpBasedSsl() { } Mono newCertificate() { - return newCertificate - .doOnNext( - appServiceCertificate -> { - if (appServiceCertificate != null) { - withCertificateThumbprint(appServiceCertificate.thumbprint()); - } - }); + return newCertificate.doOnNext(appServiceCertificate -> { + if (appServiceCertificate != null) { + withCertificateThumbprint(appServiceCertificate.thumbprint()); + } + }); } @Override @@ -196,39 +183,31 @@ public HostnameSslBindingImpl forHostname(String hostname) @Override public HostnameSslBindingImpl withExistingKeyVault(final Vault vault) { - Mono appServiceCertificateOrderObservable = - certificateInDefinition.withExistingKeyVault(vault).createAsync(); + Mono appServiceCertificateOrderObservable + = certificateInDefinition.withExistingKeyVault(vault).createAsync(); final AppServiceManager manager = this.parent().manager(); - this.newCertificate = - appServiceCertificateOrderObservable - .flatMap( - appServiceCertificateOrder -> - manager - .certificates() - .define(appServiceCertificateOrder.name()) - .withRegion(parent().regionName()) - .withExistingResourceGroup(parent().resourceGroupName()) - .withExistingCertificateOrder(appServiceCertificateOrder) - .createAsync()); + this.newCertificate + = appServiceCertificateOrderObservable.flatMap(appServiceCertificateOrder -> manager.certificates() + .define(appServiceCertificateOrder.name()) + .withRegion(parent().regionName()) + .withExistingResourceGroup(parent().resourceGroupName()) + .withExistingCertificateOrder(appServiceCertificateOrder) + .createAsync()); return this; } @Override public HostnameSslBindingImpl withNewKeyVault(String vaultName) { - Mono appServiceCertificateOrderObservable = - certificateInDefinition.withNewKeyVault(vaultName, parent().region()).createAsync(); + Mono appServiceCertificateOrderObservable + = certificateInDefinition.withNewKeyVault(vaultName, parent().region()).createAsync(); final AppServiceManager manager = this.parent().manager(); - this.newCertificate = - appServiceCertificateOrderObservable - .flatMap( - appServiceCertificateOrder -> - manager - .certificates() - .define(appServiceCertificateOrder.name()) - .withRegion(parent().regionName()) - .withExistingResourceGroup(parent().resourceGroupName()) - .withExistingCertificateOrder(appServiceCertificateOrder) - .createAsync()); + this.newCertificate + = appServiceCertificateOrderObservable.flatMap(appServiceCertificateOrder -> manager.certificates() + .define(appServiceCertificateOrder.name()) + .withRegion(parent().regionName()) + .withExistingResourceGroup(parent().resourceGroupName()) + .withExistingCertificateOrder(appServiceCertificateOrder) + .createAsync()); return this; } @@ -243,12 +222,7 @@ private String getCertificateThumbprint(String pfxPath, String password) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); inStream.close(); MessageDigest sha = MessageDigest.getInstance("SHA-1"); - return com - .azure - .resourcemanager - .appservice - .implementation - .Utils + return com.azure.resourcemanager.appservice.implementation.Utils .base16Encode(sha.digest(certificate.getEncoded())); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException ex) { throw logger.logExceptionAsError(new RuntimeException(ex)); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/KuduClient.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/KuduClient.java index 79a92c0dec147..672e36a4c5d53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/KuduClient.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/KuduClient.java @@ -68,9 +68,8 @@ class KuduClient { throw logger.logExceptionAsError( new UnsupportedOperationException("Cannot initialize kudu client before web app is created")); } - String host = webAppBase.defaultHostname().toLowerCase(Locale.ROOT) - .replace("http://", "") - .replace("https://", ""); + String host + = webAppBase.defaultHostname().toLowerCase(Locale.ROOT).replace("http://", "").replace("https://", ""); String[] parts = host.split("\\.", 2); host = parts[0] + ".scm." + parts[1]; this.host = "https://" + host; @@ -93,8 +92,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { public static DeploymentStatus fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - DeploymentStatus deserializedDeploymentStatus - = new DeploymentStatus(); + DeploymentStatus deserializedDeploymentStatus = new DeploymentStatus(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -145,59 +143,42 @@ private interface KuduService { @Get("api/logstream") Mono streamAllLogs(@HostParam("$host") String host); - @Headers({"Content-Type: application/octet-stream"}) + @Headers({ "Content-Type: application/octet-stream" }) @Post("api/wardeploy") - Mono warDeploy( - @HostParam("$host") String host, - @BodyParam("application/octet-stream") Flux warFile, - @HeaderParam("content-length") long size, + Mono warDeploy(@HostParam("$host") String host, + @BodyParam("application/octet-stream") Flux warFile, @HeaderParam("content-length") long size, @QueryParam("name") String appName); - @Headers({"Content-Type: application/octet-stream"}) + @Headers({ "Content-Type: application/octet-stream" }) @Post("api/zipdeploy") - Mono> zipDeploy( - @HostParam("$host") String host, - @BodyParam("application/octet-stream") Flux zipFile, - @HeaderParam("content-length") long size, - @QueryParam("isAsync") Boolean isAsync, - @QueryParam("deployer") String deployer - ); + Mono> zipDeploy(@HostParam("$host") String host, + @BodyParam("application/octet-stream") Flux zipFile, @HeaderParam("content-length") long size, + @QueryParam("isAsync") Boolean isAsync, @QueryParam("deployer") String deployer); // OneDeploy - @Headers({"Content-Type: application/octet-stream"}) + @Headers({ "Content-Type: application/octet-stream" }) @Post("api/publish") - Mono> deploy( - @HostParam("$host") String host, - @BodyParam("application/octet-stream") Flux file, - @HeaderParam("content-length") long size, - @QueryParam("type") DeployType type, - @QueryParam("path") String path, - @QueryParam("restart") Boolean restart, - @QueryParam("clean") Boolean clean, + Mono> deploy(@HostParam("$host") String host, + @BodyParam("application/octet-stream") Flux file, @HeaderParam("content-length") long size, + @QueryParam("type") DeployType type, @QueryParam("path") String path, + @QueryParam("restart") Boolean restart, @QueryParam("clean") Boolean clean, @QueryParam("isAsync") Boolean isAsync, - @QueryParam("trackDeploymentProgress") Boolean trackDeploymentProgress - ); + @QueryParam("trackDeploymentProgress") Boolean trackDeploymentProgress); // OneDeploy for FunctionApp of Flex Consumption plan - @Headers({"Content-Type: application/zip"}) + @Headers({ "Content-Type: application/zip" }) @Post("api/publish") - Mono> deployFlexConsumption( - @HostParam("$host") String host, - @BodyParam("application/zip") Flux file, - @HeaderParam("content-length") long size, - @QueryParam("remoteBuild") Boolean remoteBuild, - @QueryParam("deployer") String deployer - ); + Mono> deployFlexConsumption(@HostParam("$host") String host, + @BodyParam("application/zip") Flux file, @HeaderParam("content-length") long size, + @QueryParam("remoteBuild") Boolean remoteBuild, @QueryParam("deployer") String deployer); @Get("api/settings") Mono> settings(@HostParam("$host") String host); - @Headers({"Accept: application/json"}) + @Headers({ "Accept: application/json" }) @Get("api/deployments/{deploymentId}") - Mono> deploymentStatus( - @HostParam("$host") String host, - @PathParam("deploymentId") String deploymentId - ); + Mono> deploymentStatus(@HostParam("$host") String host, + @PathParam("deploymentId") String deploymentId); } Flux streamApplicationLogsAsync() { @@ -225,55 +206,53 @@ static Flux streamFromFluxBytes(final Flux source) { final byte newLineR = '\r'; final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - return source - .concatMap( - byteBuffer -> { - int index = findByte(byteBuffer, newLine); - if (index == -1) { - // no newLine byte found, not a line, put it into stream - try { - stream.write(FluxUtil.byteBufferToArray(byteBuffer)); - return Flux.empty(); - } catch (IOException e) { - return Flux.error(e); - } - } else { - // newLine byte found, at least 1 line - List lines = new ArrayList<>(); - while ((index = findByte(byteBuffer, newLine)) != -1) { - byte[] byteArray = new byte[index + 1]; - byteBuffer.get(byteArray); - try { - stream.write(byteArray); - String line = new String(stream.toByteArray(), StandardCharsets.UTF_8); - if (!line.isEmpty() && line.charAt(line.length() - 1) == newLine) { - // OK this is a line, end with newLine char - line = line.substring(0, line.length() - 1); - if (!line.isEmpty() && line.charAt(line.length() - 1) == newLineR) { - line = line.substring(0, line.length() - 1); - } - lines.add(line); - stream.reset(); - } - } catch (IOException e) { - return Flux.error(e); - } - } - if (byteBuffer.hasRemaining()) { - // put rest into stream - try { - stream.write(FluxUtil.byteBufferToArray(byteBuffer)); - } catch (IOException e) { - return Flux.error(e); + return source.concatMap(byteBuffer -> { + int index = findByte(byteBuffer, newLine); + if (index == -1) { + // no newLine byte found, not a line, put it into stream + try { + stream.write(FluxUtil.byteBufferToArray(byteBuffer)); + return Flux.empty(); + } catch (IOException e) { + return Flux.error(e); + } + } else { + // newLine byte found, at least 1 line + List lines = new ArrayList<>(); + while ((index = findByte(byteBuffer, newLine)) != -1) { + byte[] byteArray = new byte[index + 1]; + byteBuffer.get(byteArray); + try { + stream.write(byteArray); + String line = new String(stream.toByteArray(), StandardCharsets.UTF_8); + if (!line.isEmpty() && line.charAt(line.length() - 1) == newLine) { + // OK this is a line, end with newLine char + line = line.substring(0, line.length() - 1); + if (!line.isEmpty() && line.charAt(line.length() - 1) == newLineR) { + line = line.substring(0, line.length() - 1); } + lines.add(line); + stream.reset(); } - if (lines.isEmpty()) { - return Flux.empty(); - } else { - return Flux.fromIterable(lines); - } + } catch (IOException e) { + return Flux.error(e); } - }); + } + if (byteBuffer.hasRemaining()) { + // put rest into stream + try { + stream.write(FluxUtil.byteBufferToArray(byteBuffer)); + } catch (IOException e) { + return Flux.error(e); + } + } + if (lines.isEmpty()) { + return Flux.empty(); + } else { + return Flux.fromIterable(lines); + } + } + }); } private static int findByte(ByteBuffer byteBuffer, byte b) { @@ -288,14 +267,14 @@ private static int findByte(ByteBuffer byteBuffer, byte b) { return index; } -// Mono warDeployAsync(InputStream warFile, String appName) { -// InputStreamFlux flux = fluxFromInputStream(warFile); -// if (flux.flux != null) { -// return withRetry(service.warDeploy(host, flux.flux, flux.size, appName)); -// } else { -// return withRetry(service.warDeploy(host, flux.bytes, appName)); -// } -// } + // Mono warDeployAsync(InputStream warFile, String appName) { + // InputStreamFlux flux = fluxFromInputStream(warFile); + // if (flux.flux != null) { + // return withRetry(service.warDeploy(host, flux.flux, flux.size, appName)); + // } else { + // return withRetry(service.warDeploy(host, flux.bytes, appName)); + // } + // } Mono warDeployAsync(InputStream warFile, long length, String appName) { Flux flux = FluxUtil.toFluxByteBuffer(warFile); @@ -305,13 +284,13 @@ Mono warDeployAsync(InputStream warFile, long length, String appName) { Mono warDeployAsync(File warFile, String appName) throws IOException { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(warFile.toPath(), StandardOpenOption.READ); return retryOnError(service.warDeploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), appName)) - .doFinally(ignored -> { - try { - fileChannel.close(); - } catch (IOException e) { - logger.logThrowableAsError(e); - } - }); + .doFinally(ignored -> { + try { + fileChannel.close(); + } catch (IOException e) { + logger.logThrowableAsError(e); + } + }); } Mono zipDeployAsync(InputStream zipFile, long length) { @@ -328,25 +307,20 @@ Mono zipDeployAsync(File zipFile) throws IOException { } catch (IOException e) { logger.logThrowableAsError(e); } - }).then(); + }) + .then(); } - Mono deployAsync(DeployType type, - InputStream file, long length, - String path, Boolean restart, Boolean clean) { + Mono deployAsync(DeployType type, InputStream file, long length, String path, Boolean restart, + Boolean clean) { Flux flux = FluxUtil.toFluxByteBuffer(file); - return retryOnError(service.deploy(host, flux, length, type, path, restart, clean, false, false)) - .then(); + return retryOnError(service.deploy(host, flux, length, type, path, restart, clean, false, false)).then(); } - Mono deployAsync(DeployType type, - File file, - String path, Boolean restart, Boolean clean) throws IOException { + Mono deployAsync(DeployType type, File file, String path, Boolean restart, Boolean clean) throws IOException { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ); - return retryOnError(service.deploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), - type, path, restart, clean, false, false)) - .then() - .doFinally(ignored -> { + return retryOnError(service.deploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), type, path, + restart, clean, false, false)).then().doFinally(ignored -> { try { fileChannel.close(); } catch (IOException e) { @@ -355,14 +329,13 @@ Mono deployAsync(DeployType type, }); } - Mono pushDeployAsync(DeployType type, File file, String path, Boolean restart, - Boolean clean, Boolean trackDeployment) throws IOException { + Mono pushDeployAsync(DeployType type, File file, String path, Boolean restart, Boolean clean, + Boolean trackDeployment) throws IOException { final boolean trackDeploymentProgress = trackDeployment == null || trackDeployment; AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ); return getDeploymentResult(retryOnError(service.deploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), - type, path, restart, clean, true, trackDeployment)), trackDeploymentProgress) - .doFinally(ignored -> { + type, path, restart, clean, true, trackDeployment)), trackDeploymentProgress).doFinally(ignored -> { try { fileChannel.close(); } catch (IOException e) { @@ -371,11 +344,14 @@ Mono pushDeployAsync(DeployType type, File file, String pa }); } - private Mono getDeploymentResult(Mono> responseMono, boolean trackDeploymentProgress) { + private Mono getDeploymentResult(Mono> responseMono, + boolean trackDeploymentProgress) { return responseMono.map(response -> { HttpHeader deploymentIdHeader = response.getHeaders().get("SCM-DEPLOYMENT-ID"); - if (trackDeploymentProgress && (deploymentIdHeader == null || deploymentIdHeader.getValue() == null - || deploymentIdHeader.getValue().isEmpty())) { + if (trackDeploymentProgress + && (deploymentIdHeader == null + || deploymentIdHeader.getValue() == null + || deploymentIdHeader.getValue().isEmpty())) { // error, deployment ID not available throw logger.logExceptionAsError( @@ -387,9 +363,10 @@ private Mono getDeploymentResult(Mono> resp Mono pushZipDeployAsync(File file) throws IOException { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ); - return getDeploymentResult(retryOnError(service.zipDeploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), - true, DEPLOYER_JAVA_SDK)), true) - .doFinally(ignored -> { + return getDeploymentResult( + retryOnError( + service.zipDeploy(host, FluxUtil.readFile(fileChannel), fileChannel.size(), true, DEPLOYER_JAVA_SDK)), + true).doFinally(ignored -> { try { fileChannel.close(); } catch (IOException e) { @@ -400,29 +377,27 @@ Mono pushZipDeployAsync(File file) throws IOException { Mono pushZipDeployAsync(InputStream file, long length) throws IOException { Flux flux = FluxUtil.toFluxByteBuffer(file); - return getDeploymentResult(retryOnError(service.zipDeploy(host, flux, length, - true, DEPLOYER_JAVA_SDK)), true); + return getDeploymentResult(retryOnError(service.zipDeploy(host, flux, length, true, DEPLOYER_JAVA_SDK)), true); } Mono pushDeployFlexConsumptionAsync(File file) throws IOException { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ); return retryOnError(service.deployFlexConsumption(host, FluxUtil.readFile(fileChannel), fileChannel.size(), false, DEPLOYER_JAVA_SDK)) - // there is no "SCM-DEPLOYMENT-ID" header in response - .then(Mono.just(new KuduDeploymentResult("latest"))) - .doFinally(ignored -> { - try { - fileChannel.close(); - } catch (IOException e) { - logger.logThrowableAsError(e); - } - }); + // there is no "SCM-DEPLOYMENT-ID" header in response + .then(Mono.just(new KuduDeploymentResult("latest"))) + .doFinally(ignored -> { + try { + fileChannel.close(); + } catch (IOException e) { + logger.logThrowableAsError(e); + } + }); } Mono pushDeployFlexConsumptionAsync(InputStream file, long length) throws IOException { Flux flux = FluxUtil.toFluxByteBuffer(file); - return retryOnError(service.deployFlexConsumption(host, flux, length, - false, DEPLOYER_JAVA_SDK)) + return retryOnError(service.deployFlexConsumption(host, flux, length, false, DEPLOYER_JAVA_SDK)) .then(Mono.just(new KuduDeploymentResult("latest"))); } @@ -435,62 +410,50 @@ Mono> settings() { Mono pollDeploymentStatus(KuduDeploymentResult result, Duration pollInterval) { AtomicLong pollCount = new AtomicLong(); AtomicReference deploymentId = new AtomicReference<>(result.deploymentId()); - return Mono.defer(() -> service.deploymentStatus(host, deploymentId.get())) - .flatMap(response -> { - DeploymentStatus deploymentStatus = response.getValue(); - Integer status = deploymentStatus.getStatus(); - - // https://github.com/Azure/azure-cli/blob/dev/src/azure-cli/azure/cli/command_modules/appservice/custom.py - boolean succeeded = status == 4; - boolean completed = succeeded - || status == -1 - || (status >= 3 && status <= 6); - - // use deploymentId from response, as the initial deploymentId could be "latest" - // but do not use temp id - String id = deploymentStatus.getId(); - if (!CoreUtils.isNullOrEmpty(id) && deploymentStatus.getTemp() == Boolean.FALSE) { - deploymentId.set(id); - } + return Mono.defer(() -> service.deploymentStatus(host, deploymentId.get())).flatMap(response -> { + DeploymentStatus deploymentStatus = response.getValue(); + Integer status = deploymentStatus.getStatus(); + + // https://github.com/Azure/azure-cli/blob/dev/src/azure-cli/azure/cli/command_modules/appservice/custom.py + boolean succeeded = status == 4; + boolean completed = succeeded || status == -1 || (status >= 3 && status <= 6); + + // use deploymentId from response, as the initial deploymentId could be "latest" + // but do not use temp id + String id = deploymentStatus.getId(); + if (!CoreUtils.isNullOrEmpty(id) && deploymentStatus.getTemp() == Boolean.FALSE) { + deploymentId.set(id); + } - if (succeeded) { - return Mono.just(deploymentStatus); - } else if (completed) { - return Mono.error(new RuntimeException("Deployment failed, status " + status)); + if (succeeded) { + return Mono.just(deploymentStatus); + } else if (completed) { + return Mono.error(new RuntimeException("Deployment failed, status " + status)); + } else { + if (pollInterval.multipliedBy(pollCount.get()).compareTo(MAX_DEPLOY_TIMEOUT) >= 0) { + // timeout + return Mono.error(new RuntimeException("Deployment timed out, status " + status)); } else { - if (pollInterval.multipliedBy(pollCount.get()).compareTo(MAX_DEPLOY_TIMEOUT) >= 0) { - // timeout - return Mono.error(new RuntimeException("Deployment timed out, status " + status)); - } else { - // continue polling - return Mono.empty(); - } + // continue polling + return Mono.empty(); } - }) - .repeatWhenEmpty(longFlux -> longFlux.flatMap(index -> { - pollCount.set(index); - return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval)); - })) - .then(); + } + }).repeatWhenEmpty(longFlux -> longFlux.flatMap(index -> { + pollCount.set(index); + return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval)); + })).then(); } private Mono retryOnError(Mono observable) { final int retryCount = 5 + 1; // retryCount is 5, last 1 is guard - return observable - .retryWhen(Retry.withThrowable( - flux -> - flux - .zipWith( - Flux.range(1, retryCount), - (Throwable throwable, Integer count) -> { - if (count < retryCount - && (throwable instanceof TimeoutException - || throwable instanceof SocketTimeoutException)) { - return count; - } else { - throw logger.logExceptionAsError(Exceptions.propagate(throwable)); - } - }) - .flatMap(i -> Mono.delay(Duration.ofSeconds(((long) i) * 10))))); + return observable.retryWhen(Retry + .withThrowable(flux -> flux.zipWith(Flux.range(1, retryCount), (Throwable throwable, Integer count) -> { + if (count < retryCount + && (throwable instanceof TimeoutException || throwable instanceof SocketTimeoutException)) { + return count; + } else { + throw logger.logExceptionAsError(Exceptions.propagate(throwable)); + } + }).flatMap(i -> Mono.delay(Duration.ofSeconds(((long) i) * 10))))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/PublishingProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/PublishingProfileImpl.java index f9fce53b69299..833b3111dfc02 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/PublishingProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/PublishingProfileImpl.java @@ -20,15 +20,10 @@ class PublishingProfileImpl implements PublishingProfile { private final WebAppBase parent; - private static final Pattern GIT_REGEX = - Pattern - .compile( - "publishMethod=\"MSDeploy\" publishUrl=\"([^\"]+)\".+userName=\"(\\$[^\"]+)\".+userPWD=\"([^\"]+)\""); - private static final Pattern FTP_REGEX = - Pattern - .compile( - "publishMethod=\"FTP\"" - + " publishUrl=\"ftps?://([^\"]+).+userName=\"([^\"]+\\\\\\$[^\"]+)\".+userPWD=\"([^\"]+)\""); + private static final Pattern GIT_REGEX = Pattern + .compile("publishMethod=\"MSDeploy\" publishUrl=\"([^\"]+)\".+userName=\"(\\$[^\"]+)\".+userPWD=\"([^\"]+)\""); + private static final Pattern FTP_REGEX = Pattern.compile("publishMethod=\"FTP\"" + + " publishUrl=\"ftps?://([^\"]+).+userName=\"([^\"]+\\\\\\$[^\"]+)\".+userPWD=\"([^\"]+)\""); PublishingProfileImpl(String publishingProfileXml, WebAppBase parent) { Matcher matcher = GIT_REGEX.matcher(publishingProfileXml); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/StaticSitesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/StaticSitesClientImpl.java index 0aaea9b7fa768..e6a520c7cbe57 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/StaticSitesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/StaticSitesClientImpl.java @@ -5789,7 +5789,7 @@ private Mono>> registerUserProvidedFunctionAppWithStat Boolean isForced) { return beginRegisterUserProvidedFunctionAppWithStaticSiteBuildAsync(resourceGroupName, name, environmentName, functionAppName, staticSiteUserProvidedFunctionEnvelope, isForced).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -5816,7 +5816,7 @@ private Mono>> registerUserProvidedFunctionAppWithStat final Boolean isForced = null; return beginRegisterUserProvidedFunctionAppWithStaticSiteBuildAsync(resourceGroupName, name, environmentName, functionAppName, staticSiteUserProvidedFunctionEnvelope, isForced).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -5847,7 +5847,7 @@ private Mono>> registerUserProvidedFunctionAppWithStat Context context) { return beginRegisterUserProvidedFunctionAppWithStaticSiteBuildAsync(resourceGroupName, name, environmentName, functionAppName, staticSiteUserProvidedFunctionEnvelope, isForced, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -7841,7 +7841,7 @@ private Mono createOrUpdateStati Context context) { return beginCreateOrUpdateStaticSiteCustomDomainAsync(resourceGroupName, name, domainName, staticSiteCustomDomainRequestPropertiesEnvelope, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -8390,7 +8390,7 @@ private Mono validateCustomDomainCanBeAddedToStaticSiteAsync(String resour Context context) { return beginValidateCustomDomainCanBeAddedToStaticSiteAsync(resourceGroupName, name, domainName, staticSiteCustomDomainRequestPropertiesEnvelope, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -10755,7 +10755,7 @@ public Mono approveOrRejectPriv RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -10779,7 +10779,7 @@ private Mono approveOrRejectPri RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper, Context context) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -12162,7 +12162,7 @@ private Mono registerUserProv Context context) { return beginRegisterUserProvidedFunctionAppWithStaticSiteAsync(resourceGroupName, name, functionAppName, staticSiteUserProvidedFunctionEnvelope, isForced, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/Utils.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/Utils.java index 66f2fcd5d3400..99066c179b001 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/Utils.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/Utils.java @@ -106,14 +106,13 @@ private static String removeTrailingChar(String s, char c) { */ static Mono downloadFileAsync(String url, HttpPipeline httpPipeline) { HttpRequest request = new HttpRequest(HttpMethod.GET, url); - return httpPipeline.send(request) - .flatMap(response1 -> { - int code = response1.getStatusCode(); - if (code == 200) { - return Mono.just(response1); - } else { - return Mono.error(new HttpResponseException(response1)); - } - }).flatMap(HttpResponse::getBodyAsByteArray); + return httpPipeline.send(request).flatMap(response1 -> { + int code = response1.getStatusCode(); + if (code == 200) { + return Mono.just(response1); + } else { + return Mono.error(new HttpResponseException(response1)); + } + }).flatMap(HttpResponse::getBodyAsByteArray); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppAuthenticationImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppAuthenticationImpl.java index ac0771a82cad9..0167370dea242 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppAuthenticationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppAuthenticationImpl.java @@ -18,9 +18,8 @@ */ class WebAppAuthenticationImpl> extends IndexableWrapperImpl - implements WebAppAuthentication, - WebAppAuthentication.Definition>, - WebAppAuthentication.UpdateDefinition> { + implements WebAppAuthentication, WebAppAuthentication.Definition>, + WebAppAuthentication.UpdateDefinition> { private final WebAppBaseImpl parent; @@ -50,10 +49,9 @@ public WebAppAuthenticationImpl withAnonymousAuthenticatio } @Override - public WebAppAuthenticationImpl withDefaultAuthenticationProvider( - BuiltInAuthenticationProvider provider) { - innerModel() - .withUnauthenticatedClientAction(UnauthenticatedClientAction.REDIRECT_TO_LOGIN_PAGE) + public WebAppAuthenticationImpl + withDefaultAuthenticationProvider(BuiltInAuthenticationProvider provider) { + innerModel().withUnauthenticatedClientAction(UnauthenticatedClientAction.REDIRECT_TO_LOGIN_PAGE) .withDefaultProvider(provider); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBaseImpl.java index 129ae6436e414..d7fdb2c14df13 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBaseImpl.java @@ -103,11 +103,8 @@ * @param the fluent implementation of the web app or deployment slot or function app */ abstract class WebAppBaseImpl> - extends GroupableResourceImpl - implements WebAppBase, - WebAppBase.Definition, - WebAppBase.Update, - WebAppBase.UpdateStages.WithWebContainer { + extends GroupableResourceImpl implements WebAppBase, + WebAppBase.Definition, WebAppBase.Update, WebAppBase.UpdateStages.WithWebContainer { private final ClientLogger logger = new ClientLogger(getClass()); @@ -122,15 +119,14 @@ abstract class WebAppBaseImpl DNS_MAP = - new HashMap() { - { - put(AzureEnvironment.AZURE, "azurewebsites.net"); - put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn"); - put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de"); - put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us"); - } - }; + private static final Map DNS_MAP = new HashMap() { + { + put(AzureEnvironment.AZURE, "azurewebsites.net"); + put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn"); + put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de"); + put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us"); + } + }; SiteConfigResourceInner siteConfig; KuduClient kuduClient; @@ -157,12 +153,8 @@ abstract class WebAppBaseImpl webAppMsiHandler; - WebAppBaseImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, - AppServiceManager manager) { + WebAppBaseImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, + SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, manager); if (innerObject != null && innerObject.kind() != null) { innerObject.withKind(innerObject.kind().replace(";", ",")); @@ -657,30 +649,26 @@ private InputStream pipeObservableToInputStream(Flux observable) { } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } - final Disposable subscription = - observable - // Do not block current thread - .subscribeOn(Schedulers.boundedElastic()) - .subscribe( - s -> { - try { - out.write(s.getBytes(StandardCharsets.UTF_8)); - out.write('\n'); - out.flush(); - } catch (IOException e) { - throw logger.logExceptionAsError(new RuntimeException(e)); - } - }); - in - .addCallback( - () -> { - subscription.dispose(); - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - }); + final Disposable subscription = observable + // Do not block current thread + .subscribeOn(Schedulers.boundedElastic()) + .subscribe(s -> { + try { + out.write(s.getBytes(StandardCharsets.UTF_8)); + out.write('\n'); + out.flush(); + } catch (IOException e) { + throw logger.logExceptionAsError(new RuntimeException(e)); + } + }); + in.addCallback(() -> { + subscription.dispose(); + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + }); return in; } @@ -691,25 +679,13 @@ public Map getAppSettings() { @Override public Mono> getAppSettingsAsync() { - return Mono - .zip( - listAppSettings(), - listSlotConfigurations(), - (appSettingsInner, slotConfigs) -> - appSettingsInner - .properties() - .entrySet() - .stream() - .collect( - Collectors - .toMap( - Map.Entry::getKey, - entry -> - new AppSettingImpl( - entry.getKey(), - entry.getValue(), - slotConfigs.appSettingNames() != null - && slotConfigs.appSettingNames().contains(entry.getKey()))))); + return Mono.zip(listAppSettings(), listSlotConfigurations(), + (appSettingsInner, slotConfigs) -> appSettingsInner.properties() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> new AppSettingImpl(entry.getKey(), + entry.getValue(), + slotConfigs.appSettingNames() != null && slotConfigs.appSettingNames().contains(entry.getKey()))))); } @Override @@ -719,25 +695,14 @@ public Map getConnectionStrings() { @Override public Mono> getConnectionStringsAsync() { - return Mono - .zip( - listConnectionStrings(), - listSlotConfigurations(), - (connectionStringsInner, slotConfigs) -> - connectionStringsInner - .properties() - .entrySet() - .stream() - .collect( - Collectors - .toMap( - Map.Entry::getKey, - entry -> - new ConnectionStringImpl( - entry.getKey(), - entry.getValue(), - slotConfigs.connectionStringNames() != null - && slotConfigs.connectionStringNames().contains(entry.getKey()))))); + return Mono.zip(listConnectionStrings(), listSlotConfigurations(), + (connectionStringsInner, slotConfigs) -> connectionStringsInner.properties() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> new ConnectionStringImpl(entry.getKey(), entry.getValue(), + slotConfigs.connectionStringNames() != null + && slotConfigs.connectionStringNames().contains(entry.getKey()))))); } @Override @@ -793,30 +758,23 @@ public void beforeGroupCreateOrUpdate() { innerModel().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); } // Hostname and SSL bindings - IndexableTaskItem rootTaskItem = - wrapTask( - context -> { - // Submit hostname bindings - return submitHostNameBindings() - // Submit SSL bindings - .flatMap(fluentT -> submitSslBindings(fluentT.innerModel())); - }); + IndexableTaskItem rootTaskItem = wrapTask(context -> { + // Submit hostname bindings + return submitHostNameBindings() + // Submit SSL bindings + .flatMap(fluentT -> submitSslBindings(fluentT.innerModel())); + }); IndexableTaskItem lastTaskItem = rootTaskItem; // Site config lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig()); // Metadata, app settings, and connection strings - lastTaskItem = - sequentialTask( - lastTaskItem, - context -> - submitMetadata() - .flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last()) - .flatMap(ignored -> submitStickiness())); + lastTaskItem = sequentialTask(lastTaskItem, + context -> submitMetadata() + .flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last()) + .flatMap(ignored -> submitStickiness())); // Source control - lastTaskItem = - sequentialTask( - lastTaskItem, - context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate())); + lastTaskItem = sequentialTask(lastTaskItem, + context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate())); // Authentication lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication()); // Log configuration @@ -844,12 +802,10 @@ private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, Fun public Mono createResourceAsync() { this.webAppMsiHandler.processCreatedExternalIdentities(); this.webAppMsiHandler.handleExternalIdentities(); - return submitSite(innerModel()) - .map( - siteInner -> { - setInner(siteInner); - return (FluentT) WebAppBaseImpl.this; - }); + return submitSite(innerModel()).map(siteInner -> { + setInner(siteInner); + return (FluentT) WebAppBaseImpl.this; + }); } @Override @@ -877,13 +833,11 @@ public Mono updateResourceAsync() { siteUpdate.withRedundancyMode(siteInner.redundancyMode()); this.webAppMsiHandler.handleExternalIdentities(siteUpdate); - return submitSite(siteUpdate) - .map( - siteInner1 -> { - setInner(siteInner1); - webAppMsiHandler.clear(); - return (FluentT) WebAppBaseImpl.this; - }); + return submitSite(siteUpdate).map(siteInner1 -> { + setInner(siteInner1); + webAppMsiHandler.clear(); + return (FluentT) WebAppBaseImpl.this; + }); } @Override @@ -892,12 +846,10 @@ public Mono afterPostRunAsync(final boolean isGroupFaulted) { isInCreateMode = false; initializeKuduClient(); } - return Mono - .fromCallable( - () -> { - normalizeProperties(); - return null; - }); + return Mono.fromCallable(() -> { + normalizeProperties(); + return null; + }); } Mono submitSite(final SiteInner site) { @@ -907,22 +859,18 @@ Mono submitSite(final SiteInner site) { Mono submitSiteWithoutSiteConfig(final SiteInner site) { // Construct web app observable - return createOrUpdateInner(site) - .map( - siteInner -> { - site.withSiteConfig(null); - return siteInner; - }); + return createOrUpdateInner(site).map(siteInner -> { + site.withSiteConfig(null); + return siteInner; + }); } Mono submitSite(final SitePatchResourceInner siteUpdate) { // Construct web app observable - return updateInner(siteUpdate) - .map( - siteInner -> { - siteInner.withSiteConfig(null); - return siteInner; - }); + return updateInner(siteUpdate).map(siteInner -> { + siteInner.withSiteConfig(null); + return siteInner; + }); } @SuppressWarnings("unchecked") @@ -937,21 +885,15 @@ Mono submitHostNameBindings() { if (bindingObservables.isEmpty()) { return Mono.just((FluentT) this); } else { - return Flux - .zip(bindingObservables, ignored -> WebAppBaseImpl.this) - .last() - .onErrorResume( - throwable -> { - if (throwable instanceof HttpResponseException - && ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) { - return submitSite(innerModel()) - .flatMap( - ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last()); - } else { - return Mono.error(throwable); - } - }) - .flatMap(WebAppBaseImpl::refreshAsync); + return Flux.zip(bindingObservables, ignored -> WebAppBaseImpl.this).last().onErrorResume(throwable -> { + if (throwable instanceof HttpResponseException + && ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) { + return submitSite(innerModel()) + .flatMap(ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last()); + } else { + return Mono.error(throwable); + } + }).flatMap(WebAppBaseImpl::refreshAsync); } } @@ -965,15 +907,10 @@ Mono submitSslBindings(final SiteInner site) { return Mono.just((Indexable) this); } else { site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); - return Flux - .zip(certs, ignored -> site) - .last() - .flatMap(this::createOrUpdateInner) - .map( - siteInner -> { - setInner(siteInner); - return WebAppBaseImpl.this; - }); + return Flux.zip(certs, ignored -> site).last().flatMap(this::createOrUpdateInner).map(siteInner -> { + setInner(siteInner); + return WebAppBaseImpl.this; + }); } } @@ -983,39 +920,36 @@ Mono submitSiteConfig() { } if (siteConfig.azureStorageAccounts() != null) { // Remove azureStorageAccounts if any lack accessKey property. Service will reject if lack accessKey. - if (siteConfig.azureStorageAccounts().values().stream() + if (siteConfig.azureStorageAccounts() + .values() + .stream() .filter(Objects::nonNull) .anyMatch(v -> v.accessKey() == null)) { siteConfig.withAzureStorageAccounts(null); } } - return createOrUpdateSiteConfig(siteConfig) - .flatMap( - returnedSiteConfig -> { - siteConfig = returnedSiteConfig; - return Mono.just((Indexable) WebAppBaseImpl.this); - }); + return createOrUpdateSiteConfig(siteConfig).flatMap(returnedSiteConfig -> { + siteConfig = returnedSiteConfig; + return Mono.just((Indexable) WebAppBaseImpl.this); + }); } Mono submitAppSettings() { Mono observable = Mono.just((Indexable) this); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { - observable = - listAppSettings() - .switchIfEmpty(Mono.just(new StringDictionaryInner())) - .flatMap( - stringDictionaryInner -> { - if (stringDictionaryInner.properties() == null) { - stringDictionaryInner.withProperties(new HashMap()); - } - for (String appSettingKey : appSettingsToRemove) { - stringDictionaryInner.properties().remove(appSettingKey); - } - stringDictionaryInner.properties().putAll(appSettingsToAdd); - return updateAppSettings(stringDictionaryInner); - }) - .map(ignored -> WebAppBaseImpl.this); + observable = listAppSettings().switchIfEmpty(Mono.just(new StringDictionaryInner())) + .flatMap(stringDictionaryInner -> { + if (stringDictionaryInner.properties() == null) { + stringDictionaryInner.withProperties(new HashMap()); + } + for (String appSettingKey : appSettingsToRemove) { + stringDictionaryInner.properties().remove(appSettingKey); + } + stringDictionaryInner.properties().putAll(appSettingsToAdd); + return updateAppSettings(stringDictionaryInner); + }) + .map(ignored -> WebAppBaseImpl.this); } return observable; } @@ -1028,21 +962,18 @@ Mono submitMetadata() { Mono submitConnectionStrings() { Mono observable = Mono.just((Indexable) this); if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) { - observable = - listConnectionStrings() - .switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner())) - .flatMap( - dictionaryInner -> { - if (dictionaryInner.properties() == null) { - dictionaryInner.withProperties(new HashMap()); - } - for (String connectionString : connectionStringsToRemove) { - dictionaryInner.properties().remove(connectionString); - } - dictionaryInner.properties().putAll(connectionStringsToAdd); - return updateConnectionStrings(dictionaryInner); - }) - .map(ignored -> WebAppBaseImpl.this); + observable = listConnectionStrings().switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner())) + .flatMap(dictionaryInner -> { + if (dictionaryInner.properties() == null) { + dictionaryInner.withProperties(new HashMap()); + } + for (String connectionString : connectionStringsToRemove) { + dictionaryInner.properties().remove(connectionString); + } + dictionaryInner.properties().putAll(connectionStringsToAdd); + return updateConnectionStrings(dictionaryInner); + }) + .map(ignored -> WebAppBaseImpl.this); } return observable; } @@ -1050,41 +981,37 @@ Mono submitConnectionStrings() { Mono submitStickiness() { Mono observable = Mono.just((Indexable) this); if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) { - observable = - listSlotConfigurations() - .switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner())) - .flatMap( - slotConfigNamesResourceInner -> { - if (slotConfigNamesResourceInner.appSettingNames() == null) { - slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>()); - } - if (slotConfigNamesResourceInner.connectionStringNames() == null) { - slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>()); - } - Set stickyAppSettingKeys = - new HashSet<>(slotConfigNamesResourceInner.appSettingNames()); - Set stickyConnectionStringNames = - new HashSet<>(slotConfigNamesResourceInner.connectionStringNames()); - for (Map.Entry stickiness : appSettingStickiness.entrySet()) { - if (stickiness.getValue()) { - stickyAppSettingKeys.add(stickiness.getKey()); - } else { - stickyAppSettingKeys.remove(stickiness.getKey()); - } - } - for (Map.Entry stickiness : connectionStringStickiness.entrySet()) { - if (stickiness.getValue()) { - stickyConnectionStringNames.add(stickiness.getKey()); - } else { - stickyConnectionStringNames.remove(stickiness.getKey()); - } - } - slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys)); - slotConfigNamesResourceInner - .withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames)); - return updateSlotConfigurations(slotConfigNamesResourceInner); - }) - .map(ignored -> WebAppBaseImpl.this); + observable = listSlotConfigurations().switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner())) + .flatMap(slotConfigNamesResourceInner -> { + if (slotConfigNamesResourceInner.appSettingNames() == null) { + slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>()); + } + if (slotConfigNamesResourceInner.connectionStringNames() == null) { + slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>()); + } + Set stickyAppSettingKeys = new HashSet<>(slotConfigNamesResourceInner.appSettingNames()); + Set stickyConnectionStringNames + = new HashSet<>(slotConfigNamesResourceInner.connectionStringNames()); + for (Map.Entry stickiness : appSettingStickiness.entrySet()) { + if (stickiness.getValue()) { + stickyAppSettingKeys.add(stickiness.getKey()); + } else { + stickyAppSettingKeys.remove(stickiness.getKey()); + } + } + for (Map.Entry stickiness : connectionStringStickiness.entrySet()) { + if (stickiness.getValue()) { + stickyConnectionStringNames.add(stickiness.getKey()); + } else { + stickyConnectionStringNames.remove(stickiness.getKey()); + } + } + slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys)); + slotConfigNamesResourceInner + .withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames)); + return updateSlotConfigurations(slotConfigNamesResourceInner); + }) + .map(ignored -> WebAppBaseImpl.this); } return observable; } @@ -1093,8 +1020,7 @@ Mono submitSourceControlToCreate() { if (sourceControl == null || sourceControlToDelete) { return Mono.just((Indexable) this); } - return sourceControl - .registerGithubAccessToken() + return sourceControl.registerGithubAccessToken() .then(createOrUpdateSourceControl(sourceControl.innerModel())) .delayElement(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(30))) .map(ignored -> WebAppBaseImpl.this); @@ -1111,26 +1037,22 @@ Mono submitAuthentication() { if (!authenticationToUpdate) { return Mono.just((Indexable) this); } - return updateAuthentication(authentication.innerModel()) - .map( - siteAuthSettingsInner -> { - WebAppBaseImpl.this.authentication = - new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this); - return WebAppBaseImpl.this; - }); + return updateAuthentication(authentication.innerModel()).map(siteAuthSettingsInner -> { + WebAppBaseImpl.this.authentication + = new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this); + return WebAppBaseImpl.this; + }); } Mono submitLogConfiguration() { if (!diagnosticLogsToUpdate) { return Mono.just((Indexable) this); } - return updateDiagnosticLogsConfig(diagnosticLogs.innerModel()) - .map( - siteLogsConfigInner -> { - WebAppBaseImpl.this.diagnosticLogs = - new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this); - return WebAppBaseImpl.this; - }); + return updateDiagnosticLogsConfig(diagnosticLogs.innerModel()).map(siteLogsConfigInner -> { + WebAppBaseImpl.this.diagnosticLogs + = new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this); + return WebAppBaseImpl.this; + }); } @Override @@ -1138,8 +1060,8 @@ public WebDeploymentImpl deploy() { return new WebDeploymentImpl<>(this); } - WebAppBaseImpl withNewHostNameSslBinding( - final HostnameSslBindingImpl hostNameSslBinding) { + WebAppBaseImpl + withNewHostNameSslBinding(final HostnameSslBindingImpl hostNameSslBinding) { sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding); return this; } @@ -1148,14 +1070,12 @@ WebAppBaseImpl withNewHostNameSslBinding( public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) { for (String hostname : hostnames) { if ("@".equals(hostname) || hostname.equalsIgnoreCase(domain.name())) { - defineHostnameBinding() - .withAzureManagedDomain(domain) + defineHostnameBinding().withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.A) .attach(); } else { - defineHostnameBinding() - .withAzureManagedDomain(domain) + defineHostnameBinding().withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); @@ -1177,8 +1097,7 @@ public HostnameBindingImpl defineHostnameBinding() { @SuppressWarnings("unchecked") public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) { for (String hostname : hostnames) { - defineHostnameBinding() - .withThirdPartyDomain(domain) + defineHostnameBinding().withThirdPartyDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); @@ -1548,16 +1467,10 @@ void withDiagnosticLogs(WebAppDiagnosticLogsImpl diagnosti @Override @SuppressWarnings("unchecked") public Mono refreshAsync() { - return super - .refreshAsync() - .flatMap( - fluentT -> - getConfigInner() - .map( - returnedSiteConfig -> { - siteConfig = returnedSiteConfig; - return fluentT; - })); + return super.refreshAsync().flatMap(fluentT -> getConfigInner().map(returnedSiteConfig -> { + siteConfig = returnedSiteConfig; + return fluentT; + })); } @Override @@ -1581,8 +1494,7 @@ public FluentImplT withoutAuthentication() { @Override @SuppressWarnings("unchecked") public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) { - return updateDiagnosticLogsConfiguration() - .withWebServerLogging() + return updateDiagnosticLogsConfiguration().withWebServerLogging() .withWebServerLogsStoredOnFileSystem() .withWebServerFileSystemQuotaInMB(quotaInMB) .withLogRetentionDays(retentionDays) @@ -1683,7 +1595,6 @@ public WebAppDiagnosticLogsImpl updateDiagnosticLogsConfig return defineDiagnosticLogsConfiguration(); } - @Override public ManagedServiceIdentity identity() { return webSiteBase.identity(); @@ -1768,11 +1679,11 @@ public FluentImplT withAccessFromAllNetworks() { @SuppressWarnings("unchecked") public FluentImplT withAccessFromNetworkSubnet(String subnetId, int priority) { this.ensureIpSecurityRestrictions(); - this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() - .withAction(IP_RESTRICTION_ACTION_ALLOW) - .withPriority(priority) - .withTag(IpFilterTag.DEFAULT) - .withVnetSubnetResourceId(subnetId)); + this.siteConfig.ipSecurityRestrictions() + .add(new IpSecurityRestriction().withAction(IP_RESTRICTION_ACTION_ALLOW) + .withPriority(priority) + .withTag(IpFilterTag.DEFAULT) + .withVnetSubnetResourceId(subnetId)); return (FluentImplT) this; } @@ -1786,11 +1697,11 @@ public FluentImplT withAccessFromIpAddress(String ipAddress, int priority) { @SuppressWarnings("unchecked") public FluentImplT withAccessFromIpAddressRange(String ipAddressCidr, int priority) { this.ensureIpSecurityRestrictions(); - this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() - .withAction(IP_RESTRICTION_ACTION_ALLOW) - .withPriority(priority) - .withTag(IpFilterTag.DEFAULT) - .withIpAddress(ipAddressCidr)); + this.siteConfig.ipSecurityRestrictions() + .add(new IpSecurityRestriction().withAction(IP_RESTRICTION_ACTION_ALLOW) + .withPriority(priority) + .withTag(IpFilterTag.DEFAULT) + .withIpAddress(ipAddressCidr)); return (FluentImplT) this; } @@ -1806,12 +1717,12 @@ public FluentImplT withAccessRule(IpSecurityRestriction ipSecurityRule) { @SuppressWarnings("unchecked") public FluentImplT withoutNetworkSubnetAccess(String subnetId) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { - this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() + this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions() + .stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && subnetId.equalsIgnoreCase(r.vnetSubnetResourceId()))) - .collect(Collectors.toList()) - ); + .collect(Collectors.toList())); } return (FluentImplT) this; } @@ -1826,12 +1737,12 @@ public FluentImplT withoutIpAddressAccess(String ipAddress) { @SuppressWarnings("unchecked") public FluentImplT withoutIpAddressRangeAccess(String ipAddressCidr) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { - this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() + this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions() + .stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && Objects.equals(ipAddressCidr, r.ipAddress()))) - .collect(Collectors.toList()) - ); + .collect(Collectors.toList())); } return (FluentImplT) this; } @@ -1858,7 +1769,9 @@ public FluentImplT disablePublicNetworkAccess() { @Override public PublicNetworkAccess publicNetworkAccess() { - return Objects.isNull(innerModel().publicNetworkAccess()) ? null : PublicNetworkAccess.fromString(innerModel().publicNetworkAccess()); + return Objects.isNull(innerModel().publicNetworkAccess()) + ? null + : PublicNetworkAccess.fromString(innerModel().publicNetworkAccess()); } @Override @@ -1882,13 +1795,13 @@ public Mono> getSiteAppSettingsAsync() { @SuppressWarnings("unchecked") public FluentImplT withoutAccessRule(IpSecurityRestriction ipSecurityRule) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { - this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() + this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions() + .stream() .filter(r -> !(Objects.equals(r.action(), ipSecurityRule.action()) && Objects.equals(r.tag(), ipSecurityRule.tag()) && (Objects.equals(r.ipAddress(), ipSecurityRule.ipAddress()) - || Objects.equals(r.vnetSubnetResourceId(), ipSecurityRule.vnetSubnetResourceId())))) - .collect(Collectors.toList()) - ); + || Objects.equals(r.vnetSubnetResourceId(), ipSecurityRule.vnetSubnetResourceId())))) + .collect(Collectors.toList())); } return (FluentImplT) this; } @@ -1929,25 +1842,23 @@ protected static final class PrivateEndpointConnectionImpl implements PrivateEnd private final RemotePrivateEndpointConnectionArmResourceInner innerModel; private final PrivateEndpoint privateEndpoint; - private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState - privateLinkServiceConnectionState; + private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; protected PrivateEndpointConnectionImpl(RemotePrivateEndpointConnectionArmResourceInner innerModel) { this.innerModel = innerModel; - this.privateEndpoint = innerModel.privateEndpoint() == null - ? null - : new PrivateEndpoint(innerModel.privateEndpoint().id()); + this.privateEndpoint + = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( - innerModel.privateLinkServiceConnectionState().status() == null - ? null - : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus - .fromString(innerModel.privateLinkServiceConnectionState().status()), - innerModel.privateLinkServiceConnectionState().description(), - innerModel.privateLinkServiceConnectionState().actionsRequired()); + innerModel.privateLinkServiceConnectionState().status() == null + ? null + : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus + .fromString(innerModel.privateLinkServiceConnectionState().status()), + innerModel.privateLinkServiceConnectionState().description(), + innerModel.privateLinkServiceConnectionState().actionsRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBasicImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBasicImpl.java index f7307b180bac7..c22c9ccb50b58 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBasicImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppBasicImpl.java @@ -26,8 +26,7 @@ public WebApp refresh() { @Override public Mono refreshAsync() { - return this.manager().webApps().getByIdAsync(this.id()) - .doOnNext(site -> this.setInner(site.innerModel())); + return this.manager().webApps().getByIdAsync(this.id()).doOnNext(site -> this.setInner(site.innerModel())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppDiagnosticLogsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppDiagnosticLogsImpl.java index e8f1f6632a2d7..69c653caaf2c6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppDiagnosticLogsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppDiagnosticLogsImpl.java @@ -24,9 +24,8 @@ */ class WebAppDiagnosticLogsImpl> extends IndexableWrapperImpl - implements WebAppDiagnosticLogs, - WebAppDiagnosticLogs.Definition>, - WebAppDiagnosticLogs.UpdateDefinition> { + implements WebAppDiagnosticLogs, WebAppDiagnosticLogs.Definition>, + WebAppDiagnosticLogs.UpdateDefinition> { private final WebAppBaseImpl parent; @@ -76,8 +75,8 @@ public int applicationLoggingStorageBlobRetentionDays() { if (innerModel().applicationLogs() == null || innerModel().applicationLogs().azureBlobStorage() == null) { return 0; } else { - return ResourceManagerUtils.toPrimitiveInt( - innerModel().applicationLogs().azureBlobStorage().retentionInDays()); + return ResourceManagerUtils + .toPrimitiveInt(innerModel().applicationLogs().azureBlobStorage().retentionInDays()); } } @@ -183,23 +182,19 @@ public WebAppDiagnosticLogsImpl withFailedRequestTracing(b @Override public WebAppDiagnosticLogsImpl withApplicationLogsStoredOnFileSystem() { if (innerModel().applicationLogs() != null) { - innerModel() - .applicationLogs() + innerModel().applicationLogs() .withFileSystem(new FileSystemApplicationLogsConfig().withLevel(applicationLogLevel)); } return this; } @Override - public WebAppDiagnosticLogsImpl withApplicationLogsStoredOnStorageBlob( - String containerSasUrl) { + public WebAppDiagnosticLogsImpl + withApplicationLogsStoredOnStorageBlob(String containerSasUrl) { if (innerModel().applicationLogs() != null) { - innerModel() - .applicationLogs() - .withAzureBlobStorage( - new AzureBlobStorageApplicationLogsConfig() - .withLevel(applicationLogLevel) - .withSasUrl(containerSasUrl)); + innerModel().applicationLogs() + .withAzureBlobStorage(new AzureBlobStorageApplicationLogsConfig().withLevel(applicationLogLevel) + .withSasUrl(containerSasUrl)); } return this; } @@ -215,8 +210,7 @@ public WebAppDiagnosticLogsImpl withWebServerLogsStoredOnF @Override public WebAppDiagnosticLogsImpl withWebServerLogsStoredOnStorageBlob(String containerSasUrl) { if (innerModel().httpLogs() != null) { - innerModel() - .httpLogs() + innerModel().httpLogs() .withAzureBlobStorage( new AzureBlobStorageHttpLogsConfig().withEnabled(true).withSasUrl(containerSasUrl)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppImpl.java index 54a79893d8d47..3b3de16f4be5c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppImpl.java @@ -36,22 +36,14 @@ /** The implementation for WebApp. */ class WebAppImpl extends AppServiceBaseImpl - implements WebApp, - WebApp.Definition, - WebApp.DefinitionStages.ExistingWindowsPlanWithGroup, - WebApp.DefinitionStages.ExistingLinuxPlanWithGroup, - WebApp.Update, - WebApp.UpdateStages.WithCredentials, - WebApp.UpdateStages.WithStartUpCommand { + implements WebApp, WebApp.Definition, WebApp.DefinitionStages.ExistingWindowsPlanWithGroup, + WebApp.DefinitionStages.ExistingLinuxPlanWithGroup, WebApp.Update, WebApp.UpdateStages.WithCredentials, + WebApp.UpdateStages.WithStartUpCommand { private DeploymentSlots deploymentSlots; private WebAppRuntimeStack runtimeStackOnWindowsOSToUpdate; - WebAppImpl( - String name, - SiteInner innerObject, - SiteConfigResourceInner siteConfig, - SiteLogsConfigInner logConfig, + WebAppImpl(String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); } @@ -254,30 +246,23 @@ public void zipDeploy(InputStream zipFile, long length) { Mono submitMetadata() { Mono observable = super.submitMetadata(); if (runtimeStackOnWindowsOSToUpdate != null) { - observable = - observable - // list metadata - .then(listMetadata()) - // merge with change, then update - .switchIfEmpty(Mono.just(new StringDictionaryInner())) - .flatMap( - stringDictionaryInner -> { - if (stringDictionaryInner.properties() == null) { - stringDictionaryInner.withProperties(new HashMap()); - } - stringDictionaryInner - .properties() - .put("CURRENT_STACK", runtimeStackOnWindowsOSToUpdate.runtime()); - return updateMetadata(stringDictionaryInner); - }) - // clean up - .then( - Mono - .fromCallable( - () -> { - runtimeStackOnWindowsOSToUpdate = null; - return WebAppImpl.this; - })); + observable = observable + // list metadata + .then(listMetadata()) + // merge with change, then update + .switchIfEmpty(Mono.just(new StringDictionaryInner())) + .flatMap(stringDictionaryInner -> { + if (stringDictionaryInner.properties() == null) { + stringDictionaryInner.withProperties(new HashMap()); + } + stringDictionaryInner.properties().put("CURRENT_STACK", runtimeStackOnWindowsOSToUpdate.runtime()); + return updateMetadata(stringDictionaryInner); + }) + // clean up + .then(Mono.fromCallable(() -> { + runtimeStackOnWindowsOSToUpdate = null; + return WebAppImpl.this; + })); } return observable; } @@ -313,8 +298,8 @@ public Mono deployAsync(DeployType type, File file, DeployOptions deployOp deployOptions = new DeployOptions(); } try { - return kuduClient.deployAsync(type, file, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment()); + return kuduClient.deployAsync(type, file, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment()); } catch (IOException e) { return Mono.error(e); } @@ -342,8 +327,8 @@ public Mono deployAsync(DeployType type, InputStream file, long length, De if (deployOptions == null) { deployOptions = new DeployOptions(); } - return kuduClient.deployAsync(type, file, length, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment()); + return kuduClient.deployAsync(type, file, length, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment()); } @Override @@ -359,9 +344,8 @@ public Mono pushDeployAsync(DeployType type, File file, De deployOptions = new DeployOptions(); } try { - return kuduClient.pushDeployAsync(type, file, - deployOptions.path(), deployOptions.restartSite(), deployOptions.cleanDeployment(), - deployOptions.trackDeployment()); + return kuduClient.pushDeployAsync(type, file, deployOptions.path(), deployOptions.restartSite(), + deployOptions.cleanDeployment(), deployOptions.trackDeployment()); } catch (IOException e) { return Mono.error(e); } @@ -376,20 +360,22 @@ public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { public Mono getDeploymentStatusAsync(String deploymentId) { // "GET" LRO is not supported in azure-core SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - return this.manager().serviceClient().getWebApps() + return this.manager() + .serviceClient() + .getWebApps() .getProductionSiteDeploymentStatusWithResponseAsync(this.resourceGroupName(), this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); - return response.getBodyAsString() - .flatMap(bodyString -> { - CsmDeploymentStatus status; - try { - status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); - } catch (IOException e) { - return Mono.error(new ManagementException("Deserialize failed for response body.", response)); - } - return Mono.justOrEmpty(status); - }).doFinally(ignored -> response.close()); + return response.getBodyAsString().flatMap(bodyString -> { + CsmDeploymentStatus status; + try { + status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, + SerializerEncoding.JSON); + } catch (IOException e) { + return Mono.error(new ManagementException("Deserialize failed for response body.", response)); + } + return Mono.justOrEmpty(status); + }).doFinally(ignored -> response.close()); }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppMsiHandler.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppMsiHandler.java index ed14ccc085254..c8742f1818911 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppMsiHandler.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppMsiHandler.java @@ -90,8 +90,8 @@ WebAppMsiHandler withoutLocalManagedServiceIdentity() { * @param creatableIdentity yet-to-be-created identity to be associated with the virtual machine * @return WebAppMsiHandler */ - WebAppMsiHandler withNewExternalManagedServiceIdentity( - Creatable creatableIdentity) { + WebAppMsiHandler + withNewExternalManagedServiceIdentity(Creatable creatableIdentity) { this.initSiteIdentity(ManagedServiceIdentityType.USER_ASSIGNED); TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatableIdentity; @@ -211,22 +211,20 @@ private boolean handleRemoveAllExternalIdentitiesCase(SitePatchResourceInner sit } } Set removeIds = new HashSet<>(); - for (Map.Entry entrySet - : this.userAssignedIdentities.entrySet()) { + for (Map.Entry entrySet : this.userAssignedIdentities.entrySet()) { if (entrySet.getValue() == null) { removeIds.add(entrySet.getKey().toLowerCase(Locale.ROOT)); } } // If so check user want to remove all the identities - boolean removeAllCurrentIds = - currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); + boolean removeAllCurrentIds + = currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); if (removeAllCurrentIds) { // If so adjust the identity type [Setting type to SYSTEM_ASSIGNED orNONE will remove all the // identities] if (currentIdentity == null || currentIdentity.type() == null) { siteUpdate.withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE)); - } else if (currentIdentity - .type() + } else if (currentIdentity.type() .equals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)) { siteUpdate.withIdentity(currentIdentity); siteUpdate.identity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppSourceControlImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppSourceControlImpl.java index ce275e08ba8bf..a5662a05ae1da 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppSourceControlImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppSourceControlImpl.java @@ -19,9 +19,8 @@ */ class WebAppSourceControlImpl> extends IndexableWrapperImpl - implements WebAppSourceControl, - WebAppSourceControl.Definition>, - WebAppSourceControl.UpdateDefinition> { + implements WebAppSourceControl, WebAppSourceControl.Definition>, + WebAppSourceControl.UpdateDefinition> { private final WebAppBaseImpl parent; private String githubAccessToken; @@ -96,8 +95,8 @@ public WebAppSourceControlImpl withPublicMercurialReposito } @Override - public WebAppSourceControlImpl withContinuouslyIntegratedGitHubRepository( - String organization, String repository) { + public WebAppSourceControlImpl withContinuouslyIntegratedGitHubRepository(String organization, + String repository) { return withContinuouslyIntegratedGitHubRepository( String.format("https://github.com/%s/%s", organization, repository)); } @@ -119,7 +118,10 @@ Mono registerGithubAccessToken() { return Mono.empty(); } SourceControlInner sourceControlInner = new SourceControlInner().withToken(githubAccessToken); - return this.parent().manager().serviceClient().getResourceProviders() + return this.parent() + .manager() + .serviceClient() + .getResourceProviders() .updateSourceControlAsync("Github", sourceControlInner); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsClientImpl.java index 5325c70117c30..7c8da3aae7a0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsClientImpl.java @@ -28270,7 +28270,7 @@ public Mono approveOrRejectPriv RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -28294,7 +28294,7 @@ private Mono approveOrRejectPri RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper, Context context) { return beginApproveOrRejectPrivateEndpointConnectionAsync(resourceGroupName, name, privateEndpointConnectionName, privateEndpointWrapper, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -44183,7 +44183,7 @@ public Mono createOrUpdateDomainOwnershipIdentifierSlotAsync(St String domainOwnershipIdentifierName, String slot, IdentifierInner domainOwnershipIdentifier) { return createOrUpdateDomainOwnershipIdentifierSlotWithResponseAsync(resourceGroupName, name, domainOwnershipIdentifierName, slot, domainOwnershipIdentifier) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** @@ -44531,7 +44531,7 @@ public Mono updateDomainOwnershipIdentifierSlotAsync(String res String domainOwnershipIdentifierName, String slot, IdentifierInner domainOwnershipIdentifier) { return updateDomainOwnershipIdentifierSlotWithResponseAsync(resourceGroupName, name, domainOwnershipIdentifierName, slot, domainOwnershipIdentifier) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** @@ -57052,7 +57052,7 @@ public Mono approveOrRejectPriv RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper) { return beginApproveOrRejectPrivateEndpointConnectionSlotAsync(resourceGroupName, name, privateEndpointConnectionName, slot, privateEndpointWrapper).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -57077,7 +57077,7 @@ private Mono approveOrRejectPri RemotePrivateEndpointConnectionArmResourceInner privateEndpointWrapper, Context context) { return beginApproveOrRejectPrivateEndpointConnectionSlotAsync(resourceGroupName, name, privateEndpointConnectionName, slot, privateEndpointWrapper, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsImpl.java index c8a0ee154e11c..e71cc322a3354 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebAppsImpl.java @@ -33,8 +33,7 @@ import java.util.regex.Pattern; /** The implementation for WebApps. */ -public class WebAppsImpl - extends GroupableResourcesImpl +public class WebAppsImpl extends GroupableResourcesImpl implements WebApps, SupportsBatchDeletion { public WebAppsImpl(final AppServiceManager manager) { @@ -44,23 +43,17 @@ public WebAppsImpl(final AppServiceManager manager) { @Override public Mono getByResourceGroupAsync(final String resourceGroupName, final String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this - .getInnerAsync(resourceGroupName, name) - .flatMap( - siteInner -> - Mono - .zip( - this.inner().getConfigurationAsync(resourceGroupName, name), - this.inner().getDiagnosticLogsConfigurationAsync(resourceGroupName, name), - (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> - wrapModel(siteInner, siteConfigResourceInner, logsConfigInner))); + return this.getInnerAsync(resourceGroupName, name) + .flatMap(siteInner -> Mono.zip(this.inner().getConfigurationAsync(resourceGroupName, name), + this.inner().getDiagnosticLogsConfigurationAsync(resourceGroupName, name), + (SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) -> wrapModel( + siteInner, siteConfigResourceInner, logsConfigInner))); } @Override @@ -125,8 +118,8 @@ public PagedIterable listByResourceGroup(String resourceGroupName) @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return PagedConverter.flatMapPage(inner().listByResourceGroupAsync(resourceGroupName), inner -> isWebApp(inner) ? Mono.just(new WebAppBasicImpl(inner, this.manager())) : Mono.empty()); @@ -174,12 +167,12 @@ public CheckNameAvailabilityResult checkNameAvailability(String name, CheckNameR } @Override - public Mono checkNameAvailabilityAsync(String name, CheckNameResourceTypes type, boolean isFqdn) { - return manager().serviceClient().getResourceProviders() - .checkNameAvailabilityAsync(new ResourceNameAvailabilityRequest() - .withName(name) - .withType(type) - .withIsFqdn(isFqdn)) + public Mono checkNameAvailabilityAsync(String name, CheckNameResourceTypes type, + boolean isFqdn) { + return manager().serviceClient() + .getResourceProviders() + .checkNameAvailabilityAsync( + new ResourceNameAvailabilityRequest().withName(name).withType(type).withIsFqdn(isFqdn)) .map(CheckNameAvailabilityResultImpl::new); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentImpl.java index 4a342f2e2d578..02aa3de284d0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentImpl.java @@ -64,13 +64,10 @@ public WebDeploymentImpl withPackageUri(String packageUri) @Override public Mono executeWorkAsync() { - return parent - .createMSDeploy(request) - .map( - msDeployStatusInner -> { - result = msDeployStatusInner; - return WebDeploymentImpl.this; - }); + return parent.createMSDeploy(request).map(msDeployStatusInner -> { + result = msDeployStatusInner; + return WebDeploymentImpl.this; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentSlotBasicImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentSlotBasicImpl.java index 9f5cca05e8ccd..95bcae81409bd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentSlotBasicImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebDeploymentSlotBasicImpl.java @@ -31,7 +31,9 @@ public DeploymentSlot refresh() { @Override public Mono refreshAsync() { - return this.parent().deploymentSlots().getByIdAsync(this.id()) + return this.parent() + .deploymentSlots() + .getByIdAsync(this.id()) .doOnNext(site -> this.setInner(site.innerModel())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebSiteBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebSiteBaseImpl.java index 4bc52ff0720d0..6ee40dca6ed1a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebSiteBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/WebSiteBaseImpl.java @@ -279,8 +279,8 @@ protected void setInner(SiteInner innerObject) { } this.possibleOutboundIPAddressesSet.clear(); if (innerModel().possibleOutboundIpAddresses() != null) { - this.possibleOutboundIPAddressesSet.addAll(Arrays.asList( - innerModel().possibleOutboundIpAddresses().split(",[ ]*"))); + this.possibleOutboundIPAddressesSet + .addAll(Arrays.asList(innerModel().possibleOutboundIpAddresses().split(",[ ]*"))); } this.hostNameSslStateMap.clear(); if (innerModel().hostnameSslStates() != null) { @@ -294,8 +294,8 @@ protected void setInner(SiteInner innerObject) { } this.clientCertExclusionPathSet.clear(); if (innerModel().clientCertExclusionPaths() != null) { - this.clientCertExclusionPathSet.addAll(Arrays.asList( - innerModel().clientCertExclusionPaths().split(",[ ]*"))); + this.clientCertExclusionPathSet + .addAll(Arrays.asList(innerModel().clientCertExclusionPaths().split(",[ ]*"))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificate.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificate.java index 39706dac74135..281dc78a6c690 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificate.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificate.java @@ -63,12 +63,8 @@ public interface AppServiceCertificate HostingEnvironmentProfile hostingEnvironmentProfile(); /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCertificate, - DefinitionStages.WithPfxFilePassword, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCertificate, + DefinitionStages.WithPfxFilePassword, DefinitionStages.WithCreate { } /** Grouping of all the site definition stages. */ @@ -115,6 +111,7 @@ interface WithCertificate { */ WithCreate withExistingCertificateOrder(AppServiceCertificateOrder certificateOrder); } + /** An app service certificate definition allowing PFX certificate password to be set. */ interface WithPfxFilePassword { /** diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrder.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrder.java index 0171951bc8497..38b47ff736a68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrder.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrder.java @@ -20,8 +20,7 @@ @Fluent public interface AppServiceCertificateOrder extends GroupableResource, - Refreshable, - Updatable { + Refreshable, Updatable { /** @return certificate's distinguished name */ String distinguishedName(); @@ -110,12 +109,8 @@ public interface AppServiceCertificateOrder /** Container interface for all the definitions that need to be implemented. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithHostName, - DefinitionStages.WithCertificateSku, - DefinitionStages.WithDomainVerificationFromWebApp, - DefinitionStages.WithKeyVault, - DefinitionStages.WithCreate { + extends DefinitionStages.Blank, DefinitionStages.WithHostName, DefinitionStages.WithCertificateSku, + DefinitionStages.WithDomainVerificationFromWebApp, DefinitionStages.WithKeyVault, DefinitionStages.WithCreate { } /** Grouping of all the app service certificate order definition stages. */ @@ -231,11 +226,8 @@ interface WithAutoRenew { * An app service certificate order definition with sufficient inputs to create a new app service certificate * order in the cloud, but exposing additional optional inputs to specify. */ - interface WithCreate - extends Creatable, - WithValidYears, - WithAutoRenew, - GroupableResource.DefinitionWithTags { + interface WithCreate extends Creatable, WithValidYears, WithAutoRenew, + GroupableResource.DefinitionWithTags { } } @@ -257,9 +249,7 @@ interface WithAutoRenew { * The template for an app service certificate order update operation, containing all the settings that can be * modified. */ - interface Update - extends Appliable, - UpdateStages.WithAutoRenew, - GroupableResource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithAutoRenew, + GroupableResource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrders.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrders.java index 01ca46aec9c51..16d807be0c4b5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrders.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificateOrders.java @@ -17,12 +17,8 @@ /** Entry point for app service certificate order management API. */ @Fluent public interface AppServiceCertificateOrders - extends SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsListing, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { + extends SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsListing, + SupportsGettingById, SupportsDeletingByResourceGroup, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificates.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificates.java index 487acbd33ea85..462cdf682b71b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificates.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceCertificates.java @@ -16,13 +16,8 @@ /** Entry point for certificate management API. */ @Fluent -public interface AppServiceCertificates - extends SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsListing, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface AppServiceCertificates extends SupportsCreating, + SupportsDeletingById, SupportsListingByResourceGroup, SupportsListing, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingByResourceGroup, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomain.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomain.java index 20abfba4509cd..b38c813258552 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomain.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomain.java @@ -25,11 +25,8 @@ * Creatable#createAsync()} you agree to the agreements listed in {@link AppServiceDomains#listAgreements(String)}. */ @Fluent -public interface AppServiceDomain - extends GroupableResource, - HasName, - Refreshable, - Updatable { +public interface AppServiceDomain extends GroupableResource, HasName, + Refreshable, Updatable { /** @return admin contact information */ Contact adminContact(); @@ -109,12 +106,8 @@ public interface AppServiceDomain /** Container interface for all the definitions that need to be implemented. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAdminContact, - DefinitionStages.WithBillingContact, - DefinitionStages.WithRegistrantContact, - DefinitionStages.WithTechContact, - DefinitionStages.WithCreate { + extends DefinitionStages.Blank, DefinitionStages.WithAdminContact, DefinitionStages.WithBillingContact, + DefinitionStages.WithRegistrantContact, DefinitionStages.WithTechContact, DefinitionStages.WithCreate { } /** Grouping of all the domain definition stages. */ @@ -238,15 +231,8 @@ interface WithDnsZone { * A domain definition with sufficient inputs to create a new domain in the cloud, but exposing additional * optional inputs to specify. */ - interface WithCreate - extends WithDomainPrivacy, - WithAutoRenew, - WithAdminContact, - WithBillingContact, - WithTechContact, - WithDnsZone, - Creatable, - DefinitionWithTags { + interface WithCreate extends WithDomainPrivacy, WithAutoRenew, WithAdminContact, WithBillingContact, + WithTechContact, WithDnsZone, Creatable, DefinitionWithTags { } } @@ -347,14 +333,8 @@ interface WithDnsZone { } /** The template for a domain update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithAdminContact, - UpdateStages.WithBillingContact, - UpdateStages.WithTechContact, - UpdateStages.WithAutoRenew, - UpdateStages.WithDomainPrivacy, - UpdateStages.WithDnsZone, - GroupableResource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithAdminContact, + UpdateStages.WithBillingContact, UpdateStages.WithTechContact, UpdateStages.WithAutoRenew, + UpdateStages.WithDomainPrivacy, UpdateStages.WithDnsZone, GroupableResource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomains.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomains.java index 8581a84b83585..3ecc26ef64f68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomains.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServiceDomains.java @@ -17,15 +17,10 @@ /** Entry point for domain management API. */ @Fluent -public interface AppServiceDomains - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - HasManager { +public interface AppServiceDomains extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, HasManager { /** * List the agreements for purchasing a domain with a specific top level extension. * diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlan.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlan.java index 88b1ef90b222e..56733a6d9720a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlan.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlan.java @@ -15,11 +15,8 @@ /** An immutable client-side representation of an Azure App service plan. */ @Fluent -public interface AppServicePlan - extends GroupableResource, - HasName, - Refreshable, - Updatable { +public interface AppServicePlan extends GroupableResource, HasName, + Refreshable, Updatable { /** @return maximum number of instances that can be assigned */ int maxInstances(); @@ -43,12 +40,8 @@ public interface AppServicePlan **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithPricingTier, - DefinitionStages.WithOperatingSystem, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithPricingTier, + DefinitionStages.WithOperatingSystem, DefinitionStages.WithCreate { } /** Grouping of all the site definition stages. */ @@ -123,11 +116,8 @@ interface WithCapacity { * An app service plan definition with sufficient inputs to create a new website in the cloud, but exposing * additional optional inputs to specify. */ - interface WithCreate - extends WithPerSiteScaling, - WithCapacity, - Creatable, - GroupableResource.DefinitionWithTags { + interface WithCreate extends WithPerSiteScaling, WithCapacity, Creatable, + GroupableResource.DefinitionWithTags { } } @@ -168,11 +158,7 @@ interface WithCapacity { } /** The template for a site update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithCapacity, - UpdateStages.WithPerSiteScaling, - UpdateStages.WithPricingTier, - GroupableResource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithCapacity, UpdateStages.WithPerSiteScaling, + UpdateStages.WithPricingTier, GroupableResource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlans.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlans.java index 9bd10bb62cc0c..99262862e9f11 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlans.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlans.java @@ -16,13 +16,8 @@ /** Entry point for App Service plan management API. */ @Fluent -public interface AppServicePlans - extends SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsListing, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface AppServicePlans extends SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsListing, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingByResourceGroup, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlot.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlot.java index 1e522cc6c7ff6..0bf49c744fefa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlot.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlot.java @@ -17,12 +17,8 @@ /** An immutable client-side representation of an Azure Web App deployment slot. */ @Fluent public interface DeploymentSlot - extends IndependentChildResource, - WebDeploymentSlotBasic, - SupportsOneDeploy, - DeploymentSlotBase, - Updatable>, - HasParent { + extends IndependentChildResource, WebDeploymentSlotBasic, SupportsOneDeploy, + DeploymentSlotBase, Updatable>, HasParent { /** * Deploys a WAR file onto the Azure specialized Tomcat on this web app. diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlotBase.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlotBase.java index 8becb4aacb648..79342b4a5e199 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlotBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlotBase.java @@ -11,9 +11,7 @@ * * @param the type of the resource */ -public interface DeploymentSlotBase extends - WebAppBase, - Updatable> { +public interface DeploymentSlotBase extends WebAppBase, Updatable> { /** * Grouping of all the deployment slot update stages. @@ -100,12 +98,8 @@ interface WithStartUpCommand { } /** The template for a web app update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - WebAppBase.Update, - UpdateStages.WithRuntimeVersion, - UpdateStages.WithDockerContainerImage, - UpdateStages.WithStartUpCommand, - UpdateStages.WithCredentials { + interface Update extends Appliable, WebAppBase.Update, + UpdateStages.WithRuntimeVersion, UpdateStages.WithDockerContainerImage, + UpdateStages.WithStartUpCommand, UpdateStages.WithCredentials { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlots.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlots.java index 15bb9b330cd64..605e133f5c0d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlots.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlots.java @@ -16,13 +16,7 @@ /** Entry point for Azure web app deployment slot management API. */ @Fluent -public interface DeploymentSlots - extends SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByName, - HasManager, - HasParent { +public interface DeploymentSlots extends SupportsCreating, + SupportsListing, SupportsGettingByName, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByName, HasManager, HasParent { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DomainContact.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DomainContact.java index 83af45366ee9c..dc0df44d07515 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DomainContact.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DomainContact.java @@ -45,20 +45,13 @@ public interface DomainContact extends HasInnerModel, ChildResource the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithFirstName, - DefinitionStages.WithMiddleName, - DefinitionStages.WithAddressLine1, - DefinitionStages.WithAddressLine2, - DefinitionStages.WithCity, - DefinitionStages.WithStateOrProvince, - DefinitionStages.WithCountry, - DefinitionStages.WithPostalCode, - DefinitionStages.WithEmail, - DefinitionStages.WithPhoneCountryCode, - DefinitionStages.WithPhoneNumber, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithFirstName, + DefinitionStages.WithMiddleName, DefinitionStages.WithAddressLine1, + DefinitionStages.WithAddressLine2, DefinitionStages.WithCity, + DefinitionStages.WithStateOrProvince, DefinitionStages.WithCountry, + DefinitionStages.WithPostalCode, DefinitionStages.WithEmail, + DefinitionStages.WithPhoneCountryCode, DefinitionStages.WithPhoneNumber, + DefinitionStages.WithAttach { } /** Grouping of domain contact stages applicable as part of a domain creation. */ @@ -305,10 +298,8 @@ interface WithJobTitle { * @param the return type of {@link WithAttach#attach()} */ interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithOrganization, - DefinitionStages.WithJobTitle, - DefinitionStages.WithFaxNumber { + extends Attachable.InDefinition, DefinitionStages.WithOrganization, + DefinitionStages.WithJobTitle, DefinitionStages.WithFaxNumber { /** * @return the contact */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApp.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApp.java index 33dad378c534c..52aecf1a9a21e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApp.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApp.java @@ -20,11 +20,9 @@ /** An immutable client-side representation of an Azure Function App. */ @Fluent -public interface FunctionApp extends FunctionAppBasic, WebAppBase, Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, - SupportsUpdatingPrivateEndpointConnection, - SupportsOneDeploy { +public interface FunctionApp + extends FunctionAppBasic, WebAppBase, Updatable, SupportsListingPrivateLinkResource, + SupportsListingPrivateEndpointConnection, SupportsUpdatingPrivateEndpointConnection, SupportsOneDeploy { /** @return the entry point to deployment slot management API under the function app */ FunctionDeploymentSlots deploymentSlots(); @@ -152,13 +150,9 @@ public interface FunctionApp extends FunctionAppBasic, WebAppBase, Updatable, - DefinitionStages.WithNewAppServicePlan, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithRuntimeVersion, - DefinitionStages.WithDailyUsageQuota, - DefinitionStages.WithManagedEnvironment, - DefinitionStages.WithScaleRulesOrDockerContainerImage, - WebAppBase.DefinitionStages.WithCreate { + interface WithCreate extends Creatable, DefinitionStages.WithNewAppServicePlan, + DefinitionStages.WithStorageAccount, DefinitionStages.WithRuntimeVersion, + DefinitionStages.WithDailyUsageQuota, DefinitionStages.WithManagedEnvironment, + DefinitionStages.WithScaleRulesOrDockerContainerImage, WebAppBase.DefinitionStages.WithCreate { } /** @@ -811,13 +800,8 @@ interface WithManagedEnvironmentScaleRules { /** The template for a function app update operation, containing all the settings that can be modified. */ interface Update - extends WebAppBase.Update, - UpdateStages.WithAppServicePlan, - UpdateStages.WithRuntimeVersion, - UpdateStages.WithStorageAccount, - UpdateStages.WithDailyUsageQuota, - UpdateStages.WithDockerContainerImage, - UpdateStages.WithCredentials, - UpdateStages.WithManagedEnvironmentScaleRules { + extends WebAppBase.Update, UpdateStages.WithAppServicePlan, UpdateStages.WithRuntimeVersion, + UpdateStages.WithStorageAccount, UpdateStages.WithDailyUsageQuota, UpdateStages.WithDockerContainerImage, + UpdateStages.WithCredentials, UpdateStages.WithManagedEnvironmentScaleRules { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApps.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApps.java index d687878255cbb..8b067706511a6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApps.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionApps.java @@ -17,15 +17,10 @@ /** Entry point for web app management API. */ @Fluent -public interface FunctionApps - extends SupportsCreating, - SupportsDeletingById, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface FunctionApps extends SupportsCreating, SupportsDeletingById, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingByResourceGroup, + HasManager { /** * List function information elements. diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionAuthenticationPolicy.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionAuthenticationPolicy.java index 4df9119e812b8..7cd588dc4c0a5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionAuthenticationPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionAuthenticationPolicy.java @@ -27,21 +27,13 @@ public FunctionAuthenticationPolicy(FunctionApp functionApp) { @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - Mono masterKeyMono = - masterKey == null - ? functionApp - .getMasterKeyAsync() - .map( - key -> { - masterKey = key; - return key; - }) - : Mono.just(masterKey); - return masterKeyMono - .flatMap( - key -> { - context.getHttpRequest().setHeader(HEADER_NAME, key); - return next.process(); - }); + Mono masterKeyMono = masterKey == null ? functionApp.getMasterKeyAsync().map(key -> { + masterKey = key; + return key; + }) : Mono.just(masterKey); + return masterKeyMono.flatMap(key -> { + context.getHttpRequest().setHeader(HEADER_NAME, key); + return next.process(); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlot.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlot.java index 0a06c465319ee..186accd11d028 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlot.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlot.java @@ -14,13 +14,9 @@ /** An immutable client-side representation of an Azure Function App deployment slot. */ @Fluent -public interface FunctionDeploymentSlot - extends IndependentChildResource, - FunctionDeploymentSlotBasic, - DeploymentSlotBase, - Updatable>, - HasParent, - SupportsOneDeploy { +public interface FunctionDeploymentSlot extends IndependentChildResource, + FunctionDeploymentSlotBasic, DeploymentSlotBase, + Updatable>, HasParent, SupportsOneDeploy { /** @return the master key for the function app */ String getMasterKey(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlots.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlots.java index 14ea3dd1e1e3a..4a16ba5989008 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlots.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionDeploymentSlots.java @@ -16,13 +16,8 @@ /** Entry point for Azure function app deployment slot management API. */ @Fluent -public interface FunctionDeploymentSlots - extends SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByName, - HasManager, - HasParent { +public interface FunctionDeploymentSlots extends SupportsCreating, + SupportsListing, SupportsGettingByName, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByName, + HasManager, HasParent { } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionRuntimeStack.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionRuntimeStack.java index 481ac37bf0d59..db28712384e32 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionRuntimeStack.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/FunctionRuntimeStack.java @@ -11,16 +11,13 @@ public class FunctionRuntimeStack { /** JAVA 8. */ - public static final FunctionRuntimeStack JAVA_8 = new FunctionRuntimeStack("java", "~3", - "java|8"); + public static final FunctionRuntimeStack JAVA_8 = new FunctionRuntimeStack("java", "~3", "java|8"); /** JAVA 11. */ - public static final FunctionRuntimeStack JAVA_11 = new FunctionRuntimeStack("java", "~3", - "java|11"); + public static final FunctionRuntimeStack JAVA_11 = new FunctionRuntimeStack("java", "~3", "java|11"); /** JAVA 17. */ - public static final FunctionRuntimeStack JAVA_17 = new FunctionRuntimeStack("java", "~4", - "java|17"); + public static final FunctionRuntimeStack JAVA_17 = new FunctionRuntimeStack("java", "~4", "java|17"); private final String runtime; private final String version; @@ -34,10 +31,7 @@ public class FunctionRuntimeStack { * @param version the language runtime version * @param linuxFxVersion the LinuxFxVersion property value */ - public FunctionRuntimeStack( - String runtime, - String version, - String linuxFxVersion) { + public FunctionRuntimeStack(String runtime, String version, String linuxFxVersion) { this.runtime = Objects.requireNonNull(runtime); this.version = Objects.requireNonNull(version); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameBinding.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameBinding.java index 93e2bcb6bae1b..75bffa7160942 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameBinding.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameBinding.java @@ -37,12 +37,9 @@ public interface HostnameBinding * * @param the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithDomain, - DefinitionStages.WithSubDomain, - DefinitionStages.WithHostNameDnsRecordType, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithDomain, + DefinitionStages.WithSubDomain, DefinitionStages.WithHostNameDnsRecordType, + DefinitionStages.WithAttach { } /** Grouping of hostname binding definition stages applicable as part of a web app creation. */ @@ -125,12 +122,9 @@ interface WithAttach extends Attachable.InDefinition { * * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithDomain, - UpdateDefinitionStages.WithSubDomain, - UpdateDefinitionStages.WithHostNameDnsRecordType, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithDomain, UpdateDefinitionStages.WithSubDomain, + UpdateDefinitionStages.WithHostNameDnsRecordType, UpdateDefinitionStages.WithAttach { } /** Grouping of host name binding definition stages applicable as part of a web app creation. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameSslBinding.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameSslBinding.java index 38c634b6048b6..40b26d02ff7a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameSslBinding.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/HostnameSslBinding.java @@ -26,13 +26,9 @@ public interface HostnameSslBinding extends HasInnerModel, Chi * * @param the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithHostname, - DefinitionStages.WithCertificate, - DefinitionStages.WithKeyVault, - DefinitionStages.WithSslType, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithHostname, + DefinitionStages.WithCertificate, DefinitionStages.WithKeyVault, + DefinitionStages.WithSslType, DefinitionStages.WithAttach { } /** Grouping of hostname SSL binding definition stages applicable as part of a web app creation. */ @@ -164,12 +160,9 @@ interface WithAttach extends Attachable.InDefinition { * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithHostname, - UpdateDefinitionStages.WithCertificate, - UpdateDefinitionStages.WithKeyVault, - UpdateDefinitionStages.WithSslType, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithHostname, + UpdateDefinitionStages.WithCertificate, UpdateDefinitionStages.WithKeyVault, + UpdateDefinitionStages.WithSslType, UpdateDefinitionStages.WithAttach { } /** Grouping of hostname SSL binding definition stages applicable as part of a web app update. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/KuduAuthenticationPolicy.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/KuduAuthenticationPolicy.java index 9f5f0e6fe5e4b..add53d980276d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/KuduAuthenticationPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/KuduAuthenticationPolicy.java @@ -35,26 +35,14 @@ public KuduAuthenticationPolicy(WebAppBase webApp) { @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - Mono basicTokenMono = - basicToken == null - ? webApp - .getPublishingProfileAsync() - .map( - profile -> { - basicToken = - Base64 - .getEncoder() - .encodeToString( - (profile.gitUsername() + ":" + profile.gitPassword()) - .getBytes(StandardCharsets.UTF_8)); - return basicToken; - }) - : Mono.just(basicToken); - return basicTokenMono - .flatMap( - key -> { - context.getHttpRequest().setHeader(HEADER_NAME, "Basic " + basicToken); - return next.process(); - }); + Mono basicTokenMono = basicToken == null ? webApp.getPublishingProfileAsync().map(profile -> { + basicToken = Base64.getEncoder() + .encodeToString((profile.gitUsername() + ":" + profile.gitPassword()).getBytes(StandardCharsets.UTF_8)); + return basicToken; + }) : Mono.just(basicToken); + return basicTokenMono.flatMap(key -> { + context.getHttpRequest().setHeader(HEADER_NAME, "Basic " + basicToken); + return next.process(); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/OperatingSystem.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/OperatingSystem.java index 033fb6f7d17d8..752cfaa0cba93 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/OperatingSystem.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/OperatingSystem.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.appservice.models; - /** Defines values for AppServiceOperatingSystem. */ public enum OperatingSystem { /** Enum value Windows. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PricingTier.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PricingTier.java index 75f03c223b801..1fc15e92034ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PricingTier.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PricingTier.java @@ -12,72 +12,64 @@ public final class PricingTier { private static final AttributeCollection COLLECTION = new AttributeCollection<>(); /** Basic pricing tier with a small size. */ - public static final PricingTier BASIC_B1 = - COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B1")); + public static final PricingTier BASIC_B1 = COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B1")); /** Basic pricing tier with a medium size. */ - public static final PricingTier BASIC_B2 = - COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B2")); + public static final PricingTier BASIC_B2 = COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B2")); /** Basic pricing tier with a large size. */ - public static final PricingTier BASIC_B3 = - COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B3")); + public static final PricingTier BASIC_B3 = COLLECTION.addValue(new PricingTier(SkuName.BASIC.toString(), "B3")); /** Standard pricing tier with a small size. */ - public static final PricingTier STANDARD_S1 = - COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S1")); + public static final PricingTier STANDARD_S1 + = COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S1")); /** Standard pricing tier with a medium size. */ - public static final PricingTier STANDARD_S2 = - COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S2")); + public static final PricingTier STANDARD_S2 + = COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S2")); /** Standard pricing tier with a large size. */ - public static final PricingTier STANDARD_S3 = - COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S3")); + public static final PricingTier STANDARD_S3 + = COLLECTION.addValue(new PricingTier(SkuName.STANDARD.toString(), "S3")); /** Premium pricing tier with a small size. */ - public static final PricingTier PREMIUM_P1 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P1")); + public static final PricingTier PREMIUM_P1 = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P1")); /** Premium pricing tier with a medium size. */ - public static final PricingTier PREMIUM_P2 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P2")); + public static final PricingTier PREMIUM_P2 = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P2")); /** Premium pricing tier with a large size. */ - public static final PricingTier PREMIUM_P3 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P3")); + public static final PricingTier PREMIUM_P3 = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM.toString(), "P3")); /** V2 Premium pricing tier with a small size. */ - public static final PricingTier PREMIUM_P1V2 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P1v2")); + public static final PricingTier PREMIUM_P1V2 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P1v2")); /** V2 Premium pricing tier with a medium size. */ - public static final PricingTier PREMIUM_P2V2 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P2v2")); + public static final PricingTier PREMIUM_P2V2 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P2v2")); /** V2 Premium pricing tier with a large size. */ - public static final PricingTier PREMIUM_P3V2 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P3v2")); + public static final PricingTier PREMIUM_P3V2 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V2.toString(), "P3v2")); /** V3 Premium pricing tier with a small size. */ - public static final PricingTier PREMIUM_P1V3 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P1v3")); + public static final PricingTier PREMIUM_P1V3 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P1v3")); /** V3 Premium pricing tier with a medium size. */ - public static final PricingTier PREMIUM_P2V3 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P2v3")); + public static final PricingTier PREMIUM_P2V3 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P2v3")); /** V3 Premium pricing tier with a large size. */ - public static final PricingTier PREMIUM_P3V3 = - COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P3v3")); + public static final PricingTier PREMIUM_P3V3 + = COLLECTION.addValue(new PricingTier(SkuName.PREMIUM_V3.toString(), "P3v3")); /** Free pricing tier. This does not work with Linux web apps, host name bindings, and SSL bindings. */ - public static final PricingTier FREE_F1 = - COLLECTION.addValue(new PricingTier(SkuName.FREE.toString(), "F1")); + public static final PricingTier FREE_F1 = COLLECTION.addValue(new PricingTier(SkuName.FREE.toString(), "F1")); /** Shared pricing tier. This does not work with Linux web apps, host name bindings, and SSL bindings. */ - public static final PricingTier SHARED_D1 = - COLLECTION.addValue(new PricingTier(SkuName.SHARED.toString(), "D1")); + public static final PricingTier SHARED_D1 = COLLECTION.addValue(new PricingTier(SkuName.SHARED.toString(), "D1")); /** The actual serialized value for a SiteAvailabilityState instance. */ private final SkuDescription skuDescription; diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PublishingProfile.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PublishingProfile.java index 60df6dcb3095d..db88f89291486 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PublishingProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/PublishingProfile.java @@ -9,6 +9,7 @@ public interface PublishingProfile { /** @return the url for FTP publishing, with ftp:// and the root folder. E.g. ftp://ftp.contoso.com/site/wwwroot */ String ftpUrl(); + /** @return the username used for FTP publishing */ String ftpUsername(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java index 726e8d7cb1281..75368ddaf630b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java @@ -81,10 +81,12 @@ public class RuntimeStack { public static final RuntimeStack TOMCAT_9_0_JRE8 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "9.0-jre8")); /** Tomcat 10.0-java17 image with catalina root set to Azure wwwroot. */ - public static final RuntimeStack TOMCAT_10_0_JAVA17 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-java17")); + public static final RuntimeStack TOMCAT_10_0_JAVA17 + = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-java17")); /** Tomcat 10.0-java11 image with catalina root set to Azure wwwroot. */ - public static final RuntimeStack TOMCAT_10_0_JAVA11 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-java11")); + public static final RuntimeStack TOMCAT_10_0_JAVA11 + = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-java11")); /** * Tomcat 10.0-jre11 image with catalina root set to Azure wwwroot. @@ -99,16 +101,14 @@ public class RuntimeStack { public static final RuntimeStack TOMCAT_10_0_JRE8 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-jre8")); /** JBOSS EAP 7.2-java8. */ - public static final RuntimeStack JBOSS_EAP_7_2_JAVA8 = - COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7.2-java8")); + public static final RuntimeStack JBOSS_EAP_7_2_JAVA8 + = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7.2-java8")); /** JBOSS EAP 7-java8. */ - public static final RuntimeStack JBOSS_EAP_7_JAVA8 = - COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java8")); + public static final RuntimeStack JBOSS_EAP_7_JAVA8 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java8")); /** JBOSS EAP 7-java11. */ - public static final RuntimeStack JBOSS_EAP_7_JAVA11 = - COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java11")); + public static final RuntimeStack JBOSS_EAP_7_JAVA11 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java11")); /** The name of the language runtime stack. */ private final String stack; diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApp.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApp.java index 4fe925b8acf2d..2e7a2c266ddd1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApp.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApp.java @@ -18,10 +18,9 @@ /** An immutable client-side representation of an Azure Web App. */ @Fluent -public interface WebApp extends WebAppBasic, SupportsOneDeploy, WebAppBase, Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, - SupportsUpdatingPrivateEndpointConnection { +public interface WebApp + extends WebAppBasic, SupportsOneDeploy, WebAppBase, Updatable, SupportsListingPrivateLinkResource, + SupportsListingPrivateEndpointConnection, SupportsUpdatingPrivateEndpointConnection { /** @return the entry point to deployment slot management API under the web app */ DeploymentSlots deploymentSlots(); @@ -107,15 +106,10 @@ public interface WebApp extends WebAppBasic, SupportsOneDeploy, WebAppBase, Upda **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.NewAppServicePlanWithGroup, - DefinitionStages.WithNewAppServicePlan, - DefinitionStages.WithLinuxAppFramework, - DefinitionStages.WithCredentials, - DefinitionStages.WithStartUpCommand, - DefinitionStages.WithWindowsAppFramework, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.NewAppServicePlanWithGroup, + DefinitionStages.WithNewAppServicePlan, DefinitionStages.WithLinuxAppFramework, + DefinitionStages.WithCredentials, DefinitionStages.WithStartUpCommand, DefinitionStages.WithWindowsAppFramework, + DefinitionStages.WithCreate { } /** Grouping of all the web app definition stages. */ @@ -526,12 +520,7 @@ interface WithWindowsRuntimeStack { } /** The template for a web app update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithAppServicePlan, - UpdateStages.WithContainerImage, - UpdateStages.WithWindowsRuntimeStack, - UpdateStages.WithLinuxAppImage, - WebAppBase.Update { + interface Update extends Appliable, UpdateStages.WithAppServicePlan, UpdateStages.WithContainerImage, + UpdateStages.WithWindowsRuntimeStack, UpdateStages.WithLinuxAppImage, WebAppBase.Update { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppAuthentication.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppAuthentication.java index ac50da2e2600f..ccf1e34531c1a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppAuthentication.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppAuthentication.java @@ -18,10 +18,8 @@ public interface WebAppAuthentication extends HasInnerModel the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithDefaultAuthenticationProvider, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, + DefinitionStages.WithDefaultAuthenticationProvider, DefinitionStages.WithAttach { } /** Grouping of web app authentication definition stages applicable as part of a web app creation. */ @@ -146,11 +144,8 @@ interface WithExternalRedirectUrls { * * @param the return type of {@link WithAttach#attach()} */ - interface WithAttach - extends Attachable.InDefinition, - WithAuthenticationProvider, - WithTokenStore, - WithExternalRedirectUrls { + interface WithAttach extends Attachable.InDefinition, WithAuthenticationProvider, + WithTokenStore, WithExternalRedirectUrls { } } @@ -159,13 +154,10 @@ interface WithAttach * * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithDefaultAuthenticationProvider, - UpdateDefinitionStages.WithAuthenticationProvider, - UpdateDefinitionStages.WithTokenStore, - UpdateDefinitionStages.WithExternalRedirectUrls { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithDefaultAuthenticationProvider, + UpdateDefinitionStages.WithAuthenticationProvider, UpdateDefinitionStages.WithTokenStore, + UpdateDefinitionStages.WithExternalRedirectUrls { } /** Grouping of web app authentication definition stages applicable as part of a web app update. */ @@ -290,11 +282,8 @@ interface WithExternalRedirectUrls { * * @param the return type of {@link WithAttach#attach()} */ - interface WithAttach - extends Attachable.InUpdate, - WithAuthenticationProvider, - WithTokenStore, - WithExternalRedirectUrls { + interface WithAttach extends Attachable.InUpdate, WithAuthenticationProvider, + WithTokenStore, WithExternalRedirectUrls { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppBase.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppBase.java index e3ec0b71638fa..f5524b70ee1d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppBase.java @@ -358,11 +358,9 @@ public interface WebAppBase extends HasName, GroupableResource the type of the resource */ - interface Definition - extends DefinitionStages.WithWebContainer, - DefinitionStages.WithCreate, - DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, - DefinitionStages.WithUserAssignedManagedServiceIdentityBasedAccessOrCreate { + interface Definition extends DefinitionStages.WithWebContainer, + DefinitionStages.WithCreate, DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, + DefinitionStages.WithUserAssignedManagedServiceIdentityBasedAccessOrCreate { } /** Grouping of all the site definition stages. */ @@ -838,8 +836,8 @@ interface WithSystemAssignedIdentityBasedAccessOrCreate extends WithCre * @param role access role to assigned to the web app's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessTo(String resourceId, BuiltInRole role); /** * Specifies that web app's system assigned (local) identity should have the given access (described by the @@ -861,8 +859,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentit * @param roleDefinitionId access role definition to assigned to the web app's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessTo(String resourceId, String roleDefinitionId); /** * Specifies that web app's system assigned (local) identity should have the access (described by the role @@ -975,22 +973,12 @@ interface WithContainerSize { * @param the type of the resource */ interface WithCreate - extends Creatable, - GroupableResource.DefinitionWithTags>, - WithClientAffinityEnabled, - WithClientCertEnabled, - WithScmSiteAlsoStopped, - WithSiteConfigs, - WithAppSettings, - WithConnectionString, - WithSourceControl, - WithHostNameBinding, - WithHostNameSslBinding, - WithAuthentication, - WithDiagnosticLogging, - WithManagedServiceIdentity, - WithNetworkAccess, - WithContainerSize { + extends Creatable, GroupableResource.DefinitionWithTags>, + WithClientAffinityEnabled, WithClientCertEnabled, WithScmSiteAlsoStopped, + WithSiteConfigs, WithAppSettings, WithConnectionString, + WithSourceControl, WithHostNameBinding, WithHostNameSslBinding, + WithAuthentication, WithDiagnosticLogging, WithManagedServiceIdentity, + WithNetworkAccess, WithContainerSize { } } @@ -1686,6 +1674,7 @@ interface WithNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the web app, for private link feature. * @@ -1712,24 +1701,15 @@ interface WithContainerSize { * * @param the type of the resource */ - interface Update - extends Appliable, - GroupableResource.UpdateWithTags>, - UpdateStages.WithClientAffinityEnabled, - UpdateStages.WithClientCertEnabled, - UpdateStages.WithScmSiteAlsoStopped, - UpdateStages.WithSiteConfigs, - UpdateStages.WithAppSettings, - UpdateStages.WithConnectionString, - UpdateStages.WithSourceControl, - UpdateStages.WithHostNameBinding, - UpdateStages.WithHostNameSslBinding, - UpdateStages.WithAuthentication, - UpdateStages.WithDiagnosticLogging, - UpdateStages.WithManagedServiceIdentity, - UpdateStages.WithSystemAssignedIdentityBasedAccess, - UpdateStages.WithUserAssignedManagedServiceIdentityBasedAccess, - UpdateStages.WithNetworkAccess, - UpdateStages.WithContainerSize { + interface Update extends Appliable, GroupableResource.UpdateWithTags>, + UpdateStages.WithClientAffinityEnabled, UpdateStages.WithClientCertEnabled, + UpdateStages.WithScmSiteAlsoStopped, UpdateStages.WithSiteConfigs, + UpdateStages.WithAppSettings, UpdateStages.WithConnectionString, + UpdateStages.WithSourceControl, UpdateStages.WithHostNameBinding, + UpdateStages.WithHostNameSslBinding, UpdateStages.WithAuthentication, + UpdateStages.WithDiagnosticLogging, UpdateStages.WithManagedServiceIdentity, + UpdateStages.WithSystemAssignedIdentityBasedAccess, + UpdateStages.WithUserAssignedManagedServiceIdentityBasedAccess, + UpdateStages.WithNetworkAccess, UpdateStages.WithContainerSize { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppDiagnosticLogs.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppDiagnosticLogs.java index fe59c2785a825..06466ba144070 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppDiagnosticLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppDiagnosticLogs.java @@ -50,14 +50,12 @@ public interface WebAppDiagnosticLogs extends HasInnerModel * @param the return type of the final {@link Attachable#attach()} */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithDiagnosticLogging, - DefinitionStages.WithApplicationLogLevel, - DefinitionStages.WithStorageLocationForApplication, - DefinitionStages.WithStorageLocationForWebServer, - DefinitionStages.WithAttachForWebServerStorage, - DefinitionStages.WithAttachForWebServerFileSystem, - DefinitionStages.WithAttachForApplicationStorage { + extends DefinitionStages.Blank, DefinitionStages.WithDiagnosticLogging, + DefinitionStages.WithApplicationLogLevel, DefinitionStages.WithStorageLocationForApplication, + DefinitionStages.WithStorageLocationForWebServer, + DefinitionStages.WithAttachForWebServerStorage, + DefinitionStages.WithAttachForWebServerFileSystem, + DefinitionStages.WithAttachForApplicationStorage { } /** Grouping of web app diagnostic log definition stages applicable as part of a web app creation. */ @@ -262,10 +260,8 @@ interface WithAttachForWebServerFileSystem * * @param the return type of {@link WithAttach#attach()} */ - interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithDetailedErrorMessages, - DefinitionStages.WithFailedRequestTracing { + interface WithAttach extends Attachable.InDefinition, + DefinitionStages.WithDetailedErrorMessages, DefinitionStages.WithFailedRequestTracing { } } @@ -275,15 +271,10 @@ interface WithAttach * @param the return type of the final {@link Update#parent()} ()} */ interface UpdateDefinition - extends UpdateStages.Blank, - UpdateStages.Update, - UpdateStages.WithDiagnosticLogging, - UpdateStages.WithApplicationLogLevel, - UpdateStages.WithStorageLocationForApplication, - UpdateStages.WithStorageLocationForWebServer, - UpdateStages.WithAttachForWebServerStorage, - UpdateStages.WithAttachForWebServerFileSystem, - UpdateStages.WithAttachForApplicationStorage { + extends UpdateStages.Blank, UpdateStages.Update, UpdateStages.WithDiagnosticLogging, + UpdateStages.WithApplicationLogLevel, UpdateStages.WithStorageLocationForApplication, + UpdateStages.WithStorageLocationForWebServer, UpdateStages.WithAttachForWebServerStorage, + UpdateStages.WithAttachForWebServerFileSystem, UpdateStages.WithAttachForApplicationStorage { } /** Grouping of web app diagnostic log update stages applicable as part of a web app update. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppSourceControl.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppSourceControl.java index aa46688ebae35..4da3f33ba2fda 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppSourceControl.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebAppSourceControl.java @@ -31,13 +31,9 @@ public interface WebAppSourceControl extends HasInnerModel the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.GitHubWithAttach, - DefinitionStages.WithRepositoryType, - DefinitionStages.WithBranch, - DefinitionStages.WithGitHubBranch { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.GitHubWithAttach, DefinitionStages.WithRepositoryType, + DefinitionStages.WithBranch, DefinitionStages.WithGitHubBranch { } /** Grouping of web app source control definition stages applicable as part of a web app creation. */ @@ -83,8 +79,8 @@ interface WithRepositoryType { * @param repository the name of the repository, e.g. azure-sdk-for-java * @return the next stage of the definition */ - WithGitHubBranch withContinuouslyIntegratedGitHubRepository( - String organization, String repository); + WithGitHubBranch withContinuouslyIntegratedGitHubRepository(String organization, + String repository); /** * Specifies the repository to be a GitHub repository. Continuous integration will be turned on. This @@ -171,12 +167,9 @@ interface GitHubWithAttach extends WithAttach, WithGitHubAcces * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.GitHubWithAttach, - UpdateDefinitionStages.WithRepositoryType, - UpdateDefinitionStages.WithBranch, - UpdateDefinitionStages.WithGitHubBranch { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAttach, + UpdateDefinitionStages.GitHubWithAttach, UpdateDefinitionStages.WithRepositoryType, + UpdateDefinitionStages.WithBranch, UpdateDefinitionStages.WithGitHubBranch { } /** Grouping of web app source control definition stages applicable as part of a web app update. */ @@ -222,8 +215,8 @@ interface WithRepositoryType { * @param repository the name of the repository, e.g. azure-sdk-for-java * @return the next stage of the definition */ - WithGitHubBranch withContinuouslyIntegratedGitHubRepository( - String organization, String repository); + WithGitHubBranch withContinuouslyIntegratedGitHubRepository(String organization, + String repository); /** * Specifies the repository to be a GitHub repository. Continuous integration will be turned on. This diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApps.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApps.java index f604562ef03d1..b9e0609ed0b3d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApps.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/WebApps.java @@ -18,15 +18,9 @@ /** Entry point for web app management API. */ @Fluent -public interface WebApps - extends SupportsCreating, - SupportsDeletingById, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface WebApps extends SupportsCreating, SupportsDeletingById, + SupportsListing, SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, HasManager { /** * Checks whether name is available for the resource type. @@ -65,5 +59,5 @@ public interface WebApps * @return the {@link CheckNameAvailabilityResult} on successful completion of {@link Mono}. */ Mono checkNameAvailabilityAsync(String name, CheckNameResourceTypes type, - boolean isFqdn); + boolean isFqdn); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServicePlansTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServicePlansTests.java index b202c1d665a0c..036f785a0e1b8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServicePlansTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServicePlansTests.java @@ -30,21 +30,18 @@ protected void cleanUpResources() { } @Test - @Disabled( - "Permanent server side issue: Cannot modify this web hosting plan because another operation is in progress") + @Disabled("Permanent server side issue: Cannot modify this web hosting plan because another operation is in progress") public void canCRUDAppServicePlan() throws Exception { // CREATE - AppServicePlan appServicePlan = - appServiceManager - .appServicePlans() - .define(appServicePlanName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withPricingTier(PricingTier.PREMIUM_P1) - .withOperatingSystem(OperatingSystem.WINDOWS) - .withPerSiteScaling(false) - .withCapacity(2) - .create(); + AppServicePlan appServicePlan = appServiceManager.appServicePlans() + .define(appServicePlanName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withPricingTier(PricingTier.PREMIUM_P1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .withPerSiteScaling(false) + .withCapacity(2) + .create(); Assertions.assertNotNull(appServicePlan); Assertions.assertEquals(PricingTier.PREMIUM_P1, appServicePlan.pricingTier()); Assertions.assertEquals(false, appServicePlan.perSiteScaling()); @@ -52,11 +49,9 @@ public void canCRUDAppServicePlan() throws Exception { Assertions.assertEquals(0, appServicePlan.numberOfWebApps()); Assertions.assertEquals(20, appServicePlan.maxInstances()); // GET - Assertions - .assertNotNull(appServiceManager.appServicePlans().getByResourceGroup(rgName, appServicePlanName)); + Assertions.assertNotNull(appServiceManager.appServicePlans().getByResourceGroup(rgName, appServicePlanName)); // LIST - PagedIterable appServicePlans = - appServiceManager.appServicePlans().listByResourceGroup(rgName); + PagedIterable appServicePlans = appServiceManager.appServicePlans().listByResourceGroup(rgName); boolean found = false; for (AppServicePlan asp : appServicePlans) { if (appServicePlanName.equals(asp.name())) { @@ -66,13 +61,11 @@ public void canCRUDAppServicePlan() throws Exception { } Assertions.assertTrue(found); // UPDATE - appServicePlan = - appServicePlan - .update() - .withPricingTier(PricingTier.STANDARD_S1) - .withPerSiteScaling(true) - .withCapacity(3) - .apply(); + appServicePlan = appServicePlan.update() + .withPricingTier(PricingTier.STANDARD_S1) + .withPerSiteScaling(true) + .withCapacity(3) + .apply(); Assertions.assertNotNull(appServicePlan); Assertions.assertEquals(PricingTier.STANDARD_S1, appServicePlan.pricingTier()); Assertions.assertEquals(true, appServicePlan.perSiteScaling()); @@ -81,9 +74,7 @@ public void canCRUDAppServicePlan() throws Exception { @Test public void failOnAppServiceNotFound() { - resourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + resourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); Assertions.assertThrows(ManagementException.class, () -> { appServiceManager.appServicePlans().getByResourceGroup("rgName", "no_such_appservice"); }); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServiceTest.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServiceTest.java index 8bd4462cbde5f..01af0f1cd8c0d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServiceTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AppServiceTest.java @@ -60,21 +60,10 @@ public class AppServiceTest extends ResourceManagerTestProxyTestBase { protected String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -122,73 +111,59 @@ private void useExistingDomainAndCertificate() { } private void createNewDomainAndCertificate() { - domain = - appServiceManager - .domains() - .define(System.getenv("appservice-domain")) - .withExistingResourceGroup(System.getenv("appservice-group")) - .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(true) - .create(); - certificateOrder = - appServiceManager - .certificateOrders() - .define(System.getenv("appservice-certificateorder")) - .withExistingResourceGroup(System.getenv("appservice-group")) - .withHostName("*." + domain.name()) - .withWildcardSku() - .withDomainVerification(domain) - .withNewKeyVault("graphvault", Region.US_WEST) - .withValidYears(1) - .create(); + domain = appServiceManager.domains() + .define(System.getenv("appservice-domain")) + .withExistingResourceGroup(System.getenv("appservice-group")) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(true) + .create(); + certificateOrder = appServiceManager.certificateOrders() + .define(System.getenv("appservice-certificateorder")) + .withExistingResourceGroup(System.getenv("appservice-group")) + .withHostName("*." + domain.name()) + .withWildcardSku() + .withDomainVerification(domain) + .withNewKeyVault("graphvault", Region.US_WEST) + .withValidYears(1) + .create(); } protected static Response curl(String urlString) { HttpRequest request = new HttpRequest(HttpMethod.GET, urlString); - Mono> response = - stringResponse(HTTP_PIPELINE.send(request) - .flatMap(response1 -> { - int code = response1.getStatusCode(); - if (code == 200 || code == 400 || code == 404) { - return Mono.just(response1); - } else { - return Mono.error(new HttpResponseException(response1)); - } - }) - .retryWhen(Retry - .fixedDelay(3, Duration.ofSeconds(30)) - .filter(t -> t instanceof TimeoutException))); + Mono> response = stringResponse(HTTP_PIPELINE.send(request).flatMap(response1 -> { + int code = response1.getStatusCode(); + if (code == 200 || code == 400 || code == 404) { + return Mono.just(response1); + } else { + return Mono.error(new HttpResponseException(response1)); + } + }).retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(30)).filter(t -> t instanceof TimeoutException))); return response.block(); } protected static String post(String urlString, String body) { try { HttpRequest request = new HttpRequest(HttpMethod.POST, urlString).setBody(body); - Mono> response = - stringResponse(HTTP_PIPELINE.send(request) - .flatMap(response1 -> { - int code = response1.getStatusCode(); - if (code == 200 || code == 400 || code == 404) { - return Mono.just(response1); - } else { - return Mono.error(new HttpResponseException(response1)); - } - }) - .retryWhen(Retry - .fixedDelay(3, Duration.ofSeconds(30)) - .filter(t -> t instanceof TimeoutException))); + Mono> response = stringResponse(HTTP_PIPELINE.send(request).flatMap(response1 -> { + int code = response1.getStatusCode(); + if (code == 200 || code == 400 || code == 404) { + return Mono.just(response1); + } else { + return Mono.error(new HttpResponseException(response1)); + } + }).retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(30)).filter(t -> t instanceof TimeoutException))); Response ret = response.block(); return ret == null ? null : ret.getValue(); } catch (Exception e) { @@ -203,8 +178,8 @@ protected void assertFunctionAppRunning(FunctionApp functionApp) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; - Response response = curl("https://" + functionApp.defaultHostname() - + "/api/HttpTrigger-Java?name=" + name); + Response response + = curl("https://" + functionApp.defaultHostname() + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); @@ -253,13 +228,14 @@ protected Response getAppResponse(String hostname) { private static Mono> stringResponse(Mono responseMono) { return responseMono.flatMap(response -> response.getBodyAsString() - .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); + .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), + str))); } - private static final HttpPipeline HTTP_PIPELINE = new HttpPipelineBuilder() - .policies( - new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), - new RetryPolicy(new FixedDelay(3, Duration.ofSeconds(30)), "Retry-After", ChronoUnit.SECONDS), - new HttpDebugLoggingPolicy()) - .build(); + private static final HttpPipeline HTTP_PIPELINE + = new HttpPipelineBuilder() + .policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), + new RetryPolicy(new FixedDelay(3, Duration.ofSeconds(30)), "Retry-After", ChronoUnit.SECONDS), + new HttpDebugLoggingPolicy()) + .build(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AuthenticationTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AuthenticationTests.java index d0a6dae7a8659..4f8853c29f0c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AuthenticationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/AuthenticationTests.java @@ -35,18 +35,16 @@ protected void cleanUpResources() { @Disabled("Need facebook developer account") public void canCRUDWebAppWithAuthentication() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .defineAuthentication() - .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK) - .withFacebook("appId", "appSecret") - .attach() - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .defineAuthentication() + .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK) + .withFacebook("appId", "appSecret") + .attach() + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -58,8 +56,7 @@ public void canCRUDWebAppWithAuthentication() throws Exception { Assertions.assertTrue(response.contains("do not have permission")); // Update - webApp1 - .update() + webApp1.update() .defineAuthentication() .withAnonymousAuthentication() .withFacebook("appId", "appSecret") diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificateOrdersTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificateOrdersTests.java index 4ace995571735..7561fd1193e33 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificateOrdersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificateOrdersTests.java @@ -19,27 +19,24 @@ protected void cleanUpResources() { } @Test - @Disabled( - "Test is failing fix it. we may not intent to create a resource here but just to fetch existing resource.") + @Disabled("Test is failing fix it. we may not intent to create a resource here but just to fetch existing resource.") public void canCRUDCertificateOrder() throws Exception { // CREATE - AppServiceCertificateOrder certificateOrder = - appServiceManager - .certificateOrders() - .define(certificateName) - .withExistingResourceGroup(rgName) - .withHostName("*.graph-webapp-319.com") - .withWildcardSku() - .withDomainVerification(appServiceManager.domains().getByResourceGroup(rgName, "graph-webapp-319.com")) - .withNewKeyVault("graphvault", Region.US_WEST) - .withValidYears(1) - .create(); + AppServiceCertificateOrder certificateOrder = appServiceManager.certificateOrders() + .define(certificateName) + .withExistingResourceGroup(rgName) + .withHostName("*.graph-webapp-319.com") + .withWildcardSku() + .withDomainVerification(appServiceManager.domains().getByResourceGroup(rgName, "graph-webapp-319.com")) + .withNewKeyVault("graphvault", Region.US_WEST) + .withValidYears(1) + .create(); Assertions.assertNotNull(certificateOrder); // GET Assertions.assertNotNull(appServiceManager.certificateOrders().getByResourceGroup(rgName, certificateName)); // LIST - PagedIterable certificateOrders = - appServiceManager.certificateOrders().listByResourceGroup(rgName); + PagedIterable certificateOrders + = appServiceManager.certificateOrders().listByResourceGroup(rgName); boolean found = false; for (AppServiceCertificateOrder co : certificateOrders) { if (certificateName.equals(co.name())) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificatesTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificatesTests.java index fc65fd154821c..b70f30dde90f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificatesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/CertificatesTests.java @@ -26,27 +26,23 @@ protected void cleanUpResources() { @Disabled("Test is failing fix it, this is based on Existing RG and settings.") public void canCRDCertificate() throws Exception { Vault vault = keyVaultManager.vaults().getByResourceGroup(rgName, "bananagraphwebapp319com"); - AppServiceCertificate certificate = - appServiceManager - .certificates() - .define("bananacert") - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withExistingCertificateOrder( - appServiceManager.certificateOrders().getByResourceGroup(rgName, "graphwebapp319")) - .create(); + AppServiceCertificate certificate = appServiceManager.certificates() + .define("bananacert") + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withExistingCertificateOrder( + appServiceManager.certificateOrders().getByResourceGroup(rgName, "graphwebapp319")) + .create(); Assertions.assertNotNull(certificate); // CREATE - certificate = - appServiceManager - .certificates() - .define(certificateName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withPfxFile(new File("/Users/jianghlu/Documents/code/certs/myserver.pfx")) - .withPfxPassword("StrongPass!123") - .create(); + certificate = appServiceManager.certificates() + .define(certificateName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withPfxFile(new File("/Users/jianghlu/Documents/code/certs/myserver.pfx")) + .withPfxPassword("StrongPass!123") + .create(); Assertions.assertNotNull(certificate); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DeploymentSlotsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DeploymentSlotsTests.java index 6be1b9fae3ed1..65409b400b23c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DeploymentSlotsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DeploymentSlotsTests.java @@ -19,14 +19,14 @@ public class DeploymentSlotsTests extends AppServiceTest { private String webappName = ""; -// private String slotName1 = ""; + // private String slotName1 = ""; private String slotName2 = ""; private String slotName3 = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName = generateRandomResourceName("java-webapp-", 20); -// slotName1 = generateRandomResourceName("java-slot-", 20); + // slotName1 = generateRandomResourceName("java-slot-", 20); slotName2 = generateRandomResourceName("java-slot-", 20); slotName3 = generateRandomResourceName("java-slot-", 20); @@ -36,16 +36,14 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @Test public void canCRUDSwapSlots() throws Exception { // Create web app - WebApp webApp = - appServiceManager - .webApps() - .define(webappName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S2) - .withJavaVersion(JavaVersion.JAVA_1_7_0_51) - .withWebContainer(WebContainer.TOMCAT_7_0_50) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S2) + .withJavaVersion(JavaVersion.JAVA_1_7_0_51) + .withWebContainer(WebContainer.TOMCAT_7_0_50) + .create(); Assertions.assertNotNull(webApp); Assertions.assertEquals(Region.US_WEST, webApp.region()); @@ -55,8 +53,7 @@ public void canCRUDSwapSlots() throws Exception { Assertions.assertEquals(JavaVersion.JAVA_1_7_0_51, slot2.javaVersion()); // Update deployment slot - slot2 - .update() + slot2.update() .withoutJava() .withPythonVersion(PythonVersion.PYTHON_34) .withAppSetting("slot2key", "slot2value") @@ -67,11 +64,11 @@ public void canCRUDSwapSlots() throws Exception { Assertions.assertEquals(PythonVersion.PYTHON_34, slot2.pythonVersion()); // Create 3rd deployment slot with configuration from slot 2 - DeploymentSlot slot3 = - webApp.deploymentSlots().define(slotName3) - .withConfigurationFromDeploymentSlot(slot2) - .withHttpsOnly(true) - .create(); + DeploymentSlot slot3 = webApp.deploymentSlots() + .define(slotName3) + .withConfigurationFromDeploymentSlot(slot2) + .withHttpsOnly(true) + .create(); Assertions.assertNotNull(slot3); Assertions.assertEquals(JavaVersion.OFF, slot3.javaVersion()); Assertions.assertEquals(PythonVersion.PYTHON_34, slot3.pythonVersion()); @@ -82,9 +79,12 @@ public void canCRUDSwapSlots() throws Exception { Assertions.assertEquals(slot3.id(), deploymentSlot.id()); // List - WebDeploymentSlotBasic slotBasic3 = webApp.deploymentSlots().list().stream() + WebDeploymentSlotBasic slotBasic3 = webApp.deploymentSlots() + .list() + .stream() .filter(slotBasic -> slotName3.equals(slotBasic.name())) - .findFirst().orElse(null); + .findFirst() + .orElse(null); Assertions.assertNotNull(slotBasic3); Assertions.assertEquals(slot3.id(), slotBasic3.id()); Assertions.assertEquals(slot3.name(), slotBasic3.name()); @@ -96,9 +96,7 @@ public void canCRUDSwapSlots() throws Exception { Assertions.assertEquals(PythonVersion.PYTHON_34, slot3Refreshed.pythonVersion()); // Swap - slot2.update() - .withoutAppSetting("slot2key") - .apply(); + slot2.update().withoutAppSetting("slot2key").apply(); DeploymentSlot slot3Swapped = slot3Refreshed; slot3Swapped.swap(slot2.name()); @@ -107,18 +105,19 @@ public void canCRUDSwapSlots() throws Exception { @Test public void canCreateAndUpdatePublicNetworkAccess() { - WebApp webApp = - appServiceManager - .webApps() - .define(webappName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S2) - .withJavaVersion(JavaVersion.JAVA_1_7_0_51) - .withWebContainer(WebContainer.TOMCAT_7_0_50) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S2) + .withJavaVersion(JavaVersion.JAVA_1_7_0_51) + .withWebContainer(WebContainer.TOMCAT_7_0_50) + .create(); DeploymentSlot slot = webApp.deploymentSlots() - .define(slotName2).withConfigurationFromParent().disablePublicNetworkAccess().create(); + .define(slotName2) + .withConfigurationFromParent() + .disablePublicNetworkAccess() + .create(); slot.refresh(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, slot.publicNetworkAccess()); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DiagnosticLogsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DiagnosticLogsTests.java index 9afbc84daf763..5726546a034a2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DiagnosticLogsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DiagnosticLogsTests.java @@ -33,25 +33,23 @@ protected void cleanUpResources() { @Test public void canCRUDWebAppWithDiagnosticLogs() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .defineDiagnosticLogsConfiguration() - .withApplicationLogging() - .withLogLevel(LogLevel.INFORMATION) - .withApplicationLogsStoredOnFileSystem() - .attach() - .defineDiagnosticLogsConfiguration() - .withWebServerLogging() - .withWebServerLogsStoredOnFileSystem() - .withWebServerFileSystemQuotaInMB(50) - .withUnlimitedLogRetentionDays() - .attach() - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .defineDiagnosticLogsConfiguration() + .withApplicationLogging() + .withLogLevel(LogLevel.INFORMATION) + .withApplicationLogsStoredOnFileSystem() + .attach() + .defineDiagnosticLogsConfiguration() + .withWebServerLogging() + .withWebServerLogsStoredOnFileSystem() + .withWebServerFileSystemQuotaInMB(50) + .withUnlimitedLogRetentionDays() + .attach() + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -60,8 +58,8 @@ public void canCRUDWebAppWithDiagnosticLogs() throws Exception { Assertions.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier()); Assertions.assertNotNull(webApp1.diagnosticLogsConfig()); - Assertions - .assertEquals(LogLevel.INFORMATION, webApp1.diagnosticLogsConfig().applicationLoggingFileSystemLogLevel()); + Assertions.assertEquals(LogLevel.INFORMATION, + webApp1.diagnosticLogsConfig().applicationLoggingFileSystemLogLevel()); Assertions.assertEquals(LogLevel.OFF, webApp1.diagnosticLogsConfig().applicationLoggingStorageBlobLogLevel()); Assertions.assertNull(webApp1.diagnosticLogsConfig().applicationLoggingStorageBlobContainer()); Assertions.assertEquals(0, webApp1.diagnosticLogsConfig().applicationLoggingStorageBlobRetentionDays()); @@ -74,8 +72,7 @@ public void canCRUDWebAppWithDiagnosticLogs() throws Exception { Assertions.assertFalse(webApp1.diagnosticLogsConfig().failedRequestsTracing()); // Update - webApp1 - .update() + webApp1.update() .updateDiagnosticLogsConfiguration() .withoutApplicationLogging() .parent() diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DomainsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DomainsTests.java index 92df7c6e3e1c9..3baf2c5aadeaf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DomainsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/DomainsTests.java @@ -24,30 +24,27 @@ protected void cleanUpResources() { } @Test - @Disabled( - "Test is failing fix it. we may not intent to create a resource here but just to fetch existing resource.") + @Disabled("Test is failing fix it. we may not intent to create a resource here but just to fetch existing resource.") public void canCRUDDomain() throws Exception { // CREATE - AppServiceDomain domain = - appServiceManager - .domains() - .define(domainName) - .withExistingResourceGroup(rgName) - .defineRegistrantContact() - .withFirstName("Jianghao") - .withLastName("Lu") - .withEmail("jianghlu@microsoft.com") - .withAddressLine1("1 Microsoft Way") - .withCity("Seattle") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98101") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(true) - .create(); + AppServiceDomain domain = appServiceManager.domains() + .define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jianghao") + .withLastName("Lu") + .withEmail("jianghlu@microsoft.com") + .withAddressLine1("1 Microsoft Way") + .withCity("Seattle") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98101") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(true) + .create(); // Domain domain = appServiceManager.domains().getByGroup(RG_NAME, DOMAIN_NAME); Assertions.assertNotNull(domain); domain.update().withAutoRenewEnabled(false).apply(); @@ -55,7 +52,8 @@ public void canCRUDDomain() throws Exception { @Test public void canListTopLevelDomainsAgreements() { - PagedIterable iterable = appServiceManager.serviceClient().getTopLevelDomains() + PagedIterable iterable = appServiceManager.serviceClient() + .getTopLevelDomains() .listAgreements("com", new TopLevelDomainAgreementOption()); Assertions.assertNotNull(iterable.stream().collect(Collectors.toList())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionAppsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionAppsTests.java index b61f300b29eff..2689dece0fe07 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionAppsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionAppsTests.java @@ -66,13 +66,12 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile storageManager = buildManager(StorageManager.class, httpPipeline, profile); // build ContainerAppsApiManager try { - Constructor constructor = ContainerAppsApiManager.class.getDeclaredConstructor(httpPipeline.getClass(), profile.getClass(), Duration.class); + Constructor constructor = ContainerAppsApiManager.class + .getDeclaredConstructor(httpPipeline.getClass(), profile.getClass(), Duration.class); Runnable runnable = () -> constructor.setAccessible(true); runnable.run(); ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); - containerAppsApiManager = constructor.newInstance( - httpPipeline, - profile, + containerAppsApiManager = constructor.newInstance(httpPipeline, profile, // Lite packages need this for playback mode, since they take defaultPollInterval directly as polling interval. ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(30))); @@ -100,13 +99,11 @@ protected void cleanUpResources() { @Test public void canCRUDFunctionApp() throws Exception { // Create with consumption - FunctionApp functionApp1 = - appServiceManager - .functionApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .create(); + FunctionApp functionApp1 = appServiceManager.functionApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); Assertions.assertFalse(functionApp1.alwaysOn()); @@ -119,40 +116,33 @@ public void canCRUDFunctionApp() throws Exception { // consumption plan requires this 2 settings 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.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), + functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); // verify accountKey if (!isPlaybackMode()) { - Assertions - .assertEquals( - functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); + Assertions.assertEquals(functionAppResource1.storageAccount.getKeys().get(0).value(), + functionAppResource1.accountKey); } // Create with the same consumption plan - FunctionApp functionApp2 = - appServiceManager - .functionApps() - .define(webappName2) - .withExistingAppServicePlan(plan1) - .withNewResourceGroup(rgName2) - .withExistingStorageAccount(functionApp1.storageAccount()) - .create(); + FunctionApp functionApp2 = appServiceManager.functionApps() + .define(webappName2) + .withExistingAppServicePlan(plan1) + .withNewResourceGroup(rgName2) + .withExistingStorageAccount(functionApp1.storageAccount()) + .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); Assertions.assertFalse(functionApp2.alwaysOn()); // Create with app service plan - FunctionApp functionApp3 = - appServiceManager - .functionApps() - .define(webappName3) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName2) - .withNewAppServicePlan(PricingTier.BASIC_B1) - .withExistingStorageAccount(functionApp1.storageAccount()) - .create(); + FunctionApp functionApp3 = appServiceManager.functionApps() + .define(webappName3) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName2) + .withNewAppServicePlan(PricingTier.BASIC_B1) + .withExistingStorageAccount(functionApp1.storageAccount()) + .create(); Assertions.assertNotNull(functionApp3); Assertions.assertEquals(Region.US_WEST, functionApp3.region()); Assertions.assertTrue(functionApp3.alwaysOn()); @@ -164,9 +154,8 @@ public void canCRUDFunctionApp() throws Exception { Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); // verify accountKey if (!isPlaybackMode()) { - Assertions - .assertEquals( - functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); + Assertions.assertEquals(functionAppResource3.storageAccount.getKeys().get(0).value(), + functionAppResource3.accountKey); } // Get @@ -188,42 +177,32 @@ public void canCRUDFunctionApp() throws Exception { 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(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()); if (!isPlaybackMode()) { - Assertions - .assertEquals( - functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); + Assertions.assertEquals(functionAppResource2.storageAccount.getKeys().get(0).value(), + functionAppResource2.accountKey); } // Update, verify modify AppSetting does not create new storage account // https://github.com/Azure/azure-libraries-for-net/issues/457 - int numStorageAccountBefore = - TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); + int numStorageAccountBefore + = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); - int numStorageAccountAfter = - TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); + 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()); + 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()); // Scale functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); @@ -231,26 +210,24 @@ public void canCRUDFunctionApp() throws Exception { Assertions.assertTrue(functionApp3.alwaysOn()); } - private static final String FUNCTION_APP_PACKAGE_URL = - "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; + private static final String FUNCTION_APP_PACKAGE_URL + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; // function app with consumption plan - 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) - .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) - .create(); + 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) + .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) + .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); Assertions.assertFalse(functionApp1.alwaysOn()); @@ -261,42 +238,34 @@ public void canCRUDLinuxFunctionApp() throws Exception { 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"))); + Assertions.assertTrue(Arrays.asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) + .containsAll(Arrays.asList("linux", "functionapp"))); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); // consumption plan requires this 2 settings 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.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), + functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); // verify accountKey if (!isPlaybackMode()) { - Assertions - .assertEquals( - functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); + Assertions.assertEquals(functionAppResource1.storageAccount.getKeys().get(0).value(), + functionAppResource1.accountKey); } PagedIterable functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); // function app with app service plan - 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(); + 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); Assertions.assertTrue(functionApp2.alwaysOn()); @@ -307,16 +276,14 @@ public void canCRUDLinuxFunctionApp() throws Exception { Assertions.assertTrue(plan2.innerModel().reserved()); // one more function app using existing app service plan - 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(); + 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); Assertions.assertTrue(functionApp3.alwaysOn()); @@ -330,16 +297,16 @@ public void canCRUDLinuxFunctionApp() throws Exception { Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); // verify deploy - PagedIterable functions = - appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); + PagedIterable functions + = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); - functions = - appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); + functions + = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); - functions = - appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); + functions + = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @@ -348,17 +315,15 @@ public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; // function app with premium plan - 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(); + 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); Assertions.assertFalse(functionApp1.alwaysOn()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); @@ -377,8 +342,8 @@ public void canCRUDLinuxFunctionAppPremium() { } // verify deploy - PagedIterable functions = - appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); + PagedIterable functions + = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @@ -386,19 +351,16 @@ public void canCRUDLinuxFunctionAppPremium() { @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { // function app with premium plan with private docker - 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://weidxuregistry.azurecr.io") - .withCredentials("weidxuregistry", "PASSWORD") - .withRuntime("java") - .withRuntimeVersion("~3") - .create(); + 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://weidxuregistry.azurecr.io") + .withCredentials("weidxuregistry", "PASSWORD") + .withRuntime("java") + .withRuntimeVersion("~3") + .create(); Assertions.assertFalse(functionApp1.alwaysOn()); @@ -415,7 +377,8 @@ public void canCRUDLinuxFunctionAppJava11() throws Exception { String runtimeVersion = "~4"; // function app with consumption plan - FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) + FunctionApp functionApp1 = appServiceManager.functionApps() + .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() @@ -435,7 +398,8 @@ public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; // function app with consumption plan - FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) + FunctionApp functionApp1 = appServiceManager.functionApps() + .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() @@ -471,9 +435,7 @@ public void canCreateAndUpdateFunctionAppWithContainerSize() { Assertions.assertEquals(512, functionApp1.containerSize()); Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); - functionApp1.update() - .withContainerSize(320) - .apply(); + functionApp1.update().withContainerSize(320).apply(); functionApp1.refresh(); @@ -481,9 +443,7 @@ public void canCreateAndUpdateFunctionAppWithContainerSize() { Assertions.assertEquals(256, functionDeploymentSlot.containerSize()); - functionDeploymentSlot.update() - .withContainerSize(128) - .apply(); + functionDeploymentSlot.update().withContainerSize(128).apply(); functionDeploymentSlot.refresh(); @@ -495,19 +455,15 @@ public void canCreateAndUpdateFunctionAppOnACA() { rgName2 = null; Region region = Region.US_EAST; - ResourceGroup resourceGroup = appServiceManager.resourceManager() - .resourceGroups() - .define(rgName1) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = appServiceManager.resourceManager().resourceGroups().define(rgName1).withRegion(region).create(); webappName1 = generateRandomResourceName("java-function-", 20); // function app not created, get will throw exception - Assertions.assertThrows(ManagementException.class, () -> appServiceManager - .serviceClient().getWebApps().getByResourceGroup(rgName1, webappName1)); + Assertions.assertThrows(ManagementException.class, + () -> appServiceManager.serviceClient().getWebApps().getByResourceGroup(rgName1, webappName1)); String managedEnvironmentId = createAcaEnvironment(region, resourceGroup); - appServiceManager - .functionApps() + appServiceManager.functionApps() .define(webappName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -517,7 +473,7 @@ public void canCreateAndUpdateFunctionAppOnACA() { .withPublicDockerHubImage("mcr.microsoft.com/azure-functions/dotnet7-quickstart-demo:1.0") // backend has bug, it returns Array instead of Object: // https://github.com/Azure/azure-rest-api-specs/issues/27176 -// .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) + // .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) .withAppSetting("customSetting", "mySettingValue") .create(); @@ -529,23 +485,19 @@ public void canCreateAndUpdateFunctionAppOnACA() { Assertions.assertNotNull(functionApp.getAppSettings()); Assertions.assertEquals("mySettingValue", functionApp.getAppSettings().get("customSetting").value()); -// Assertions.assertEquals("connectionValue", functionApp.getConnectionStrings().get("connectionName").value()); + // Assertions.assertEquals("connectionValue", functionApp.getConnectionStrings().get("connectionName").value()); functionApp.update() .withPublicDockerHubImage("mcr.microsoft.com/azure-functions/dotnet7-quickstart-demo:1.0") .apply(); - functionApp.update() - .withMaxReplicas(15) - .apply(); + functionApp.update().withMaxReplicas(15).apply(); // only changed max, min not changed Assertions.assertEquals(15, functionApp.maxReplicas()); Assertions.assertEquals(3, functionApp.minReplicas()); - functionApp.update() - .withMinReplicas(5) - .apply(); + functionApp.update().withMinReplicas(5).apply(); // only changed min, max not changed Assertions.assertEquals(15, functionApp.maxReplicas()); @@ -556,21 +508,17 @@ public void canCreateAndUpdateFunctionAppOnACA() { @Disabled("need private registry image") public void canCreateAndUpdateFunctionAppOnAcaWithPrivateRegistryImage() { Region region = Region.US_EAST; - ResourceGroup resourceGroup = appServiceManager.resourceManager() - .resourceGroups() - .define(rgName1) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = appServiceManager.resourceManager().resourceGroups().define(rgName1).withRegion(region).create(); webappName1 = generateRandomResourceName("java-function-", 20); // function app not created, get will throw exception - Assertions.assertThrows(ManagementException.class, () -> appServiceManager - .serviceClient().getWebApps().getByResourceGroup(rgName1, webappName1)); + Assertions.assertThrows(ManagementException.class, + () -> appServiceManager.serviceClient().getWebApps().getByResourceGroup(rgName1, webappName1)); String password = "PASSWORD"; String managedEnvironmentId = createAcaEnvironment(region, resourceGroup); - appServiceManager - .functionApps() + appServiceManager.functionApps() .define(webappName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -601,7 +549,8 @@ public void canCreateAndUpdateFunctionAppOnAcaWithPrivateRegistryImage() { Assertions.assertEquals(15, functionApp.maxReplicas()); Assertions.assertEquals(3, functionApp.minReplicas()); - Assertions.assertNotEquals(connectionString, functionApp.getAppSettings().get(KEY_AZURE_WEB_JOBS_STORAGE).value()); + Assertions.assertNotEquals(connectionString, + functionApp.getAppSettings().get(KEY_AZURE_WEB_JOBS_STORAGE).value()); // when serverUrl has no protocol(https), use imageAndTag directly functionApp.update() @@ -651,23 +600,17 @@ private static Map assertLinuxJava(FunctionApp functionApp, } private static Map assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, - String runtimeVersion) { + 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(Arrays.asList(functionApp.innerModel().kind().split(Pattern.quote(","))) + .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map 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, + 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; diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionDeploymentSlotsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionDeploymentSlotsTests.java index 1ca3c5704caf6..1e6a42c92e0ac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionDeploymentSlotsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/FunctionDeploymentSlotsTests.java @@ -44,19 +44,17 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @Test public void canCRUDFunctionSwapSlots() throws Exception { // Create with consumption - FunctionApp functionApp1 = - appServiceManager - .functionApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewAppServicePlan(PricingTier.STANDARD_S1) - .withAppSetting("appkey", "appvalue") - .withStickyAppSetting("stickykey", "stickyvalue") - .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) - .withStickyConnectionString("stickyName", "stickyValue", ConnectionStringType.CUSTOM) - .withPythonVersion(PythonVersion.PYTHON_27) - .create(); + FunctionApp functionApp1 = appServiceManager.functionApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewAppServicePlan(PricingTier.STANDARD_S1) + .withAppSetting("appkey", "appvalue") + .withStickyAppSetting("stickykey", "stickyvalue") + .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) + .withStickyConnectionString("stickyName", "stickyValue", ConnectionStringType.CUSTOM) + .withPythonVersion(PythonVersion.PYTHON_27) + .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); @@ -70,25 +68,23 @@ public void canCRUDFunctionSwapSlots() throws Exception { */ // Create a deployment slot with empty config - FunctionDeploymentSlot slot1 = - functionApp1 - .deploymentSlots() - .define(slotName1) - .withBrandNewConfiguration() - .withPythonVersion(PythonVersion.PYTHON_34) - .create(); + FunctionDeploymentSlot slot1 = functionApp1.deploymentSlots() + .define(slotName1) + .withBrandNewConfiguration() + .withPythonVersion(PythonVersion.PYTHON_34) + .create(); Assertions.assertNotNull(slot1); Assertions.assertEquals(PythonVersion.PYTHON_34, slot1.pythonVersion()); -// Map appSettingMap = slot1.getAppSettings(); -// Assertions.assertFalse(appSettingMap.containsKey("appkey")); -// Assertions.assertFalse(appSettingMap.containsKey("stickykey")); -// Map connectionStringMap = slot1.getConnectionStrings(); -// Assertions.assertFalse(connectionStringMap.containsKey("connectionName")); -// Assertions.assertFalse(connectionStringMap.containsKey("stickyName")); + // Map appSettingMap = slot1.getAppSettings(); + // Assertions.assertFalse(appSettingMap.containsKey("appkey")); + // Assertions.assertFalse(appSettingMap.containsKey("stickykey")); + // Map connectionStringMap = slot1.getConnectionStrings(); + // Assertions.assertFalse(connectionStringMap.containsKey("connectionName")); + // Assertions.assertFalse(connectionStringMap.containsKey("stickyName")); // Create a deployment slot with web app's config - FunctionDeploymentSlot slot2 = - functionApp1.deploymentSlots().define(slotName2).withConfigurationFromParent().create(); + FunctionDeploymentSlot slot2 + = functionApp1.deploymentSlots().define(slotName2).withConfigurationFromParent().create(); Assertions.assertNotNull(slot2); Assertions.assertEquals(PythonVersion.PYTHON_27, slot2.pythonVersion()); Map appSettingMap = slot2.getAppSettings(); @@ -103,8 +99,7 @@ public void canCRUDFunctionSwapSlots() throws Exception { Assertions.assertEquals(true, connectionStringMap.get("stickyName").sticky()); // Update deployment slot - slot2 - .update() + slot2.update() .withPythonVersion(PythonVersion.PYTHON_34) .withAppSetting("slot2key", "slot2value") .withStickyAppSetting("sticky2key", "sticky2value") @@ -115,17 +110,14 @@ public void canCRUDFunctionSwapSlots() throws Exception { Assertions.assertEquals("slot2value", appSettingMap.get("slot2key").value()); // Create 3rd deployment slot with configuration from slot 2 - FunctionDeploymentSlot slot3 = - functionApp1.deploymentSlots().define(slotName3).withConfigurationFromDeploymentSlot(slot2).create(); + FunctionDeploymentSlot slot3 + = functionApp1.deploymentSlots().define(slotName3).withConfigurationFromDeploymentSlot(slot2).create(); Assertions.assertNotNull(slot3); Assertions.assertEquals(PythonVersion.PYTHON_34, slot3.pythonVersion()); appSettingMap = slot3.getAppSettings(); Assertions.assertEquals("slot2value", appSettingMap.get("slot2key").value()); - slot3 - .update() - .withPythonVersion(PythonVersion.PYTHON_27) - .apply(); + slot3.update().withPythonVersion(PythonVersion.PYTHON_27).apply(); // Get FunctionDeploymentSlot deploymentSlot = functionApp1.deploymentSlots().getByName(slotName3); @@ -148,12 +140,13 @@ public void canCRUDFunctionSwapSlots() throws Exception { Assertions.assertEquals("stickyvalue", slot3AppSettings.get("stickykey").value()); } - private static final String FUNCTION_APP_PACKAGE_URL = - "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; + private static final String FUNCTION_APP_PACKAGE_URL + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; @Test public void canCRUDFunctionSlots() { - FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) + FunctionApp functionApp1 = appServiceManager.functionApps() + .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) @@ -163,18 +156,16 @@ public void canCRUDFunctionSlots() { .create(); Assertions.assertNotNull(functionApp1); - FunctionDeploymentSlot slot1 = functionApp1.deploymentSlots().define("slot1") - .withConfigurationFromParent() - .create(); + FunctionDeploymentSlot slot1 + = functionApp1.deploymentSlots().define("slot1").withConfigurationFromParent().create(); - slot1.update() - .withPublicDockerHubImage("wordpress") - .apply(); + slot1.update().withPublicDockerHubImage("wordpress").apply(); } @Test public void canCreateAndUpdatePublicNetworkAccess() { - FunctionApp functionApp = appServiceManager.functionApps().define(webappName1) + FunctionApp functionApp = appServiceManager.functionApps() + .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/HostnameSslTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/HostnameSslTests.java index 0b46229c24623..2cdd61f1280bc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/HostnameSslTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/HostnameSslTests.java @@ -33,8 +33,7 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @Disabled("Need a domain and a certificate") public void canBindHostnameAndSsl() throws Exception { // hostname binding - appServiceManager - .webApps() + appServiceManager.webApps() .define(webappName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) @@ -64,31 +63,30 @@ public void canBindHostnameAndSsl() throws Exception { Assertions.assertNotNull(response.getValue()); } // SSL binding - webApp - .update() + webApp.update() .defineSslBinding() .forHostname(webappName + "." + domainName) .withExistingAppServiceCertificateOrder(certificateOrder) .withSniBasedSsl() .attach() .apply(); -// if (!isPlaybackMode()) { -// Response response = null; -// int retryCount = 3; -// while (response == null && retryCount > 0) { -// // TODO (weidxu) this probably not work after switch from okhttp to azure-core -// try { -// response = curl("https://" + webappName + "." + domainName); -// } catch (SSLPeerUnverifiedException e) { -// retryCount--; -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// } -// } -// if (retryCount == 0) { -// Assertions.fail(); -// } -// Assertions.assertEquals(200, response.getStatusCode()); -// Assertions.assertNotNull(response.getValue()); -// } + // if (!isPlaybackMode()) { + // Response response = null; + // int retryCount = 3; + // while (response == null && retryCount > 0) { + // // TODO (weidxu) this probably not work after switch from okhttp to azure-core + // try { + // response = curl("https://" + webappName + "." + domainName); + // } catch (SSLPeerUnverifiedException e) { + // retryCount--; + // ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + // } + // } + // if (retryCount == 0) { + // Assertions.fail(); + // } + // Assertions.assertEquals(200, response.getStatusCode()); + // Assertions.assertNotNull(response.getValue()); + // } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/LinuxWebAppsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/LinuxWebAppsTests.java index d57b8481cd78d..d930d9496253d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/LinuxWebAppsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/LinuxWebAppsTests.java @@ -47,15 +47,13 @@ protected void cleanUpResources() { @Test public void canCRUDLinuxWebApp() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewLinuxPlan(PricingTier.BASIC_B1) - .withPublicDockerHubImage("wordpress") - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewLinuxPlan(PricingTier.BASIC_B1) + .withPublicDockerHubImage("wordpress") + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -66,15 +64,13 @@ public void canCRUDLinuxWebApp() throws Exception { Assertions.assertEquals(OperatingSystem.LINUX, webApp1.operatingSystem()); // Create in a new group with existing app service plan - WebApp webApp2 = - appServiceManager - .webApps() - .define(webappName2) - .withExistingLinuxPlan(plan1) - .withNewResourceGroup(rgName2) - .withPublicDockerHubImage("tomcat") - .withContainerLoggingEnabled() - .create(); + WebApp webApp2 = appServiceManager.webApps() + .define(webappName2) + .withExistingLinuxPlan(plan1) + .withNewResourceGroup(rgName2) + .withPublicDockerHubImage("tomcat") + .withContainerLoggingEnabled() + .create(); Assertions.assertNotNull(webApp2); Assertions.assertEquals(Region.US_WEST, webApp2.region()); Assertions.assertEquals(OperatingSystem.LINUX, webApp2.operatingSystem()); @@ -121,15 +117,13 @@ public void canCRUDLinuxWebApp() throws Exception { public void canCRUDLinuxJava11WebApp() throws Exception { rgName2 = null; // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewLinuxPlan(PricingTier.BASIC_B1) - .withBuiltInImage(RuntimeStack.TOMCAT_9_0_JAVA11) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewLinuxPlan(PricingTier.BASIC_B1) + .withBuiltInImage(RuntimeStack.TOMCAT_9_0_JAVA11) + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -143,15 +137,13 @@ public void canCRUDLinuxJava11WebApp() throws Exception { @Test public void canCRUDLinuxJava17WebApp() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewLinuxPlan(PricingTier.BASIC_B1) - .withBuiltInImage(RuntimeStack.TOMCAT_10_0_JAVA17) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewLinuxPlan(PricingTier.BASIC_B1) + .withBuiltInImage(RuntimeStack.TOMCAT_10_0_JAVA17) + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -160,7 +152,9 @@ public void canCRUDLinuxJava17WebApp() throws Exception { Assertions.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier()); Assertions.assertEquals(OperatingSystem.LINUX, plan1.operatingSystem()); Assertions.assertEquals(OperatingSystem.LINUX, webApp1.operatingSystem()); - Assertions.assertEquals(String.format("%s|%s", RuntimeStack.TOMCAT_10_0_JAVA17.stack(), RuntimeStack.TOMCAT_10_0_JAVA17.version()), webApp1.linuxFxVersion()); + Assertions.assertEquals( + String.format("%s|%s", RuntimeStack.TOMCAT_10_0_JAVA17.stack(), RuntimeStack.TOMCAT_10_0_JAVA17.version()), + webApp1.linuxFxVersion()); rgName2 = null; } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java index 8b1ac2730fc31..c538120ec16c8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java @@ -58,24 +58,23 @@ public class OneDeployTests extends AppServiceTest { - private static final String HELLOWORLD_JAR_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/helloworld.jar"; + private static final String HELLOWORLD_JAR_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/helloworld.jar"; @Test @DoNotRecord(skipInPlayback = true) public void canDeployZip() { String webAppName1 = generateRandomResourceName("webapp", 10); - WebApp webApp1 = - appServiceManager - .webApps() - .define(webAppName1) - .withRegion(Region.US_WEST3) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_5_NEWEST) - .withHttpsOnly(true) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webAppName1) + .withRegion(Region.US_WEST3) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_5_NEWEST) + .withHttpsOnly(true) + .create(); File zipFile = new File(OneDeployTests.class.getResource("/webapps.zip").getPath()); webApp1.deploy(DeployType.ZIP, zipFile); @@ -92,16 +91,14 @@ public void canDeployZip() { public void canPushDeployJar() throws Exception { String webAppName1 = generateRandomResourceName("webapp", 10); - WebApp webApp1 = - appServiceManager - .webApps() - .define(webAppName1) - .withRegion(Region.US_WEST3) - .withNewResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) - .withHttpsOnly(true) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webAppName1) + .withRegion(Region.US_WEST3) + .withNewResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) + .withHttpsOnly(true) + .create(); // deploy File jarFile = new File("helloworld.jar"); @@ -109,13 +106,13 @@ public void canPushDeployJar() throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(HELLOWORLD_JAR_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); - OutputStream outputStream = new FileOutputStream(jarFile)) { + OutputStream outputStream = new FileOutputStream(jarFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } - KuduDeploymentResult deployResult = - webApp1.pushDeploy(DeployType.JAR, jarFile, new DeployOptions().withTrackDeployment(true)); + KuduDeploymentResult deployResult + = webApp1.pushDeploy(DeployType.JAR, jarFile, new DeployOptions().withTrackDeployment(true)); String deploymentId = deployResult.deploymentId(); Assertions.assertNotNull(deploymentId); @@ -127,13 +124,10 @@ public void canPushDeployJar() throws Exception { // deploy another slot String slotName = generateRandomResourceName("slot", 10); - DeploymentSlot slot2 = webApp1.deploymentSlots() - .define(slotName) - .withConfigurationFromParent() - .create(); + DeploymentSlot slot2 = webApp1.deploymentSlots().define(slotName).withConfigurationFromParent().create(); - KuduDeploymentResult slotDeployResult = - slot2.pushDeploy(DeployType.JAR, jarFile, new DeployOptions().withTrackDeployment(true)); + KuduDeploymentResult slotDeployResult + = slot2.pushDeploy(DeployType.JAR, jarFile, new DeployOptions().withTrackDeployment(true)); String slotDeploymentId = slotDeployResult.deploymentId(); Assertions.assertNotNull(slotDeploymentId); @@ -144,7 +138,7 @@ public void canPushDeployJar() throws Exception { // test uses storage account key and connection string to configure the function app @DoNotRecord(skipInPlayback = true) @ParameterizedTest - @ValueSource(booleans = {false, true}) + @ValueSource(booleans = { false, true }) public void canDeployFlexConsumptionFunctionApp(boolean pushDeploy) throws FileNotFoundException { final PricingTier flexConsumptionTier = new PricingTier("FlexConsumption", "FC1"); @@ -162,50 +156,50 @@ public void canDeployFlexConsumptionFunctionApp(boolean pushDeploy) throws FileN .withCapacity(1) .create(); - StorageAccount storageAccount = appServiceManager.storageManager().storageAccounts() + StorageAccount storageAccount = appServiceManager.storageManager() + .storageAccounts() .define(storageAccountName) .withRegion(Region.US_WEST3) .withExistingResourceGroup(rgName) .create(); - BlobContainer blobContainer = appServiceManager.storageManager().blobContainers() + BlobContainer blobContainer = appServiceManager.storageManager() + .blobContainers() .defineContainer(containerName) .withExistingStorageAccount(storageAccount) .withPublicAccess(PublicAccess.NONE) .create(); - String connectionString = ResourceManagerUtils - .getStorageConnectionString(storageAccountName, storageAccount.getKeys().get(0).value(), AzureEnvironment.AZURE); + String connectionString = ResourceManagerUtils.getStorageConnectionString(storageAccountName, + storageAccount.getKeys().get(0).value(), AzureEnvironment.AZURE); // create FunctionApp of Flex Consumption Plan - SiteInner site = appServiceManager.webApps() - .manager() - .serviceClient() - .getWebApps() - .createOrUpdate(rgName, functionAppName, new SiteInner().withLocation(Region.US_WEST3.name()) - .withKind("functionapp,linux") - .withHttpsOnly(true) - .withServerFarmId(appServicePlan.id()) - .withSiteConfig(new SiteConfigInner().withAppSettings(Arrays.asList( - new NameValuePair() - .withName("AzureWebJobsStorage") - .withValue(connectionString), - new NameValuePair() - .withName("DEPLOYMENT_STORAGE_CONNECTION_STRING") - .withValue(connectionString)))) - .withFunctionAppConfig(new FunctionAppConfig() - .withDeployment(new FunctionsDeployment().withStorage( - new FunctionsDeploymentStorage() - .withType(FunctionsDeploymentStorageType.BLOB_CONTAINER) - .withValue(storageAccount.endPoints().primary().blob() + containerName) - .withAuthentication(new FunctionsDeploymentStorageAuthentication() - .withType(AuthenticationType.STORAGE_ACCOUNT_CONNECTION_STRING) - .withStorageAccountConnectionStringName("DEPLOYMENT_STORAGE_CONNECTION_STRING")))) - .withRuntime(new FunctionsRuntime().withName(RuntimeName.JAVA).withVersion("11")) - .withScaleAndConcurrency(new FunctionsScaleAndConcurrency() - .withMaximumInstanceCount(100) - .withInstanceMemoryMB(2048))), - com.azure.core.util.Context.NONE); + SiteInner site + = appServiceManager.webApps() + .manager() + .serviceClient() + .getWebApps() + .createOrUpdate(rgName, functionAppName, + new SiteInner().withLocation(Region.US_WEST3.name()) + .withKind("functionapp,linux") + .withHttpsOnly(true) + .withServerFarmId(appServicePlan.id()) + .withSiteConfig(new SiteConfigInner().withAppSettings(Arrays.asList( + new NameValuePair().withName("AzureWebJobsStorage").withValue(connectionString), + new NameValuePair() + .withName("DEPLOYMENT_STORAGE_CONNECTION_STRING") + .withValue(connectionString)))) + .withFunctionAppConfig(new FunctionAppConfig() + .withDeployment(new FunctionsDeployment().withStorage(new FunctionsDeploymentStorage() + .withType(FunctionsDeploymentStorageType.BLOB_CONTAINER) + .withValue(storageAccount.endPoints().primary().blob() + containerName) + .withAuthentication(new FunctionsDeploymentStorageAuthentication() + .withType(AuthenticationType.STORAGE_ACCOUNT_CONNECTION_STRING) + .withStorageAccountConnectionStringName("DEPLOYMENT_STORAGE_CONNECTION_STRING")))) + .withRuntime(new FunctionsRuntime().withName(RuntimeName.JAVA).withVersion("11")) + .withScaleAndConcurrency(new FunctionsScaleAndConcurrency().withMaximumInstanceCount(100) + .withInstanceMemoryMB(2048))), + com.azure.core.util.Context.NONE); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName, functionAppName); @@ -233,22 +227,20 @@ public void canDeployFlexConsumptionFunctionApp(boolean pushDeploy) throws FileN @DoNotRecord(skipInPlayback = true) @ParameterizedTest - @ValueSource(booleans = {false, true}) + @ValueSource(booleans = { false, true }) public void canDeployFunctionApp(boolean pushDeploy) { String functionAppName = generateRandomResourceName("functionapp", 20); - FunctionApp functionApp = - appServiceManager - .functionApps() - .define(functionAppName) - .withRegion(Region.US_WEST2) - .withNewResourceGroup(rgName) - // zipDeploy does not work for LinuxConsumptionPlan - // Use "WEBSITE_RUN_FROM_PACKAGE" in AppSettings for LinuxConsumptionPlan - .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) - .withBuiltInImage(FunctionRuntimeStack.JAVA_11) - .withHttpsOnly(true) - .create(); + FunctionApp functionApp = appServiceManager.functionApps() + .define(functionAppName) + .withRegion(Region.US_WEST2) + .withNewResourceGroup(rgName) + // zipDeploy does not work for LinuxConsumptionPlan + // Use "WEBSITE_RUN_FROM_PACKAGE" in AppSettings for LinuxConsumptionPlan + .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) + .withBuiltInImage(FunctionRuntimeStack.JAVA_11) + .withHttpsOnly(true) + .create(); File zipFile = new File(OneDeployTests.class.getResource("/java-functions.zip").getPath()); // test deploy (currently it would call "zipDeploy", as one deploy is not supported for non-Flex consumption plan) @@ -270,10 +262,8 @@ public void canDeployFunctionApp(boolean pushDeploy) { } String slotName = generateRandomResourceName("slot", 10); - FunctionDeploymentSlot slot = functionApp.deploymentSlots() - .define(slotName) - .withConfigurationFromParent() - .create(); + FunctionDeploymentSlot slot + = functionApp.deploymentSlots().define(slotName).withConfigurationFromParent().create(); if (!isPlaybackMode()) { if (pushDeploy) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/SourceControlTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/SourceControlTests.java index c279ce3dac03a..9571d29761ded 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/SourceControlTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/SourceControlTests.java @@ -25,18 +25,16 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @Test public void canDeploySourceControl() throws Exception { // Create web app - WebApp webApp = - appServiceManager - .webApps() - .define(webappName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") - .withBranch("master") - .attach() - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); Assertions.assertNotNull(webApp); if (!isPlaybackMode()) { Response response = curl("http://" + webappName + "." + "azurewebsites.net"); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WarDeployTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WarDeployTests.java index 4f0d05dd81b5e..9ba0bbc5f4010 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WarDeployTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WarDeployTests.java @@ -40,16 +40,14 @@ public void canDeployWar() throws Exception { // https://api.travis-ci.org/v3/job/427936160/log.txt // // Create web app - WebApp webApp = - appServiceManager - .webApps() - .define(webappName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_9_0_NEWEST) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_9_0_NEWEST) + .create(); Assertions.assertNotNull(webApp); webApp.warDeploy(warFile); @@ -69,16 +67,14 @@ public void canDeployWar() throws Exception { @Test public void canDeployMultipleWars() throws Exception { // Create web app - WebApp webApp = - appServiceManager - .webApps() - .define(webappName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_9_0_NEWEST) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_9_0_NEWEST) + .create(); Assertions.assertNotNull(webApp); if (!isPlaybackMode()) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppConfigTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppConfigTests.java index 8d53db34808fe..0337a7582ba58 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppConfigTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppConfigTests.java @@ -35,8 +35,7 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @Test public void canCRUDWebAppConfig() throws Exception { // Create with new app service plan - appServiceManager - .webApps() + appServiceManager.webApps() .define(webappName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) @@ -78,8 +77,7 @@ public void canCRUDWebAppConfig() throws Exception { Assertions.assertEquals(true, appSettingMap.get("stickykey").sticky()); // Connection strings - webApp - .update() + webApp.update() .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) .withStickyConnectionString("stickyName", "stickyValue", ConnectionStringType.CUSTOM) .apply(); @@ -114,8 +112,7 @@ public void canCRUDWebAppConfig() throws Exception { @Test public void canCRUDWebAppConfigJava11() throws Exception { // Create with new app service plan - appServiceManager - .webApps() + appServiceManager.webApps() .define(webappName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) @@ -155,8 +152,7 @@ public void canCRUDWebAppConfigJava11() throws Exception { Assertions.assertEquals(true, appSettingMap.get("stickykey").sticky()); // Connection strings - webApp - .update() + webApp.update() .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM) .withStickyConnectionString("stickyName", "stickyValue", ConnectionStringType.CUSTOM) .apply(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsMsiTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsMsiTests.java index 1c386cae98eef..6fa9ba8498574 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsMsiTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsMsiTests.java @@ -53,19 +53,17 @@ protected void cleanUpResources() { @Test public void canCRUDWebAppWithMsi() throws Exception { // Create with new app service plan - WebApp webApp = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .create(); Assertions.assertNotNull(webApp); Assertions.assertEquals(Region.US_WEST, webApp.region()); AppServicePlan plan = appServiceManager.appServicePlans().getById(webApp.appServicePlanId()); @@ -98,50 +96,44 @@ public void canCRUDWebAppWithUserAssignedMsi() throws Exception { // Prepare a definition for yet-to-be-created resource group // - Creatable creatableRG = - resourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST); + Creatable creatableRG + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST); // Create an "User Assigned (External) MSI" residing in the above RG and assign reader access to the virtual // network // - final Identity createdIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(creatableRG) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .create(); + final Identity createdIdentity = msiManager.identities() + .define(identityName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(creatableRG) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName2) - .withRegion(Region.US_WEST) - .withNewResourceGroup(creatableRG) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName2) + .withRegion(Region.US_WEST) + .withNewResourceGroup(creatableRG) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create with new app service plan - WebApp webApp = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .withUserAssignedManagedServiceIdentity() - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .withUserAssignedManagedServiceIdentity() + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .create(); Assertions.assertNotNull(webApp); Assertions.assertEquals(Region.US_WEST, webApp.region()); AppServicePlan plan = appServiceManager.appServicePlans().getById(webApp.appServicePlanId()); @@ -171,22 +163,22 @@ public void canCRUDWebAppWithUserAssignedMsi() throws Exception { } } -// private static void enableFtps(WebApp webApp) { -// webApp.manager().resourceManager().genericResources().define("ftp") -// .withRegion(webApp.regionName()) -// .withExistingResourceGroup(webApp.resourceGroupName()) -// .withResourceType("basicPublishingCredentialsPolicies") -// .withProviderNamespace("Microsoft.Web") -// .withoutPlan() -// .withParentResourcePath("sites/" + webApp.name()) -// .withApiVersion("2018-11-01") -// .withProperties(new CsmPublishingCredentialsPoliciesEntityProperties().withAllow(true)) -// .create(); -// -// webApp.update() -// .withFtpsState(FtpsState.FTPS_ONLY) -// .apply(); -// } + // private static void enableFtps(WebApp webApp) { + // webApp.manager().resourceManager().genericResources().define("ftp") + // .withRegion(webApp.regionName()) + // .withExistingResourceGroup(webApp.resourceGroupName()) + // .withResourceType("basicPublishingCredentialsPolicies") + // .withProviderNamespace("Microsoft.Web") + // .withoutPlan() + // .withParentResourcePath("sites/" + webApp.name()) + // .withApiVersion("2018-11-01") + // .withProperties(new CsmPublishingCredentialsPoliciesEntityProperties().withAllow(true)) + // .create(); + // + // webApp.update() + // .withFtpsState(FtpsState.FTPS_ONLY) + // .apply(); + // } private static boolean setContainsValue(Set stringSet, String value) { boolean found = false; diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsTests.java index 77b2abbaff1fc..9d660167d8dfa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsTests.java @@ -56,15 +56,13 @@ protected void cleanUpResources() { @Test public void canCRUDWebApp() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -74,13 +72,11 @@ public void canCRUDWebApp() throws Exception { Assertions.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier()); // Create in a new group with existing app service plan - WebApp webApp2 = - appServiceManager - .webApps() - .define(webappName2) - .withExistingWindowsPlan(plan1) - .withNewResourceGroup(rgName2) - .create(); + WebApp webApp2 = appServiceManager.webApps() + .define(webappName2) + .withExistingWindowsPlan(plan1) + .withNewResourceGroup(rgName2) + .create(); Assertions.assertNotNull(webApp2); Assertions.assertEquals(Region.US_WEST, webApp1.region()); @@ -97,8 +93,7 @@ public void canCRUDWebApp() throws Exception { Assertions.assertEquals(1, TestUtilities.getSize(webApps)); // Update - webApp1 - .update() + webApp1.update() .withNewAppServicePlan(PricingTier.STANDARD_S2) .withRuntimeStack(WebAppRuntimeStack.NETCORE) .apply(); @@ -106,60 +101,49 @@ public void canCRUDWebApp() throws Exception { Assertions.assertNotNull(plan2); Assertions.assertEquals(Region.US_WEST, plan2.region()); Assertions.assertEquals(PricingTier.STANDARD_S2, plan2.pricingTier()); - Assertions - .assertEquals( - WebAppRuntimeStack.NETCORE.runtime(), - webApp1 - .manager() - .serviceClient() - .getWebApps() - .listMetadata(webApp1.resourceGroupName(), webApp1.name()) - .properties() - .get("CURRENT_STACK")); - - WebApp webApp3 = - appServiceManager - .webApps() - .define(webappName3) - .withExistingWindowsPlan(plan1) - .withExistingResourceGroup(rgName2) - .withRuntimeStack(WebAppRuntimeStack.NET) - .withNetFrameworkVersion(NetFrameworkVersion.V4_6) - .create(); - Assertions - .assertEquals( - WebAppRuntimeStack.NET.runtime(), - webApp3 - .manager() - .serviceClient() - .getWebApps() - .listMetadata(webApp3.resourceGroupName(), webApp3.name()) - .properties() - .get("CURRENT_STACK")); + Assertions.assertEquals(WebAppRuntimeStack.NETCORE.runtime(), + webApp1.manager() + .serviceClient() + .getWebApps() + .listMetadata(webApp1.resourceGroupName(), webApp1.name()) + .properties() + .get("CURRENT_STACK")); + + WebApp webApp3 = appServiceManager.webApps() + .define(webappName3) + .withExistingWindowsPlan(plan1) + .withExistingResourceGroup(rgName2) + .withRuntimeStack(WebAppRuntimeStack.NET) + .withNetFrameworkVersion(NetFrameworkVersion.V4_6) + .create(); + Assertions.assertEquals(WebAppRuntimeStack.NET.runtime(), + webApp3.manager() + .serviceClient() + .getWebApps() + .listMetadata(webApp3.resourceGroupName(), webApp3.name()) + .properties() + .get("CURRENT_STACK")); } @Test public void canListWebApp() throws Exception { rgName2 = null; - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .withHttpsOnly(true) - .defineDiagnosticLogsConfiguration() - .withApplicationLogging() - .withLogLevel(LogLevel.VERBOSE) - .withApplicationLogsStoredOnFileSystem() - .attach() - .create(); - - PagedIterable webApps = appServiceManager.webApps() - .listByResourceGroup(rgName1); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .withHttpsOnly(true) + .defineDiagnosticLogsConfiguration() + .withApplicationLogging() + .withLogLevel(LogLevel.VERBOSE) + .withApplicationLogsStoredOnFileSystem() + .attach() + .create(); + + PagedIterable webApps = appServiceManager.webApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(webApps)); WebAppBasic webAppBasic1 = webApps.iterator().next(); @@ -180,7 +164,8 @@ public void canListWebApp() throws Exception { public void canCRUDWebAppWithContainer() { rgName2 = null; - AppServicePlan plan1 = appServiceManager.appServicePlans().define(appServicePlanName1) + AppServicePlan plan1 = appServiceManager.appServicePlans() + .define(appServicePlanName1) .withRegion(Region.US_EAST) // many other regions does not have quota for PREMIUM_P1V3 .withNewResourceGroup(rgName1) .withPricingTier(PricingTier.PREMIUM_P1V3) @@ -189,7 +174,8 @@ public void canCRUDWebAppWithContainer() { final String imageAndTag = "mcr.microsoft.com/azure-app-service/samples/aspnethelloworld:latest"; - WebApp webApp1 = appServiceManager.webApps().define(webappName1) + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) .withExistingWindowsPlan(plan1) .withExistingResourceGroup(rgName1) .withPublicDockerHubImage(imageAndTag) @@ -231,42 +217,37 @@ public void canListWebAppAndFunctionApp() { @Test public void canUpdateIpRestriction() { - WebApp webApp2 = - appServiceManager - .webApps() - .define(webappName2) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName2) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .create(); + WebApp webApp2 = appServiceManager.webApps() + .define(webappName2) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName2) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .create(); webApp2.refresh(); Assertions.assertEquals(1, webApp2.ipSecurityRules().size()); Assertions.assertEquals("Allow", webApp2.ipSecurityRules().iterator().next().action()); Assertions.assertEquals("Any", webApp2.ipSecurityRules().iterator().next().ipAddress()); - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .withAccessFromIpAddressRange("167.220.0.0/16", 300) - .withAccessFromIpAddress("167.220.0.1", 400) - .withAccessRule(new IpSecurityRestriction() - .withAction("Allow") - .withPriority(500) - .withTag(IpFilterTag.SERVICE_TAG) - .withIpAddress("AzureFrontDoor.Backend")) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .withAccessFromIpAddressRange("167.220.0.0/16", 300) + .withAccessFromIpAddress("167.220.0.1", 400) + .withAccessRule(new IpSecurityRestriction().withAction("Allow") + .withPriority(500) + .withTag(IpFilterTag.SERVICE_TAG) + .withIpAddress("AzureFrontDoor.Backend")) + .create(); Assertions.assertEquals(3 + 1, webApp1.ipSecurityRules().size()); - Assertions.assertTrue(webApp1.ipSecurityRules().stream().anyMatch(r -> "Deny".equals(r.action()) && "Any".equals(r.ipAddress()))); + Assertions.assertTrue( + webApp1.ipSecurityRules().stream().anyMatch(r -> "Deny".equals(r.action()) && "Any".equals(r.ipAddress()))); - IpSecurityRestriction serviceTagRule = webApp1.ipSecurityRules().stream() - .filter(r -> r.tag() == IpFilterTag.SERVICE_TAG) - .findFirst().get(); + IpSecurityRestriction serviceTagRule + = webApp1.ipSecurityRules().stream().filter(r -> r.tag() == IpFilterTag.SERVICE_TAG).findFirst().get(); webApp1.update() .withoutIpAddressAccess("167.220.0.1") @@ -277,9 +258,7 @@ public void canUpdateIpRestriction() { Assertions.assertEquals(1 + 1, webApp1.ipSecurityRules().size()); - webApp1.update() - .withAccessFromAllNetworks() - .apply(); + webApp1.update().withAccessFromAllNetworks().apply(); Assertions.assertEquals(1, webApp1.ipSecurityRules().size()); Assertions.assertEquals("Allow", webApp1.ipSecurityRules().iterator().next().action()); @@ -290,16 +269,14 @@ public void canUpdateIpRestriction() { public void canCreateWebAppWithDisablePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName1).withRegion(Region.US_WEST).create(); resourceManager.resourceGroups().define(rgName2).withRegion(Region.US_WEST).create(); - WebApp webApp = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName1) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .disablePublicNetworkAccess() - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName1) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .disablePublicNetworkAccess() + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .create(); webApp.refresh(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, webApp.publicNetworkAccess()); } @@ -308,15 +285,13 @@ public void canCreateWebAppWithDisablePublicNetworkAccess() { public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName1).withRegion(Region.US_WEST).create(); resourceManager.resourceGroups().define(rgName2).withRegion(Region.US_WEST).create(); - WebApp webApp = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName1) - .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) - .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) - .create(); + WebApp webApp = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName1) + .withNewWindowsPlan(appServicePlanName1, PricingTier.BASIC_B1) + .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) + .create(); webApp.update().disablePublicNetworkAccess().apply(); webApp.refresh(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsWebDeployTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsWebDeployTests.java index a6380cf20f799..f3b1de5592c16 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsWebDeployTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/WebAppsWebDeployTests.java @@ -39,16 +39,14 @@ protected void cleanUpResources() { @Test public void canDeployWarFile() throws Exception { // Create with new app service plan - WebApp webApp1 = - appServiceManager - .webApps() - .define(webappName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName1) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .create(); + WebApp webApp1 = appServiceManager.webApps() + .define(webappName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName1) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .create(); Assertions.assertNotNull(webApp1); Assertions.assertEquals(Region.US_WEST, webApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); @@ -56,13 +54,11 @@ public void canDeployWarFile() throws Exception { Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier()); - WebDeployment deployment = - webApp1 - .deploy() - .withPackageUri( - "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/webapps.zip") - .withExistingDeploymentsDeleted(true) - .execute(); + WebDeployment deployment = webApp1.deploy() + .withPackageUri( + "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/webapps.zip") + .withExistingDeploymentsDeleted(true) + .execute(); Assertions.assertNotNull(deployment); if (!isPlaybackMode()) { diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/ZipDeployTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/ZipDeployTests.java index 05ce572d69911..1e522c28952a1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/ZipDeployTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/ZipDeployTests.java @@ -32,13 +32,11 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile @DoNotRecord(skipInPlayback = true) public void canZipDeployFunction() { // Create function app - FunctionApp functionApp = - appServiceManager - .functionApps() - .define(webappName4) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .create(); + FunctionApp functionApp = appServiceManager.functionApps() + .define(webappName4) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .create(); Assertions.assertNotNull(functionApp); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); functionApp.zipDeploy(new File(FunctionAppsTests.class.getResource("/square-function-app.zip").getPath())); @@ -47,15 +45,12 @@ public void canZipDeployFunction() { Assertions.assertNotNull(response); Assertions.assertEquals("625", response); - PagedIterable envelopes = - appServiceManager.functionApps().listFunctions(rgName, functionApp.name()); + PagedIterable envelopes + = appServiceManager.functionApps().listFunctions(rgName, functionApp.name()); Assertions.assertNotNull(envelopes); Assertions.assertEquals(1, TestUtilities.getSize(envelopes)); - Assertions - .assertEquals( - envelopes.iterator().next().href(), - "https://" + webappName4 + ".scm.azurewebsites.net/api/functions/square"); - + Assertions.assertEquals(envelopes.iterator().next().href(), + "https://" + webappName4 + ".scm.azurewebsites.net/api/functions/square"); Assertions.assertNull(functionApp.listFunctionKeys("square").get("my-key")); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/KuduTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/KuduTests.java index 98809fd61ceee..b692b9bc69663 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/KuduTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/KuduTests.java @@ -15,8 +15,8 @@ public class KuduTests { - private static final String LOG_STREAM = - "2020-02-25T07:19:40 Welcome, you are now connected to log-streaming service. The default timeout is 2 hours." + private static final String LOG_STREAM + = "2020-02-25T07:19:40 Welcome, you are now connected to log-streaming service. The default timeout is 2 hours." + " Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds).\n" + "2020-02-25T07:20:40 No new trace in the past 1 min(s).\n" + "2020-02-25T07:21:40 No new trace in the past 2 min(s).\n" @@ -35,8 +35,7 @@ public class KuduTests { + " Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/79.0.3945.130+Safari/537.36" + " JSESSIONID=3080AD1F0E745FFB80CE3DC1039A820F;+ARRAffinity=9c45f76fcf2ed72fc0f79776f0387a38a4f53d6739f8aa06a66a120a04466857" + " http://wa1-weidxu.azurewebsites.net/coffeeshop/Content/Site.css wa1-weidxu.azurewebsites.net 404 0 0" - + " 1405 1099 15\n" - + "2020-02-25 07:23:07 WA1-WEIDXU GET /coffeeshop/Images/brand.png" + + " 1405 1099 15\n" + "2020-02-25 07:23:07 WA1-WEIDXU GET /coffeeshop/Images/brand.png" + " X-ARR-LOG-ID=200dda67-062b-445f-9501-03fd716b3b49 80 - 13.64.92.44" + " Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/79.0.3945.130+Safari/537.36" + " JSESSIONID=3080AD1F0E745FFB80CE3DC1039A820F;+ARRAffinity=9c45f76fcf2ed72fc0f79776f0387a38a4f53d6739f8aa06a66a120a04466857" diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/UtilsTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/UtilsTests.java index db33a95985f13..59dfa297726d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/UtilsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/implementation/UtilsTests.java @@ -21,70 +21,40 @@ public class UtilsTests { @Test public void testWebAppPrivateRegistryImage() throws Exception { // completion - Assertions - .assertEquals( - "weidxuregistry.azurecr.io/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "weidxuregistry.azurecr.io/az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("weidxuregistry.azurecr.io/az-func-java:v1", Utils.smartCompletionPrivateRegistryImage( + "weidxuregistry.azurecr.io/az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion - Assertions - .assertEquals( - "weidxuregistry.azurecr.io/az-func-java:v1", - Utils.smartCompletionPrivateRegistryImage("az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("weidxuregistry.azurecr.io/az-func-java:v1", + Utils.smartCompletionPrivateRegistryImage("az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion - Assertions - .assertEquals( - "weidxuregistry.azurecr.io/weidxu/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "weidxu/az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("weidxuregistry.azurecr.io/weidxu/az-func-java:v1", + Utils.smartCompletionPrivateRegistryImage("weidxu/az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion - Assertions - .assertEquals( - "weidxuregistry.azurecr.io:5000/weidxu/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "weidxu/az-func-java:v1", "https://weidxuregistry.azurecr.io:5000")); + Assertions.assertEquals("weidxuregistry.azurecr.io:5000/weidxu/az-func-java:v1", Utils + .smartCompletionPrivateRegistryImage("weidxu/az-func-java:v1", "https://weidxuregistry.azurecr.io:5000")); // completion - Assertions - .assertEquals( - "weidxuregistry.azurecr.io/weidxu/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "az-func-java:v1", "https://weidxuregistry.azurecr.io/weidxu")); + Assertions.assertEquals("weidxuregistry.azurecr.io/weidxu/az-func-java:v1", + Utils.smartCompletionPrivateRegistryImage("az-func-java:v1", "https://weidxuregistry.azurecr.io/weidxu")); // completion not happen due to possible host - Assertions - .assertEquals( - "host.name/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "host.name/az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("host.name/az-func-java:v1", Utils + .smartCompletionPrivateRegistryImage("host.name/az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion not happen due to possible port - Assertions - .assertEquals( - "host:port/az-func-java:v1", - Utils - .smartCompletionPrivateRegistryImage( - "host:port/az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("host:port/az-func-java:v1", Utils + .smartCompletionPrivateRegistryImage("host:port/az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion not happen due to no idea what it is - Assertions - .assertEquals( - "/az-func-java:v1", - Utils.smartCompletionPrivateRegistryImage("/az-func-java:v1", "https://weidxuregistry.azurecr.io")); + Assertions.assertEquals("/az-func-java:v1", + Utils.smartCompletionPrivateRegistryImage("/az-func-java:v1", "https://weidxuregistry.azurecr.io")); // completion not happen due to incorrect serviceUrl - Assertions - .assertEquals( - "az-func-java:v1", - Utils.smartCompletionPrivateRegistryImage("az-func-java:v1", "weidxuregistry.azurecr.io")); + Assertions.assertEquals("az-func-java:v1", + Utils.smartCompletionPrivateRegistryImage("az-func-java:v1", "weidxuregistry.azurecr.io")); } @Test @@ -104,21 +74,20 @@ private static void testBase16Encoding(String decoded, String encoded) { @Test public void testBase64Url() { - String encoded = - "eyJuYmYiOjE1ODI2OTM0NTIsImV4cCI6MTU4MjY5Mzc1MiwiaWF0IjoxNTgyNjkzNDUyLCJpc3MiOiJodHRwczovL3dhMS13ZWlkeHUuc2NtLmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiaHR0cHM6Ly93YTEtd2VpZHh1LmF6dXJld2Vic2l0ZXMubmV0L2F6dXJlZnVuY3Rpb25zIn0"; - String decoded = - "{\"nbf\":1582693452,\"exp\":1582693752,\"iat\":1582693452,\"iss\":\"https://wa1-weidxu.scm.azurewebsites.net\",\"aud\":\"https://wa1-weidxu.azurewebsites.net/azurefunctions\"}"; + String encoded + = "eyJuYmYiOjE1ODI2OTM0NTIsImV4cCI6MTU4MjY5Mzc1MiwiaWF0IjoxNTgyNjkzNDUyLCJpc3MiOiJodHRwczovL3dhMS13ZWlkeHUuc2NtLmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiaHR0cHM6Ly93YTEtd2VpZHh1LmF6dXJld2Vic2l0ZXMubmV0L2F6dXJlZnVuY3Rpb25zIn0"; + String decoded + = "{\"nbf\":1582693452,\"exp\":1582693752,\"iat\":1582693452,\"iss\":\"https://wa1-weidxu.scm.azurewebsites.net\",\"aud\":\"https://wa1-weidxu.azurewebsites.net/azurefunctions\"}"; Assertions.assertEquals(decoded, new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8)); } @Test public void canDownloadFile() throws Exception { - HttpPipeline httpPipeline = new HttpPipelineBuilder() - .policies( - new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS) - ) - .build(); + HttpPipeline httpPipeline + = new HttpPipelineBuilder() + .policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)), + new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) + .build(); byte[] content = Utils.downloadFileAsync("https://www.google.com/humans.txt", httpPipeline).block(); String contentString = new String(content); Assertions.assertNotNull(contentString); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml index 62c74fbe406ac..0de0f9414ab8f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml @@ -48,6 +48,7 @@ com.azure.json,com.azure.core.*,*.fluent:,*.fluent*: - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/AuthorizationManager.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/AuthorizationManager.java index 4041709f73eac..159adef60b86b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/AuthorizationManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/AuthorizationManager.java @@ -107,8 +107,7 @@ public interface Configurable extends AzureConfigurable { /** The implementation for Configurable interface. */ private static class ConfigurableImpl extends AzureConfigurableImpl implements Configurable { public AuthorizationManager authenticate(TokenCredential credential, AzureProfile profile) { - return AuthorizationManager - .authenticate(buildHttpPipeline(credential, profile), profile); + return AuthorizationManager.authenticate(buildHttpPipeline(credential, profile), profile); } } @@ -118,17 +117,12 @@ private AuthorizationManager(HttpPipeline httpPipeline, AzureProfile profile) { ? graphEndpoint + DEFAULT_GRAPH_ENDPOINT_SUFFIX : graphEndpoint + "/" + DEFAULT_GRAPH_ENDPOINT_SUFFIX; - this.microsoftGraphClient = - new MicrosoftGraphClientBuilder() - .pipeline(httpPipeline) - .endpoint(graphEndpoint) - .buildClient(); - this.authorizationManagementClient = - new AuthorizationManagementClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .subscriptionId(profile.getSubscriptionId()) - .buildClient(); + this.microsoftGraphClient + = new MicrosoftGraphClientBuilder().pipeline(httpPipeline).endpoint(graphEndpoint).buildClient(); + this.authorizationManagementClient = new AuthorizationManagementClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .buildClient(); this.tenantId = profile.getTenantId(); this.environment = profile.getEnvironment(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationImpl.java index df067a96a0b5f..491383506ab41 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationImpl.java @@ -28,15 +28,10 @@ import java.util.Set; /** Implementation for ServicePrincipal and its parent interfaces. */ -class ActiveDirectoryApplicationImpl - extends CreatableUpdatableImpl< - ActiveDirectoryApplication, - MicrosoftGraphApplicationInner, - ActiveDirectoryApplicationImpl> - implements ActiveDirectoryApplication, - ActiveDirectoryApplication.Definition, - ActiveDirectoryApplication.Update, - HasCredential { +class ActiveDirectoryApplicationImpl extends + CreatableUpdatableImpl + implements ActiveDirectoryApplication, ActiveDirectoryApplication.Definition, ActiveDirectoryApplication.Update, + HasCredential { private AuthorizationManager manager; private final Map cachedPasswordCredentials; private final Map cachedCertificateCredentials; @@ -63,8 +58,7 @@ public boolean isInCreateMode() { public Mono createResourceAsync() { Retry retry = RetryUtils.backoffRetryFor404ResourceNotFound(); - return manager - .serviceClient() + return manager.serviceClient() .getApplicationsApplications() .createApplicationAsync(innerModel()) .map(innerToFluentMap(this)) @@ -74,11 +68,12 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return manager.serviceClient().getApplicationsApplications().updateApplicationAsync(id(), innerModel()) + return manager.serviceClient() + .getApplicationsApplications() + .updateApplicationAsync(id(), innerModel()) .then(submitCredentialAsync(null).doOnComplete(this::postRequest).then(refreshAsync())); } - private void refreshCredentials(MicrosoftGraphApplicationInner inner) { cachedCertificateCredentials.clear(); cachedPasswordCredentials.clear(); @@ -99,18 +94,17 @@ private void refreshCredentials(MicrosoftGraphApplicationInner inner) { } private Flux submitCredentialAsync(Retry retry) { - return Flux.defer(() -> Flux.fromIterable(passwordCredentialToCreate) - .flatMap(passwordCredential -> { - Mono monoAddPassword = - manager().serviceClient().getApplications() - .addPasswordAsync(id(), new ApplicationsAddPasswordRequestBodyInner() - .withPasswordCredential(passwordCredential.innerModel())); - if (retry != null) { - monoAddPassword = monoAddPassword.retryWhen(retry); - } - monoAddPassword = monoAddPassword.doOnNext(passwordCredential::setInner); - return monoAddPassword; - })); + return Flux.defer(() -> Flux.fromIterable(passwordCredentialToCreate).flatMap(passwordCredential -> { + Mono monoAddPassword = manager().serviceClient() + .getApplications() + .addPasswordAsync(id(), new ApplicationsAddPasswordRequestBodyInner() + .withPasswordCredential(passwordCredential.innerModel())); + if (retry != null) { + monoAddPassword = monoAddPassword.retryWhen(retry); + } + monoAddPassword = monoAddPassword.doOnNext(passwordCredential::setInner); + return monoAddPassword; + })); } private void postRequest() { @@ -184,7 +178,9 @@ public Map certificateCredentials() { @Override protected Mono getInnerAsync() { - return manager.serviceClient().getApplicationsApplications().getApplicationAsync(id()) + return manager.serviceClient() + .getApplicationsApplications() + .getApplicationAsync(id()) .doOnSuccess(this::refreshCredentials); } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationsImpl.java index 17a67aad08d41..4e5ba5c5df775 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryApplicationsImpl.java @@ -18,11 +18,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation of Applications and its parent interfaces. */ -public class ActiveDirectoryApplicationsImpl - extends CreatableResourcesImpl< - ActiveDirectoryApplication, - ActiveDirectoryApplicationImpl, - MicrosoftGraphApplicationInner> +public class ActiveDirectoryApplicationsImpl extends + CreatableResourcesImpl implements ActiveDirectoryApplications, HasManager { private AuthorizationManager manager; @@ -55,9 +52,7 @@ public ActiveDirectoryApplicationImpl getById(String id) { @Override public Mono getByIdAsync(String id) { - return inner() - .getApplicationAsync(id) - .map(this::wrapModel); + return inner().getApplicationAsync(id).map(this::wrapModel); } @Override @@ -68,8 +63,7 @@ public ActiveDirectoryApplication getByName(String spn) { @Override public Mono getByNameAsync(String name) { final String trimmed = name.replaceFirst("^'+", "").replaceAll("'+$", ""); - return listByFilterAsync(String.format("displayName eq '%s'", trimmed)) - .singleOrEmpty() + return listByFilterAsync(String.format("displayName eq '%s'", trimmed)).singleOrEmpty() .switchIfEmpty(Mono.defer(() -> { try { UUID.fromString(trimmed); @@ -83,8 +77,8 @@ public Mono getByNameAsync(String name) { @Override protected ActiveDirectoryApplicationImpl wrapModel(String name) { - return new ActiveDirectoryApplicationImpl( - new MicrosoftGraphApplicationInner().withDisplayName(name), manager()); + return new ActiveDirectoryApplicationImpl(new MicrosoftGraphApplicationInner().withDisplayName(name), + manager()); } @Override @@ -113,7 +107,7 @@ public PagedIterable listByFilter(String filter) { @Override public PagedFlux listByFilterAsync(String filter) { - return PagedConverter.mapPage(inner().listApplicationAsync(null, null, null, null, filter, null, null, null, null), - this::wrapModel); + return PagedConverter.mapPage( + inner().listApplicationAsync(null, null, null, null, filter, null, null, null, null), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupImpl.java index 915cd38c583b5..52f0c0352837c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupImpl.java @@ -65,31 +65,27 @@ public List listMembers() { @Override public PagedFlux listMembersAsync() { - return PagedConverter.flatMapPage(manager() - .serviceClient() - .getGroups() - .listMembersAsync(id()), - directoryObjectInner -> Mono.justOrEmpty(parseDirectoryObject(directoryObjectInner)) - ); + return PagedConverter.flatMapPage(manager().serviceClient().getGroups().listMembersAsync(id()), + directoryObjectInner -> Mono.justOrEmpty(parseDirectoryObject(directoryObjectInner))); } private ActiveDirectoryObject parseDirectoryObject(MicrosoftGraphDirectoryObjectInner inner) { if (inner.additionalProperties() != null) { Object odataTypeObject = inner.additionalProperties().get("@odata.type"); if (odataTypeObject instanceof String) { - SerializerAdapter serializerAdapter = - ((MicrosoftGraphClientImpl) manager().serviceClient()).getSerializerAdapter(); + SerializerAdapter serializerAdapter + = ((MicrosoftGraphClientImpl) manager().serviceClient()).getSerializerAdapter(); String odataType = ((String) odataTypeObject).toLowerCase(Locale.ROOT); try { String jsonString = serializerAdapter.serialize(inner, SerializerEncoding.JSON); if (odataType.endsWith("#microsoft.graph.user")) { - MicrosoftGraphUserInner userInner = serializerAdapter.deserialize( - jsonString, MicrosoftGraphUserInner.class, SerializerEncoding.JSON); + MicrosoftGraphUserInner userInner = serializerAdapter.deserialize(jsonString, + MicrosoftGraphUserInner.class, SerializerEncoding.JSON); return new ActiveDirectoryUserImpl(userInner, manager()); } else if (odataType.endsWith("#microsoft.graph.group")) { - MicrosoftGraphGroupInner groupInner = serializerAdapter.deserialize( - jsonString, MicrosoftGraphGroupInner.class, SerializerEncoding.JSON); + MicrosoftGraphGroupInner groupInner = serializerAdapter.deserialize(jsonString, + MicrosoftGraphGroupInner.class, SerializerEncoding.JSON); return new ActiveDirectoryGroupImpl(groupInner, manager()); } else if (odataType.endsWith("#microsoft.graph.serviceprincipal")) { @@ -98,8 +94,8 @@ private ActiveDirectoryObject parseDirectoryObject(MicrosoftGraphDirectoryObject return new ServicePrincipalImpl(servicePrincipalInner, manager()); } else if (odataType.endsWith("#microsoft.graph.application")) { - MicrosoftGraphApplicationInner applicationInner = serializerAdapter.deserialize( - jsonString, MicrosoftGraphApplicationInner.class, SerializerEncoding.JSON); + MicrosoftGraphApplicationInner applicationInner = serializerAdapter.deserialize(jsonString, + MicrosoftGraphApplicationInner.class, SerializerEncoding.JSON); return new ActiveDirectoryApplicationImpl(applicationInner, manager()); } else { logger.warning("Can't recognize member type '{}' of ActiveDirectoryGroup", odataType); @@ -134,32 +130,24 @@ public Mono createResourceAsync() { if (innerModel().securityEnabled() == null) { innerModel().withSecurityEnabled(true); } - group = manager().serviceClient().getGroupsGroups().createGroupAsync(innerModel()) + group = manager().serviceClient() + .getGroupsGroups() + .createGroupAsync(innerModel()) .map(innerToFluentMap(this)); } if (!membersToRemove.isEmpty()) { - group = - group - .flatMap( - o -> - Flux - .fromIterable(membersToRemove) - .flatMap(s -> manager().serviceClient().getGroups().deleteRefMemberAsync(id(), s)) - .singleOrEmpty() - .thenReturn(this) - .doFinally(signalType -> membersToRemove.clear())); + group = group.flatMap(o -> Flux.fromIterable(membersToRemove) + .flatMap(s -> manager().serviceClient().getGroups().deleteRefMemberAsync(id(), s)) + .singleOrEmpty() + .thenReturn(this) + .doFinally(signalType -> membersToRemove.clear())); } if (!membersToAdd.isEmpty()) { - group = - group - .flatMap( - o -> - Flux - .fromIterable(membersToAdd) - .flatMap(s -> manager().serviceClient().getGroups().createRefMembersAsync(id(), s)) - .singleOrEmpty() - .thenReturn(this) - .doFinally(signalType -> membersToAdd.clear())); + group = group.flatMap(o -> Flux.fromIterable(membersToAdd) + .flatMap(s -> manager().serviceClient().getGroups().createRefMembersAsync(id(), s)) + .singleOrEmpty() + .thenReturn(this) + .doFinally(signalType -> membersToAdd.clear())); } return group; } @@ -180,9 +168,8 @@ public ActiveDirectoryGroupImpl withEmailAlias(String mailNickname) { public ActiveDirectoryGroupImpl withMember(String objectId) { // https://docs.microsoft.com/en-us/graph/api/group-post-members String membersKey = "@odata.id"; - membersToAdd.add( - Collections.singletonMap(membersKey, - String.format("%s/directoryObjects/%s", manager().serviceClient().getEndpoint(), objectId))); + membersToAdd.add(Collections.singletonMap(membersKey, + String.format("%s/directoryObjects/%s", manager().serviceClient().getEndpoint(), objectId))); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupsImpl.java index 39f73240a3bac..fe64342204a05 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryGroupsImpl.java @@ -44,8 +44,7 @@ public ActiveDirectoryGroupImpl getById(String objectId) { @Override public Mono getByIdAsync(String id) { - return inner().getGroupAsync(id) - .map(groupInner -> new ActiveDirectoryGroupImpl(groupInner, manager())); + return inner().getGroupAsync(id).map(groupInner -> new ActiveDirectoryGroupImpl(groupInner, manager())); } @Override @@ -55,8 +54,7 @@ public PagedFlux listAsync() { @Override public Mono getByNameAsync(String name) { - return listByFilterAsync(String.format("displayName eq '%s'", name)) - .singleOrEmpty(); + return listByFilterAsync(String.format("displayName eq '%s'", name)).singleOrEmpty(); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUserImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUserImpl.java index 907cfb4724c3d..6b8b9eebf97c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUserImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUserImpl.java @@ -75,19 +75,13 @@ public ActiveDirectoryUserImpl withPassword(String password) { @Override protected Mono getInnerAsync() { - return manager.serviceClient().getUsersUsers().getUserWithResponseAsync( - id(), - null, - Arrays.asList( - Get2ItemsItem.ID, - Get2ItemsItem.DISPLAY_NAME, - Get2ItemsItem.USER_PRINCIPAL_NAME, - Get2ItemsItem.MAIL, - Get2ItemsItem.MAIL_NICKNAME, - Get2ItemsItem.USAGE_LOCATION, - Get2ItemsItem.ACCOUNT_ENABLED - ), - null) + return manager.serviceClient() + .getUsersUsers() + .getUserWithResponseAsync(id(), null, + Arrays.asList(Get2ItemsItem.ID, Get2ItemsItem.DISPLAY_NAME, Get2ItemsItem.USER_PRINCIPAL_NAME, + Get2ItemsItem.MAIL, Get2ItemsItem.MAIL_NICKNAME, Get2ItemsItem.USAGE_LOCATION, + Get2ItemsItem.ACCOUNT_ENABLED), + null) .flatMap(FluxUtil::toMono); } @@ -103,24 +97,19 @@ public Mono createResourceAsync() { } Flux flux = Flux.empty(); if (emailAlias != null) { - flux = manager().serviceClient().getDomainsDomains().listDomainAsync() - .flatMap(domainInner -> { - if (domainInner.isVerified() && domainInner.isDefault()) { - withUserPrincipalName(emailAlias + "@" + domainInner.id()); - } - return Mono.empty(); - }); + flux = manager().serviceClient().getDomainsDomains().listDomainAsync().flatMap(domainInner -> { + if (domainInner.isVerified() && domainInner.isDefault()) { + withUserPrincipalName(emailAlias + "@" + domainInner.id()); + } + return Mono.empty(); + }); } return flux.then(manager().serviceClient().getUsersUsers().createUserAsync(innerModel())) .map(innerToFluentMap(this)); } public Mono updateResourceAsync() { - return manager() - .serviceClient() - .getUsersUsers() - .updateUserAsync(id(), innerModel()) - .then(this.refreshAsync()); + return manager().serviceClient().getUsersUsers().updateUserAsync(id(), innerModel()).then(this.refreshAsync()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUsersImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUsersImpl.java index c9641e5b2107b..a35fb58871333 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUsersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ActiveDirectoryUsersImpl.java @@ -45,8 +45,7 @@ public ActiveDirectoryUserImpl getById(String objectId) { @Override public Mono getByIdAsync(String id) { - return inner().getUserAsync(id) - .map(userInner -> new ActiveDirectoryUserImpl(userInner, manager())); + return inner().getUserAsync(id).map(userInner -> new ActiveDirectoryUserImpl(userInner, manager())); } @Override @@ -58,19 +57,15 @@ public ActiveDirectoryUserImpl getByName(String upn) { public Mono getByNameAsync(final String name) { return inner().getUserAsync(name) .map(userInner -> (ActiveDirectoryUser) new ActiveDirectoryUserImpl(userInner, manager())) - .onErrorResume( - ManagementException.class, - e -> { - if (name.contains("@")) { - return listByFilterAsync( - String - .format("mail eq '%s' or mailNickName eq '%s#EXT#'", name, name.replace("@", "_"))) + .onErrorResume(ManagementException.class, e -> { + if (name.contains("@")) { + return listByFilterAsync( + String.format("mail eq '%s' or mailNickName eq '%s#EXT#'", name, name.replace("@", "_"))) .singleOrEmpty(); - } else { - return listByFilterAsync(String.format("displayName eq '%s'", name)) - .singleOrEmpty(); - } - }); + } else { + return listByFilterAsync(String.format("displayName eq '%s'", name)).singleOrEmpty(); + } + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/CertificateCredentialImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/CertificateCredentialImpl.java index 1002eb49e9ae3..d4d1dd7cdb4fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/CertificateCredentialImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/CertificateCredentialImpl.java @@ -40,12 +40,10 @@ class CertificateCredentialImpl> } CertificateCredentialImpl(String name, HasCredential parent) { - super( - new MicrosoftGraphKeyCredentialInner() - .withUsage("Verify") - .withDisplayName(name) - .withStartDateTime(OffsetDateTime.now()) - .withEndDateTime(OffsetDateTime.now().plusYears(1))); + super(new MicrosoftGraphKeyCredentialInner().withUsage("Verify") + .withDisplayName(name) + .withStartDateTime(OffsetDateTime.now()) + .withEndDateTime(OffsetDateTime.now().plusYears(1))); this.name = name; this.parent = parent; } @@ -120,17 +118,13 @@ public CertificateCredentialImpl withSecretKey(byte[] secret) { } void exportAuthFile(ServicePrincipalImpl servicePrincipal) { - exportAuthFile(servicePrincipal.manager().environment(), - servicePrincipal.applicationId(), - servicePrincipal.manager().tenantId(), - servicePrincipal.assignedSubscription); + exportAuthFile(servicePrincipal.manager().environment(), servicePrincipal.applicationId(), + servicePrincipal.manager().tenantId(), servicePrincipal.assignedSubscription); } void exportAuthFile(ActiveDirectoryApplicationImpl activeDirectoryApplication) { - exportAuthFile(activeDirectoryApplication.manager().environment(), - activeDirectoryApplication.applicationId(), - activeDirectoryApplication.manager().tenantId(), - null); + exportAuthFile(activeDirectoryApplication.manager().environment(), activeDirectoryApplication.applicationId(), + activeDirectoryApplication.manager().tenantId(), null); } void exportAuthFile(AzureEnvironment environment, String clientId, String tenantId, String subscriptionId) { @@ -138,45 +132,29 @@ void exportAuthFile(AzureEnvironment environment, String clientId, String tenant return; } StringBuilder builder = new StringBuilder("{\n"); - builder - .append(" ") - .append(String.format("\"clientId\": \"%s\",", clientId)) - .append("\n"); - builder - .append(" ") + builder.append(" ").append(String.format("\"clientId\": \"%s\",", clientId)).append("\n"); + builder.append(" ") .append(String.format("\"clientCertificate\": \"%s\",", privateKeyPath.replace("\\", "\\\\"))) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"clientCertificatePassword\": \"%s\",", privateKeyPassword)) .append("\n"); - builder - .append(" ") - .append(String.format("\"tenantId\": \"%s\",", tenantId)) - .append("\n"); - builder - .append(" ") - .append(String.format("\"subscriptionId\": \"%s\",", subscriptionId)) - .append("\n"); - builder - .append(" ") + builder.append(" ").append(String.format("\"tenantId\": \"%s\",", tenantId)).append("\n"); + builder.append(" ").append(String.format("\"subscriptionId\": \"%s\",", subscriptionId)).append("\n"); + builder.append(" ") .append(String.format("\"activeDirectoryEndpointUrl\": \"%s\",", environment.getActiveDirectoryEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"resourceManagerEndpointUrl\": \"%s\",", environment.getResourceManagerEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"activeDirectoryGraphResourceId\": \"%s\",", environment.getGraphEndpoint())) .append("\n"); - builder - .append(" ") - .append(String.format("\"%s\": \"%s\",", - AzureEnvironment.Endpoint.MICROSOFT_GRAPH.identifier(), environment.getMicrosoftGraphEndpoint())) + builder.append(" ") + .append(String.format("\"%s\": \"%s\",", AzureEnvironment.Endpoint.MICROSOFT_GRAPH.identifier(), + environment.getMicrosoftGraphEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"managementEndpointUrl\": \"%s\"", environment.getManagementEndpoint())) .append("\n"); builder.append("}"); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/HasCredential.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/HasCredential.java index 34def983c38a3..ab6f15d667253 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/HasCredential.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/HasCredential.java @@ -14,6 +14,7 @@ interface HasCredential> { * @return the interface itself */ T withCertificateCredential(CertificateCredentialImpl credential); + /** * Attach a credential to this model. * diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PasswordCredentialImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PasswordCredentialImpl.java index 583dacbe2d88b..ba733bd574b53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PasswordCredentialImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PasswordCredentialImpl.java @@ -41,11 +41,9 @@ class PasswordCredentialImpl> } PasswordCredentialImpl(String name, HasCredential parent) { - super( - new MicrosoftGraphPasswordCredentialInner() - .withDisplayName(name) - .withStartDateTime(OffsetDateTime.now()) - .withEndDateTime(OffsetDateTime.now().plusYears(1))); + super(new MicrosoftGraphPasswordCredentialInner().withDisplayName(name) + .withStartDateTime(OffsetDateTime.now()) + .withEndDateTime(OffsetDateTime.now().plusYears(1))); this.name = name; this.parent = parent; } @@ -102,14 +100,12 @@ public PasswordCredentialImpl withAuthFileToExport(OutputStream outputStream) } void exportAuthFile(ServicePrincipalImpl servicePrincipal) { - exportAuthFile(servicePrincipal.manager().environment(), - servicePrincipal.applicationId(), + exportAuthFile(servicePrincipal.manager().environment(), servicePrincipal.applicationId(), servicePrincipal.manager().tenantId()); } void exportAuthFile(ActiveDirectoryApplicationImpl activeDirectoryApplication) { - exportAuthFile(activeDirectoryApplication.manager().environment(), - activeDirectoryApplication.applicationId(), + exportAuthFile(activeDirectoryApplication.manager().environment(), activeDirectoryApplication.applicationId(), activeDirectoryApplication.manager().tenantId()); } @@ -119,38 +115,24 @@ void exportAuthFile(AzureEnvironment environment, String clientId, String tenant } StringBuilder builder = new StringBuilder("{\n"); - builder - .append(" ") - .append(String.format("\"clientId\": \"%s\",", clientId)) - .append("\n"); + builder.append(" ").append(String.format("\"clientId\": \"%s\",", clientId)).append("\n"); builder.append(" ").append(String.format("\"clientSecret\": \"%s\",", value())).append("\n"); - builder - .append(" ") - .append(String.format("\"tenantId\": \"%s\",", tenantId)) - .append("\n"); - builder - .append(" ") - .append(String.format("\"subscriptionId\": \"%s\",", subscriptionId)) - .append("\n"); - builder - .append(" ") + builder.append(" ").append(String.format("\"tenantId\": \"%s\",", tenantId)).append("\n"); + builder.append(" ").append(String.format("\"subscriptionId\": \"%s\",", subscriptionId)).append("\n"); + builder.append(" ") .append(String.format("\"activeDirectoryEndpointUrl\": \"%s\",", environment.getActiveDirectoryEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"resourceManagerEndpointUrl\": \"%s\",", environment.getResourceManagerEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"activeDirectoryGraphResourceId\": \"%s\",", environment.getGraphEndpoint())) .append("\n"); - builder - .append(" ") - .append(String.format("\"%s\": \"%s\",", - AzureEnvironment.Endpoint.MICROSOFT_GRAPH.identifier(), environment.getMicrosoftGraphEndpoint())) + builder.append(" ") + .append(String.format("\"%s\": \"%s\",", AzureEnvironment.Endpoint.MICROSOFT_GRAPH.identifier(), + environment.getMicrosoftGraphEndpoint())) .append("\n"); - builder - .append(" ") + builder.append(" ") .append(String.format("\"managementEndpointUrl\": \"%s\"", environment.getManagementEndpoint())) .append("\n"); builder.append("}"); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PercentEscaper.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PercentEscaper.java index 0c6ad6532aeff..c9fa62be85928 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PercentEscaper.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/PercentEscaper.java @@ -243,8 +243,8 @@ private static int getCodePoint(String original, int index, int end) { } else if (Character.isHighSurrogate(char1)) { // High surrogates will occur first in the string. if (index == end) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "String contains trailing high surrogate without paired low surrogate.")); + throw LOGGER.logExceptionAsError( + new IllegalStateException("String contains trailing high surrogate without paired low surrogate.")); } char char2 = original.charAt(index); @@ -252,11 +252,11 @@ private static int getCodePoint(String original, int index, int end) { return Character.toCodePoint(char1, char2); } - throw LOGGER.logExceptionAsError(new IllegalStateException( - "String contains high surrogate without trailing low surrogate.")); + throw LOGGER.logExceptionAsError( + new IllegalStateException("String contains high surrogate without trailing low surrogate.")); } else { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "String contains low surrogate without leading high surrogate.")); + throw LOGGER.logExceptionAsError( + new IllegalStateException("String contains low surrogate without leading high surrogate.")); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentImpl.java index 56efa646623cc..9fefce6dc8109 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentImpl.java @@ -60,33 +60,24 @@ public Mono createResourceAsync() { if (roleDefinitionId != null) { roleDefinitionIdObservable = Mono.just(roleDefinitionId); } else if (roleName != null) { - roleDefinitionIdObservable = - manager() - .roleDefinitions() - .getByScopeAndRoleNameAsync(scope(), roleName) - .map(roleDefinition -> roleDefinition.id()); + roleDefinitionIdObservable = manager().roleDefinitions() + .getByScopeAndRoleNameAsync(scope(), roleName) + .map(roleDefinition -> roleDefinition.id()); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please pass a non-null value for either role name or role definition ID")); } return Mono - .zip( - objectIdObservable, - roleDefinitionIdObservable, - (objectId, roleDefinitionId) -> - new RoleAssignmentCreateParameters() - .withPrincipalId(objectId) - .withRoleDefinitionId(roleDefinitionId) - .withDescription(description)) - .flatMap( - roleAssignmentPropertiesInner -> - manager() - .roleServiceClient() - .getRoleAssignments() - .createAsync(scope(), name(), roleAssignmentPropertiesInner) - // if the service principal is newly created (also apply to the case that MSI is new), wait for eventual consistency from AAD - .retryWhen(RetryUtils.backoffRetryFor400PrincipalNotFound())) + .zip(objectIdObservable, roleDefinitionIdObservable, + (objectId, roleDefinitionId) -> new RoleAssignmentCreateParameters().withPrincipalId(objectId) + .withRoleDefinitionId(roleDefinitionId) + .withDescription(description)) + .flatMap(roleAssignmentPropertiesInner -> manager().roleServiceClient() + .getRoleAssignments() + .createAsync(scope(), name(), roleAssignmentPropertiesInner) + // if the service principal is newly created (also apply to the case that MSI is new), wait for eventual consistency from AAD + .retryWhen(RetryUtils.backoffRetryFor400PrincipalNotFound())) .map(innerToFluentMap(this)); } @@ -194,6 +185,7 @@ public RoleAssignmentImpl withDescription(String description) { this.description = description; return this; } + @Override public String id() { return innerModel().id(); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentsImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentsImpl.java index e06b549a0c9de..a15abf4759d50 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleAssignmentsImpl.java @@ -41,11 +41,9 @@ public RoleAssignmentImpl getById(String objectId) { @Override public Mono getByIdAsync(String id) { - return inner() - .getByIdAsync(id) - .map( - roleAssignmentInner -> - new RoleAssignmentImpl(roleAssignmentInner.name(), roleAssignmentInner, manager())); + return inner().getByIdAsync(id) + .map(roleAssignmentInner -> new RoleAssignmentImpl(roleAssignmentInner.name(), roleAssignmentInner, + manager())); } @Override @@ -76,8 +74,8 @@ public PagedIterable listByServicePrincipal(ServicePrincipal ser @Override public PagedFlux listByServicePrincipalAsync(String principalId) { PercentEscaper percentEscaper = new PercentEscaper("-._~" + "/?", false); - String filterStr = percentEscaper.escape( - String.format("principalId eq '%s'", Objects.requireNonNull(principalId))); + String filterStr + = percentEscaper.escape(String.format("principalId eq '%s'", Objects.requireNonNull(principalId))); return PagedConverter.mapPage(inner().listAsync(filterStr, null), this::wrapModel); } @@ -88,11 +86,9 @@ public PagedIterable listByServicePrincipal(String principalId) @Override public Mono getByScopeAsync(String scope, String name) { - return inner() - .getAsync(scope, name) - .map( - roleAssignmentInner -> - new RoleAssignmentImpl(roleAssignmentInner.name(), roleAssignmentInner, manager())); + return inner().getAsync(scope, name) + .map(roleAssignmentInner -> new RoleAssignmentImpl(roleAssignmentInner.name(), roleAssignmentInner, + manager())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleDefinitionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleDefinitionsImpl.java index 867dccd889cca..62a40a3a267fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleDefinitionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/RoleDefinitionsImpl.java @@ -38,8 +38,7 @@ public RoleDefinition getById(String objectId) { @Override public Mono getByIdAsync(String id) { - return inner() - .getByIdAsync(id) + return inner().getByIdAsync(id) .map(roleDefinitionInner -> new RoleDefinitionImpl(roleDefinitionInner, manager())); } @@ -50,8 +49,7 @@ public RoleDefinition getByScope(String scope, String name) { @Override public Mono getByScopeAsync(String scope, String name) { - return inner() - .getAsync(scope, name) + return inner().getAsync(scope, name) .map(roleDefinitionInner -> new RoleDefinitionImpl(roleDefinitionInner, manager())); } @@ -62,8 +60,7 @@ public RoleDefinition getByScopeAndRoleName(String scope, String roleName) { @Override public PagedFlux listByScopeAsync(String scope) { - return PagedConverter.mapPage(inner() - .listAsync(scope, null), + return PagedConverter.mapPage(inner().listAsync(scope, null), roleDefinitionInner -> new RoleDefinitionImpl(roleDefinitionInner, manager())); } @@ -74,8 +71,7 @@ public PagedIterable listByScope(String scope) { @Override public Mono getByScopeAndRoleNameAsync(String scope, String roleName) { - return inner() - .listAsync(scope, String.format("roleName eq '%s'", roleName)) + return inner().listAsync(scope, String.format("roleName eq '%s'", roleName)) .singleOrEmpty() .map(roleDefinitionInner -> new RoleDefinitionImpl(roleDefinitionInner, manager())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalImpl.java index db30649efda02..11c4de3df3c9f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalImpl.java @@ -29,12 +29,9 @@ import java.util.Set; /** Implementation for ServicePrincipal and its parent interfaces. */ -class ServicePrincipalImpl - extends CreatableUpdatableImpl - implements ServicePrincipal, - ServicePrincipal.Definition, - ServicePrincipal.Update, - HasCredential { +class ServicePrincipalImpl extends + CreatableUpdatableImpl implements + ServicePrincipal, ServicePrincipal.Definition, ServicePrincipal.Update, HasCredential { private AuthorizationManager manager; private Map cachedPasswordCredentials; @@ -89,7 +86,9 @@ public Set roleAssignments() { @Override protected Mono getInnerAsync() { - return manager.serviceClient().getServicePrincipalsServicePrincipals().getServicePrincipalAsync(id()) + return manager.serviceClient() + .getServicePrincipalsServicePrincipals() + .getServicePrincipalAsync(id()) .doOnSuccess(this::refreshCredentials); } @@ -104,81 +103,76 @@ public Mono createResourceAsync() { ActiveDirectoryApplication application = this.taskResult(applicationCreatable.key()); innerModel().withAppId(application.applicationId()); } - sp = manager.serviceClient().getServicePrincipalsServicePrincipals() - .createServicePrincipalAsync(innerModel()).map(innerToFluentMap(this)); + sp = manager.serviceClient() + .getServicePrincipalsServicePrincipals() + .createServicePrincipalAsync(innerModel()) + .map(innerToFluentMap(this)); if (applicationCreatable != null) { // retry on 400, if app is created with "withNewApplication" sp = sp.retryWhen(RetryUtils.backoffRetryFor400BadRequest()); } } else { - sp = manager().serviceClient().getServicePrincipalsServicePrincipals() - .updateServicePrincipalAsync(id(), new MicrosoftGraphServicePrincipalInner() - .withKeyCredentials(innerModel().keyCredentials()) - .withPasswordCredentials(innerModel().passwordCredentials()) - ).then(refreshAsync()); + sp = manager().serviceClient() + .getServicePrincipalsServicePrincipals() + .updateServicePrincipalAsync(id(), + new MicrosoftGraphServicePrincipalInner().withKeyCredentials(innerModel().keyCredentials()) + .withPasswordCredentials(innerModel().passwordCredentials())) + .then(refreshAsync()); } - return sp - .flatMap( - servicePrincipal -> - submitCredentialsAsync(servicePrincipal, retry) - // retry for Microsoft.Authorization is done in RoleAssignmentImpl - .mergeWith(submitRolesAsync(servicePrincipal)) - .last()) - .map( - servicePrincipal -> { - for (PasswordCredentialImpl passwordCredential : passwordCredentialsToCreate) { - passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal); - passwordCredential.consumeSecret(); - } - for (CertificateCredentialImpl certificateCredential : certificateCredentialsToCreate) { - certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal); - } - passwordCredentialsToCreate.clear(); - certificateCredentialsToCreate.clear(); - return servicePrincipal; - }); + return sp.flatMap(servicePrincipal -> submitCredentialsAsync(servicePrincipal, retry) + // retry for Microsoft.Authorization is done in RoleAssignmentImpl + .mergeWith(submitRolesAsync(servicePrincipal)) + .last()).map(servicePrincipal -> { + for (PasswordCredentialImpl passwordCredential : passwordCredentialsToCreate) { + passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal); + passwordCredential.consumeSecret(); + } + for (CertificateCredentialImpl certificateCredential : certificateCredentialsToCreate) { + certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal); + } + passwordCredentialsToCreate.clear(); + certificateCredentialsToCreate.clear(); + return servicePrincipal; + }); } private Mono submitCredentialsAsync(final ServicePrincipal servicePrincipal, Retry retry) { return Flux.defer(() -> -// Flux.fromIterable(certificateCredentialsToCreate) -// .flatMap(certificateCredential -> -// manager().serviceClient().getServicePrincipals() -// .addKeyAsync(id(), -// new ServicePrincipalsAddKeyRequestBodyInner() -// .withKeyCredential(certificateCredential.innerModel()))), -// Flux.fromIterable(certificateCredentialsToDelete) -// .flatMap(id -> manager().serviceClient().getServicePrincipals() -// .removeKeyAsync(id(), -// new ServicePrincipalsRemoveKeyRequestBody() -// .withKeyId(UUID.fromString(id)))), - Flux.fromIterable(passwordCredentialsToCreate) - .flatMap(passwordCredential -> { - Mono monoAddPassword = - manager().serviceClient().getServicePrincipals() - .addPasswordAsync(id(), - new ServicePrincipalsAddPasswordRequestBodyInner() - .withPasswordCredential(passwordCredential.innerModel())); - if (retry != null) { - monoAddPassword = monoAddPassword.retryWhen(retry); - } - monoAddPassword = monoAddPassword.doOnNext(passwordCredential::setInner); - return monoAddPassword; - }) -// Flux.fromIterable(passwordCredentialsToDelete) -// .flatMap(id -> manager().serviceClient().getServicePrincipals() -// .removePasswordAsync(id(), -// new ServicePrincipalsRemovePasswordRequestBody() -// .withKeyId(UUID.fromString(id)))) - ) - .then(Mono.defer(() -> { - Mono monoRefresh = refreshAsync(); - if (retry != null) { - monoRefresh = monoRefresh.retryWhen(retry); - } - return monoRefresh; - })); + // Flux.fromIterable(certificateCredentialsToCreate) + // .flatMap(certificateCredential -> + // manager().serviceClient().getServicePrincipals() + // .addKeyAsync(id(), + // new ServicePrincipalsAddKeyRequestBodyInner() + // .withKeyCredential(certificateCredential.innerModel()))), + // Flux.fromIterable(certificateCredentialsToDelete) + // .flatMap(id -> manager().serviceClient().getServicePrincipals() + // .removeKeyAsync(id(), + // new ServicePrincipalsRemoveKeyRequestBody() + // .withKeyId(UUID.fromString(id)))), + Flux.fromIterable(passwordCredentialsToCreate).flatMap(passwordCredential -> { + Mono monoAddPassword = manager().serviceClient() + .getServicePrincipals() + .addPasswordAsync(id(), new ServicePrincipalsAddPasswordRequestBodyInner() + .withPasswordCredential(passwordCredential.innerModel())); + if (retry != null) { + monoAddPassword = monoAddPassword.retryWhen(retry); + } + monoAddPassword = monoAddPassword.doOnNext(passwordCredential::setInner); + return monoAddPassword; + }) + // Flux.fromIterable(passwordCredentialsToDelete) + // .flatMap(id -> manager().serviceClient().getServicePrincipals() + // .removePasswordAsync(id(), + // new ServicePrincipalsRemovePasswordRequestBody() + // .withKeyId(UUID.fromString(id)))) + ).then(Mono.defer(() -> { + Mono monoRefresh = refreshAsync(); + if (retry != null) { + monoRefresh = monoRefresh.retryWhen(retry); + } + return monoRefresh; + })); } private Mono submitRolesAsync(final ServicePrincipal servicePrincipal) { @@ -186,46 +180,34 @@ private Mono submitRolesAsync(final ServicePrincipal servicePr if (rolesToCreate.isEmpty()) { create = Mono.just(servicePrincipal); } else { - create = - Flux - .fromIterable(rolesToCreate.entrySet()) - .flatMap(roleEntry -> manager() - .roleAssignments() - .define(this.manager().internalContext().randomUuid()) - .forServicePrincipal(servicePrincipal) - .withBuiltInRole(roleEntry.getValue()) - .withScope(roleEntry.getKey()) - .createAsync()) - .doOnNext( - indexable -> - cachedRoleAssignments.put(indexable.id(), indexable)) - .last() - .map( - indexable -> { - rolesToCreate.clear(); - return servicePrincipal; - }); + create = Flux.fromIterable(rolesToCreate.entrySet()) + .flatMap(roleEntry -> manager().roleAssignments() + .define(this.manager().internalContext().randomUuid()) + .forServicePrincipal(servicePrincipal) + .withBuiltInRole(roleEntry.getValue()) + .withScope(roleEntry.getKey()) + .createAsync()) + .doOnNext(indexable -> cachedRoleAssignments.put(indexable.id(), indexable)) + .last() + .map(indexable -> { + rolesToCreate.clear(); + return servicePrincipal; + }); } Mono delete; if (rolesToDelete.isEmpty()) { delete = Mono.just(servicePrincipal); } else { - delete = - Flux - .fromIterable(rolesToDelete) - .flatMap( - role -> - manager() - .roleAssignments() - .deleteByIdAsync(cachedRoleAssignments.get(role).id()) - .thenReturn(role)) - .doOnNext(s -> cachedRoleAssignments.remove(s)) - .last() - .map( - s -> { - rolesToDelete.clear(); - return servicePrincipal; - }); + delete = Flux.fromIterable(rolesToDelete) + .flatMap(role -> manager().roleAssignments() + .deleteByIdAsync(cachedRoleAssignments.get(role).id()) + .thenReturn(role)) + .doOnNext(s -> cachedRoleAssignments.remove(s)) + .last() + .map(s -> { + rolesToDelete.clear(); + return servicePrincipal; + }); } return create.mergeWith(delete).last(); } @@ -322,8 +304,7 @@ public ServicePrincipalImpl withNewApplication(String signOnUrl) { @Override public ServicePrincipalImpl withNewApplication() { - return withNewApplication( - manager.applications().define(name())); + return withNewApplication(manager.applications().define(name())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalsImpl.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalsImpl.java index 43b8433741e1c..fe257c3458a51 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/implementation/ServicePrincipalsImpl.java @@ -50,9 +50,7 @@ public ServicePrincipalImpl getById(String id) { @Override public Mono getByIdAsync(String id) { - return inner() - .getServicePrincipalAsync(id) - .map(this::wrapModel); + return inner().getServicePrincipalAsync(id).map(this::wrapModel); } @Override @@ -62,8 +60,7 @@ public ServicePrincipal getByName(String spn) { @Override public Mono getByNameAsync(final String name) { - return listByFilterAsync(String.format("displayName eq '%s'", name)) - .singleOrEmpty() + return listByFilterAsync(String.format("displayName eq '%s'", name)).singleOrEmpty() .switchIfEmpty( listByFilterAsync(String.format("servicePrincipalNames/any(c:c eq '%s')", name)).singleOrEmpty()); } @@ -99,7 +96,7 @@ public PagedIterable listByFilter(String filter) { @Override public PagedFlux listByFilterAsync(String filter) { - return PagedConverter.mapPage(inner().listServicePrincipalAsync(null, null, null, null, filter, null, null, null, null), - this::wrapModel); + return PagedConverter.mapPage( + inner().listServicePrincipalAsync(null, null, null, null, filter, null, null, null, null), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplication.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplication.java index b2ed04745f3cb..cc9041e7b6380 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplication.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplication.java @@ -16,10 +16,8 @@ /** An immutable client-side representation of an Azure AD application. */ @Fluent -public interface ActiveDirectoryApplication - extends ActiveDirectoryObject, - HasInnerModel, - Updatable { +public interface ActiveDirectoryApplication extends ActiveDirectoryObject, + HasInnerModel, Updatable { /** @return the application ID */ String applicationId(); @@ -158,14 +156,8 @@ interface WithAccountType { * An application definition with sufficient inputs to create a new application in the cloud, but exposing * additional optional inputs to specify. */ - interface WithCreate - extends Creatable, - WithSignOnUrl, - WithIdentifierUrl, - WithReplyUrl, - WithCredential, - WithAccountType, - WithMultiTenant { + interface WithCreate extends Creatable, WithSignOnUrl, WithIdentifierUrl, + WithReplyUrl, WithCredential, WithAccountType, WithMultiTenant { } } @@ -228,8 +220,7 @@ interface WithCredential { * @param name the descriptive name of the certificate credential * @return the first stage in certificate credential definition */ - CertificateCredential.DefinitionStages.Blank - defineCertificateCredential(String name); + CertificateCredential.DefinitionStages.Blank defineCertificateCredential(String name); /** * Starts the definition of a password credential. @@ -288,13 +279,8 @@ interface WithAccountType { } /** The template for an application update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithSignOnUrl, - UpdateStages.WithIdentifierUrl, - UpdateStages.WithReplyUrl, - UpdateStages.WithCredential, - UpdateStages.WithAccountType, - UpdateStages.WithMultiTenant { + interface Update extends Appliable, UpdateStages.WithSignOnUrl, + UpdateStages.WithIdentifierUrl, UpdateStages.WithReplyUrl, UpdateStages.WithCredential, + UpdateStages.WithAccountType, UpdateStages.WithMultiTenant { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplications.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplications.java index d0dceebb4be18..772cb25304427 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplications.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryApplications.java @@ -17,12 +17,8 @@ /** Entry point to application management API. */ @Fluent public interface ActiveDirectoryApplications - extends SupportsListing, - SupportsListingByFilter, - SupportsGettingById, - SupportsGettingByName, - SupportsCreating, - SupportsBatchCreation, - SupportsDeletingById, - HasManager { + extends SupportsListing, SupportsListingByFilter, + SupportsGettingById, SupportsGettingByName, + SupportsCreating, + SupportsBatchCreation, SupportsDeletingById, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryGroups.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryGroups.java index 48e14ce5a8c67..b765960e113c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryGroups.java @@ -15,12 +15,8 @@ /** Entry point to AD group management API. */ @Fluent -public interface ActiveDirectoryGroups - extends SupportsListing, - SupportsListingByFilter, - SupportsGettingById, - SupportsGettingByName, - SupportsCreating, - SupportsDeletingById, - HasManager { +public interface ActiveDirectoryGroups extends SupportsListing, + SupportsListingByFilter, SupportsGettingById, + SupportsGettingByName, SupportsCreating, + SupportsDeletingById, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUser.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUser.java index ff49eb1393816..9e293c1b3e7da 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUser.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUser.java @@ -32,11 +32,8 @@ public interface ActiveDirectoryUser **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithUserPrincipalName, - DefinitionStages.WithPassword, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithUserPrincipalName, + DefinitionStages.WithPassword, DefinitionStages.WithCreate { } /** Grouping of all the user definition stages. */ @@ -114,11 +111,8 @@ interface WithUsageLocation { * An AD user definition with sufficient inputs to create a new user in the cloud, but exposing additional * optional inputs to specify. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithAccontEnabled, - DefinitionStages.WithPromptToChangePasswordOnLogin, - DefinitionStages.WithUsageLocation { + interface WithCreate extends Creatable, DefinitionStages.WithAccontEnabled, + DefinitionStages.WithPromptToChangePasswordOnLogin, DefinitionStages.WithUsageLocation { } } @@ -171,11 +165,7 @@ interface WithUsageLocation { } /** The template for a user update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithAccontEnabled, - UpdateStages.WithPassword, - UpdateStages.WithPromptToChangePasswordOnLogin, - UpdateStages.WithUsageLocation { + interface Update extends Appliable, UpdateStages.WithAccontEnabled, UpdateStages.WithPassword, + UpdateStages.WithPromptToChangePasswordOnLogin, UpdateStages.WithUsageLocation { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUsers.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUsers.java index c4116124b9044..8cccc721cb1ec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUsers.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ActiveDirectoryUsers.java @@ -15,12 +15,8 @@ /** Entry point to AD user management API. */ @Fluent -public interface ActiveDirectoryUsers - extends SupportsGettingById, - SupportsGettingByName, - SupportsListing, - SupportsListingByFilter, - SupportsCreating, - SupportsDeletingById, - HasManager { +public interface ActiveDirectoryUsers extends SupportsGettingById, + SupportsGettingByName, SupportsListing, + SupportsListingByFilter, SupportsCreating, + SupportsDeletingById, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ApplicationAccountType.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ApplicationAccountType.java index ee5e40fbd470a..d1c0e87ee15d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ApplicationAccountType.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ApplicationAccountType.java @@ -17,8 +17,8 @@ public final class ApplicationAccountType extends ExpandableStringEnum { /** A role that can manage API Management service and the APIs. */ - public static final BuiltInRole API_MANAGEMENT_SERVICE_CONTRIBUTOR = - BuiltInRole.fromString("API Management Service Contributor"); + public static final BuiltInRole API_MANAGEMENT_SERVICE_CONTRIBUTOR + = BuiltInRole.fromString("API Management Service Contributor"); /** A role that can manage API Management service, but not the APIs themselves. */ - public static final BuiltInRole API_MANAGEMENT_SERVICE_OPERATOR_ROLE = - BuiltInRole.fromString("API Management Service Operator Role"); + public static final BuiltInRole API_MANAGEMENT_SERVICE_OPERATOR_ROLE + = BuiltInRole.fromString("API Management Service Operator Role"); /** A role that has read-only access to API Management service and APIs. */ - public static final BuiltInRole API_MANAGEMENT_SERVICE_READER_ROLE = - BuiltInRole.fromString("API Management Service Reader Role"); + public static final BuiltInRole API_MANAGEMENT_SERVICE_READER_ROLE + = BuiltInRole.fromString("API Management Service Reader Role"); /** A role that can manage Application Insights components. */ - public static final BuiltInRole APPLICATION_INSIGHTS_COMPONENT_CONTRIBUTOR = - BuiltInRole.fromString("Application Insights Component Contributor"); + public static final BuiltInRole APPLICATION_INSIGHTS_COMPONENT_CONTRIBUTOR + = BuiltInRole.fromString("Application Insights Component Contributor"); /** A role that is able to start, stop, suspend, and resume jobs. */ public static final BuiltInRole AUTOMATION_OPERATOR = BuiltInRole.fromString("Automation Operator"); @@ -50,8 +50,8 @@ public final class BuiltInRole extends ExpandableStringEnum { public static final BuiltInRole BIZTALK_CONTRIBUTOR = BuiltInRole.fromString("BizTalk Contributor"); /** A role that can manage ClearDB MySQL databases. */ - public static final BuiltInRole CLEARDB_MYSQL_DB_CONTRIBUTOR = - BuiltInRole.fromString("ClearDB MySQL DB Contributor"); + public static final BuiltInRole CLEARDB_MYSQL_DB_CONTRIBUTOR + = BuiltInRole.fromString("ClearDB MySQL DB Contributor"); /** A role that can manage everything except access.. */ public static final BuiltInRole CONTRIBUTOR = BuiltInRole.fromString("Contributor"); @@ -66,16 +66,16 @@ public final class BuiltInRole extends ExpandableStringEnum { public static final BuiltInRole DNS_ZONE_CONTRIBUTOR = BuiltInRole.fromString("DNS Zone Contributor"); /** A role that can manage Azure Cosmos DB accounts. */ - public static final BuiltInRole AZURE_COSMOS_DB_ACCOUNT_CONTRIBUTOR = - BuiltInRole.fromString("Azure Cosmos DB Account Contributor"); + public static final BuiltInRole AZURE_COSMOS_DB_ACCOUNT_CONTRIBUTOR + = BuiltInRole.fromString("Azure Cosmos DB Account Contributor"); /** A role that can manage Intelligent Systems accounts. */ - public static final BuiltInRole INTELLIGENT_SYSTEMS_ACCOUNT_CONTRIBUTOR = - BuiltInRole.fromString("Intelligent Systems Account Contributor"); + public static final BuiltInRole INTELLIGENT_SYSTEMS_ACCOUNT_CONTRIBUTOR + = BuiltInRole.fromString("Intelligent Systems Account Contributor"); /** A role that can manage user assigned identities. */ - public static final BuiltInRole MANAGED_IDENTITY_CONTRIBUTOR = - BuiltInRole.fromString("Managed Identity Contributor"); + public static final BuiltInRole MANAGED_IDENTITY_CONTRIBUTOR + = BuiltInRole.fromString("Managed Identity Contributor"); /** A role that can read and assign user assigned identities. */ public static final BuiltInRole MANAGED_IDENTITY_OPERATOR = BuiltInRole.fromString("Managed Identity Operator"); @@ -90,8 +90,8 @@ public final class BuiltInRole extends ExpandableStringEnum { public static final BuiltInRole NETWORK_CONTRIBUTOR = BuiltInRole.fromString("Network Contributor"); /** A role that can manage New Relic Application Performance Management accounts and applications. */ - public static final BuiltInRole NEW_RELIC_APM_ACCOUNT_CONTRIBUTOR = - BuiltInRole.fromString("New Relic APM Account Contributor"); + public static final BuiltInRole NEW_RELIC_APM_ACCOUNT_CONTRIBUTOR + = BuiltInRole.fromString("New Relic APM Account Contributor"); /** A role that can manage everything, including access. */ public static final BuiltInRole OWNER = BuiltInRole.fromString("Owner"); @@ -103,8 +103,8 @@ public final class BuiltInRole extends ExpandableStringEnum { public static final BuiltInRole REDIS_CACHE_CONTRIBUTOR = BuiltInRole.fromString("Redis Cache Contributor"); /** A role that can manage scheduler job collections. */ - public static final BuiltInRole SCHEDULER_JOB_COLLECTIONS_CONTRIBUTOR = - BuiltInRole.fromString("Scheduler Job Collections Contributor"); + public static final BuiltInRole SCHEDULER_JOB_COLLECTIONS_CONTRIBUTOR + = BuiltInRole.fromString("Scheduler Job Collections Contributor"); /** A role that can manage search services. */ public static final BuiltInRole SEARCH_SERVICE_CONTRIBUTOR = BuiltInRole.fromString("Search Service Contributor"); @@ -122,8 +122,8 @@ public final class BuiltInRole extends ExpandableStringEnum { public static final BuiltInRole SQL_SERVER_CONTRIBUTOR = BuiltInRole.fromString("SQL Server Contributor"); /** A role that can manage classic storage accounts. */ - public static final BuiltInRole CLASSIC_STORAGE_ACCOUNT_CONTRIBUTOR = - BuiltInRole.fromString("Classic Storage Account Contributor"); + public static final BuiltInRole CLASSIC_STORAGE_ACCOUNT_CONTRIBUTOR + = BuiltInRole.fromString("Classic Storage Account Contributor"); /** A role that can manage storage accounts. */ public static final BuiltInRole STORAGE_ACCOUNT_CONTRIBUTOR = BuiltInRole.fromString("Storage Account Contributor"); @@ -135,8 +135,8 @@ public final class BuiltInRole extends ExpandableStringEnum { * A role that can manage classic virtual machines, but not the virtual network or storage account to which they are * connected. */ - public static final BuiltInRole CLASSIC_VIRTUAL_MACHINE_CONTRIBUTOR = - BuiltInRole.fromString("Classic Virtual Machine Contributor"); + public static final BuiltInRole CLASSIC_VIRTUAL_MACHINE_CONTRIBUTOR + = BuiltInRole.fromString("Classic Virtual Machine Contributor"); /** * A role that can manage virtual machines, but not the virtual network or storage account to which they are @@ -158,91 +158,81 @@ public final class BuiltInRole extends ExpandableStringEnum { // Storage data related roles /** Storage Account Key Operators are allowed to list and regenerate keys on Storage Accounts. */ - public static final BuiltInRole STORAGE_ACCOUNT_KEY_OPERATOR_SERVICE_ROLE = - BuiltInRole.fromString("Storage Account Key Operator Service Role"); + public static final BuiltInRole STORAGE_ACCOUNT_KEY_OPERATOR_SERVICE_ROLE + = BuiltInRole.fromString("Storage Account Key Operator Service Role"); /** Allows for read, write and delete access to Azure Storage blob containers and data. */ - public static final BuiltInRole STORAGE_BLOB_DATA_CONTRIBUTOR = - BuiltInRole.fromString("Storage Blob Data Contributor"); + public static final BuiltInRole STORAGE_BLOB_DATA_CONTRIBUTOR + = BuiltInRole.fromString("Storage Blob Data Contributor"); /** Allows for full access to Azure Storage blob containers and data, including assigning POSIX access control. */ - public static final BuiltInRole STORAGE_BLOB_DATA_OWNER = - BuiltInRole.fromString("Storage Blob Data Owner"); + public static final BuiltInRole STORAGE_BLOB_DATA_OWNER = BuiltInRole.fromString("Storage Blob Data Owner"); /** Allows for read access to Azure Storage blob containers and data. */ - public static final BuiltInRole STORAGE_BLOB_DATA_READER = - BuiltInRole.fromString("Storage Blob Data Reader"); + public static final BuiltInRole STORAGE_BLOB_DATA_READER = BuiltInRole.fromString("Storage Blob Data Reader"); /** Allows for read, write, and delete access to Azure Storage queues and queue messages. */ - public static final BuiltInRole STORAGE_QUEUE_DATA_CONTRIBUTOR = - BuiltInRole.fromString("Storage Queue Data Contributor"); + public static final BuiltInRole STORAGE_QUEUE_DATA_CONTRIBUTOR + = BuiltInRole.fromString("Storage Queue Data Contributor"); /** Allows for peek, receive, and delete access to Azure Storage queue messages. */ - public static final BuiltInRole STORAGE_QUEUE_DATA_MESSAGE_PROCESSOR = - BuiltInRole.fromString("Storage Queue Data Message Processor"); + public static final BuiltInRole STORAGE_QUEUE_DATA_MESSAGE_PROCESSOR + = BuiltInRole.fromString("Storage Queue Data Message Processor"); /** Allows for sending of Azure Storage queue messages. */ - public static final BuiltInRole STORAGE_QUEUE_DATA_MESSAGE_SENDER = - BuiltInRole.fromString("Storage Queue Data Message Sender"); + public static final BuiltInRole STORAGE_QUEUE_DATA_MESSAGE_SENDER + = BuiltInRole.fromString("Storage Queue Data Message Sender"); /** Allows for read access to Azure Storage queues and queue messages. */ - public static final BuiltInRole STORAGE_QUEUE_DATA_READER = - BuiltInRole.fromString("Storage Queue Data Reader"); + public static final BuiltInRole STORAGE_QUEUE_DATA_READER = BuiltInRole.fromString("Storage Queue Data Reader"); /** Allows for read access to Azure File Share over SMB. */ - public static final BuiltInRole STORAGE_FILE_DATA_SMB_SHARE_READER = - BuiltInRole.fromString("Storage File Data SMB Share Reader"); + public static final BuiltInRole STORAGE_FILE_DATA_SMB_SHARE_READER + = BuiltInRole.fromString("Storage File Data SMB Share Reader"); /** Allows for read, write, and delete access in Azure Storage file shares over SMB. */ - public static final BuiltInRole STORAGE_FILE_DATA_SMB_SHARE_CONTRIBUTOR = - BuiltInRole.fromString("Storage File Data SMB Share Contributor"); + public static final BuiltInRole STORAGE_FILE_DATA_SMB_SHARE_CONTRIBUTOR + = BuiltInRole.fromString("Storage File Data SMB Share Contributor"); // Key Vault data related roles /** * Perform all data plane operations on a key vault and all objects in it, including certificates, keys, and * secrets. */ - public static final BuiltInRole KEY_VAULT_ADMINISTRATOR = - BuiltInRole.fromString("Key Vault Administrator"); + public static final BuiltInRole KEY_VAULT_ADMINISTRATOR = BuiltInRole.fromString("Key Vault Administrator"); /** Perform any action on the keys of a key vault, except manage permissions. */ - public static final BuiltInRole KEY_VAULT_CRYPTO_OFFICER = - BuiltInRole.fromString("Key Vault Crypto Officer"); + public static final BuiltInRole KEY_VAULT_CRYPTO_OFFICER = BuiltInRole.fromString("Key Vault Crypto Officer"); /** Perform cryptographic operations using keys. */ - public static final BuiltInRole KEY_VAULT_CRYPTO_USER = - BuiltInRole.fromString("Key Vault Crypto User"); + public static final BuiltInRole KEY_VAULT_CRYPTO_USER = BuiltInRole.fromString("Key Vault Crypto User"); /** Perform any action on the secrets of a key vault, except manage permissions. */ - public static final BuiltInRole KEY_VAULT_SECRETS_OFFICER = - BuiltInRole.fromString("Key Vault Secrets Officer"); + public static final BuiltInRole KEY_VAULT_SECRETS_OFFICER = BuiltInRole.fromString("Key Vault Secrets Officer"); /** Read secret contents. */ - public static final BuiltInRole KEY_VAULT_SECRETS_USER = - BuiltInRole.fromString("Key Vault Secrets User"); + public static final BuiltInRole KEY_VAULT_SECRETS_USER = BuiltInRole.fromString("Key Vault Secrets User"); /** Perform any action on the certificates of a key vault, except manage permissions. */ - public static final BuiltInRole KEY_VAULT_CERTIFICATES_OFFICER = - BuiltInRole.fromString("Key Vault Certificates Officer"); + public static final BuiltInRole KEY_VAULT_CERTIFICATES_OFFICER + = BuiltInRole.fromString("Key Vault Certificates Officer"); /** Read metadata of key vaults and its certificates, keys, and secrets. */ - public static final BuiltInRole KEY_VAULT_READER = - BuiltInRole.fromString("Key Vault Reader"); + public static final BuiltInRole KEY_VAULT_READER = BuiltInRole.fromString("Key Vault Reader"); /** Read metadata of keys and perform wrap/unwrap operations. */ - public static final BuiltInRole KEY_VAULT_CRYPTO_SERVICE_ENCRYPTION_USER = - BuiltInRole.fromString("Key Vault Crypto Service Encryption User"); + public static final BuiltInRole KEY_VAULT_CRYPTO_SERVICE_ENCRYPTION_USER + = BuiltInRole.fromString("Key Vault Crypto Service Encryption User"); // AKS related roles /** Lets you manage all resources in the cluster. */ - public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_CLUSTER_ADMIN = - BuiltInRole.fromString("Azure Kubernetes Service RBAC Cluster Admin"); + public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_CLUSTER_ADMIN + = BuiltInRole.fromString("Azure Kubernetes Service RBAC Cluster Admin"); /** Lets you manage all resources under cluster/namespace, * except update or delete resource quotas and namespaces. */ - public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_ADMIN = - BuiltInRole.fromString("Azure Kubernetes Service RBAC Admin"); + public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_ADMIN + = BuiltInRole.fromString("Azure Kubernetes Service RBAC Admin"); /** Allows read-only access to see most objects in a namespace. It does not allow viewing roles or role bindings. * This role does not allow viewing Secrets, since reading the contents of Secrets enables access to ServiceAccount * credentials in the namespace, which would allow API access as any ServiceAccount in the namespace * (a form of privilege escalation). * Applying this role at cluster scope will give access across all namespaces. */ - public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_READER = - BuiltInRole.fromString("Azure Kubernetes Service RBAC Reader"); + public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_READER + = BuiltInRole.fromString("Azure Kubernetes Service RBAC Reader"); /** Allows read/write access to most objects in a namespace. * This role does not allow viewing or modifying roles or role bindings. * However, this role allows accessing Secrets and running Pods as any ServiceAccount in the namespace, * so it can be used to gain the API access levels of any ServiceAccount in the namespace. * Applying this role at cluster scope will give access across all namespaces. */ - public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_WRITER = - BuiltInRole.fromString("Azure Kubernetes Service RBAC Writer"); + public static final BuiltInRole AZURE_KUBERNETES_SERVICE_RBAC_WRITER + = BuiltInRole.fromString("Azure Kubernetes Service RBAC Writer"); /** Read and create quota requests, get quota request status, and create support tickets. */ - public static final BuiltInRole QUOTA_REQUEST_OPERATOR = - BuiltInRole.fromString("Quota Request Operator"); + public static final BuiltInRole QUOTA_REQUEST_OPERATOR = BuiltInRole.fromString("Quota Request Operator"); /** * Finds or creates a role instance based on the specified name. diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/CertificateCredential.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/CertificateCredential.java index 79e20db63dbfb..b59fbe3a6337d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/CertificateCredential.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/CertificateCredential.java @@ -25,14 +25,10 @@ public interface CertificateCredential extends Credential, HasInnerModel the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithCertificateType, - DefinitionStages.WithPublicKey, - DefinitionStages.WithSymmetricKey, - DefinitionStages.WithAttach, - DefinitionStages.WithAuthFileCertificate, - DefinitionStages.WithAuthFileCertificatePassword { + interface Definition extends DefinitionStages.Blank, + DefinitionStages.WithCertificateType, DefinitionStages.WithPublicKey, + DefinitionStages.WithSymmetricKey, DefinitionStages.WithAttach, + DefinitionStages.WithAuthFileCertificate, DefinitionStages.WithAuthFileCertificatePassword { } /** Grouping of credential definition stages applicable as part of a application or service principal creation. */ @@ -172,11 +168,8 @@ interface WithAuthFileCertificatePassword { * * @param the return type of {@link WithAttach#attach()} */ - interface WithAttach - extends Attachable.InDefinition, - WithStartDate, - WithDuration, - WithAuthFile { + interface WithAttach extends Attachable.InDefinition, WithStartDate, + WithDuration, WithAuthFile { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/PasswordCredential.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/PasswordCredential.java index 4175d0a3b09a4..aba1b2dc506de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/PasswordCredential.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/PasswordCredential.java @@ -26,10 +26,8 @@ public interface PasswordCredential extends Credential, HasInnerModel the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithSubscriptionInAuthFile, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, + DefinitionStages.WithSubscriptionInAuthFile, DefinitionStages.WithAttach { } /** Grouping of credential definition stages applicable as part of a application or service principal creation. */ @@ -127,12 +125,8 @@ interface WithConsumer { * * @param the return type of {@link WithAttach#attach()} */ - interface WithAttach - extends Attachable.InDefinition, - WithStartDate, - WithDuration, - WithConsumer, - WithAuthFile { + interface WithAttach extends Attachable.InDefinition, WithStartDate, + WithDuration, WithConsumer, WithAuthFile { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignment.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignment.java index f997c3412b281..a281b7e96a5d7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignment.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignment.java @@ -49,11 +49,8 @@ public interface RoleAssignment **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithRole, - DefinitionStages.WithScope, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithRole, DefinitionStages.WithScope, + DefinitionStages.WithCreate { } /** Grouping of all the role assignment definition stages. */ @@ -122,6 +119,7 @@ interface WithRole { * @return the next stage in role assignment definition */ WithScope withBuiltInRole(BuiltInRole role); + /** * Specifies the ID of the custom role for this assignment. * diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignments.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignments.java index e88f209a7a6a0..7b087a75e1371 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignments.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleAssignments.java @@ -17,11 +17,8 @@ /** Entry point to role assignment management API. */ @Fluent public interface RoleAssignments - extends SupportsGettingById, - SupportsCreating, - SupportsBatchCreation, - SupportsDeletingById, - HasManager { + extends SupportsGettingById, SupportsCreating, + SupportsBatchCreation, SupportsDeletingById, HasManager { /** * Gets the information about a role assignment based on scope and name. * @@ -72,7 +69,6 @@ public interface RoleAssignments */ PagedIterable listByServicePrincipal(ServicePrincipal servicePrincipal); - /** * List role assignments for a service principal. * diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleDefinitions.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleDefinitions.java index 0e910c091dd84..baaa64e7c47ff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleDefinitions.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/RoleDefinitions.java @@ -13,8 +13,7 @@ /** Entry point to role definition management API. */ @Fluent -public interface RoleDefinitions - extends SupportsGettingById, HasManager { +public interface RoleDefinitions extends SupportsGettingById, HasManager { /** * Gets the information about a role definition based on scope and name. * diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipal.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipal.java index d88d533056a54..99db96377d33f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipal.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipal.java @@ -17,10 +17,8 @@ /** An immutable client-side representation of an Azure AD service principal. */ @Fluent -public interface ServicePrincipal - extends ActiveDirectoryObject, - HasInnerModel, - Updatable { +public interface ServicePrincipal extends ActiveDirectoryObject, HasInnerModel, + Updatable { /** @return app id. */ String applicationId(); @@ -159,8 +157,7 @@ interface WithCredential { * @param name the descriptive name of the certificate credential * @return the first stage in certificate credential update */ - CertificateCredential.DefinitionStages.Blank - defineCertificateCredential(String name); + CertificateCredential.DefinitionStages.Blank defineCertificateCredential(String name); /** * Starts the definition of a password credential. @@ -219,9 +216,7 @@ interface WithRoleAssignment { } /** The template for a service principal update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - ServicePrincipal.UpdateStages.WithCredential, - ServicePrincipal.UpdateStages.WithRoleAssignment { + interface Update extends Appliable, ServicePrincipal.UpdateStages.WithCredential, + ServicePrincipal.UpdateStages.WithRoleAssignment { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipals.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipals.java index d264b9e4bda62..ad3f2462f418a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipals.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/models/ServicePrincipals.java @@ -15,12 +15,7 @@ /** Entry point to service principal management API. */ @Fluent -public interface ServicePrincipals - extends SupportsListing, - SupportsListingByFilter, - SupportsGettingById, - SupportsGettingByName, - SupportsCreating, - SupportsDeletingById, - HasManager { +public interface ServicePrincipals extends SupportsListing, SupportsListingByFilter, + SupportsGettingById, SupportsGettingByName, + SupportsCreating, SupportsDeletingById, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/utils/RoleAssignmentHelper.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/utils/RoleAssignmentHelper.java index 2ce03fa8d2d64..d3902e459d7f3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/utils/RoleAssignmentHelper.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/utils/RoleAssignmentHelper.java @@ -30,6 +30,7 @@ public class RoleAssignmentHelper { public interface IdProvider { /** @return the service principal id (object id) */ String principalId(); + /** @return ARM resource id of the resource */ String resourceId(); } @@ -47,8 +48,8 @@ public interface IdProvider { * @param taskGroup the pre-run task group after which role assignments create/remove tasks should run * @param idProvider the provider that provides service principal id and resource id */ - public RoleAssignmentHelper( - final AuthorizationManager authorizationManager, TaskGroup taskGroup, IdProvider idProvider) { + public RoleAssignmentHelper(final AuthorizationManager authorizationManager, TaskGroup taskGroup, + IdProvider idProvider) { this.authorizationManager = Objects.requireNonNull(authorizationManager); this.idProvider = Objects.requireNonNull(idProvider); this.preRunTaskGroup = Objects.requireNonNull(taskGroup); @@ -74,35 +75,32 @@ public RoleAssignmentHelper withAccessToCurrentResourceGroup(BuiltInRole asRole) * @return RoleAssignmentHelper */ public RoleAssignmentHelper withAccessTo(final String scope, final BuiltInRole asRole) { - FunctionalTaskItem creator = - cxt -> { - final String principalId = idProvider.principalId(); - if (principalId == null) { - return cxt.voidMono(); - } - final String roleAssignmentName = authorizationManager.internalContext().randomUuid(); - final String resourceScope; - if (scope.equals(CURRENT_RESOURCE_GROUP_SCOPE)) { - resourceScope = resourceGroupId(idProvider.resourceId()); - } else { - resourceScope = scope; - } - return authorizationManager - .roleAssignments() - .define(roleAssignmentName) - .forObjectId(principalId) - .withBuiltInRole(asRole) - .withScope(resourceScope) - .createAsync() - .cast(Indexable.class) - .onErrorResume( - throwable -> { - if (isRoleAssignmentExists(throwable)) { - return cxt.voidMono(); - } - return Mono.error(throwable); - }); - }; + FunctionalTaskItem creator = cxt -> { + final String principalId = idProvider.principalId(); + if (principalId == null) { + return cxt.voidMono(); + } + final String roleAssignmentName = authorizationManager.internalContext().randomUuid(); + final String resourceScope; + if (scope.equals(CURRENT_RESOURCE_GROUP_SCOPE)) { + resourceScope = resourceGroupId(idProvider.resourceId()); + } else { + resourceScope = scope; + } + return authorizationManager.roleAssignments() + .define(roleAssignmentName) + .forObjectId(principalId) + .withBuiltInRole(asRole) + .withScope(resourceScope) + .createAsync() + .cast(Indexable.class) + .onErrorResume(throwable -> { + if (isRoleAssignmentExists(throwable)) { + return cxt.voidMono(); + } + return Mono.error(throwable); + }); + }; this.preRunTaskGroup.addPostRunDependent(creator, authorizationManager.internalContext()); return this; } @@ -127,35 +125,32 @@ public RoleAssignmentHelper withAccessToCurrentResourceGroup(String roleDefiniti * @return RoleAssignmentHelper */ public RoleAssignmentHelper withAccessTo(final String scope, final String roleDefinitionId) { - FunctionalTaskItem creator = - cxt -> { - final String principalId = idProvider.principalId(); - if (principalId == null) { - return cxt.voidMono(); - } - final String roleAssignmentName = authorizationManager.internalContext().randomUuid(); - final String resourceScope; - if (scope.equals(CURRENT_RESOURCE_GROUP_SCOPE)) { - resourceScope = resourceGroupId(idProvider.resourceId()); - } else { - resourceScope = scope; - } - return authorizationManager - .roleAssignments() - .define(roleAssignmentName) - .forObjectId(principalId) - .withRoleDefinition(roleDefinitionId) - .withScope(resourceScope) - .createAsync() - .cast(Indexable.class) - .onErrorResume( - throwable -> { - if (isRoleAssignmentExists(throwable)) { - return cxt.voidMono(); - } - return Mono.error(throwable); - }); - }; + FunctionalTaskItem creator = cxt -> { + final String principalId = idProvider.principalId(); + if (principalId == null) { + return cxt.voidMono(); + } + final String roleAssignmentName = authorizationManager.internalContext().randomUuid(); + final String resourceScope; + if (scope.equals(CURRENT_RESOURCE_GROUP_SCOPE)) { + resourceScope = resourceGroupId(idProvider.resourceId()); + } else { + resourceScope = scope; + } + return authorizationManager.roleAssignments() + .define(roleAssignmentName) + .forObjectId(principalId) + .withRoleDefinition(roleDefinitionId) + .withScope(resourceScope) + .createAsync() + .cast(Indexable.class) + .onErrorResume(throwable -> { + if (isRoleAssignmentExists(throwable)) { + return cxt.voidMono(); + } + return Mono.error(throwable); + }); + }; this.preRunTaskGroup.addPostRunDependent(creator, authorizationManager.internalContext()); return this; } @@ -171,8 +166,8 @@ public RoleAssignmentHelper withoutAccessTo(final RoleAssignment roleAssignment) if (principalId == null || !principalId.equalsIgnoreCase(idProvider.principalId())) { return this; } - FunctionalTaskItem remover = - cxt -> authorizationManager.roleAssignments().deleteByIdAsync(roleAssignment.id()).then(cxt.voidMono()); + FunctionalTaskItem remover + = cxt -> authorizationManager.roleAssignments().deleteByIdAsync(roleAssignment.id()).then(cxt.voidMono()); this.preRunTaskGroup.addPostRunDependent(remover); return this; } @@ -185,38 +180,24 @@ public RoleAssignmentHelper withoutAccessTo(final RoleAssignment roleAssignment) * @return RoleAssignmentHelper */ public RoleAssignmentHelper withoutAccessTo(final String scope, final BuiltInRole asRole) { - FunctionalTaskItem remover = - cxt -> - authorizationManager - .roleDefinitions() - .getByScopeAndRoleNameAsync(scope, asRole.toString()) - .flatMap( - (Function>) - roleDefinition -> - authorizationManager - .roleAssignments() - .listByScopeAsync(scope) - .filter( - roleAssignment -> { - if (roleDefinition != null && roleAssignment != null) { - return roleAssignment - .roleDefinitionId() - .equalsIgnoreCase(roleDefinition.id()) - && roleAssignment - .principalId() - .equalsIgnoreCase(idProvider.principalId()); - } else { - return false; - } - }) - .last()) - .flatMap( - (Function>) - roleAssignment -> - authorizationManager - .roleAssignments() - .deleteByIdAsync(roleAssignment.id()) - .then(cxt.voidMono())); + FunctionalTaskItem remover = cxt -> authorizationManager.roleDefinitions() + .getByScopeAndRoleNameAsync(scope, asRole.toString()) + .flatMap((Function>) roleDefinition -> authorizationManager + .roleAssignments() + .listByScopeAsync(scope) + .filter(roleAssignment -> { + if (roleDefinition != null && roleAssignment != null) { + return roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) + && roleAssignment.principalId().equalsIgnoreCase(idProvider.principalId()); + } else { + return false; + } + }) + .last()) + .flatMap( + (Function>) roleAssignment -> authorizationManager.roleAssignments() + .deleteByIdAsync(roleAssignment.id()) + .then(cxt.voidMono())); this.preRunTaskGroup.addPostRunDependent(remover); return this; } @@ -230,8 +211,7 @@ public RoleAssignmentHelper withoutAccessTo(final String scope, final BuiltInRol private static String resourceGroupId(String id) { final ResourceId resourceId = ResourceId.fromString(id); final StringBuilder builder = new StringBuilder(); - builder - .append("/subscriptions/") + builder.append("/subscriptions/") .append(resourceId.subscriptionId()) .append("/resourceGroups/") .append(resourceId.resourceGroupName()); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ApplicationsTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ApplicationsTests.java index 2e1eae998607a..e1e4a7af60133 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ApplicationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ApplicationsTests.java @@ -19,20 +19,18 @@ public void canCRUDApplication() throws Exception { ActiveDirectoryApplication application = null; try { - application = - authorizationManager - .applications() - .define(name) - .withSignOnUrl("http://easycreate.azure.com/" + name) - .definePasswordCredential("passwd") - .withDuration(Duration.ofDays(700)) - .attach() - .defineCertificateCredential("cert") - .withAsymmetricX509Certificate() - .withPublicKey(replaceCRLF(readAllBytes(this.getClass().getResourceAsStream("/myTest.cer")))) - .withDuration(Duration.ofDays(100)) - .attach() - .create(); + application = authorizationManager.applications() + .define(name) + .withSignOnUrl("http://easycreate.azure.com/" + name) + .definePasswordCredential("passwd") + .withDuration(Duration.ofDays(700)) + .attach() + .defineCertificateCredential("cert") + .withAsymmetricX509Certificate() + .withPublicKey(replaceCRLF(readAllBytes(this.getClass().getResourceAsStream("/myTest.cer")))) + .withDuration(Duration.ofDays(100)) + .attach() + .create(); System.out.println(application.id() + " - " + application.applicationId()); Assertions.assertNotNull(application.id()); Assertions.assertNotNull(application.applicationId()); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GraphRbacManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GraphRbacManagementTest.java index 8563d635543d5..cc6e248508b99 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GraphRbacManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GraphRbacManagementTest.java @@ -29,21 +29,10 @@ public abstract class GraphRbacManagementTest extends ResourceManagerTestProxyTe protected ResourceManager resourceManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -53,7 +42,6 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile resourceManager = buildManager(ResourceManager.class, httpPipeline, profile); } - @Override protected void cleanUpResources() { } @@ -69,8 +57,6 @@ protected byte[] readAllBytes(InputStream inputStream) throws IOException { } protected byte[] replaceCRLF(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8) - .replace("\r\n", "\n") - .getBytes(StandardCharsets.UTF_8); + return new String(bytes, StandardCharsets.UTF_8).replace("\r\n", "\n").getBytes(StandardCharsets.UTF_8); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GroupsTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GroupsTests.java index 8411c067cce4b..9c58d035fffce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GroupsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/GroupsTests.java @@ -31,26 +31,21 @@ public void canCRUDGroup() throws Exception { // Disable `$.appId` sanitizer for this test interceptorManager.removeSanitizers("AZSDK3432"); try { - user = - authorizationManager - .users() - .define(userName) - .withEmailAlias(userName) - .withPassword(password()) - .create(); - servicePrincipal = - authorizationManager.servicePrincipals().define(spName).withNewApplication().create(); + user = authorizationManager.users() + .define(userName) + .withEmailAlias(userName) + .withPassword(password()) + .create(); + servicePrincipal = authorizationManager.servicePrincipals().define(spName).withNewApplication().create(); group1 = authorizationManager.groups().define(group1Name).withEmailAlias(group1Name).create(); ResourceManagerUtils.sleep(Duration.ofSeconds(15)); - group2 = - authorizationManager - .groups() - .define(group2Name) - .withEmailAlias(group2Name) - .withMember(user.id()) - .withMember(servicePrincipal.id()) - .withMember(group1.id()) - .create(); + group2 = authorizationManager.groups() + .define(group2Name) + .withEmailAlias(group2Name) + .withMember(user.id()) + .withMember(servicePrincipal.id()) + .withMember(group1.id()) + .create(); Assertions.assertNotNull(group2); Assertions.assertNotNull(group2.id()); @@ -65,9 +60,9 @@ public void canCRUDGroup() throws Exception { try { authorizationManager.servicePrincipals().deleteById(servicePrincipal.id()); } finally { - authorizationManager.applications().deleteById( - authorizationManager.applications().getByName(servicePrincipal.applicationId()).id() - ); + authorizationManager.applications() + .deleteById( + authorizationManager.applications().getByName(servicePrincipal.applicationId()).id()); } } } finally { diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleAssignmentTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleAssignmentTests.java index 8e07b35df5e82..c117f48724873 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleAssignmentTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleAssignmentTests.java @@ -21,26 +21,25 @@ public void canCRUDRoleAssignment() throws Exception { String spName = generateRandomResourceName("sp", 20); // Disable `$.appId` sanitizer for this test interceptorManager.removeSanitizers("AZSDK3432"); - ServicePrincipal sp = - authorizationManager.servicePrincipals().define(spName).withNewApplication().create(); + ServicePrincipal sp = authorizationManager.servicePrincipals().define(spName).withNewApplication().create(); try { ResourceManagerUtils.sleep(Duration.ofSeconds(15)); - RoleAssignment roleAssignment = - authorizationManager - .roleAssignments() - .define(roleAssignmentName) - .forServicePrincipal(sp) - .withBuiltInRole(BuiltInRole.CONTRIBUTOR) - .withSubscriptionScope(resourceManager.subscriptionId()) - .withDescription("contributor role") - .create(); + RoleAssignment roleAssignment = authorizationManager.roleAssignments() + .define(roleAssignmentName) + .forServicePrincipal(sp) + .withBuiltInRole(BuiltInRole.CONTRIBUTOR) + .withSubscriptionScope(resourceManager.subscriptionId()) + .withDescription("contributor role") + .create(); Assertions.assertNotNull(roleAssignment); List roleAssignments = authorizationManager.roleAssignments() - .listByServicePrincipal(sp.id()).stream().collect(Collectors.toList()); + .listByServicePrincipal(sp.id()) + .stream() + .collect(Collectors.toList()); Assertions.assertEquals(1, roleAssignments.size()); RoleAssignment roleAssignment1 = roleAssignments.iterator().next(); @@ -54,8 +53,7 @@ public void canCRUDRoleAssignment() throws Exception { Assertions.assertEquals("contributor role", roleAssignment1.description()); } finally { authorizationManager.servicePrincipals().deleteById(sp.id()); - authorizationManager - .applications() + authorizationManager.applications() .deleteById(authorizationManager.applications().getByName(sp.applicationId()).id()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleDefinitionTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleDefinitionTests.java index 58377c079a4ee..fac238993ee2a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleDefinitionTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/RoleDefinitionTests.java @@ -14,10 +14,8 @@ public class RoleDefinitionTests extends GraphRbacManagementTest { @Test public void canGetRoleByRoleName() throws Exception { - RoleDefinition roleDefinition = - authorizationManager - .roleDefinitions() - .getByScopeAndRoleName("subscriptions/" + resourceManager.subscriptionId(), "Contributor"); + RoleDefinition roleDefinition = authorizationManager.roleDefinitions() + .getByScopeAndRoleName("subscriptions/" + resourceManager.subscriptionId(), "Contributor"); Assertions.assertNotNull(roleDefinition); Assertions.assertEquals("Contributor", roleDefinition.roleName()); } @@ -25,8 +23,8 @@ public void canGetRoleByRoleName() throws Exception { @Test @Disabled("Util to generate missing built-in role") public void generateMissingRole() { - PagedIterable roleDefinitions = - authorizationManager.roleDefinitions().listByScope("subscriptions/" + resourceManager.subscriptionId()); + PagedIterable roleDefinitions + = authorizationManager.roleDefinitions().listByScope("subscriptions/" + resourceManager.subscriptionId()); StringBuilder sb = new StringBuilder(); @@ -35,9 +33,18 @@ public void generateMissingRole() { .forEach(r -> { String roleEnumName = r.roleName().toUpperCase(Locale.ROOT).replaceAll(" ", "_"); - sb.append("/** ").append(r.description()).append(". */").append(System.lineSeparator()) - .append("public static final BuiltInRole ").append(roleEnumName).append(" =").append(System.lineSeparator()) - .append(" BuiltInRole.fromString(\"").append(r.roleName()).append("\");").append(System.lineSeparator()); + sb.append("/** ") + .append(r.description()) + .append(". */") + .append(System.lineSeparator()) + .append("public static final BuiltInRole ") + .append(roleEnumName) + .append(" =") + .append(System.lineSeparator()) + .append(" BuiltInRole.fromString(\"") + .append(r.roleName()) + .append("\");") + .append(System.lineSeparator()); }); System.out.print(sb.toString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ServicePrincipalsTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ServicePrincipalsTests.java index 58e6ab6ab2504..90802d0b4d347 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ServicePrincipalsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/ServicePrincipalsTests.java @@ -35,16 +35,13 @@ public void canCRUDServicePrincipal() throws Exception { interceptorManager.removeSanitizers("AZSDK3432"); try { // Create - servicePrincipal = - authorizationManager - .servicePrincipals() - .define(name) - .withNewApplication() - .definePasswordCredential("sppass") - .attach() - .create(); - System - .out + servicePrincipal = authorizationManager.servicePrincipals() + .define(name) + .withNewApplication() + .definePasswordCredential("sppass") + .attach() + .create(); + System.out .println(servicePrincipal.id() + " - " + String.join(",", servicePrincipal.servicePrincipalNames())); Assertions.assertNotNull(servicePrincipal.id()); Assertions.assertNotNull(servicePrincipal.applicationId()); @@ -61,12 +58,12 @@ public void canCRUDServicePrincipal() throws Exception { Assertions.assertEquals(0, servicePrincipal.certificateCredentials().size()); // Update - servicePrincipal - .update() + servicePrincipal.update() .withoutCredential("sppass") .defineCertificateCredential("spcert") .withAsymmetricX509Certificate() - .withPublicKey(replaceCRLF(readAllBytes(ServicePrincipalsTests.class.getResourceAsStream("/myTest.cer")))) + .withPublicKey( + replaceCRLF(readAllBytes(ServicePrincipalsTests.class.getResourceAsStream("/myTest.cer")))) .withDuration(Duration.ofDays(1)) .attach() .apply(); @@ -78,8 +75,7 @@ public void canCRUDServicePrincipal() throws Exception { } finally { if (servicePrincipal != null) { authorizationManager.servicePrincipals().deleteById(servicePrincipal.id()); - authorizationManager - .applications() + authorizationManager.applications() .deleteById(authorizationManager.applications().getByName(servicePrincipal.applicationId()).id()); } } @@ -99,41 +95,41 @@ public void canConsumeServicePrincipalPassword() { ServicePrincipal servicePrincipal = null; try { - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST) - .create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - servicePrincipal = authorizationManager.servicePrincipals().define(name) + servicePrincipal = authorizationManager.servicePrincipals() + .define(name) .withNewApplication() .definePasswordCredential(passwordName) - .withPasswordConsumer(password -> clientSecret.add(password.value())) - .attach() + .withPasswordConsumer(password -> clientSecret.add(password.value())) + .attach() .withNewRoleInResourceGroup(BuiltInRole.READER, resourceGroup) .create(); Assertions.assertEquals(1, clientSecret.size()); - TokenCredential credential = new ClientSecretCredentialBuilder() - .clientId(servicePrincipal.applicationId()) + TokenCredential credential = new ClientSecretCredentialBuilder().clientId(servicePrincipal.applicationId()) .clientSecret(clientSecret.get(0)) .tenantId(profile().getTenantId()) .authorityHost(profile().getEnvironment().getActiveDirectoryEndpoint()) .httpClient(generateHttpClientWithProxy(null, null)) .build(); - ResourceManager resourceManager1 = ResourceManager.authenticate(credential, profile()) - .withDefaultSubscription(); + ResourceManager resourceManager1 + = ResourceManager.authenticate(credential, profile()).withDefaultSubscription(); - Assertions.assertEquals(resourceGroup.id(), resourceManager1.resourceGroups().getByName(resourceGroup.name()).id()); + Assertions.assertEquals(resourceGroup.id(), + resourceManager1.resourceGroups().getByName(resourceGroup.name()).id()); } finally { try { if (servicePrincipal != null) { try { authorizationManager.servicePrincipals().deleteById(servicePrincipal.id()); } finally { - authorizationManager.applications().deleteById( - authorizationManager.applications().getByName(servicePrincipal.applicationId()).id() - ); + authorizationManager.applications() + .deleteById( + authorizationManager.applications().getByName(servicePrincipal.applicationId()).id()); } } } finally { @@ -152,41 +148,36 @@ public void canCRUDServicePrincipalWithRole() throws Exception { String subscription = "0b1f6471-1bf0-4dda-aec3-cb9272f09590"; try { // Create - servicePrincipal = - authorizationManager - .servicePrincipals() - .define(name) - .withNewApplication() - .definePasswordCredential("sppass") - .attach() - .defineCertificateCredential("spcert") - .withAsymmetricX509Certificate() - .withPublicKey(Files.readAllBytes(Paths.get("/Users/jianghlu/Documents/code/certs/myserver.crt"))) - .withDuration(Duration.ofDays(7)) - .withAuthFileToExport(new FileOutputStream(authFile)) - .withPrivateKeyFile("/Users/jianghlu/Documents/code/certs/myserver.pfx") - .withPrivateKeyPassword("StrongPass!123") - .attach() - .withNewRoleInSubscription(BuiltInRole.CONTRIBUTOR, subscription) - .create(); - System - .out + servicePrincipal = authorizationManager.servicePrincipals() + .define(name) + .withNewApplication() + .definePasswordCredential("sppass") + .attach() + .defineCertificateCredential("spcert") + .withAsymmetricX509Certificate() + .withPublicKey(Files.readAllBytes(Paths.get("/Users/jianghlu/Documents/code/certs/myserver.crt"))) + .withDuration(Duration.ofDays(7)) + .withAuthFileToExport(new FileOutputStream(authFile)) + .withPrivateKeyFile("/Users/jianghlu/Documents/code/certs/myserver.pfx") + .withPrivateKeyPassword("StrongPass!123") + .attach() + .withNewRoleInSubscription(BuiltInRole.CONTRIBUTOR, subscription) + .create(); + System.out .println(servicePrincipal.id() + " - " + String.join(",", servicePrincipal.servicePrincipalNames())); Assertions.assertNotNull(servicePrincipal.id()); Assertions.assertNotNull(servicePrincipal.applicationId()); Assertions.assertEquals(2, servicePrincipal.servicePrincipalNames().size()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); - ResourceManager resourceManager = - ResourceManager - .authenticate(new DefaultAzureCredentialBuilder().build(), profile()) + ResourceManager resourceManager + = ResourceManager.authenticate(new DefaultAzureCredentialBuilder().build(), profile()) .withSubscription(subscription); ResourceGroup group = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); // Update RoleAssignment ra = servicePrincipal.roleAssignments().iterator().next(); - servicePrincipal - .update() + servicePrincipal.update() .withoutRole(ra) .withNewRoleInResourceGroup(BuiltInRole.CONTRIBUTOR, group) .apply(); @@ -205,8 +196,7 @@ public void canCRUDServicePrincipalWithRole() throws Exception { } catch (Exception e) { } try { - authorizationManager - .applications() + authorizationManager.applications() .deleteById(authorizationManager.applications().getByName(servicePrincipal.applicationId()).id()); } catch (Exception e) { } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/UsersTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/UsersTests.java index 2bc0d49ee6fab..b46e5891a0ff7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/UsersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/UsersTests.java @@ -34,14 +34,12 @@ public void canGetUserByDisplayName() throws Exception { @Test public void canCreateUser() throws Exception { String name = generateRandomResourceName("user", 16); - ActiveDirectoryUser user = - authorizationManager - .users() - .define("Automatic " + name) - .withEmailAlias(name) - .withPassword(password()) - .withPromptToChangePasswordOnLogin(true) - .create(); + ActiveDirectoryUser user = authorizationManager.users() + .define("Automatic " + name) + .withEmailAlias(name) + .withPassword(password()) + .withPromptToChangePasswordOnLogin(true) + .create(); try { Assertions.assertNotNull(user); @@ -55,13 +53,11 @@ public void canCreateUser() throws Exception { @Test public void canUpdateUser() throws Exception { String name = generateRandomResourceName("user", 16); - ActiveDirectoryUser user = - authorizationManager - .users() - .define("Test " + name) - .withEmailAlias(name) - .withPassword(password()) - .create(); + ActiveDirectoryUser user = authorizationManager.users() + .define("Test " + name) + .withEmailAlias(name) + .withPassword(password()) + .create(); try { user = user.update().withUsageLocation(CountryIsoCode.AUSTRALIA).apply(); @@ -69,7 +65,8 @@ public void canUpdateUser() throws Exception { Assertions.assertEquals(CountryIsoCode.AUSTRALIA, user.usageLocation()); ActiveDirectoryUser finalUser = user; - Assertions.assertTrue(authorizationManager.users().list().stream().anyMatch(x -> x.id().equals(finalUser.id()))); + Assertions + .assertTrue(authorizationManager.users().list().stream().anyMatch(x -> x.id().equals(finalUser.id()))); } finally { authorizationManager.users().deleteById(user.id()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java index 3e50a823425b5..6886afb8ed175 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java @@ -54,17 +54,20 @@ public void testRetryForGraph() { retryCount.set(0); StepVerifier.create(monoError400.retryWhen(retry)) .expectSubscription() - .expectErrorMatches(e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 400) + .expectErrorMatches( + e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 400) .verify(); Assertions.assertEquals(0, retryCount.get()); // 404 but not expected error code, no retry - Mono monoError404WrongErrorCode = Mono.error(new ManagementException("error", mockedResponse404, new ManagementError("WrongErrorCode", ""))); + Mono monoError404WrongErrorCode = Mono + .error(new ManagementException("error", mockedResponse404, new ManagementError("WrongErrorCode", ""))); retryCount.set(0); StepVerifier.create(monoError404WrongErrorCode.retryWhen(retry)) .expectSubscription() - .expectErrorMatches(e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 404) + .expectErrorMatches( + e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 404) .verify(); Assertions.assertEquals(0, retryCount.get()); @@ -74,7 +77,8 @@ public void testRetryForGraph() { retryCount.set(0); StepVerifier.create(monoError404.retryWhen(retry)) .expectSubscription() - .expectErrorMatches(e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 404) + .expectErrorMatches( + e -> e instanceof ManagementException && ((ManagementException) e).getResponse().getStatusCode() == 404) .verify(); Assertions.assertEquals(3, retryCount.get()); diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml index 4955d9f7b43cd..b858c9c9907f1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml @@ -46,6 +46,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/CdnManager.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/CdnManager.java index bf2c85f288da4..c5830ffc26c2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/CdnManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/CdnManager.java @@ -84,11 +84,8 @@ public CdnManager authenticate(TokenCredential credential, AzureProfile profile) } private CdnManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new CdnManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new CdnManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointImpl.java index 0461014d98a1e..a71e923b53575 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointImpl.java @@ -42,26 +42,20 @@ * Implementation for {@link CdnEndpoint}. */ @SuppressWarnings("unchecked") -class CdnEndpointImpl - extends ExternalChildResourceImpl< - CdnEndpoint, - EndpointInner, - CdnProfileImpl, - CdnProfile> +class CdnEndpointImpl extends ExternalChildResourceImpl implements CdnEndpoint, - CdnEndpoint.DefinitionStages.Blank.StandardEndpoint, - CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint, - CdnEndpoint.DefinitionStages.WithStandardAttach, - CdnEndpoint.DefinitionStages.WithPremiumAttach, + CdnEndpoint.DefinitionStages.Blank.StandardEndpoint, + CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint, + CdnEndpoint.DefinitionStages.WithStandardAttach, + CdnEndpoint.DefinitionStages.WithPremiumAttach, - CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint, - CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint, - CdnEndpoint.UpdateDefinitionStages.WithStandardAttach, - CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach, + CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint, + CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint, + CdnEndpoint.UpdateDefinitionStages.WithStandardAttach, + CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach, - CdnEndpoint.UpdateStandardEndpoint, - CdnEndpoint.UpdatePremiumEndpoint { + CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List customDomainList; private List deletedCustomDomainList; @@ -86,32 +80,38 @@ public Mono createResourceAsync() { if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { - this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() - .withRules(this.standardRulesEngineRuleMap.values() - .stream() - .sorted(Comparator.comparingInt(DeliveryRule::order)) - .collect(Collectors.toList()))); + this.innerModel() + .withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() + .withRules(this.standardRulesEngineRuleMap.values() + .stream() + .sorted(Comparator.comparingInt(DeliveryRule::order)) + .collect(Collectors.toList()))); } - return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - this.innerModel()) + return this.parent() + .manager() + .serviceClient() + .getEndpoints() + .createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) - .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() - .getCustomDomains().createAsync( - self.parent().resourceGroupName(), - self.parent().name(), - self.name(), - self.parent().manager().resourceManager().internalContext() + .flatMapDelayError(customDomainInner -> self.parent() + .manager() + .serviceClient() + .getCustomDomains() + .createAsync(self.parent().resourceGroupName(), self.parent().name(), self.name(), + self.parent() + .manager() + .resourceManager() + .internalContext() .randomResourceName("CustomDomain", 50), - new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) - .then(self.parent().manager().serviceClient() - .getCustomDomains().listByEndpointAsync( - self.parent().resourceGroupName(), - self.parent().name(), - self.name()) + new CustomDomainParameters().withHostname(customDomainInner.hostname())), + 32, 32) + .then(self.parent() + .manager() + .serviceClient() + .getCustomDomains() + .listByEndpointAsync(self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); @@ -125,15 +125,15 @@ public Mono updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) - .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) - .withOriginPath(this.innerModel().originPath()) - .withOriginHostHeader(this.innerModel().originHostHeader()) - .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) - .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) - .withGeoFilters(this.innerModel().geoFilters()) - .withOptimizationType(this.innerModel().optimizationType()) - .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) - .withTags(this.innerModel().tags()); + .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) + .withOriginPath(this.innerModel().originPath()) + .withOriginHostHeader(this.innerModel().originHostHeader()) + .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) + .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) + .withGeoFilters(this.innerModel().geoFilters()) + .withOptimizationType(this.innerModel().optimizationType()) + .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) + .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List rules = this.standardRulesEngineRuleMap.values() @@ -141,103 +141,106 @@ public Mono updateResourceAsync() { .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); ensureDeliveryPolicy(); - endpointUpdateParameters.withDeliveryPolicy( - new EndpointPropertiesUpdateParametersDeliveryPolicy() - .withRules(rules)); + endpointUpdateParameters + .withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy().withRules(rules)); } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); - OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() - .withHostname(originInner.hostname()) + OriginUpdateParameters originUpdateParameters + = new OriginUpdateParameters().withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); - Mono originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - originInner.name(), + Mono originUpdateTask = this.parent() + .manager() + .serviceClient() + .getOrigins() + .updateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); - Mono endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), + Mono endpointUpdateTask = this.parent() + .manager() + .serviceClient() + .getEndpoints() + .updateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux customDomainCreateTask = Flux.fromIterable(this.customDomainList) - .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - self.parent().manager().resourceManager().internalContext() - .randomResourceName("CustomDomain", 50), - new CustomDomainParameters().withHostname(itemToCreate.hostname()) - ), 32, 32); + .flatMapDelayError(itemToCreate -> this.parent() + .manager() + .serviceClient() + .getCustomDomains() + .createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), + self.parent().manager().resourceManager().internalContext().randomResourceName("CustomDomain", 50), + new CustomDomainParameters().withHostname(itemToCreate.hostname())), + 32, 32); Flux customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) - .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - itemToDelete.name() - ), 32, 32); - - Mono customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) - .then(Mono.empty()); + .flatMapDelayError(itemToDelete -> this.parent() + .manager() + .serviceClient() + .getCustomDomains() + .deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name()), + 32, 32); - return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) - .last() - .map(inner -> { - self.setInner(inner); - self.customDomainList.clear(); - self.deletedCustomDomainList.clear(); - return self; - }); + Mono customDomainTask + = Flux.concat(customDomainCreateTask, customDomainDeleteTask).then(Mono.empty()); + + return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask).last().map(inner -> { + self.setInner(inner); + self.customDomainList.clear(); + self.deletedCustomDomainList.clear(); + return self; + }); } @Override public Mono deleteResourceAsync() { - return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), - this.parent().name(), - this.name()); + return this.parent() + .manager() + .serviceClient() + .getEndpoints() + .deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono refreshAsync() { final CdnEndpointImpl self = this; - return super.refreshAsync() - .flatMap(cdnEndpoint -> { - self.customDomainList.clear(); - self.deletedCustomDomainList.clear(); - initializeRuleMapForStandardMicrosoftSku(); - return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( - self.parent().resourceGroupName(), - self.parent().name(), - self.name() - ) - .collectList() - .map(customDomainInners -> { - self.customDomainList.addAll(customDomainInners); - return self; - }); - }); + return super.refreshAsync().flatMap(cdnEndpoint -> { + self.customDomainList.clear(); + self.deletedCustomDomainList.clear(); + initializeRuleMapForStandardMicrosoftSku(); + return self.parent() + .manager() + .serviceClient() + .getCustomDomains() + .listByEndpointAsync(self.parent().resourceGroupName(), self.parent().name(), self.name()) + .collectList() + .map(customDomainInners -> { + self.customDomainList.addAll(customDomainInners); + return self; + }); + }); } @Override protected Mono getInnerAsync() { - return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), - this.parent().name(), - this.name()); + return this.parent() + .manager() + .serviceClient() + .getEndpoints() + .getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable listResourceUsage() { - return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( - this.parent().resourceGroupName(), - this.parent().name(), - this.name()), + return PagedConverter.mapPage( + this.parent() + .manager() + .serviceClient() + .getEndpoints() + .listResourceUsage(this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @@ -348,7 +351,10 @@ public int httpsPort() { @Override public Set customDomains() { Set set = new HashSet<>(); - for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() + for (CustomDomainInner customDomainInner : this.parent() + .manager() + .serviceClient() + .getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } @@ -409,10 +415,7 @@ public Mono validateCustomDomainAsync(String hostN @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { - this.innerModel().origins().add( - new DeepCreatedOrigin() - .withName(originName) - .withHostname(hostname)); + this.innerModel().origins().add(new DeepCreatedOrigin().withName(originName).withHostname(hostname)); return this; } @@ -551,8 +554,8 @@ public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions actio } @Override - public CdnEndpointImpl withGeoFilter( - String relativePath, GeoFilterActions action, Collection countryCodes) { + public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, + Collection countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { @@ -624,8 +627,7 @@ private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions a } else { this.innerModel().geoFilters().remove(geoFilter); } - geoFilter.withRelativePath(relativePath) - .withAction(action); + geoFilter.withRelativePath(relativePath).withAction(action); return geoFilter; } @@ -647,9 +649,9 @@ private boolean isStandardMicrosoftSku() { private void throwIfNotStandardMicrosoftSku() { if (!isStandardMicrosoftSku()) { - throw new IllegalStateException(String.format( - "Standard rules engine only supports for Standard Microsoft SKU, " - + "current SKU is %s", parent().sku().name())); + throw new IllegalStateException( + String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", + parent().sku().name())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointsImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointsImpl.java index a08effbe036f2..c0e8f582e3ee3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnEndpointsImpl.java @@ -20,11 +20,7 @@ * Represents an endpoint collection associated with a CDN manager profile. */ class CdnEndpointsImpl extends - ExternalChildResourcesNonCachedImpl { + ExternalChildResourcesNonCachedImpl { CdnEndpointsImpl(CdnProfileImpl parent) { super(parent, parent.taskGroup(), "Endpoint"); @@ -35,10 +31,16 @@ class CdnEndpointsImpl extends */ Map endpointsAsMap() { Map result = new HashMap<>(); - for (EndpointInner endpointInner : this.getParent().manager().serviceClient().getEndpoints() + for (EndpointInner endpointInner : this.getParent() + .manager() + .serviceClient() + .getEndpoints() .listByProfile(this.getParent().resourceGroupName(), this.getParent().name())) { CdnEndpointImpl endpoint = new CdnEndpointImpl(endpointInner.name(), this.getParent(), endpointInner); - for (CustomDomainInner customDomainInner : this.getParent().manager().serviceClient().getCustomDomains() + for (CustomDomainInner customDomainInner : this.getParent() + .manager() + .serviceClient() + .getCustomDomains() .listByEndpoint(this.getParent().resourceGroupName(), this.getParent().name(), endpoint.name())) { endpoint.withCustomDomain(customDomainInner.hostname()); } @@ -67,10 +69,9 @@ public void addEndpoint(CdnEndpointImpl endpoint) { public CdnEndpointImpl defineNewEndpoint(String endpointName, String originName, String endpointOriginHostname) { CdnEndpointImpl endpoint = this.defineNewEndpoint(endpointName); - endpoint.innerModel().origins().add( - new DeepCreatedOrigin() - .withName(originName) - .withHostname(endpointOriginHostname)); + endpoint.innerModel() + .origins() + .add(new DeepCreatedOrigin().withName(originName).withHostname(endpointOriginHostname)); return endpoint; } @@ -79,8 +80,8 @@ public CdnEndpointImpl defineNewEndpoint(String endpointName, String endpointOri } public CdnEndpointImpl defineNewEndpoint(String name) { - CdnEndpointImpl endpoint = this.prepareInlineDefine( - new CdnEndpointImpl(name, this.getParent(), new EndpointInner())); + CdnEndpointImpl endpoint + = this.prepareInlineDefine(new CdnEndpointImpl(name, this.getParent(), new EndpointInner())); endpoint.innerModel().withLocation(endpoint.parent().region().toString()); endpoint.innerModel().withOrigins(new ArrayList<>()); return endpoint; @@ -98,10 +99,12 @@ public CdnEndpointImpl defineNewEndpointWithOriginHostname(String endpointOrigin } public CdnEndpointImpl updateEndpoint(String name) { - EndpointInner endpointInner = this.getParent().manager().serviceClient().getEndpoints() + EndpointInner endpointInner = this.getParent() + .manager() + .serviceClient() + .getEndpoints() .get(this.getParent().resourceGroupName(), this.getParent().name(), name); - CdnEndpointImpl endpoint = this.prepareInlineUpdate( - new CdnEndpointImpl(name, this.getParent(), endpointInner)); + CdnEndpointImpl endpoint = this.prepareInlineUpdate(new CdnEndpointImpl(name, this.getParent(), endpointInner)); return endpoint; } @@ -110,7 +113,10 @@ private String generateUniqueEndpointName(String endpointNamePrefix) { CheckNameAvailabilityResult result; do { - endpointName = this.getParent().manager().resourceManager().internalContext() + endpointName = this.getParent() + .manager() + .resourceManager() + .internalContext() .randomResourceName(endpointNamePrefix, 50); result = this.getParent().checkEndpointNameAvailability(endpointName); } while (!result.nameAvailable()); diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfileImpl.java index ac0ca86d30d8e..cc3b94634fb37 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfileImpl.java @@ -29,16 +29,8 @@ /** * Implementation for CdnProfile. */ -class CdnProfileImpl - extends GroupableResourceImpl< - CdnProfile, - ProfileInner, - CdnProfileImpl, - CdnManager> - implements - CdnProfile, - CdnProfile.Definition, - CdnProfile.Update { +class CdnProfileImpl extends GroupableResourceImpl + implements CdnProfile, CdnProfile.Definition, CdnProfile.Update { private CdnEndpointsImpl endpoints; @@ -59,7 +51,10 @@ public String generateSsoUri() { @Override public Mono generateSsoUriAsync() { - return this.manager().serviceClient().getProfiles().generateSsoUriAsync(this.resourceGroupName(), this.name()) + return this.manager() + .serviceClient() + .getProfiles() + .generateSsoUriAsync(this.resourceGroupName(), this.name()) .map(SsoUriInner::ssoUriValue); } @@ -70,7 +65,9 @@ public void startEndpoint(String endpointName) { @Override public Mono startEndpointAsync(String endpointName) { - return this.manager().serviceClient().getEndpoints() + return this.manager() + .serviceClient() + .getEndpoints() .startAsync(this.resourceGroupName(), this.name(), endpointName) .then(); } @@ -82,14 +79,17 @@ public void stopEndpoint(String endpointName) { @Override public Mono stopEndpointAsync(String endpointName) { - return this.manager().serviceClient().getEndpoints() + return this.manager() + .serviceClient() + .getEndpoints() .stopAsync(this.resourceGroupName(), this.name(), endpointName) .then(); } @Override public PagedIterable listResourceUsage() { - return PagedConverter.mapPage(this.manager().serviceClient().getProfiles().listResourceUsage(this.resourceGroupName(), this.name()), + return PagedConverter.mapPage( + this.manager().serviceClient().getProfiles().listResourceUsage(this.resourceGroupName(), this.name()), ResourceUsage::new); } @@ -101,7 +101,9 @@ public void purgeEndpointContent(String endpointName, Set contentPaths) @Override public Mono purgeEndpointContentAsync(String endpointName, Set contentPaths) { if (contentPaths != null) { - return this.manager().serviceClient().getEndpoints() + return this.manager() + .serviceClient() + .getEndpoints() .purgeContentAsync(this.resourceGroupName(), this.name(), endpointName, new PurgeParameters().withContentPaths(new ArrayList<>(contentPaths))); } @@ -116,7 +118,9 @@ public void loadEndpointContent(String endpointName, Set contentPaths) { @Override public Mono loadEndpointContentAsync(String endpointName, Set contentPaths) { if (contentPaths != null) { - return this.manager().serviceClient().getEndpoints() + return this.manager() + .serviceClient() + .getEndpoints() .loadContentAsync(this.resourceGroupName(), this.name(), endpointName, new LoadParameters().withContentPaths(new ArrayList<>(contentPaths))); } @@ -130,8 +134,11 @@ public CustomDomainValidationResult validateEndpointCustomDomain(String endpoint @Override public Mono validateEndpointCustomDomainAsync(String endpointName, String hostName) { - return this.manager().serviceClient().getEndpoints().validateCustomDomainAsync( - this.resourceGroupName(), this.name(), endpointName, new ValidateCustomDomainInput().withHostname(hostName)) + return this.manager() + .serviceClient() + .getEndpoints() + .validateCustomDomainAsync(this.resourceGroupName(), this.name(), endpointName, + new ValidateCustomDomainInput().withHostname(hostName)) .map(CustomDomainValidationResult::new); } @@ -147,9 +154,7 @@ public Mono checkEndpointNameAvailabilityAsync(Stri @Override public boolean isPremiumVerizon() { - return this.sku() != null - && this.sku().name() != null - && this.sku().name().equals(SkuName.PREMIUM_VERIZON); + return this.sku() != null && this.sku().name() != null && this.sku().name().equals(SkuName.PREMIUM_VERIZON); } @Override @@ -169,20 +174,27 @@ public String resourceState() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getProfiles() + return this.manager() + .serviceClient() + .getProfiles() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getProfiles().createAsync(resourceGroupName(), name(), innerModel()) - .map(innerToFluentMap(this)); + return this.manager() + .serviceClient() + .getProfiles() + .createAsync(resourceGroupName(), name(), innerModel()) + .map(innerToFluentMap(this)); } @Override public Mono updateResourceAsync() { final CdnProfileImpl self = this; - return this.manager().serviceClient().getProfiles() + return this.manager() + .serviceClient() + .getProfiles() .updateAsync(this.resourceGroupName(), this.name(), new ProfileUpdateParameters().withTags(innerModel().tags())) .map(inner -> { @@ -203,42 +215,33 @@ public Mono afterPostRunAsync(final boolean isGroupFaulted) { @Override public Mono refreshAsync() { - return super.refreshAsync() - .map(cdnProfile -> { - endpoints.clear(); - return cdnProfile; - }); + return super.refreshAsync().map(cdnProfile -> { + endpoints.clear(); + return cdnProfile; + }); } @Override public CdnProfileImpl withStandardAkamaiSku() { - this.innerModel() - .withSku(new Sku() - .withName(SkuName.STANDARD_AKAMAI)); + this.innerModel().withSku(new Sku().withName(SkuName.STANDARD_AKAMAI)); return this; } @Override public CdnProfileImpl withStandardVerizonSku() { - this.innerModel() - .withSku(new Sku() - .withName(SkuName.STANDARD_VERIZON)); + this.innerModel().withSku(new Sku().withName(SkuName.STANDARD_VERIZON)); return this; } @Override public CdnProfileImpl withPremiumVerizonSku() { - this.innerModel() - .withSku(new Sku() - .withName(SkuName.PREMIUM_VERIZON)); + this.innerModel().withSku(new Sku().withName(SkuName.PREMIUM_VERIZON)); return this; } @Override public CdnProfileImpl withStandardMicrosoftSku() { - this.innerModel() - .withSku(new Sku() - .withName(SkuName.STANDARD_MICROSOFT)); + this.innerModel().withSku(new Sku().withName(SkuName.STANDARD_MICROSOFT)); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfilesImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfilesImpl.java index 908bde364cf24..7ffd80c9c1162 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfilesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnProfilesImpl.java @@ -28,12 +28,7 @@ * Implementation for {@link CdnProfiles}. */ public final class CdnProfilesImpl - extends TopLevelModifiableResourcesImpl< - CdnProfile, - CdnProfileImpl, - ProfileInner, - ProfilesClient, - CdnManager> + extends TopLevelModifiableResourcesImpl implements CdnProfiles { public CdnProfilesImpl(final CdnManager cdnManager) { @@ -47,7 +42,7 @@ protected CdnProfileImpl wrapModel(String name) { @Override protected CdnProfileImpl wrapModel(ProfileInner inner) { - if (inner == null) { + if (inner == null) { return null; } return new CdnProfileImpl(inner.name(), inner, this.manager()); @@ -60,8 +55,8 @@ public CdnProfileImpl define(String name) { @Override public String generateSsoUri(String resourceGroupName, String profileName) { - SsoUriInner ssoUri = this.manager().serviceClient().getProfiles() - .generateSsoUri(resourceGroupName, profileName); + SsoUriInner ssoUri + = this.manager().serviceClient().getProfiles().generateSsoUri(resourceGroupName, profileName); if (ssoUri != null) { return ssoUri.ssoUriValue(); } @@ -75,29 +70,26 @@ public CheckNameAvailabilityResult checkEndpointNameAvailability(String name) { @Override public Mono checkEndpointNameAvailabilityAsync(String name) { - return this.manager().serviceClient() - .checkNameAvailabilityAsync(new CheckNameAvailabilityInput() - .withName(name) - .withType(ResourceType.MICROSOFT_CDN_PROFILES_ENDPOINTS)) + return this.manager() + .serviceClient() + .checkNameAvailabilityAsync( + new CheckNameAvailabilityInput().withName(name).withType(ResourceType.MICROSOFT_CDN_PROFILES_ENDPOINTS)) .map(CheckNameAvailabilityResult::new); } @Override public PagedIterable listOperations() { - return PagedConverter.mapPage(this.manager().serviceClient().getOperations().list(), - Operation::new); + return PagedConverter.mapPage(this.manager().serviceClient().getOperations().list(), Operation::new); } @Override public PagedIterable listResourceUsage() { - return PagedConverter.mapPage(this.manager().serviceClient().getResourceUsages().list(), - ResourceUsage::new); + return PagedConverter.mapPage(this.manager().serviceClient().getResourceUsages().list(), ResourceUsage::new); } @Override public PagedIterable listEdgeNodes() { - return PagedConverter.mapPage(this.manager().serviceClient().getEdgeNodes().list(), - EdgeNode::new); + return PagedConverter.mapPage(this.manager().serviceClient().getEdgeNodes().list(), EdgeNode::new); } @Override @@ -111,17 +103,21 @@ public void stopEndpoint(String resourceGroupName, String profileName, String en } @Override - public void purgeEndpointContent( - String resourceGroupName, String profileName, String endpointName, List contentPaths) { - this.manager().serviceClient().getEndpoints() + public void purgeEndpointContent(String resourceGroupName, String profileName, String endpointName, + List contentPaths) { + this.manager() + .serviceClient() + .getEndpoints() .purgeContent(resourceGroupName, profileName, endpointName, new PurgeParameters().withContentPaths(contentPaths)); } @Override - public void loadEndpointContent( - String resourceGroupName, String profileName, String endpointName, List contentPaths) { - this.manager().serviceClient().getEndpoints() + public void loadEndpointContent(String resourceGroupName, String profileName, String endpointName, + List contentPaths) { + this.manager() + .serviceClient() + .getEndpoints() .loadContent(resourceGroupName, profileName, endpointName, new LoadParameters().withContentPaths(contentPaths)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnStandardRulesEngineRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnStandardRulesEngineRuleImpl.java index c908d0c0a12da..99a4ae04c3ea3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnStandardRulesEngineRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/CdnStandardRulesEngineRuleImpl.java @@ -17,10 +17,8 @@ /** * Implementation for {@link CdnStandardRulesEngineRule}. */ -class CdnStandardRulesEngineRuleImpl - extends ChildResourceImpl - implements CdnStandardRulesEngineRule, - CdnStandardRulesEngineRule.Definition, +class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl + implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition, CdnStandardRulesEngineRule.Update { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/LogAnalyticsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/LogAnalyticsClientImpl.java index 550bb0f74fd47..c5358d591c9b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/LogAnalyticsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/LogAnalyticsClientImpl.java @@ -354,7 +354,7 @@ public Mono getLogAnalyticsMetricsAsync(String resourceGro final List countryOrRegions = null; return getLogAnalyticsMetricsWithResponseAsync(resourceGroupName, profileName, metrics, dateTimeBegin, dateTimeEnd, granularity, customDomains, protocols, groupBy, continents, countryOrRegions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnEndpoint.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnEndpoint.java index 56d7f1b5c637b..5c76cf56f585f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnEndpoint.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnEndpoint.java @@ -20,9 +20,7 @@ * An immutable client-side representation of an Azure CDN endpoint. */ @Fluent -public interface CdnEndpoint extends - ExternalChildResource, - HasInnerModel { +public interface CdnEndpoint extends ExternalChildResource, HasInnerModel { /** * @return origin host header @@ -357,8 +355,8 @@ interface WithStandardAttach extends AttachableStandard { * @param countryCode an ISO 2 letter country code * @return the next stage of the definition */ - WithStandardAttach withGeoFilter( - String relativePath, GeoFilterActions action, CountryIsoCode countryCode); + WithStandardAttach withGeoFilter(String relativePath, GeoFilterActions action, + CountryIsoCode countryCode); /** * Sets the geo filters list for the specified countries list. @@ -368,8 +366,8 @@ WithStandardAttach withGeoFilter( * @param countryCodes a list of the ISO 2 letter country codes. * @return the next stage of the definition */ - WithStandardAttach withGeoFilter( - String relativePath, GeoFilterActions action, Collection countryCodes); + WithStandardAttach withGeoFilter(String relativePath, GeoFilterActions action, + Collection countryCodes); /** * Adds a new CDN custom domain within an endpoint. @@ -387,7 +385,8 @@ WithStandardAttach withGeoFilter( * @param the next stage of the endpoint definition * @return the first stage of the rule definition */ - > CdnStandardRulesEngineRule.DefinitionStage.Blank defineNewStandardRulesEngineRule(String name); + > CdnStandardRulesEngineRule.DefinitionStage.Blank + defineNewStandardRulesEngineRule(String name); } /** The final stage of the CDN profile Premium Verizon endpoint definition. @@ -396,8 +395,7 @@ WithStandardAttach withGeoFilter( * definition can be attached to the parent CDN profile definition. * @param the stage of the parent CDN profile definition to return to after attaching this definition */ - interface WithPremiumAttach - extends AttachablePremium { + interface WithPremiumAttach extends AttachablePremium { /** * Specifies the origin path. * @@ -529,8 +527,8 @@ interface PremiumEndpoint { * @param originHostName origin host name * @return the next stage of the definition */ - UpdateDefinitionStages.WithPremiumAttach withPremiumOrigin( - String originName, String originHostName); + UpdateDefinitionStages.WithPremiumAttach withPremiumOrigin(String originName, + String originHostName); /** * Specifies the origin of the CDN endpoint. @@ -549,8 +547,7 @@ UpdateDefinitionStages.WithPremiumAttach withPremiumOrigin( * definition can be attached to the parent CDN profile definition * @param the stage of the parent CDN profile update to return to after attaching this definition */ - interface WithStandardAttach - extends AttachableStandard { + interface WithStandardAttach extends AttachableStandard { /** * Specifies the origin path. * @@ -648,8 +645,8 @@ interface WithStandardAttach * @param countryCode an ISO 2 letter country code * @return the next stage of the definition */ - WithStandardAttach withGeoFilter( - String relativePath, GeoFilterActions action, CountryIsoCode countryCode); + WithStandardAttach withGeoFilter(String relativePath, GeoFilterActions action, + CountryIsoCode countryCode); /** * Sets the geo filters list for the specified countries list. @@ -659,8 +656,8 @@ WithStandardAttach withGeoFilter( * @param countryCodes a list of ISO 2 letter country codes * @return the next stage of the definition */ - WithStandardAttach withGeoFilter( - String relativePath, GeoFilterActions action, Collection countryCodes); + WithStandardAttach withGeoFilter(String relativePath, GeoFilterActions action, + Collection countryCodes); /** * Adds a new CDN custom domain within an endpoint. @@ -678,7 +675,8 @@ WithStandardAttach withGeoFilter( * @param the next stage of the endpoint definition * @return the first stage of the delivery rule definition */ - > CdnStandardRulesEngineRule.DefinitionStage.Blank defineNewStandardRulesEngineRule(String name); + > CdnStandardRulesEngineRule.DefinitionStage.Blank + defineNewStandardRulesEngineRule(String name); } /** @@ -688,8 +686,7 @@ WithStandardAttach withGeoFilter( * definition can be attached to the parent CDN profile definition * @param the stage of the parent CDN profile update to return to after attaching this definition */ - interface WithPremiumAttach - extends AttachablePremium { + interface WithPremiumAttach extends AttachablePremium { /** * Specifies the origin path. * @@ -908,8 +905,8 @@ interface UpdateStandardEndpoint extends Update { * @param countryCodes a list of ISO 2 letter country codes * @return the next stage of the definition */ - UpdateStandardEndpoint withGeoFilter( - String relativePath, GeoFilterActions action, Collection countryCodes); + UpdateStandardEndpoint withGeoFilter(String relativePath, GeoFilterActions action, + Collection countryCodes); /** * Removes an entry from the geo filters list. @@ -943,7 +940,8 @@ UpdateStandardEndpoint withGeoFilter( * @param the next stage of the endpoint update * @return the first stage of the delivery rule update */ - CdnStandardRulesEngineRule.DefinitionStage.Blank defineNewStandardRulesEngineRule(String name); + CdnStandardRulesEngineRule.DefinitionStage.Blank + defineNewStandardRulesEngineRule(String name); /** * Begins the update of the Standard rules engine rule. @@ -953,7 +951,8 @@ UpdateStandardEndpoint withGeoFilter( * @param the next stage of the endpoint update * @return the first stage of the delivery rule update */ - CdnStandardRulesEngineRule.Update updateStandardRulesEngineRule(String name); + CdnStandardRulesEngineRule.Update + updateStandardRulesEngineRule(String name); /** * Removes the rule from the endpoint's Standard rules engine. @@ -1038,7 +1037,6 @@ interface UpdatePremiumEndpoint extends Update { /** * The entirety of a CDN endpoint update as part of a CDN profile update. */ - interface Update extends - Settable { + interface Update extends Settable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfile.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfile.java index ef157e973ce4e..b9fd103d0dad9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfile.java @@ -22,10 +22,8 @@ * An immutable client-side representation of an Azure CDN profile. */ @Fluent -public interface CdnProfile extends - GroupableResource, - Refreshable, - Updatable { +public interface CdnProfile + extends GroupableResource, Refreshable, Updatable { /** * @return the SKU of the CDN profile @@ -175,13 +173,8 @@ public interface CdnProfile extends /** * The entirety of a CDN profile definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSku, - DefinitionStages.WithStandardCreate, - DefinitionStages.WithPremiumVerizonCreate, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSku, + DefinitionStages.WithStandardCreate, DefinitionStages.WithPremiumVerizonCreate, DefinitionStages.WithCreate { } /** @@ -286,8 +279,8 @@ interface WithStandardCreate extends WithCreate { * @return the first stage of a new CDN endpoint definition */ // Why is define() taking more than just the name? - CdnEndpoint.DefinitionStages.WithStandardAttach defineNewEndpoint( - String name, String endpointOriginHostname); + CdnEndpoint.DefinitionStages.WithStandardAttach defineNewEndpoint(String name, + String endpointOriginHostname); } /** @@ -317,8 +310,8 @@ interface WithPremiumVerizonCreate extends WithCreate { * @param name a name for the endpoint * @return the first stage of a new CDN endpoint definition */ - CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint defineNewPremiumEndpoint( - String name); + CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint + defineNewPremiumEndpoint(String name); /** * Starts the definition of a new endpoint to be attached to the CDN profile. @@ -328,17 +321,15 @@ CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint def * @return the stage representing configuration for the endpoint */ // Why is define() taking more than just the name? - CdnEndpoint.DefinitionStages.WithPremiumAttach defineNewPremiumEndpoint( - String name, String endpointOriginHostname); + CdnEndpoint.DefinitionStages.WithPremiumAttach + defineNewPremiumEndpoint(String name, String endpointOriginHostname); } /** * The stage of the definition which contains all the minimum required inputs for the resource to be created * but also allows for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, Resource.DefinitionWithTags { } } @@ -382,8 +373,8 @@ interface WithEndpoint { * @return the first stage of an endpoint definition */ // TODO: Why define() is taking more than the name? - CdnEndpoint.UpdateDefinitionStages.WithStandardAttach defineNewEndpoint( - String name, String endpointOriginHostname); + CdnEndpoint.UpdateDefinitionStages.WithStandardAttach defineNewEndpoint(String name, + String endpointOriginHostname); /** * Adds new endpoint to current Premium Verizon CDN profile. @@ -417,8 +408,8 @@ CdnEndpoint.UpdateDefinitionStages.WithStandardAttach defineNewEndpoint( * @return the first stage of an endpoint definition */ // TODO: why is this taking more than just the name? - CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach defineNewPremiumEndpoint( - String name, String endpointOriginHostname); + CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach defineNewPremiumEndpoint(String name, + String endpointOriginHostname); /** * Begins the description of an update of an existing endpoint in current profile. @@ -449,9 +440,6 @@ CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach defineNewPremiumEnd /** * The template for an update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithEndpoint, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithEndpoint, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfiles.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfiles.java index 1048cbf2c8ab2..94f0902160d38 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfiles.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnProfiles.java @@ -24,17 +24,10 @@ * Entry point for CDN profile management API. */ @Fluent -public interface CdnProfiles extends - SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface CdnProfiles extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Generates a dynamic SSO URI used to sign in to the CDN supplemental portal. @@ -112,8 +105,8 @@ public interface CdnProfiles extends * @param endpointName name of the endpoint under the profile which is unique globally. * @param contentPaths the path to the content to be purged. Can describe a file path or a wild card directory. */ - void purgeEndpointContent( - String resourceGroupName, String profileName, String endpointName, List contentPaths); + void purgeEndpointContent(String resourceGroupName, String profileName, String endpointName, + List contentPaths); /** * Forcibly pre-loads CDN endpoint content. Available for Verizon profiles. @@ -123,6 +116,6 @@ void purgeEndpointContent( * @param endpointName name of the endpoint under the profile which is unique globally. * @param contentPaths the path to the content to be loaded. Should describe a file path. */ - void loadEndpointContent( - String resourceGroupName, String profileName, String endpointName, List contentPaths); + void loadEndpointContent(String resourceGroupName, String profileName, String endpointName, + List contentPaths); } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnStandardRulesEngineRule.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnStandardRulesEngineRule.java index 7d83d64ee97d0..e16be336736b7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnStandardRulesEngineRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/CdnStandardRulesEngineRule.java @@ -22,7 +22,8 @@ interface DefinitionStage { * * @param the stage of the parent CDN endpoint definition to return to after attaching this definition */ - interface Blank extends WithOrder {} + interface Blank extends WithOrder { + } /** * The stage of a CDN Standard rules engine rule definition allowing to specify the order of the rule. @@ -49,7 +50,8 @@ interface WithOrder { * * @param the stage of the parent CDN endpoint definition to return to after attaching this definition */ - interface WithMatchConditionsOrActions extends WithMatchConditions, WithActions {} + interface WithMatchConditionsOrActions extends WithMatchConditions, WithActions { + } /** * The stage of a CDN Standard rules engine rule definition allowing to specify match conditions. @@ -142,10 +144,8 @@ interface WithActions { * * @param the stage of the parent CDN endpoint definition to return to after attaching this definition */ - interface Definition - extends DefinitionStage.Blank, - DefinitionStage.WithMatchConditionsOrActions, - Attachable { + interface Definition extends DefinitionStage.Blank, + DefinitionStage.WithMatchConditionsOrActions, Attachable { } /** @@ -153,10 +153,7 @@ interface Definition * * @param the stage of the parent CDN endpoint update to return to after updating this definition */ - interface Update - extends Settable, - UpdateStages.WithOrder, - UpdateStages.WithMatchConditions, - UpdateStages.WithActions { + interface Update extends Settable, UpdateStages.WithOrder, + UpdateStages.WithMatchConditions, UpdateStages.WithActions { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/EdgeNode.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/EdgeNode.java index d6001a812efa1..d9d1771975b83 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/EdgeNode.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/EdgeNode.java @@ -31,7 +31,6 @@ public String id() { return this.inner.id(); } - /** * Edge node resource name. * diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnManagementTest.java index 879b1277400f2..ca77c6c29124f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnManagementTest.java @@ -25,21 +25,10 @@ public abstract class CdnManagementTest extends ResourceManagerTestProxyTestBase protected CdnManager cdnManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnProfileOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnProfileOperationsTests.java index e7611cf08f1ae..f133b0fe0cc64 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnProfileOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/src/test/java/com/azure/resourcemanager/cdn/CdnProfileOperationsTests.java @@ -53,14 +53,13 @@ protected void cleanUpResources() { public void canCreateCdnProfile() { String cdnProfileName = generateRandomResourceName("cdnp", 15); - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); CheckNameAvailabilityResult result = cdnManager.profiles().checkEndpointNameAvailability(cdnProfileName); Assertions.assertTrue(result.nameAvailable()); - CdnProfile cdnProfile = cdnManager.profiles().define(cdnProfileName) + CdnProfile cdnProfile = cdnManager.profiles() + .define(cdnProfileName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withStandardMicrosoftSku() @@ -84,14 +83,13 @@ public void canCreateUpdateCdnProfile() { String cdnProfileName = generateRandomResourceName("cdnp", 15); String cdnEndpointName = generateRandomResourceName("cdnendp", 15); - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); CheckNameAvailabilityResult result = cdnManager.profiles().checkEndpointNameAvailability(cdnProfileName); Assertions.assertTrue(result.nameAvailable()); - CdnProfile cdnProfile = cdnManager.profiles().define(cdnProfileName) + CdnProfile cdnProfile = cdnManager.profiles() + .define(cdnProfileName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withStandardMicrosoftSku() @@ -103,10 +101,10 @@ public void canCreateUpdateCdnProfile() { cdnProfile.update() .defineNewEndpoint(cdnEndpointName) - .withOrigin("origin1", "www.someDomain.net") - .withHttpAllowed(true) - .withHttpsAllowed(true) - .attach() + .withOrigin("origin1", "www.someDomain.net") + .withHttpAllowed(true) + .withHttpsAllowed(true) + .attach() .apply(); Map cdnEndpointMap = cdnProfile.endpoints(); @@ -124,22 +122,21 @@ public void canCreateUpdateCdnEndpoint() { String cdnProfileName = generateRandomResourceName("cdnp", 15); String cdnEndpointName = generateRandomResourceName("cdnendp", 15); - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); CheckNameAvailabilityResult result = cdnManager.profiles().checkEndpointNameAvailability(cdnProfileName); Assertions.assertTrue(result.nameAvailable()); - CdnProfile cdnProfile = cdnManager.profiles().define(cdnProfileName) + CdnProfile cdnProfile = cdnManager.profiles() + .define(cdnProfileName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withStandardMicrosoftSku() .defineNewEndpoint(cdnEndpointName) - .withOrigin("origin1", "www.someDomain.net") - .withHttpAllowed(false) - .withHttpsAllowed(true) - .attach() + .withOrigin("origin1", "www.someDomain.net") + .withHttpAllowed(false) + .withHttpsAllowed(true) + .attach() .create(); Assertions.assertNotNull(cdnProfile); @@ -156,9 +153,9 @@ public void canCreateUpdateCdnEndpoint() { cdnProfile.update() .updateEndpoint(cdnEndpointName) - .withHttpAllowed(true) - .withHttpsAllowed(false) - .parent() + .withHttpAllowed(true) + .withHttpsAllowed(false) + .parent() .apply(); cdnEndpoint.refresh(); @@ -178,50 +175,40 @@ public void canCrudStandardRulesEngineRules() { String originName1 = generateRandomResourceName("origin", 15); String originName2 = generateRandomResourceName("origin", 15); - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); CheckNameAvailabilityResult result = cdnManager.profiles().checkEndpointNameAvailability(cdnProfileName); Assertions.assertTrue(result.nameAvailable()); // create cdnProfile with one cdnEndpoint, with 1 rule - CdnProfile cdnProfile = cdnManager.profiles().define(cdnProfileName) + CdnProfile cdnProfile = cdnManager.profiles() + .define(cdnProfileName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withStandardMicrosoftSku() .defineNewEndpoint(cdnEndpointName) - .withOrigin(originName1, "www.someDomain.net") - .withHttpAllowed(false) - .withHttpsAllowed(true) - // define Global rule - .defineNewStandardRulesEngineRule("Global") - .withOrder(0) - .withActions( - new DeliveryRuleCacheExpirationAction() - .withParameters( - new CacheExpirationActionParameters() - .withCacheBehavior(CacheBehavior.SET_IF_MISSING) - .withCacheDuration("00:05:00") - .withCacheType(CacheType.ALL))) - .attach() - .defineNewStandardRulesEngineRule(ruleName1) - .withOrder(1) - .withMatchConditions( - new DeliveryRuleRequestSchemeCondition() - .withParameters( - new RequestSchemeMatchConditionParameters() - .withMatchValues( - Arrays.asList(RequestSchemeMatchConditionParametersMatchValuesItem.HTTP)))) - .withActions( - new UrlRedirectAction() - .withParameters( - new UrlRedirectActionParameters() - .withRedirectType(RedirectType.FOUND) - .withDestinationProtocol(DestinationProtocol.HTTPS) - .withCustomHostname(""))) - .attach() - .attach() + .withOrigin(originName1, "www.someDomain.net") + .withHttpAllowed(false) + .withHttpsAllowed(true) + // define Global rule + .defineNewStandardRulesEngineRule("Global") + .withOrder(0) + .withActions(new DeliveryRuleCacheExpirationAction() + .withParameters(new CacheExpirationActionParameters().withCacheBehavior(CacheBehavior.SET_IF_MISSING) + .withCacheDuration("00:05:00") + .withCacheType(CacheType.ALL))) + .attach() + .defineNewStandardRulesEngineRule(ruleName1) + .withOrder(1) + .withMatchConditions( + new DeliveryRuleRequestSchemeCondition().withParameters(new RequestSchemeMatchConditionParameters() + .withMatchValues(Arrays.asList(RequestSchemeMatchConditionParametersMatchValuesItem.HTTP)))) + .withActions(new UrlRedirectAction() + .withParameters(new UrlRedirectActionParameters().withRedirectType(RedirectType.FOUND) + .withDestinationProtocol(DestinationProtocol.HTTPS) + .withCustomHostname(""))) + .attach() + .attach() .create(); cdnProfile.refresh(); @@ -243,51 +230,38 @@ public void canCrudStandardRulesEngineRules() { // update cdnProfile, add 1 additional rule, update existing rule to existing endpoint // and define a new endpoint with 1 rule - cdnProfile - .update() + cdnProfile.update() .updateEndpoint(cdnEndpointName) // define new Standard rules engine rule .defineNewStandardRulesEngineRule(ruleName2) - .withOrder(1) - .withMatchConditions( - new DeliveryRuleHttpVersionCondition() - .withParameters( - new HttpVersionMatchConditionParameters() - .withOperator(HttpVersionOperator.EQUAL) - .withMatchValues(Arrays.asList("2.0")))) - .withActions( - new DeliveryRuleCacheExpirationAction() - .withParameters( - new CacheExpirationActionParameters() - .withCacheType(CacheType.ALL) - .withCacheBehavior(CacheBehavior.BYPASS_CACHE))) - .attach() + .withOrder(1) + .withMatchConditions(new DeliveryRuleHttpVersionCondition() + .withParameters(new HttpVersionMatchConditionParameters().withOperator(HttpVersionOperator.EQUAL) + .withMatchValues(Arrays.asList("2.0")))) + .withActions(new DeliveryRuleCacheExpirationAction() + .withParameters(new CacheExpirationActionParameters().withCacheType(CacheType.ALL) + .withCacheBehavior(CacheBehavior.BYPASS_CACHE))) + .attach() // update existing Standard rules engine rule .updateStandardRulesEngineRule(ruleName1) - .withOrder(2) - .parent() + .withOrder(2) + .parent() .parent() // define new endpoint with 1 rule .defineNewEndpoint(cdnEndpointName2) - .withOrigin(originName2, "www.someDomain.net") - .withHttpAllowed(false) - .withHttpsAllowed(true) - .defineNewStandardRulesEngineRule(ruleName3) - .withOrder(1) - .withMatchConditions( - new DeliveryRuleHttpVersionCondition() - .withParameters( - new HttpVersionMatchConditionParameters() - .withOperator(HttpVersionOperator.EQUAL) - .withMatchValues(Arrays.asList("1.1")))) - .withActions( - new DeliveryRuleCacheExpirationAction() - .withParameters( - new CacheExpirationActionParameters() - .withCacheType(CacheType.ALL) - .withCacheDuration("00:05:00") - .withCacheBehavior(CacheBehavior.OVERRIDE))) - .attach() + .withOrigin(originName2, "www.someDomain.net") + .withHttpAllowed(false) + .withHttpsAllowed(true) + .defineNewStandardRulesEngineRule(ruleName3) + .withOrder(1) + .withMatchConditions(new DeliveryRuleHttpVersionCondition() + .withParameters(new HttpVersionMatchConditionParameters().withOperator(HttpVersionOperator.EQUAL) + .withMatchValues(Arrays.asList("1.1")))) + .withActions(new DeliveryRuleCacheExpirationAction() + .withParameters(new CacheExpirationActionParameters().withCacheType(CacheType.ALL) + .withCacheDuration("00:05:00") + .withCacheBehavior(CacheBehavior.OVERRIDE))) + .attach() .attach() .apply(); @@ -320,11 +294,7 @@ public void canCrudStandardRulesEngineRules() { DeliveryRule rule3 = endpoint2.standardRulesEngineRules().get(ruleName3); Assertions.assertNotNull(rule3); - cdnProfile.update() - .updateEndpoint(cdnEndpointName) - .withoutStandardRulesEngineRule(ruleName1) - .parent() - .apply(); + cdnProfile.update().updateEndpoint(cdnEndpointName).withoutStandardRulesEngineRule(ruleName1).parent().apply(); cdnProfile.refresh(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml index a50b3e2f43eeb..a407164867ef0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml @@ -57,6 +57,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/ComputeManager.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/ComputeManager.java index 30bbd5ba386d8..14d40e6bf1596 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/ComputeManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/ComputeManager.java @@ -141,11 +141,8 @@ public ComputeManager authenticate(TokenCredential credential, AzureProfile prof } private ComputeManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new ComputeManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new ComputeManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); @@ -173,12 +170,10 @@ public VirtualMachines virtualMachines() { /** @return the virtual machine image resource management API entry point */ public VirtualMachineImages virtualMachineImages() { if (virtualMachineImages == null) { - virtualMachineImages = - new VirtualMachineImagesImpl( - new VirtualMachinePublishersImpl( - this.serviceClient().getVirtualMachineImages(), - this.serviceClient().getVirtualMachineExtensionImages()), - this.serviceClient().getVirtualMachineImages()); + virtualMachineImages = new VirtualMachineImagesImpl( + new VirtualMachinePublishersImpl(this.serviceClient().getVirtualMachineImages(), + this.serviceClient().getVirtualMachineExtensionImages()), + this.serviceClient().getVirtualMachineImages()); } return virtualMachineImages; } @@ -186,11 +181,9 @@ public VirtualMachineImages virtualMachineImages() { /** @return the virtual machine extension image resource management API entry point */ public VirtualMachineExtensionImages virtualMachineExtensionImages() { if (virtualMachineExtensionImages == null) { - virtualMachineExtensionImages = - new VirtualMachineExtensionImagesImpl( - new VirtualMachinePublishersImpl( - this.serviceClient().getVirtualMachineImages(), - this.serviceClient().getVirtualMachineExtensionImages())); + virtualMachineExtensionImages = new VirtualMachineExtensionImagesImpl( + new VirtualMachinePublishersImpl(this.serviceClient().getVirtualMachineImages(), + this.serviceClient().getVirtualMachineExtensionImages())); } return virtualMachineExtensionImages; } @@ -198,8 +191,8 @@ public VirtualMachineExtensionImages virtualMachineExtensionImages() { /** @return the virtual machine scale set resource management API entry point */ public VirtualMachineScaleSets virtualMachineScaleSets() { if (virtualMachineScaleSets == null) { - virtualMachineScaleSets = - new VirtualMachineScaleSetsImpl(this, storageManager, networkManager, this.authorizationManager); + virtualMachineScaleSets + = new VirtualMachineScaleSetsImpl(this, storageManager, networkManager, this.authorizationManager); } return virtualMachineScaleSets; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetImpl.java index 057699bc09c8d..821ee734e2164 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetImpl.java @@ -80,11 +80,9 @@ public ProximityPlacementGroup proximityPlacementGroup() { return null; } else { ResourceId id = ResourceId.fromString(innerModel().proximityPlacementGroup().id()); - ProximityPlacementGroupInner plgInner = - manager() - .serviceClient() - .getProximityPlacementGroups() - .getByResourceGroup(id.resourceGroupName(), id.name()); + ProximityPlacementGroupInner plgInner = manager().serviceClient() + .getProximityPlacementGroups() + .getByResourceGroup(id.resourceGroupName(), id.name()); if (plgInner == null) { return null; } else { @@ -100,29 +98,23 @@ public List statuses() { @Override public PagedIterable listVirtualMachineSizes() { - return PagedConverter.mapPage(manager() - .serviceClient() - .getAvailabilitySets() - .listAvailableSizes(resourceGroupName(), name()), + return PagedConverter.mapPage( + manager().serviceClient().getAvailabilitySets().listAvailableSizes(resourceGroupName(), name()), virtualMachineSizeInner -> new VirtualMachineSizeImpl(virtualMachineSizeInner)); } @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - availabilitySet -> { - AvailabilitySetImpl impl = (AvailabilitySetImpl) availabilitySet; - impl.idOfVMsInSet = null; - return impl; - }); + return super.refreshAsync().map(availabilitySet -> { + AvailabilitySetImpl impl = (AvailabilitySetImpl) availabilitySet; + impl.idOfVMsInSet = null; + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAvailabilitySets() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -158,8 +150,8 @@ public AvailabilitySetImpl withProximityPlacementGroup(String proximityPlacement } @Override - public AvailabilitySetImpl withNewProximityPlacementGroup( - String proximityPlacementGroupName, ProximityPlacementGroupType type) { + public AvailabilitySetImpl withNewProximityPlacementGroup(String proximityPlacementGroupName, + ProximityPlacementGroupType type) { this.newProximityPlacementGroupName = proximityPlacementGroupName; this.newProximityPlacementGroupType = type; @@ -185,20 +177,15 @@ public Mono createResourceAsync() { if (this.innerModel().platformUpdateDomainCount() == null) { this.innerModel().withPlatformUpdateDomainCount(5); } - return this - .createNewProximityPlacementGroupAsync() - .flatMap( - availabilitySet -> - manager() - .serviceClient() - .getAvailabilitySets() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) - .map( - availabilitySetInner -> { - self.setInner(availabilitySetInner); - idOfVMsInSet = null; - return self; - })); + return this.createNewProximityPlacementGroupAsync() + .flatMap(availabilitySet -> manager().serviceClient() + .getAvailabilitySets() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) + .map(availabilitySetInner -> { + self.setInner(availabilitySetInner); + idOfVMsInSet = null; + return self; + })); } private Mono createNewProximityPlacementGroupAsync() { @@ -207,18 +194,14 @@ private Mono createNewProximityPlacementGroupAsync() { ProximityPlacementGroupInner plgInner = new ProximityPlacementGroupInner(); plgInner.withProximityPlacementGroupType(this.newProximityPlacementGroupType); plgInner.withLocation(this.innerModel().location()); - return this - .manager() + return this.manager() .serviceClient() .getProximityPlacementGroups() .createOrUpdateAsync(this.resourceGroupName(), this.newProximityPlacementGroupName, plgInner) - .map( - createdPlgInner -> { - this - .innerModel() - .withProximityPlacementGroup(new SubResource().withId(createdPlgInner.id())); - return this; - }); + .map(createdPlgInner -> { + this.innerModel().withProximityPlacementGroup(new SubResource().withId(createdPlgInner.id())); + return this; + }); } } return Mono.just(this); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetsImpl.java index 548b51d6a5577..8f26f805e7cc8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/AvailabilitySetsImpl.java @@ -16,9 +16,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for AvailabilitySets. */ -public class AvailabilitySetsImpl - extends GroupableResourcesImpl< - AvailabilitySet, AvailabilitySetImpl, AvailabilitySetInner, AvailabilitySetsClient, ComputeManager> +public class AvailabilitySetsImpl extends + GroupableResourcesImpl implements AvailabilitySets { public AvailabilitySetsImpl(final ComputeManager computeManager) { @@ -32,7 +31,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getAvailabilitySets().listAsync(), this::wrapModel); + return PagedConverter.mapPage(this.manager().serviceClient().getAvailabilitySets().listAsync(), + this::wrapModel); } @Override @@ -43,8 +43,8 @@ public PagedIterable listByResourceGroup(String groupName) { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ComputeSkusImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ComputeSkusImpl.java index 0bcfd3d39bd4d..fa586f5fc3b8a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ComputeSkusImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ComputeSkusImpl.java @@ -57,8 +57,7 @@ public PagedFlux listByRegionAsync(String regionName) { @Override public PagedFlux listByRegionAsync(final Region region) { - return PagedConverter.mapPage( - inner().listAsync(String.format("location eq '%s'", region.name()), null), + return PagedConverter.mapPage(inner().listAsync(String.format("location eq '%s'", region.name()), null), this::wrapModel); } @@ -78,16 +77,13 @@ public PagedIterable listByResourceType(ComputeResourceType resource @Override public PagedFlux listByResourceTypeAsync(final ComputeResourceType resourceType) { - return PagedConverter - .flatMapPage( - wrapPageAsync(inner().listAsync()), - computeSku -> { - if (computeSku.resourceType() != null && computeSku.resourceType().equals(resourceType)) { - return Mono.just(computeSku); - } else { - return Mono.empty(); - } - }); + return PagedConverter.flatMapPage(wrapPageAsync(inner().listAsync()), computeSku -> { + if (computeSku.resourceType() != null && computeSku.resourceType().equals(resourceType)) { + return Mono.just(computeSku); + } else { + return Mono.empty(); + } + }); } @Override @@ -96,17 +92,15 @@ public PagedIterable listByRegionAndResourceType(Region region, Comp } @Override - public PagedFlux listByRegionAndResourceTypeAsync( - final Region region, final ComputeResourceType resourceType) { - return PagedConverter - .flatMapPage( - wrapPageAsync(inner().listAsync(String.format("location eq '%s'", region.name()), null)), - computeSku -> { - if (computeSku.resourceType() != null && computeSku.resourceType().equals(resourceType)) { - return Mono.just(computeSku); - } else { - return Mono.empty(); - } - }); + public PagedFlux listByRegionAndResourceTypeAsync(final Region region, + final ComputeResourceType resourceType) { + return PagedConverter.flatMapPage( + wrapPageAsync(inner().listAsync(String.format("location eq '%s'", region.name()), null)), computeSku -> { + if (computeSku.resourceType() != null && computeSku.resourceType().equals(resourceType)) { + return Mono.just(computeSku); + } else { + return Mono.empty(); + } + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/CustomImageDataDiskImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/CustomImageDataDiskImpl.java index e7eee3bdcdd66..dbcd193e235c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/CustomImageDataDiskImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/CustomImageDataDiskImpl.java @@ -14,8 +14,7 @@ class CustomImageDataDiskImpl extends ChildResourceImpl implements VirtualMachineCustomImage.CustomImageDataDisk, - VirtualMachineCustomImage.CustomImageDataDisk.Definition< - VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings> { + VirtualMachineCustomImage.CustomImageDataDisk.Definition { CustomImageDataDiskImpl(ImageDataDisk inner, VirtualMachineCustomImageImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskAccessesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskAccessesClientImpl.java index 5e22acef23e4d..9aa6da4e669d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskAccessesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskAccessesClientImpl.java @@ -1690,7 +1690,7 @@ public Mono updateAPrivateEndpointConnectionAsyn PrivateEndpointConnectionInner privateEndpointConnection) { return beginUpdateAPrivateEndpointConnectionAsync(resourceGroupName, diskAccessName, privateEndpointConnectionName, privateEndpointConnection).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1716,7 +1716,7 @@ private Mono updateAPrivateEndpointConnectionAsy PrivateEndpointConnectionInner privateEndpointConnection, Context context) { return beginUpdateAPrivateEndpointConnectionAsync(resourceGroupName, diskAccessName, privateEndpointConnectionName, privateEndpointConnection, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetImpl.java index d8fea608befb8..83b4c512d8ace 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetImpl.java @@ -19,9 +19,7 @@ public class DiskEncryptionSetImpl extends GroupableResourceImpl - implements DiskEncryptionSet, - DiskEncryptionSet.Definition, - DiskEncryptionSet.Update { + implements DiskEncryptionSet, DiskEncryptionSet.Definition, DiskEncryptionSet.Update { private DiskEncryptionSetUpdate patchToUpdate = new DiskEncryptionSetUpdate(); private boolean updated; private final DiskEncryptionSetMsiHandler msiHandler; @@ -132,12 +130,13 @@ public DiskEncryptionSetImpl withRoleBasedAccessToCurrentKeyVault() { @Override public Mono createResourceAsync() { - return manager().serviceClient().getDiskEncryptionSets().createOrUpdateAsync( - resourceGroupName(), name(), innerModel() - ).map(inner -> { - setInner(inner); - return this; - }); + return manager().serviceClient() + .getDiskEncryptionSets() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) + .map(inner -> { + setInner(inner); + return this; + }); } @Override @@ -151,23 +150,25 @@ public Mono updateResourceAsync() { if (!updated) { return Mono.just(this); } - return manager().serviceClient().getDiskEncryptionSets().updateAsync( - resourceGroupName(), name(), patchToUpdate - ).map(inner -> { - setInner(inner); - this.updated = false; - return this; - }); + return manager().serviceClient() + .getDiskEncryptionSets() + .updateAsync(resourceGroupName(), name(), patchToUpdate) + .map(inner -> { + setInner(inner); + this.updated = false; + return this; + }); } @Override protected Mono getInnerAsync() { - return manager().serviceClient().getDiskEncryptionSets().getByResourceGroupAsync( - resourceGroupName(), name() - ).map(inner -> { - this.updated = false; - return inner; - }); + return manager().serviceClient() + .getDiskEncryptionSets() + .getByResourceGroupAsync(resourceGroupName(), name()) + .map(inner -> { + this.updated = false; + return inner; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetsImpl.java index 1319eca28282d..f1a4c46b1733a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskEncryptionSetsImpl.java @@ -10,13 +10,8 @@ import com.azure.resourcemanager.compute.models.DiskEncryptionSets; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; -public class DiskEncryptionSetsImpl - extends TopLevelModifiableResourcesImpl< - DiskEncryptionSet, - DiskEncryptionSetImpl, - DiskEncryptionSetInner, - DiskEncryptionSetsClient, - ComputeManager> +public class DiskEncryptionSetsImpl extends + TopLevelModifiableResourcesImpl implements DiskEncryptionSets { public DiskEncryptionSetsImpl(ComputeManager manager) { super(manager.serviceClient().getDiskEncryptionSets(), manager); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskImpl.java index 9d60a52e28b7b..95f3637e5bad7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DiskImpl.java @@ -121,8 +121,7 @@ public Mono grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); - return this - .manager() + return this.manager() .serviceClient() .getDisks() .grantAccessAsync(this.resourceGroupName(), this.name(), grantAccessDataInner) @@ -161,8 +160,7 @@ public PublicNetworkAccess publicNetworkAccess() { @Override public DiskImpl withLinuxFromVhd(String vhdUrl) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -173,8 +171,7 @@ public DiskImpl withLinuxFromVhd(String vhdUrl) { @Override public DiskImpl withLinuxFromDisk(String sourceDiskId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -195,8 +192,7 @@ public DiskImpl withLinuxFromDisk(Disk sourceDisk) { @Override public DiskImpl withLinuxFromSnapshot(String sourceSnapshotId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -217,8 +213,7 @@ public DiskImpl withLinuxFromSnapshot(Snapshot sourceSnapshot) { @Override public DiskImpl withWindowsFromVhd(String vhdUrl) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -229,8 +224,7 @@ public DiskImpl withWindowsFromVhd(String vhdUrl) { @Override public DiskImpl withWindowsFromDisk(String sourceDiskId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -251,8 +245,7 @@ public DiskImpl withWindowsFromDisk(Disk sourceDisk) { @Override public DiskImpl withWindowsFromSnapshot(String sourceSnapshotId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -279,8 +272,7 @@ public DiskImpl withData() { @Override public DiskImpl fromVhd(String vhdUrl) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) @@ -290,8 +282,7 @@ public DiskImpl fromVhd(String vhdUrl) { @Override public DiskImpl withUploadSizeInMB(long uploadSizeInMB) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.UPLOAD) @@ -301,8 +292,7 @@ public DiskImpl withUploadSizeInMB(long uploadSizeInMB) { @Override public DiskImpl fromSnapshot(String snapshotId) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) @@ -317,8 +307,7 @@ public DiskImpl fromSnapshot(Snapshot snapshot) { @Override public DiskImpl fromDisk(String managedDiskId) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) @@ -357,15 +346,8 @@ public DiskImpl withStorageAccountId(String storageAccountId) { @Override public DiskImpl withStorageAccountName(String storageAccountName) { - String id = - ResourceUtils - .constructResourceId( - this.myManager.subscriptionId(), - this.resourceGroupName(), - "Microsoft.Storage", - "storageAccounts", - storageAccountName, - ""); + String id = ResourceUtils.constructResourceId(this.myManager.subscriptionId(), this.resourceGroupName(), + "Microsoft.Storage", "storageAccounts", storageAccountName, ""); return this.withStorageAccountId(id); } @@ -431,8 +413,7 @@ public DiskImpl withLogicalSectorSizeInBytes(int logicalSectorSizeInBytes) { @Override public Mono createResourceAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getDisks() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) .map(innerToFluentMap(this)); @@ -445,27 +426,18 @@ protected Mono getInnerAsync() { @Override public Accepted beginCreate() { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> - this - .manager() - .serviceClient() - .getDisks() - .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) - .block(), - inner -> new DiskImpl(inner.name(), inner, this.manager()), - DiskInner.class, - () -> { - Flux dependencyTasksAsync = - taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); - dependencyTasksAsync.blockLast(); - }, - this::setInner, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.manager() + .serviceClient() + .getDisks() + .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) + .block(), + inner -> new DiskImpl(inner.name(), inner, this.manager()), DiskInner.class, () -> { + Flux dependencyTasksAsync + = taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); + dependencyTasksAsync.blockLast(); + }, this::setInner, Context.NONE); } private DiskSkuTypes fromSnapshotSkuType(SnapshotSkuType skuType) { diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DisksImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DisksImpl.java index 27afec273e962..cf11deb6f7dbe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DisksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/DisksImpl.java @@ -36,12 +36,11 @@ public String grantAccess(String resourceGroupName, String diskName, AccessLevel } @Override - public Mono grantAccessAsync( - String resourceGroupName, String diskName, AccessLevel accessLevel, int accessDuration) { + public Mono grantAccessAsync(String resourceGroupName, String diskName, AccessLevel accessLevel, + int accessDuration) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(accessLevel).withDurationInSeconds(accessDuration); - return this - .inner() + return this.inner() .grantAccessAsync(resourceGroupName, diskName, grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @@ -63,16 +62,10 @@ public Accepted beginDeleteById(String id) { @Override public Accepted beginDeleteByResourceGroup(String resourceGroupName, String name) { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), Function.identity(), + Void.class, null, Context.NONE); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/EncryptionSettings.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/EncryptionSettings.java index d6bdb6b97b2bf..ca2025a23790e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/EncryptionSettings.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/EncryptionSettings.java @@ -18,8 +18,10 @@ abstract class EncryptionSettings { /** @return encryption specific settings to be set on virtual machine storage profile */ abstract DiskEncryptionSettings storageProfileEncryptionSettings(); + /** @return encryption extension public settings */ abstract HashMap extensionPublicSettings(); + /** @return encryption extension protected settings */ abstract HashMap extensionProtectedSettings(); @@ -30,8 +32,8 @@ abstract class EncryptionSettings { * @param the config type * @return enable settings */ - static > Enable createEnable( - final VirtualMachineEncryptionConfiguration config) { + static > Enable + createEnable(final VirtualMachineEncryptionConfiguration config) { return new Enable(config); } @@ -68,8 +70,7 @@ DiskEncryptionSettings storageProfileEncryptionSettings() { } } DiskEncryptionSettings diskEncryptionSettings = new DiskEncryptionSettings(); - diskEncryptionSettings - .withEnabled(true) + diskEncryptionSettings.withEnabled(true) .withKeyEncryptionKey(keyEncryptionKey) .withDiskEncryptionKey(new KeyVaultSecretReference()) .diskEncryptionKey() @@ -86,10 +87,7 @@ HashMap extensionPublicSettings() { publicSettings.put("VolumeType", config.volumeType().toString()); publicSettings.put("SequenceVersion", UUID.randomUUID()); if (config.keyEncryptionKeyUrl() != null) { - publicSettings - .put( - "KeyEncryptionKeyURL", - config.keyEncryptionKeyUrl()); // KeyVault to hold Key for encrypting "Disk Encryption Key" (aka + publicSettings.put("KeyEncryptionKeyURL", config.keyEncryptionKeyUrl()); // KeyVault to hold Key for encrypting "Disk Encryption Key" (aka // kek). } if (this.requestedForLegacyEncryptExtension()) { diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleriesImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleriesImpl.java index c7572ccd1a580..44a15616dc70f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleriesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleriesImpl.java @@ -21,9 +21,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for Galleries. */ -public class GalleriesImpl - extends GroupableResourcesImpl - implements Galleries { +public class GalleriesImpl extends + GroupableResourcesImpl implements Galleries { public GalleriesImpl(ComputeManager manager) { super(manager.serviceClient().getGalleries(), manager); } @@ -68,8 +67,8 @@ public PagedIterable listByResourceGroup(String resourceGroupName) { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return PagedConverter.mapPage(inner().listByResourceGroupAsync(resourceGroupName), this::wrapModel); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryApplicationVersionsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryApplicationVersionsClientImpl.java index 444ae42654072..a9928ff42de20 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryApplicationVersionsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryApplicationVersionsClientImpl.java @@ -404,7 +404,7 @@ public Mono createOrUpdateAsync(String resourceG GalleryApplicationVersionInner galleryApplicationVersion) { return beginCreateOrUpdateAsync(resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -432,7 +432,7 @@ private Mono createOrUpdateAsync(String resource GalleryApplicationVersionInner galleryApplicationVersion, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageImpl.java index 89135c58a2c65..5fcf76d919da0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageImpl.java @@ -70,32 +70,28 @@ class GalleryImageImpl extends CreatableUpdatableImpl getVersionAsync(String versionName) { - return this - .manager() + return this.manager() .galleryImageVersions() .getByGalleryImageAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, versionName); } @Override public GalleryImageVersion getVersion(String versionName) { - return this - .manager() + return this.manager() .galleryImageVersions() .getByGalleryImage(this.resourceGroupName, this.galleryName, this.galleryImageName, versionName); } @Override public PagedFlux listVersionsAsync() { - return this - .manager() + return this.manager() .galleryImageVersions() .listByGalleryImageAsync(this.resourceGroupName, this.galleryName, this.galleryImageName); } @Override public PagedIterable listVersions() { - return this - .manager() + return this.manager() .galleryImageVersions() .listByGalleryImage(this.resourceGroupName, this.galleryName, this.galleryImageName); } @@ -107,8 +103,7 @@ public ComputeManager manager() { @Override public Mono createResourceAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImages() .createOrUpdateAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, this.innerModel()) .map(innerToFluentMap(this)); @@ -122,12 +117,10 @@ public GalleryImageImpl update() { @Override public Mono updateResourceAsync() { - this.galleryImageUpdate - .withOsState(innerModel().osState()) + this.galleryImageUpdate.withOsState(innerModel().osState()) .withOsType(innerModel().osType()) .withIdentifier(innerModel().identifier()); - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImages() .updateAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, this.galleryImageUpdate) .map(innerToFluentMap(this)); @@ -135,8 +128,7 @@ public Mono updateResourceAsync() { @Override protected Mono getInnerAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImages() .getAsync(this.resourceGroupName, this.galleryName, this.galleryImageName); } @@ -243,8 +235,8 @@ public HyperVGeneration hyperVGeneration() { public SecurityTypes securityType() { return CoreUtils.isNullOrEmpty(this.innerModel().features()) ? null - : - this.innerModel().features() + : this.innerModel() + .features() .stream() .filter(feature -> FEATURE_SECURITY_TYPE.equals(feature.name())) .findAny() @@ -296,8 +288,7 @@ public GalleryImageImpl withIdentifier(GalleryImageIdentifier identifier) { @Override public GalleryImageImpl withIdentifier(String publisher, String offer, String sku) { - this - .innerModel() + this.innerModel() .withIdentifier(new GalleryImageIdentifier().withPublisher(publisher).withOffer(offer).withSku(sku)); return this; } @@ -542,8 +533,8 @@ public GalleryImageImpl withRecommendedMemoryForVirtualMachine(int minMB, int ma } @Override - public GalleryImageImpl withRecommendedConfigurationForVirtualMachine( - RecommendedMachineConfiguration recommendedConfig) { + public GalleryImageImpl + withRecommendedConfigurationForVirtualMachine(RecommendedMachineConfiguration recommendedConfig) { this.innerModel().withRecommended(recommendedConfig); if (isInUpdateMode()) { this.galleryImageUpdate.withRecommended(recommendedConfig); @@ -577,16 +568,13 @@ public GalleryImageImpl withHyperVGeneration(HyperVGeneration hyperVGeneration) @Override public GalleryImageImpl withTrustedLaunch() { - this.innerModel().withFeatures( - Stream.concat( - ensureFeatures() - .stream() - .filter(feature -> !FEATURE_SECURITY_TYPE.equals(feature.name())), - Stream.of(new GalleryImageFeature() - .withName(FEATURE_SECURITY_TYPE) - .withValue(SecurityTypes.TRUSTED_LAUNCH.toString())) - ).collect(Collectors.toList()) - ); + this.innerModel() + .withFeatures( + Stream + .concat(ensureFeatures().stream().filter(feature -> !FEATURE_SECURITY_TYPE.equals(feature.name())), + Stream.of(new GalleryImageFeature().withName(FEATURE_SECURITY_TYPE) + .withValue(SecurityTypes.TRUSTED_LAUNCH.toString()))) + .collect(Collectors.toList())); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionImpl.java index 688c029d91b00..4e56427f02784 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionImpl.java @@ -65,36 +65,25 @@ public ComputeManager manager() { @Override public Mono createResourceAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImageVersions() - .createOrUpdateAsync( - this.resourceGroupName, - this.galleryName, - this.galleryImageName, - this.galleryImageVersionName, - this.innerModel()) + .createOrUpdateAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, + this.galleryImageVersionName, this.innerModel()) .map(innerToFluentMap(this)); } @Override public Mono updateResourceAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImageVersions() - .createOrUpdateAsync( - this.resourceGroupName, - this.galleryName, - this.galleryImageName, - this.galleryImageVersionName, - this.innerModel()) + .createOrUpdateAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, + this.galleryImageVersionName, this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono getInnerAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleryImageVersions() .getAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, this.galleryImageVersionName); } @@ -135,11 +124,8 @@ public List availableRegions() { if (this.innerModel().publishingProfile() != null && this.innerModel().publishingProfile().targetRegions() != null) { for (TargetRegion targetRegion : this.innerModel().publishingProfile().targetRegions()) { - regions - .add( - new TargetRegion() - .withName(targetRegion.name()) - .withRegionalReplicaCount(targetRegion.regionalReplicaCount())); + regions.add(new TargetRegion().withName(targetRegion.name()) + .withRegionalReplicaCount(targetRegion.regionalReplicaCount())); } } return Collections.unmodifiableList(regions); @@ -184,8 +170,8 @@ public String type() { } @Override - public GalleryImageVersionImpl withExistingImage( - String resourceGroupName, String galleryName, String galleryImageName) { + public GalleryImageVersionImpl withExistingImage(String resourceGroupName, String galleryName, + String galleryImageName) { this.resourceGroupName = resourceGroupName; this.galleryName = galleryName; this.galleryImageName = galleryImageName; @@ -252,8 +238,8 @@ public GalleryImageVersionImpl withRegionAvailability(Region region, int replica } } if (!found) { - TargetRegion targetRegion = - new TargetRegion().withName(newRegionName).withRegionalReplicaCount(replicaCount); + TargetRegion targetRegion + = new TargetRegion().withName(newRegionName).withRegionalReplicaCount(replicaCount); this.innerModel().publishingProfile().targetRegions().add(targetRegion); } // @@ -270,10 +256,8 @@ public GalleryImageVersionImpl withRegionAvailability(Region region, int replica } } if (!found) { - TargetRegion defaultTargetRegion = - new TargetRegion() - .withName(this.location()) - .withRegionalReplicaCount(null); // null means default where service default to 1 replica + TargetRegion defaultTargetRegion + = new TargetRegion().withName(this.location()).withRegionalReplicaCount(null); // null means default where service default to 1 replica this.innerModel().publishingProfile().targetRegions().add(defaultTargetRegion); } // @@ -300,10 +284,8 @@ public GalleryImageVersionImpl withRegionAvailability(List targetR } } if (!found) { - TargetRegion defaultTargetRegion = - new TargetRegion() - .withName(this.location()) - .withRegionalReplicaCount(null); // null means default where service default to 1 replica + TargetRegion defaultTargetRegion + = new TargetRegion().withName(this.location()).withRegionalReplicaCount(null); // null means default where service default to 1 replica this.innerModel().publishingProfile().targetRegions().add(defaultTargetRegion); } // diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionsImpl.java index ca5282df999e4..c27f7147755ff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImageVersionsImpl.java @@ -41,48 +41,43 @@ private GalleryImageVersionImpl wrapModel(String name) { } @Override - public PagedFlux listByGalleryImageAsync( - final String resourceGroupName, final String galleryName, final String galleryImageName) { - return PagedConverter.mapPage(innerModel() - .listByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName), - this::wrapModel); + public PagedFlux listByGalleryImageAsync(final String resourceGroupName, + final String galleryName, final String galleryImageName) { + return PagedConverter.mapPage( + innerModel().listByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName), this::wrapModel); } @Override - public PagedIterable listByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName) { - return PagedConverter.mapPage(innerModel() - .listByGalleryImage(resourceGroupName, galleryName, galleryImageName), + public PagedIterable listByGalleryImage(String resourceGroupName, String galleryName, + String galleryImageName) { + return PagedConverter.mapPage(innerModel().listByGalleryImage(resourceGroupName, galleryName, galleryImageName), this::wrapModel); } @Override - public Mono getByGalleryImageAsync( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName) { - return innerModel() - .getAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) + public Mono getByGalleryImageAsync(String resourceGroupName, String galleryName, + String galleryImageName, String galleryImageVersionName) { + return innerModel().getAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) .map(this::wrapModel); } @Override - public GalleryImageVersion getByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName) { - return this - .getByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) + public GalleryImageVersion getByGalleryImage(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName) { + return this.getByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) .block(); } @Override - public Mono deleteByGalleryImageAsync( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName) { + public Mono deleteByGalleryImageAsync(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName) { return innerModel().deleteAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName); } @Override - public void deleteByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName) { - this - .deleteByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) + public void deleteByGalleryImage(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName) { + this.deleteByGalleryImageAsync(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) .block(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImpl.java index 29859cc45548d..312677f5aac7d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/GalleryImpl.java @@ -25,8 +25,7 @@ class GalleryImpl extends GroupableResourceImpl createResourceAsync() { - return manager() - .serviceClient() + return manager().serviceClient() .getGalleries() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); @@ -39,8 +38,7 @@ public Mono updateResourceAsync() { updateParameters.withTags(this.innerModel().tags()); } - return manager() - .serviceClient() + return manager().serviceClient() .getGalleries() .updateAsync(this.resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeLegacyEncryptionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeLegacyEncryptionMonitorImpl.java index 34406572d36f7..1cf11aaeeca26 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeLegacyEncryptionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeLegacyEncryptionMonitorImpl.java @@ -81,13 +81,10 @@ public DiskVolumeEncryptionMonitor refresh() { public Mono refreshAsync() { // Refreshes the cached encryption extension installed in the Linux virtual machine. final DiskVolumeEncryptionMonitor self = this; - return retrieveEncryptExtensionWithInstanceViewAsync() - .flatMap( - virtualMachineExtensionInner -> { - encryptionExtension = virtualMachineExtensionInner; - return Mono.just(self); - }) - .switchIfEmpty(Mono.just(self)); + return retrieveEncryptExtensionWithInstanceViewAsync().flatMap(virtualMachineExtensionInner -> { + encryptionExtension = virtualMachineExtensionInner; + return Mono.just(self); + }).switchIfEmpty(Mono.just(self)); } /** @@ -113,10 +110,9 @@ private Mono retrieveEncryptExtensionWithInstanceV * @param extension the extension name * @return an observable that emits the retrieved extension */ - private Mono retrieveExtensionWithInstanceViewAsync( - VirtualMachineExtensionInner extension) { - return computeManager - .serviceClient() + private Mono + retrieveExtensionWithInstanceViewAsync(VirtualMachineExtensionInner extension) { + return computeManager.serviceClient() .getVirtualMachineExtensions() .getWithResponseAsync(rgName, vmName, extension.name(), "instanceView") .map(Response::getValue); @@ -130,24 +126,22 @@ private Mono retrieveExtensionWithInstanceViewAsyn * @return the retrieved extension */ private Mono retrieveEncryptExtensionWithInstanceViewFromVMAsync() { - return computeManager - .serviceClient() + return computeManager.serviceClient() .getVirtualMachines() .getByResourceGroupAsync(rgName, vmName) // Exception if vm not found - .flatMap( - virtualMachine -> { - if (virtualMachine.resources() != null) { - for (VirtualMachineExtensionInner extension : virtualMachine.resources()) { - if (EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisher()) - && EncryptionExtensionIdentifier - .isEncryptionTypeName(extension.typePropertiesType(), OperatingSystemTypes.LINUX)) { - return retrieveExtensionWithInstanceViewAsync(extension); - } + .flatMap(virtualMachine -> { + if (virtualMachine.resources() != null) { + for (VirtualMachineExtensionInner extension : virtualMachine.resources()) { + if (EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisher()) + && EncryptionExtensionIdentifier.isEncryptionTypeName(extension.typePropertiesType(), + OperatingSystemTypes.LINUX)) { + return retrieveExtensionWithInstanceViewAsync(extension); } } - return Mono.empty(); - }); + } + return Mono.empty(); + }); } private boolean hasEncryptionExtension() { diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeNoAADEncryptionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeNoAADEncryptionMonitorImpl.java index 844645eeb391c..dcc26b796738c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeNoAADEncryptionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/LinuxDiskVolumeNoAADEncryptionMonitorImpl.java @@ -99,26 +99,23 @@ public DiskVolumeEncryptionMonitor refresh() { public Mono refreshAsync() { final LinuxDiskVolumeNoAADEncryptionMonitorImpl self = this; // Refreshes the cached virtual machine and installed encryption extension - return retrieveVirtualMachineAsync() - .flatMap( - virtualMachine -> { - self.virtualMachine = virtualMachine; - if (virtualMachine.instanceView() != null && virtualMachine.instanceView().extensions() != null) { - for (VirtualMachineExtensionInstanceView eiv : virtualMachine.instanceView().extensions()) { - if (eiv.type() != null - && eiv - .type() - .toLowerCase(Locale.ROOT) - .startsWith(EncryptionExtensionIdentifier.publisherName().toLowerCase(Locale.ROOT)) - && eiv.name() != null - && EncryptionExtensionIdentifier.isEncryptionTypeName(eiv.name(), osType())) { - self.extensionInstanceView = eiv; - break; - } - } + return retrieveVirtualMachineAsync().flatMap(virtualMachine -> { + self.virtualMachine = virtualMachine; + if (virtualMachine.instanceView() != null && virtualMachine.instanceView().extensions() != null) { + for (VirtualMachineExtensionInstanceView eiv : virtualMachine.instanceView().extensions()) { + if (eiv.type() != null + && eiv.type() + .toLowerCase(Locale.ROOT) + .startsWith(EncryptionExtensionIdentifier.publisherName().toLowerCase(Locale.ROOT)) + && eiv.name() != null + && EncryptionExtensionIdentifier.isEncryptionTypeName(eiv.name(), osType())) { + self.extensionInstanceView = eiv; + break; } - return Mono.just(self); - }); + } + } + return Mono.just(self); + }); } /** @@ -127,7 +124,8 @@ public Mono refreshAsync() { * @return the retrieved virtual machine */ private Mono retrieveVirtualMachineAsync() { - return computeManager.serviceClient().getVirtualMachines() + return computeManager.serviceClient() + .getVirtualMachines() .getByResourceGroupWithResponseAsync(rgName, vmName, InstanceViewTypes.INSTANCE_VIEW) .map(Response::getValue); // Exception if vm not found diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ManagedUnmanagedDiskErrors.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ManagedUnmanagedDiskErrors.java index 0eb1d8dd706fb..a8d4516256e6e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ManagedUnmanagedDiskErrors.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ManagedUnmanagedDiskErrors.java @@ -4,24 +4,24 @@ /** Shared managed vs unmanaged disks errors between virtual machine and virtual machine scale set. */ class ManagedUnmanagedDiskErrors { - static final String VM_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED = - "This virtual machine is based on managed disk(s), both un-managed and managed disk cannot exists together in" + static final String VM_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED + = "This virtual machine is based on managed disk(s), both un-managed and managed disk cannot exists together in" + " a virtual machine"; - static final String VMSS_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED = - "This virtual machine scale set is based on managed disk(s), both un-managed and managed cannot exists" + static final String VMSS_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED + = "This virtual machine scale set is based on managed disk(s), both un-managed and managed cannot exists" + " together in a virtual machine scale set"; - static final String VM_NO_UNMANAGED_DISK_TO_UPDATE = - "This virtual machine is based on managed disk(s) and there is no un-managed disk to update"; - static final String VM_NO_MANAGED_DISK_TO_UPDATE = - "This virtual machine is based on un-managed disk(s) and there is no managed disk to update"; - static final String VMSS_NO_UNMANAGED_DISK_TO_UPDATE = - "This virtual machine scale set is based on managed disk(s) and there is no un-managed disk to update"; - static final String VMSS_NO_MANAGED_DISK_TO_UPDATE = - "This virtual machine scale set is based on un-managed disk(s) and there is no managed disk to update"; - static final String VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED = - "This virtual machine is based on un-managed disks (s), both un-managed and managed disk cannot exists" + static final String VM_NO_UNMANAGED_DISK_TO_UPDATE + = "This virtual machine is based on managed disk(s) and there is no un-managed disk to update"; + static final String VM_NO_MANAGED_DISK_TO_UPDATE + = "This virtual machine is based on un-managed disk(s) and there is no managed disk to update"; + static final String VMSS_NO_UNMANAGED_DISK_TO_UPDATE + = "This virtual machine scale set is based on managed disk(s) and there is no un-managed disk to update"; + static final String VMSS_NO_MANAGED_DISK_TO_UPDATE + = "This virtual machine scale set is based on un-managed disk(s) and there is no managed disk to update"; + static final String VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED + = "This virtual machine is based on un-managed disks (s), both un-managed and managed disk cannot exists" + " together in a virtual machine"; - static final String VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED = - "This virtual machine scale set is based on un-managed disk(s), both un-managed and managed cannot exists" + static final String VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED + = "This virtual machine scale set is based on un-managed disk(s), both un-managed and managed cannot exists" + " together in a virtual machine scale set"; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ProxyEncryptionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ProxyEncryptionMonitorImpl.java index 2de7618fc5549..d6b026e106251 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ProxyEncryptionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/ProxyEncryptionMonitorImpl.java @@ -79,28 +79,23 @@ public Mono refreshAsync() { return this.resolvedEncryptionMonitor.refreshAsync(); } else { final ProxyEncryptionMonitorImpl self = this; - return retrieveVirtualMachineAsync() - .flatMap( - virtualMachine -> { - VirtualMachineExtensionInner extension = encryptionExtension(virtualMachine); - if (extension != null) { - if (EncryptionExtensionIdentifier.isNoAADVersion(osType(), - extension.typeHandlerVersion())) { - self.resolvedEncryptionMonitor = (osType() == OperatingSystemTypes.LINUX) - ? new LinuxDiskVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), computeManager) - : new WindowsVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), computeManager); - } else { - self.resolvedEncryptionMonitor = (osType() == OperatingSystemTypes.LINUX) - ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl( - virtualMachine.id(), computeManager) - : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), computeManager); - } - return self.resolvedEncryptionMonitor.refreshAsync(); - } else { - return Mono.just(self); - } - }) - .switchIfEmpty(Mono.just(self)); + return retrieveVirtualMachineAsync().flatMap(virtualMachine -> { + VirtualMachineExtensionInner extension = encryptionExtension(virtualMachine); + if (extension != null) { + if (EncryptionExtensionIdentifier.isNoAADVersion(osType(), extension.typeHandlerVersion())) { + self.resolvedEncryptionMonitor = (osType() == OperatingSystemTypes.LINUX) + ? new LinuxDiskVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), computeManager) + : new WindowsVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), computeManager); + } else { + self.resolvedEncryptionMonitor = (osType() == OperatingSystemTypes.LINUX) + ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), computeManager) + : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), computeManager); + } + return self.resolvedEncryptionMonitor.refreshAsync(); + } else { + return Mono.just(self); + } + }).switchIfEmpty(Mono.just(self)); } } @@ -110,8 +105,7 @@ public Mono refreshAsync() { * @return the retrieved virtual machine */ private Mono retrieveVirtualMachineAsync() { - return computeManager - .serviceClient() + return computeManager.serviceClient() .getVirtualMachines() .getByResourceGroupAsync(ResourceUtils.groupFromResourceId(vmId), ResourceUtils.nameFromResourceId(vmId)); // Exception if vm not found diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotImpl.java index 0c238e71c83e3..ff1b45f265ae8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotImpl.java @@ -91,8 +91,7 @@ public String grantAccess(int accessDurationInSeconds) { public Mono grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); - return manager() - .serviceClient() + return manager().serviceClient() .getSnapshots() .grantAccessAsync(resourceGroupName(), name(), grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); @@ -117,7 +116,8 @@ public void awaitCopyStartCompletion() { public Boolean awaitCopyStartCompletion(Duration maxWaitTime) { Objects.requireNonNull(maxWaitTime); if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { - throw new IllegalArgumentException(String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); + throw new IllegalArgumentException( + String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); } return this.awaitCopyStartCompletionAsync() .then(Mono.just(Boolean.TRUE)) @@ -133,12 +133,15 @@ public PublicNetworkAccess publicNetworkAccess() { @Override public Mono awaitCopyStartCompletionAsync() { if (creationMethod() != DiskCreateOption.COPY_START) { - return Mono.error(logger.logThrowableAsError(new IllegalStateException( - String.format( - "\"awaitCopyStartCompletionAsync\" cannot be called on snapshot \"%s\" when \"creationMethod\" is not \"CopyStart\"", this.name())))); + return Mono.error(logger.logThrowableAsError(new IllegalStateException(String.format( + "\"awaitCopyStartCompletionAsync\" cannot be called on snapshot \"%s\" when \"creationMethod\" is not \"CopyStart\"", + this.name())))); } - return Flux.interval(Duration.ZERO, ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(manager().serviceClient().getDefaultPollInterval())) + return Flux + .interval(Duration.ZERO, + ResourceManagerUtils.InternalRuntimeContext + .getDelayDuration(manager().serviceClient().getDefaultPollInterval())) .flatMap(ignored -> getInnerAsync()) .flatMap(inner -> { setInner(inner); @@ -152,8 +155,8 @@ public Mono awaitCopyStartCompletionAsync() { if (Float.valueOf(100).equals(inner.completionPercent())) { return true; } else { // in progress - logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", - inner.name(), inner.completionPercent()); + logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", inner.name(), + inner.completionPercent()); return false; } }) @@ -167,8 +170,7 @@ public SnapshotImpl withLinuxFromVhd(String vhdUrl) { @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -180,8 +182,7 @@ public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { @Override public SnapshotImpl withLinuxFromDisk(String sourceDiskId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -201,8 +202,7 @@ public SnapshotImpl withLinuxFromDisk(Disk sourceDisk) { @Override public SnapshotImpl withLinuxFromSnapshot(String sourceSnapshotId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() @@ -228,8 +228,7 @@ public SnapshotImpl withWindowsFromVhd(String vhdUrl) { @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -241,8 +240,7 @@ public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { @Override public SnapshotImpl withWindowsFromDisk(String sourceDiskId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -262,8 +260,7 @@ public SnapshotImpl withWindowsFromDisk(Disk sourceDisk) { @Override public SnapshotImpl withWindowsFromSnapshot(String sourceSnapshotId) { - this - .innerModel() + this.innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() @@ -289,8 +286,7 @@ public SnapshotImpl withDataFromVhd(String vhdUrl) { @Override public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) @@ -301,8 +297,7 @@ public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { @Override public SnapshotImpl withDataFromSnapshot(String snapshotId) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) @@ -317,16 +312,13 @@ public SnapshotImpl withDataFromSnapshot(Snapshot snapshot) { @Override public SnapshotImpl withCopyStart() { - this.innerModel() - .creationData() - .withCreateOption(DiskCreateOption.COPY_START); + this.innerModel().creationData().withCreateOption(DiskCreateOption.COPY_START); return this; } @Override public SnapshotImpl withDataFromDisk(String managedDiskId) { - this - .innerModel() + this.innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) @@ -365,8 +357,7 @@ public SnapshotImpl withSku(SnapshotSkuType sku) { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getSnapshots() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) @@ -375,8 +366,7 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getSnapshots() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -384,18 +374,11 @@ protected Mono getInnerAsync() { private String constructStorageAccountId(String vhdUrl) { try { - return ResourceUtils - .constructResourceId( - this.manager().subscriptionId(), - resourceGroupName(), - "Microsoft.Storage", - "storageAccounts", - vhdUrl.split("\\.")[0].replace("https://", ""), - ""); + return ResourceUtils.constructResourceId(this.manager().subscriptionId(), resourceGroupName(), + "Microsoft.Storage", "storageAccounts", vhdUrl.split("\\.")[0].replace("https://", ""), ""); } catch (RuntimeException ex) { - throw logger - .logExceptionAsError( - new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); + throw logger.logExceptionAsError( + new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotsImpl.java index d9b2a63e59562..192f5911b5a4a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/SnapshotsImpl.java @@ -23,18 +23,17 @@ public SnapshotsImpl(ComputeManager computeManager) { } @Override - public Mono grantAccessAsync( - String resourceGroupName, String snapshotName, AccessLevel accessLevel, int accessDuration) { + public Mono grantAccessAsync(String resourceGroupName, String snapshotName, AccessLevel accessLevel, + int accessDuration) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(accessLevel).withDurationInSeconds(accessDuration); - return inner() - .grantAccessAsync(resourceGroupName, snapshotName, grantAccessDataInner) + return inner().grantAccessAsync(resourceGroupName, snapshotName, grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @Override - public String grantAccess( - String resourceGroupName, String snapshotName, AccessLevel accessLevel, int accessDuration) { + public String grantAccess(String resourceGroupName, String snapshotName, AccessLevel accessLevel, + int accessDuration) { return this.grantAccessAsync(resourceGroupName, snapshotName, accessLevel, accessDuration).block(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/UnmanagedDataDiskImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/UnmanagedDataDiskImpl.java index f5ae61469b4a5..0c7b7ef920503 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/UnmanagedDataDiskImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/UnmanagedDataDiskImpl.java @@ -20,12 +20,12 @@ /** The implementation for {@link DataDisk} and its create and update interfaces. */ class UnmanagedDataDiskImpl extends ChildResourceImpl implements VirtualMachineUnmanagedDataDisk, - VirtualMachineUnmanagedDataDisk.DefinitionWithExistingVhd, - VirtualMachineUnmanagedDataDisk.DefinitionWithNewVhd, - VirtualMachineUnmanagedDataDisk.DefinitionWithImage, - VirtualMachineUnmanagedDataDisk.UpdateDefinitionWithExistingVhd, - VirtualMachineUnmanagedDataDisk.UpdateDefinitionWithNewVhd, - VirtualMachineUnmanagedDataDisk.Update { + VirtualMachineUnmanagedDataDisk.DefinitionWithExistingVhd, + VirtualMachineUnmanagedDataDisk.DefinitionWithNewVhd, + VirtualMachineUnmanagedDataDisk.DefinitionWithImage, + VirtualMachineUnmanagedDataDisk.UpdateDefinitionWithExistingVhd, + VirtualMachineUnmanagedDataDisk.UpdateDefinitionWithNewVhd, + VirtualMachineUnmanagedDataDisk.Update { protected UnmanagedDataDiskImpl(DataDisk inner, VirtualMachineImpl parent) { super(inner, parent); @@ -83,8 +83,7 @@ public UnmanagedDataDiskImpl withNewVhd(int sizeInGB) { @Override public UnmanagedDataDiskImpl withExistingVhd(String storageAccountName, String containerName, String vhdName) { - this - .innerModel() + this.innerModel() .withCreateOption(DiskCreateOptionTypes.ATTACH) .withVhd(new VirtualHardDisk().withUri(blobUrl(storageAccountName, containerName, vhdName))); return this; @@ -155,26 +154,18 @@ protected static void setDataDisksDefaults(List } } - protected static void ensureDisksVhdUri( - List dataDisks, StorageAccount storageAccount, String namePrefix) { + protected static void ensureDisksVhdUri(List dataDisks, + StorageAccount storageAccount, String namePrefix) { for (VirtualMachineUnmanagedDataDisk dataDisk : dataDisks) { if (dataDisk.creationMethod() == DiskCreateOptionTypes.EMPTY || dataDisk.creationMethod() == DiskCreateOptionTypes.FROM_IMAGE) { // New empty and from image data disk requires Vhd Uri to be set if (dataDisk.innerModel().vhd() == null) { dataDisk.innerModel().withVhd(new VirtualHardDisk()); - dataDisk - .innerModel() + dataDisk.innerModel() .vhd() - .withUri( - storageAccount.endPoints().primary().blob() - + "vhds/" - + namePrefix - + "-data-disk-" - + dataDisk.lun() - + "-" - + UUID.randomUUID().toString() - + ".vhd"); + .withUri(storageAccount.endPoints().primary().blob() + "vhds/" + namePrefix + "-data-disk-" + + dataDisk.lun() + "-" + UUID.randomUUID().toString() + ".vhd"); } } } @@ -195,17 +186,10 @@ protected static void ensureDisksVhdUri(List da // New data disk requires Vhd Uri to be set if (dataDisk.innerModel().vhd() == null) { dataDisk.innerModel().withVhd(new VirtualHardDisk()); - dataDisk - .innerModel() + dataDisk.innerModel() .vhd() - .withUri( - containerUrl - + namePrefix - + "-data-disk-" - + dataDisk.lun() - + "-" - + UUID.randomUUID().toString() - + ".vhd"); + .withUri(containerUrl + namePrefix + "-data-disk-" + dataDisk.lun() + "-" + + UUID.randomUUID().toString() + ".vhd"); } } } @@ -214,13 +198,7 @@ protected static void ensureDisksVhdUri(List da private String blobUrl(String storageAccountName, String containerName, String blobName) { AzureEnvironment azureEnvironment = this.parent().environment(); - return "https://" - + storageAccountName - + ".blob" - + azureEnvironment.getStorageEndpointSuffix() - + "/" - + containerName - + "/" - + blobName; + return "https://" + storageAccountName + ".blob" + azureEnvironment.getStorageEndpointSuffix() + "/" + + containerName + "/" + blobName; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VMSSPatchPayload.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VMSSPatchPayload.java index dc1aa39df5e02..67ab238c2dd18 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VMSSPatchPayload.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VMSSPatchPayload.java @@ -45,13 +45,12 @@ static VirtualMachineScaleSetUpdate preparePatchPayload(VirtualMachineScaleSet s // if (scaleSet.innerModel().virtualMachineProfile().storageProfile() != null) { // -- -- - VirtualMachineScaleSetUpdateStorageProfile storageProfile = - new VirtualMachineScaleSetUpdateStorageProfile(); + VirtualMachineScaleSetUpdateStorageProfile storageProfile + = new VirtualMachineScaleSetUpdateStorageProfile(); storageProfile .withDataDisks(scaleSet.innerModel().virtualMachineProfile().storageProfile().dataDisks()); - storageProfile - .withImageReference( - scaleSet.innerModel().virtualMachineProfile().storageProfile().imageReference()); + storageProfile.withImageReference( + scaleSet.innerModel().virtualMachineProfile().storageProfile().imageReference()); if (scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk() != null // Filling patch payload with osDisk property for VMSS with ephemeral OS disks will be considered updating VM model. @@ -59,26 +58,20 @@ static VirtualMachineScaleSetUpdate preparePatchPayload(VirtualMachineScaleSet s // e.g. scale out using `withCapacity`, especially if the scale set's `updatePolicy` is `Rolling` or `Automatic`, which may trigger // a VM restart. // Thus, we won't fill for VMSS with ephemeral OS disks. - && !scaleSet.isEphemeralOSDisk() - ) { + && !scaleSet.isEphemeralOSDisk()) { VirtualMachineScaleSetUpdateOSDisk osDisk = new VirtualMachineScaleSetUpdateOSDisk(); osDisk .withCaching(scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().caching()); osDisk.withImage(scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().image()); - osDisk - .withManagedDisk( - scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().managedDisk()); - osDisk - .withVhdContainers( - scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().vhdContainers()); - osDisk - .withWriteAcceleratorEnabled( - scaleSet - .innerModel() - .virtualMachineProfile() - .storageProfile() - .osDisk() - .writeAcceleratorEnabled()); + osDisk.withManagedDisk( + scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().managedDisk()); + osDisk.withVhdContainers( + scaleSet.innerModel().virtualMachineProfile().storageProfile().osDisk().vhdContainers()); + osDisk.withWriteAcceleratorEnabled(scaleSet.innerModel() + .virtualMachineProfile() + .storageProfile() + .osDisk() + .writeAcceleratorEnabled()); storageProfile.withOsDisk(osDisk); } updateVMProfile.withStorageProfile(storageProfile); @@ -88,34 +81,29 @@ static VirtualMachineScaleSetUpdate preparePatchPayload(VirtualMachineScaleSet s // -- -- VirtualMachineScaleSetUpdateOSProfile osProfile = new VirtualMachineScaleSetUpdateOSProfile(); osProfile.withCustomData(scaleSet.innerModel().virtualMachineProfile().osProfile().customData()); - osProfile - .withLinuxConfiguration( - scaleSet.innerModel().virtualMachineProfile().osProfile().linuxConfiguration()); + osProfile.withLinuxConfiguration( + scaleSet.innerModel().virtualMachineProfile().osProfile().linuxConfiguration()); osProfile.withSecrets(scaleSet.innerModel().virtualMachineProfile().osProfile().secrets()); - osProfile - .withWindowsConfiguration( - scaleSet.innerModel().virtualMachineProfile().osProfile().windowsConfiguration()); + osProfile.withWindowsConfiguration( + scaleSet.innerModel().virtualMachineProfile().osProfile().windowsConfiguration()); updateVMProfile.withOsProfile(osProfile); // -- -- } if (scaleSet.innerModel().virtualMachineProfile().networkProfile() != null) { // -- -- - VirtualMachineScaleSetUpdateNetworkProfile networkProfile = - new VirtualMachineScaleSetUpdateNetworkProfile(); - networkProfile.withNetworkApiVersion(scaleSet.innerModel().virtualMachineProfile().networkProfile().networkApiVersion()); + VirtualMachineScaleSetUpdateNetworkProfile networkProfile + = new VirtualMachineScaleSetUpdateNetworkProfile(); + networkProfile.withNetworkApiVersion( + scaleSet.innerModel().virtualMachineProfile().networkProfile().networkApiVersion()); if (scaleSet.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations() != null) { - networkProfile - .withNetworkInterfaceConfigurations( - new ArrayList<>()); - for (VirtualMachineScaleSetNetworkConfiguration nicConfig - : scaleSet - .innerModel() - .virtualMachineProfile() - .networkProfile() - .networkInterfaceConfigurations()) { - VirtualMachineScaleSetUpdateNetworkConfiguration nicPatchConfig = - new VirtualMachineScaleSetUpdateNetworkConfiguration(); + networkProfile.withNetworkInterfaceConfigurations(new ArrayList<>()); + for (VirtualMachineScaleSetNetworkConfiguration nicConfig : scaleSet.innerModel() + .virtualMachineProfile() + .networkProfile() + .networkInterfaceConfigurations()) { + VirtualMachineScaleSetUpdateNetworkConfiguration nicPatchConfig + = new VirtualMachineScaleSetUpdateNetworkConfiguration(); nicPatchConfig.withDnsSettings(nicConfig.dnsSettings()); nicPatchConfig.withEnableAcceleratedNetworking(nicConfig.enableAcceleratedNetworking()); nicPatchConfig.withEnableIpForwarding(nicConfig.enableIpForwarding()); @@ -123,14 +111,12 @@ static VirtualMachineScaleSetUpdate preparePatchPayload(VirtualMachineScaleSet s nicPatchConfig.withNetworkSecurityGroup(nicConfig.networkSecurityGroup()); nicPatchConfig.withPrimary(nicConfig.primary()); if (nicConfig.ipConfigurations() != null) { - nicPatchConfig - .withIpConfigurations(new ArrayList<>()); + nicPatchConfig.withIpConfigurations(new ArrayList<>()); for (VirtualMachineScaleSetIpConfiguration ipConfig : nicConfig.ipConfigurations()) { - VirtualMachineScaleSetUpdateIpConfiguration patchIpConfig = - new VirtualMachineScaleSetUpdateIpConfiguration(); - patchIpConfig - .withApplicationGatewayBackendAddressPools( - ipConfig.applicationGatewayBackendAddressPools()); + VirtualMachineScaleSetUpdateIpConfiguration patchIpConfig + = new VirtualMachineScaleSetUpdateIpConfiguration(); + patchIpConfig.withApplicationGatewayBackendAddressPools( + ipConfig.applicationGatewayBackendAddressPools()); patchIpConfig .withLoadBalancerBackendAddressPools(ipConfig.loadBalancerBackendAddressPools()); patchIpConfig.withLoadBalancerInboundNatPools(ipConfig.loadBalancerInboundNatPools()); @@ -139,25 +125,20 @@ static VirtualMachineScaleSetUpdate preparePatchPayload(VirtualMachineScaleSet s patchIpConfig.withPrivateIpAddressVersion(ipConfig.privateIpAddressVersion()); patchIpConfig.withSubnet(ipConfig.subnet()); if (ipConfig.publicIpAddressConfiguration() != null) { - patchIpConfig - .withPublicIpAddressConfiguration( - new VirtualMachineScaleSetUpdatePublicIpAddressConfiguration()); - patchIpConfig - .publicIpAddressConfiguration() + patchIpConfig.withPublicIpAddressConfiguration( + new VirtualMachineScaleSetUpdatePublicIpAddressConfiguration()); + patchIpConfig.publicIpAddressConfiguration() .withDnsSettings(ipConfig.publicIpAddressConfiguration().dnsSettings()); - patchIpConfig - .publicIpAddressConfiguration() + patchIpConfig.publicIpAddressConfiguration() .withIdleTimeoutInMinutes( ipConfig.publicIpAddressConfiguration().idleTimeoutInMinutes()); - patchIpConfig - .publicIpAddressConfiguration() + patchIpConfig.publicIpAddressConfiguration() .withName(ipConfig.publicIpAddressConfiguration().name()); } if (ipConfig.applicationSecurityGroups() != null) { patchIpConfig.withApplicationSecurityGroups(new ArrayList<>()); for (SubResource asg : ipConfig.applicationSecurityGroups()) { - patchIpConfig - .applicationSecurityGroups() + patchIpConfig.applicationSecurityGroups() .add(new SubResource().withId(asg.id())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImageImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImageImpl.java index 2cf05a2ba7a4d..9aafd6fb93e4c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImageImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImageImpl.java @@ -86,8 +86,7 @@ public VirtualMachineCustomImageImpl fromVirtualMachine(VirtualMachine virtualMa @Override public VirtualMachineCustomImageImpl withWindowsFromVhd(String sourceVhdUrl, OperatingSystemStateTypes osState) { - this - .ensureOsDiskImage() + this.ensureOsDiskImage() .withOsState(osState) .withOsType(OperatingSystemTypes.WINDOWS) .withBlobUri(sourceVhdUrl); @@ -101,10 +100,9 @@ public VirtualMachineCustomImageImpl withLinuxFromVhd(String sourceVhdUrl, Opera } @Override - public VirtualMachineCustomImageImpl withWindowsFromSnapshot( - String sourceSnapshotId, OperatingSystemStateTypes osState) { - this - .ensureOsDiskImage() + public VirtualMachineCustomImageImpl withWindowsFromSnapshot(String sourceSnapshotId, + OperatingSystemStateTypes osState) { + this.ensureOsDiskImage() .withOsState(osState) .withOsType(OperatingSystemTypes.WINDOWS) .withSnapshot(new SubResource().withId(sourceSnapshotId)); @@ -112,10 +110,9 @@ public VirtualMachineCustomImageImpl withWindowsFromSnapshot( } @Override - public VirtualMachineCustomImageImpl withLinuxFromSnapshot( - String sourceSnapshotId, OperatingSystemStateTypes osState) { - this - .ensureOsDiskImage() + public VirtualMachineCustomImageImpl withLinuxFromSnapshot(String sourceSnapshotId, + OperatingSystemStateTypes osState) { + this.ensureOsDiskImage() .withOsState(osState) .withOsType(OperatingSystemTypes.LINUX) .withSnapshot(new SubResource().withId(sourceSnapshotId)); @@ -124,22 +121,21 @@ public VirtualMachineCustomImageImpl withLinuxFromSnapshot( } @Override - public VirtualMachineCustomImageImpl withWindowsFromSnapshot( - Snapshot sourceSnapshot, OperatingSystemStateTypes osState) { + public VirtualMachineCustomImageImpl withWindowsFromSnapshot(Snapshot sourceSnapshot, + OperatingSystemStateTypes osState) { return this.withWindowsFromSnapshot(sourceSnapshot.id(), osState); } @Override - public VirtualMachineCustomImageImpl withLinuxFromSnapshot( - Snapshot sourceSnapshot, OperatingSystemStateTypes osState) { + public VirtualMachineCustomImageImpl withLinuxFromSnapshot(Snapshot sourceSnapshot, + OperatingSystemStateTypes osState) { return this.withLinuxFromSnapshot(sourceSnapshot.id(), osState); } @Override - public VirtualMachineCustomImageImpl withWindowsFromDisk( - String sourceManagedDiskId, OperatingSystemStateTypes osState) { - this - .ensureOsDiskImage() + public VirtualMachineCustomImageImpl withWindowsFromDisk(String sourceManagedDiskId, + OperatingSystemStateTypes osState) { + this.ensureOsDiskImage() .withOsState(osState) .withOsType(OperatingSystemTypes.WINDOWS) .withManagedDisk(new SubResource().withId(sourceManagedDiskId)); @@ -147,10 +143,9 @@ public VirtualMachineCustomImageImpl withWindowsFromDisk( } @Override - public VirtualMachineCustomImageImpl withLinuxFromDisk( - String sourceManagedDiskId, OperatingSystemStateTypes osState) { - this - .ensureOsDiskImage() + public VirtualMachineCustomImageImpl withLinuxFromDisk(String sourceManagedDiskId, + OperatingSystemStateTypes osState) { + this.ensureOsDiskImage() .withOsState(osState) .withOsType(OperatingSystemTypes.LINUX) .withManagedDisk(new SubResource().withId(sourceManagedDiskId)); @@ -158,8 +153,8 @@ public VirtualMachineCustomImageImpl withLinuxFromDisk( } @Override - public VirtualMachineCustomImageImpl withWindowsFromDisk( - Disk sourceManagedDisk, OperatingSystemStateTypes osState) { + public VirtualMachineCustomImageImpl withWindowsFromDisk(Disk sourceManagedDisk, + OperatingSystemStateTypes osState) { return withWindowsFromDisk(sourceManagedDisk.id(), osState); } @@ -212,8 +207,7 @@ public VirtualMachineCustomImageImpl withZoneResilient() { @Override public Mono createResourceAsync() { ensureDefaultLuns(); - return this - .manager() + return this.manager() .serviceClient() .getImages() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) @@ -222,8 +216,7 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getImages() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -282,8 +275,7 @@ VirtualMachineCustomImageImpl withCustomImageDataDisk(CustomImageDataDiskImpl cu } @Override - public VirtualMachineCustomImageImpl withHyperVGeneration( - HyperVGenerationTypes hyperVGeneration) { + public VirtualMachineCustomImageImpl withHyperVGeneration(HyperVGenerationTypes hyperVGeneration) { this.innerModel().withHyperVGeneration(hyperVGeneration); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImagesImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImagesImpl.java index f233e4040bccd..6c0dfa9d4065d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImagesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineCustomImagesImpl.java @@ -12,9 +12,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** The implementation for VirtualMachineCustomImages. */ -public class VirtualMachineCustomImagesImpl - extends TopLevelModifiableResourcesImpl< - VirtualMachineCustomImage, VirtualMachineCustomImageImpl, ImageInner, ImagesClient, ComputeManager> +public class VirtualMachineCustomImagesImpl extends + TopLevelModifiableResourcesImpl implements VirtualMachineCustomImages { public VirtualMachineCustomImagesImpl(final ComputeManager computeManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionHelper.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionHelper.java index eb02b903ed53b..d33876af43259 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionHelper.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionHelper.java @@ -18,24 +18,25 @@ class VirtualMachineEncryptionHelper { private final OperatingSystemTypes osType; private final VirtualMachine virtualMachine; // Error messages - private static final String ERROR_ENCRYPTION_EXTENSION_NOT_FOUND = - "Expected encryption extension not found in the VM"; - private static final String ERROR_NON_SUCCESS_PROVISIONING_STATE = - "Extension needed for disk encryption was not provisioned correctly, found ProvisioningState as '%s'"; - private static final String ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND = - "Could not found URL pointing to the secret for disk encryption"; - private static final String ERROR_EXPECTED_ENCRYPTION_EXTENSION_STATUS_NOT_FOUND = - "Encryption extension with successful status not found in the VM"; + private static final String ERROR_ENCRYPTION_EXTENSION_NOT_FOUND + = "Expected encryption extension not found in the VM"; + private static final String ERROR_NON_SUCCESS_PROVISIONING_STATE + = "Extension needed for disk encryption was not provisioned correctly, found ProvisioningState as '%s'"; + private static final String ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND + = "Could not found URL pointing to the secret for disk encryption"; + private static final String ERROR_EXPECTED_ENCRYPTION_EXTENSION_STATUS_NOT_FOUND + = "Encryption extension with successful status not found in the VM"; private static final String ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY = "Encryption extension status is empty"; - private static final String ERROR_ON_LINUX_ONLY_DATA_DISK_CAN_BE_DECRYPTED = - "Only data disk is supported to disable encryption on Linux VM"; - private static final String ERROR_LEGACY_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_REQUIRED = - "VM has Legacy Encryption Extension installed, updating it requires aadClientId and aadSecret parameters"; - private static final String ERROR_NOAAD_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_NOT_REQUIRED = - "VM has NoAAD Encryption Extension installed, aadClientId and aadSecret parameters are not allowed for this" + private static final String ERROR_ON_LINUX_ONLY_DATA_DISK_CAN_BE_DECRYPTED + = "Only data disk is supported to disable encryption on Linux VM"; + private static final String ERROR_LEGACY_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_REQUIRED + = "VM has Legacy Encryption Extension installed, updating it requires aadClientId and aadSecret parameters"; + private static final String ERROR_NOAAD_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_NOT_REQUIRED + = "VM has NoAAD Encryption Extension installed, aadClientId and aadSecret parameters are not allowed for this" + " extension."; - private static final String ERROR_NO_DECRYPT_ENCRYPTION_EXTENSION_NOT_FOUND = - ERROR_ENCRYPTION_EXTENSION_NOT_FOUND + ", no decryption to perform"; + private static final String ERROR_NO_DECRYPT_ENCRYPTION_EXTENSION_NOT_FOUND + = ERROR_ENCRYPTION_EXTENSION_NOT_FOUND + ", no decryption to perform"; + /** * Creates VirtualMachineEncryptionHelper. * @@ -53,8 +54,8 @@ class VirtualMachineEncryptionHelper { * @param the Windows or Linux encryption settings * @return an observable that emits the encryption status */ - > Mono enableEncryptionAsync( - final VirtualMachineEncryptionConfiguration encryptionConfig) { + > Mono + enableEncryptionAsync(final VirtualMachineEncryptionConfiguration encryptionConfig) { final EncryptionSettings.Enable encryptSettings = EncryptionSettings.createEnable(encryptionConfig); // If encryption extension is already installed then ensure user input aligns with state of the extension return validateBeforeEncryptAsync(encryptSettings) @@ -63,14 +64,13 @@ > Mono updateEncryptionExtensionAsync(encryptSettings, virtualMachineExtension)) // If encryption extension is not installed then install it .switchIfEmpty(installEncryptionExtensionAsync(encryptSettings)) - .flatMap( - virtualMachine -> { - if (encryptSettings.requestedForNoAADEncryptExtension()) { - return noAADExtensionEncryptPostProcessingAsync(virtualMachine); - } else { - return legacyExtensionEncryptPostProcessingAsync(encryptSettings); - } - }); + .flatMap(virtualMachine -> { + if (encryptSettings.requestedForNoAADEncryptExtension()) { + return noAADExtensionEncryptPostProcessingAsync(virtualMachine); + } else { + return legacyExtensionEncryptPostProcessingAsync(encryptSettings); + } + }); } /** @@ -84,18 +84,15 @@ Mono disableEncryptionAsync(final DiskVolumeType vo // return validateBeforeDecryptAsync(volumeType) // Update the encryption extension - .flatMap( - virtualMachineExtension -> - updateEncryptionExtensionAsync(encryptSettings, virtualMachineExtension) - .map(virtualMachine -> new VMExtTuple(virtualMachine, virtualMachineExtension))) - .flatMap( - vmExt -> { - if (EncryptionExtensionIdentifier.isNoAADVersion(osType, vmExt.encryptExtension.versionName())) { - return noAADExtensionDecryptPostProcessingAsync(vmExt.virtualMachine); - } else { - return legacyExtensionDecryptPostProcessingAsync(encryptSettings); - } - }); + .flatMap(virtualMachineExtension -> updateEncryptionExtensionAsync(encryptSettings, virtualMachineExtension) + .map(virtualMachine -> new VMExtTuple(virtualMachine, virtualMachineExtension))) + .flatMap(vmExt -> { + if (EncryptionExtensionIdentifier.isNoAADVersion(osType, vmExt.encryptExtension.versionName())) { + return noAADExtensionDecryptPostProcessingAsync(vmExt.virtualMachine); + } else { + return legacyExtensionDecryptPostProcessingAsync(encryptSettings); + } + }); } /** @@ -104,8 +101,8 @@ Mono disableEncryptionAsync(final DiskVolumeType vo * @param virtualMachine the encrypted virtual machine * @return the encryption progress monitor */ - private Mono noAADExtensionEncryptPostProcessingAsync( - final VirtualMachine virtualMachine) { + private Mono + noAADExtensionEncryptPostProcessingAsync(final VirtualMachine virtualMachine) { // Gets the encryption status return osType == OperatingSystemTypes.LINUX ? new LinuxDiskVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) @@ -119,21 +116,18 @@ private Mono noAADExtensionEncryptPostProcessingAsy * @param encryptConfig the user provided encryption config * @return the encryption progress monitor */ - private > - Mono legacyExtensionEncryptPostProcessingAsync( - final EncryptionSettings.Enable encryptConfig) { + private > Mono + legacyExtensionEncryptPostProcessingAsync(final EncryptionSettings.Enable encryptConfig) { // Retrieve the encryption key URL after extension install or update return retrieveEncryptionExtensionStatusStringAsync(ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND) // Update the VM's OS Disk (in storage profile) with the encryption metadata .flatMap(keyVaultSecretUrl -> updateVMStorageProfileAsync(encryptConfig, keyVaultSecretUrl)) // Gets the encryption status - .flatMap( - virtualMachine -> - osType == OperatingSystemTypes.LINUX - ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) - .refreshAsync() - : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) - .refreshAsync()); + .flatMap(virtualMachine -> osType == OperatingSystemTypes.LINUX + ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) + .refreshAsync() + : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) + .refreshAsync()); } /** @@ -142,8 +136,8 @@ Mono legacyExtensionEncryptPostProcessingAsync( * @param virtualMachine the decrypted virtual machine * @return the decryption progress monitor */ - private Mono noAADExtensionDecryptPostProcessingAsync( - final VirtualMachine virtualMachine) { + private Mono + noAADExtensionDecryptPostProcessingAsync(final VirtualMachine virtualMachine) { // Gets the encryption status return osType == OperatingSystemTypes.LINUX ? new LinuxDiskVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) @@ -157,19 +151,17 @@ private Mono noAADExtensionDecryptPostProcessingAsy * @param encryptConfig the user provided encryption config * @return the encryption progress monitor */ - private Mono legacyExtensionDecryptPostProcessingAsync( - final EncryptionSettings.Disable encryptConfig) { + private Mono + legacyExtensionDecryptPostProcessingAsync(final EncryptionSettings.Disable encryptConfig) { return retrieveEncryptionExtensionStatusStringAsync(ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY) // Update the VM's OS profile by marking encryption disabled .flatMap(s -> updateVMStorageProfileAsync(encryptConfig)) // Gets the encryption status - .flatMap( - virtualMachine -> - osType == OperatingSystemTypes.LINUX - ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) - .refreshAsync() - : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) - .refreshAsync()); + .flatMap(virtualMachine -> osType == OperatingSystemTypes.LINUX + ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) + .refreshAsync() + : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()) + .refreshAsync()); } /** @@ -180,34 +172,27 @@ private Mono legacyExtensionDecryptPostProcessingAs * @param encryptSettings the user provided configuration * @return observable emitting error, extension or empty. */ - private > - Mono validateBeforeEncryptAsync(final EncryptionSettings.Enable encryptSettings) { + private > Mono + validateBeforeEncryptAsync(final EncryptionSettings.Enable encryptSettings) { if (this.virtualMachine.storageProfile().osDisk().encryptionSettings() != null && encryptSettings.requestedForNoAADEncryptExtension()) { return Mono.error(new RuntimeException(ERROR_LEGACY_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_REQUIRED)); } - return getEncryptionExtensionInstalledInVMAsync() - .flatMap( - extension -> { - if (EncryptionExtensionIdentifier.isNoAADVersion(osType, extension.versionName())) { - // NoAAD-Encrypt-Extension exists so Legacy-Encrypt-Extension cannot be installed hence AAD - // params are not required. - return encryptSettings.requestedForNoAADEncryptExtension() - ? Mono.just(extension) - : Mono - .error( - new RuntimeException( - ERROR_NOAAD_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_NOT_REQUIRED)); - } else { - // Legacy-Encrypt-Extension exists so NoAAD-Encrypt-Extension cannot be installed hence AAD - // params are required. - return encryptSettings.requestedForNoAADEncryptExtension() - ? Mono - .error( - new RuntimeException(ERROR_LEGACY_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_REQUIRED)) - : Mono.just(extension); - } - }); + return getEncryptionExtensionInstalledInVMAsync().flatMap(extension -> { + if (EncryptionExtensionIdentifier.isNoAADVersion(osType, extension.versionName())) { + // NoAAD-Encrypt-Extension exists so Legacy-Encrypt-Extension cannot be installed hence AAD + // params are not required. + return encryptSettings.requestedForNoAADEncryptExtension() + ? Mono.just(extension) + : Mono.error(new RuntimeException(ERROR_NOAAD_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_NOT_REQUIRED)); + } else { + // Legacy-Encrypt-Extension exists so NoAAD-Encrypt-Extension cannot be installed hence AAD + // params are required. + return encryptSettings.requestedForNoAADEncryptExtension() + ? Mono.error(new RuntimeException(ERROR_LEGACY_ENCRYPTION_EXTENSION_FOUND_AAD_PARAMS_REQUIRED)) + : Mono.just(extension); + } + }); } /** @@ -231,15 +216,12 @@ private Mono validateBeforeDecryptAsync(final DiskVolum * @return an observable that emits the encryption extension installed in the virtual machine */ private Mono getEncryptionExtensionInstalledInVMAsync() { - return virtualMachine - .listExtensionsAsync() + return virtualMachine.listExtensionsAsync() .flatMapMany(Flux::fromIterable) // firstOrDefault() is used intentionally here instead of first() to ensure // this method return empty observable if matching extension is not found. - .filter( - extension -> - EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisherName()) - && EncryptionExtensionIdentifier.isEncryptionTypeName(extension.typeName(), osType)) + .filter(extension -> EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisherName()) + && EncryptionExtensionIdentifier.isEncryptionTypeName(extension.typeName(), osType)) .singleOrEmpty(); } @@ -252,10 +234,9 @@ private Mono getEncryptionExtensionInstalledInVMAsync() * @return an observable that emits updated virtual machine if extension was already installed otherwise an empty * observable. */ - private Mono updateEncryptionExtensionAsync( - final EncryptionSettings encryptSettings, VirtualMachineExtension encryptionExtension) { - return virtualMachine - .update() + private Mono updateEncryptionExtensionAsync(final EncryptionSettings encryptSettings, + VirtualMachineExtension encryptionExtension) { + return virtualMachine.update() .updateExtension(encryptionExtension.name()) .withPublicSettings(encryptSettings.extensionPublicSettings()) .withProtectedSettings(encryptSettings.extensionProtectedSettings()) @@ -269,24 +250,21 @@ private Mono updateEncryptionExtensionAsync( * @param encryptSettings the volume encryption configuration * @return an observable that emits updated virtual machine */ - private > Mono installEncryptionExtensionAsync( - final EncryptionSettings.Enable encryptSettings) { - return Mono - .defer( - () -> { - final String typeName = EncryptionExtensionIdentifier.typeName(osType); - return virtualMachine - .update() - .defineNewExtension(typeName) - .withPublisher(EncryptionExtensionIdentifier.publisherName()) - .withType(typeName) - .withVersion(encryptSettings.encryptionExtensionVersion()) - .withPublicSettings(encryptSettings.extensionPublicSettings()) - .withProtectedSettings(encryptSettings.extensionProtectedSettings()) - .withMinorVersionAutoUpgrade() - .attach() - .applyAsync(); - }); + private > Mono + installEncryptionExtensionAsync(final EncryptionSettings.Enable encryptSettings) { + return Mono.defer(() -> { + final String typeName = EncryptionExtensionIdentifier.typeName(osType); + return virtualMachine.update() + .defineNewExtension(typeName) + .withPublisher(EncryptionExtensionIdentifier.publisherName()) + .withType(typeName) + .withVersion(encryptSettings.encryptionExtensionVersion()) + .withPublicSettings(encryptSettings.extensionPublicSettings()) + .withProtectedSettings(encryptSettings.extensionProtectedSettings()) + .withMinorVersionAutoUpgrade() + .attach() + .applyAsync(); + }); } /** @@ -301,23 +279,20 @@ private Mono retrieveEncryptionExtensionStatusStringAsync(final String s final VirtualMachineEncryptionHelper self = this; return getEncryptionExtensionInstalledInVMAsync() .switchIfEmpty(self.toErrorMono(ERROR_ENCRYPTION_EXTENSION_NOT_FOUND)) - .flatMap( - extension -> { - if (!extension.provisioningState().equalsIgnoreCase("Succeeded")) { - return self - .toErrorMono( - (String.format(ERROR_NON_SUCCESS_PROVISIONING_STATE, extension.provisioningState()))); - } - return extension.getInstanceViewAsync(); - }) - .flatMap( - instanceView -> { - String extensionStatus = instanceView.statuses().get(0).message(); - if (extensionStatus == null) { - return self.toErrorMono(statusEmptyErrorMessage); - } - return Mono.just(extensionStatus); - }) + .flatMap(extension -> { + if (!extension.provisioningState().equalsIgnoreCase("Succeeded")) { + return self.toErrorMono( + (String.format(ERROR_NON_SUCCESS_PROVISIONING_STATE, extension.provisioningState()))); + } + return extension.getInstanceViewAsync(); + }) + .flatMap(instanceView -> { + String extensionStatus = instanceView.statuses().get(0).message(); + if (extensionStatus == null) { + return self.toErrorMono(statusEmptyErrorMessage); + } + return Mono.just(extensionStatus); + }) .switchIfEmpty(self.toErrorMono(ERROR_EXPECTED_ENCRYPTION_EXTENSION_STATUS_NOT_FOUND)); } @@ -329,8 +304,8 @@ private Mono retrieveEncryptionExtensionStatusStringAsync(final String s * @param encryptionSecretKeyVaultUrl the keyVault URL pointing to secret holding disk encryption key * @return an observable that emits updated virtual machine */ - private Mono updateVMStorageProfileAsync( - final EncryptionSettings encryptSettings, final String encryptionSecretKeyVaultUrl) { + private Mono updateVMStorageProfileAsync(final EncryptionSettings encryptSettings, + final String encryptionSecretKeyVaultUrl) { DiskEncryptionSettings diskEncryptionSettings = encryptSettings.storageProfileEncryptionSettings(); diskEncryptionSettings.diskEncryptionKey().withSecretUrl(encryptionSecretKeyVaultUrl); return virtualMachine.update().withOSDiskEncryptionSettings(diskEncryptionSettings).applyAsync(); @@ -361,6 +336,7 @@ private Mono toErrorMono(String message) { private static class VMExtTuple { private final VirtualMachine virtualMachine; private final VirtualMachineExtension encryptExtension; + // VMExtTuple(VirtualMachine vm, VirtualMachineExtension ext) { this.virtualMachine = vm; diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionImpl.java index 5d038ad9ce25c..f8b66a6cf515e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineEncryptionImpl.java @@ -30,13 +30,11 @@ class VirtualMachineEncryptionImpl implements VirtualMachineEncryption { @Override public Mono enableAsync(String keyVaultId, String aadClientId, String aadSecret) { if (this.virtualMachine.osType() == OperatingSystemTypes.LINUX) { - return enableAsync( - new LinuxVMDiskEncryptionConfiguration(keyVaultId, aadClientId, aadSecret, - virtualMachine.manager().environment())); + return enableAsync(new LinuxVMDiskEncryptionConfiguration(keyVaultId, aadClientId, aadSecret, + virtualMachine.manager().environment())); } else { - return enableAsync( - new WindowsVMDiskEncryptionConfiguration(keyVaultId, aadClientId, aadSecret, - virtualMachine.manager().environment())); + return enableAsync(new WindowsVMDiskEncryptionConfiguration(keyVaultId, aadClientId, aadSecret, + virtualMachine.manager().environment())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageImpl.java index 2b599c145b8b0..f8b4c57eafcb7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageImpl.java @@ -14,8 +14,8 @@ class VirtualMachineExtensionImageImpl extends WrapperImpl +class VirtualMachineExtensionImageTypesImpl extends + ReadableWrappersImpl implements VirtualMachineExtensionImageTypes { private final VirtualMachineExtensionImagesClient client; private final VirtualMachinePublisher publisher; - VirtualMachineExtensionImageTypesImpl( - VirtualMachineExtensionImagesClient client, VirtualMachinePublisher publisher) { + VirtualMachineExtensionImageTypesImpl(VirtualMachineExtensionImagesClient client, + VirtualMachinePublisher publisher) { this.client = client; this.publisher = publisher; } @@ -41,9 +40,9 @@ protected VirtualMachineExtensionImageTypeImpl wrapModel(VirtualMachineExtension @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter - .convertListToPagedFlux(client.listTypesWithResponseAsync( - this.publisher.region().toString(), this.publisher.name())), + return PagedConverter.mapPage( + PagedConverter.convertListToPagedFlux( + client.listTypesWithResponseAsync(this.publisher.region().toString(), this.publisher.name())), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionImpl.java index 4650f1dae6004..7fdcd45e0c962 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionImpl.java @@ -16,10 +16,8 @@ class VirtualMachineExtensionImageVersionImpl extends WrapperImpl getImageAsync() { final VirtualMachineExtensionImageVersionImpl self = this; - return client - .getAsync(regionName(), type().publisher().name(), type().name(), name()) + return client.getAsync(regionName(), type().publisher().name(), type().name(), name()) .map(inner -> new VirtualMachineExtensionImageImpl(self, inner)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionsImpl.java index 6043a20784b0c..f4053130221ac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImageVersionsImpl.java @@ -13,15 +13,14 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for VirtualMachineExtensionImageVersions. */ -public class VirtualMachineExtensionImageVersionsImpl - extends ReadableWrappersImpl< - VirtualMachineExtensionImageVersion, VirtualMachineExtensionImageVersionImpl, VirtualMachineExtensionImageInner> +public class VirtualMachineExtensionImageVersionsImpl extends + ReadableWrappersImpl implements VirtualMachineExtensionImageVersions { private final VirtualMachineExtensionImagesClient client; private final VirtualMachineExtensionImageType type; - VirtualMachineExtensionImageVersionsImpl( - VirtualMachineExtensionImagesClient client, VirtualMachineExtensionImageType type) { + VirtualMachineExtensionImageVersionsImpl(VirtualMachineExtensionImagesClient client, + VirtualMachineExtensionImageType type) { this.client = client; this.type = type; } @@ -41,9 +40,8 @@ protected VirtualMachineExtensionImageVersionImpl wrapModel(VirtualMachineExtens @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter - .convertListToPagedFlux(client.listVersionsWithResponseAsync( - type.regionName(), type.publisher().name(), type.name(), null, null, null)), + return PagedConverter.mapPage(PagedConverter.convertListToPagedFlux(client + .listVersionsWithResponseAsync(type.regionName(), type.publisher().name(), type.name(), null, null, null)), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImagesImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImagesImpl.java index f99a977a1a6eb..29caac9535c6c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImagesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImagesImpl.java @@ -38,19 +38,13 @@ public PagedFlux listByRegionAsync(Region region) @Override public PagedFlux listByRegionAsync(String regionName) { - return PagedConverter - .flatMapPage( - publishers.listByRegionAsync(regionName), - virtualMachinePublisher -> - virtualMachinePublisher - .extensionTypes() - .listAsync() - .onErrorResume( - ManagementException.class, - e -> e.getResponse().getStatusCode() == 404 ? Flux.empty() : Flux.error(e)) - .flatMap( - virtualMachineExtensionImageType -> virtualMachineExtensionImageType.versions().listAsync()) - .flatMap(VirtualMachineExtensionImageVersion::getImageAsync)); + return PagedConverter.flatMapPage(publishers.listByRegionAsync(regionName), + virtualMachinePublisher -> virtualMachinePublisher.extensionTypes() + .listAsync() + .onErrorResume(ManagementException.class, + e -> e.getResponse().getStatusCode() == 404 ? Flux.empty() : Flux.error(e)) + .flatMap(virtualMachineExtensionImageType -> virtualMachineExtensionImageType.versions().listAsync()) + .flatMap(VirtualMachineExtensionImageVersion::getImageAsync)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImpl.java index 7230fd1e08850..7173bea2e5345 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionImpl.java @@ -24,30 +24,24 @@ import java.util.TreeMap; /** Implementation of VirtualMachineExtension. */ -class VirtualMachineExtensionImpl - extends ExternalChildResourceImpl< - VirtualMachineExtension, VirtualMachineExtensionInner, VirtualMachineImpl, VirtualMachine> - implements VirtualMachineExtension, - VirtualMachineExtension.Definition, - VirtualMachineExtension.UpdateDefinition, - VirtualMachineExtension.Update { +class VirtualMachineExtensionImpl extends + ExternalChildResourceImpl + implements VirtualMachineExtension, VirtualMachineExtension.Definition, + VirtualMachineExtension.UpdateDefinition, VirtualMachineExtension.Update { private final ClientLogger logger = new ClientLogger(VirtualMachineExtensionImpl.class); private final VirtualMachineExtensionsClient client; private Map publicSettings; private Map protectedSettings; - VirtualMachineExtensionImpl( - String name, - VirtualMachineImpl parent, - VirtualMachineExtensionInner inner, + VirtualMachineExtensionImpl(String name, VirtualMachineImpl parent, VirtualMachineExtensionInner inner, VirtualMachineExtensionsClient client) { super(name, parent, inner); this.client = client; initializeSettings(); } - protected static VirtualMachineExtensionImpl newVirtualMachineExtension( - String name, VirtualMachineImpl parent, VirtualMachineExtensionsClient client) { + protected static VirtualMachineExtensionImpl newVirtualMachineExtension(String name, VirtualMachineImpl parent, + VirtualMachineExtensionsClient client) { VirtualMachineExtensionInner inner = new VirtualMachineExtensionInner(); inner.withLocation(parent.regionName()); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl(name, parent, inner, client); @@ -87,8 +81,8 @@ public Map publicSettings() { @Override public String publicSettingsAsJsonString() { try { - return ((ComputeManagementClientImpl) parent().manager().serviceClient()) - .getSerializerAdapter().serialize(this.publicSettings, SerializerEncoding.JSON); + return ((ComputeManagementClientImpl) parent().manager().serviceClient()).getSerializerAdapter() + .serialize(this.publicSettings, SerializerEncoding.JSON); } catch (IOException e) { logger.atWarning().log("Serialization failed for publicSettings.", e); return null; @@ -102,8 +96,7 @@ public VirtualMachineExtensionInstanceView getInstanceView() { @Override public Mono getInstanceViewAsync() { - return this - .client + return this.client .getWithResponseAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), "instanceView") .flatMap(inner -> Mono.justOrEmpty(inner.getValue().instanceView())); } @@ -136,8 +129,7 @@ public VirtualMachineExtensionImpl withoutMinorVersionAutoUpgrade() { @Override public VirtualMachineExtensionImpl withImage(VirtualMachineExtensionImage image) { - this - .innerModel() + this.innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); @@ -232,16 +224,14 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { final VirtualMachineExtensionImpl self = this; - return this - .client - .createOrUpdateAsync( - this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - self.initializeSettings(); - return self; - }); + return this.client + .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), + this.innerModel()) + .map(inner -> { + self.setInner(inner); + self.initializeSettings(); + return self; + }); } @Override @@ -250,35 +240,30 @@ public Mono updateResourceAsync() { this.nullifySettingsIfEmpty(); if (this.isReference()) { String extensionName = ResourceUtils.nameFromResourceId(this.innerModel().id()); - return this - .client - .getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) - .flatMap( - resource -> { - innerModel() - .withPublisher(resource.publisher()) - .withTypePropertiesType(resource.typePropertiesType()) - .withTypeHandlerVersion(resource.typeHandlerVersion()); - if (innerModel().autoUpgradeMinorVersion() == null) { - innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); + return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) + .flatMap(resource -> { + innerModel().withPublisher(resource.publisher()) + .withTypePropertiesType(resource.typePropertiesType()) + .withTypeHandlerVersion(resource.typeHandlerVersion()); + if (innerModel().autoUpgradeMinorVersion() == null) { + innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); + } + LinkedHashMap publicSettings = (LinkedHashMap) resource.settings(); + if (publicSettings != null && publicSettings.size() > 0) { + LinkedHashMap innerPublicSettings + = (LinkedHashMap) innerModel().settings(); + if (innerPublicSettings == null) { + innerModel().withSettings(new LinkedHashMap()); + innerPublicSettings = (LinkedHashMap) innerModel().settings(); } - LinkedHashMap publicSettings = - (LinkedHashMap) resource.settings(); - if (publicSettings != null && publicSettings.size() > 0) { - LinkedHashMap innerPublicSettings = - (LinkedHashMap) innerModel().settings(); - if (innerPublicSettings == null) { - innerModel().withSettings(new LinkedHashMap()); - innerPublicSettings = (LinkedHashMap) innerModel().settings(); - } - for (Map.Entry entry : publicSettings.entrySet()) { - if (!innerPublicSettings.containsKey(entry.getKey())) { - innerPublicSettings.put(entry.getKey(), entry.getValue()); - } + for (Map.Entry entry : publicSettings.entrySet()) { + if (!innerPublicSettings.containsKey(entry.getKey())) { + innerPublicSettings.put(entry.getKey(), entry.getValue()); } } - return createResourceAsync(); - }); + } + return createResourceAsync(); + }); } else { return this.createResourceAsync(); } @@ -337,7 +322,9 @@ private Map loadSettings(Object settings) { } else if (settings instanceof Map) { return (Map) settings; } else { - logger.atWarning().log("[VirtualMachineExtensionImpl] unrecognized setting type: {}, value: {}", settings.getClass(), settings); + logger.atWarning() + .log("[VirtualMachineExtensionImpl] unrecognized setting type: {}, value: {}", settings.getClass(), + settings); return new LinkedHashMap<>(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionsImpl.java index 406603111bd1a..0ae5b359213ee 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineExtensionsImpl.java @@ -18,13 +18,8 @@ import reactor.core.publisher.Mono; /** Represents a extension collection associated with a virtual machine. */ -class VirtualMachineExtensionsImpl - extends ExternalChildResourcesCachedImpl< - VirtualMachineExtensionImpl, - VirtualMachineExtension, - VirtualMachineExtensionInner, - VirtualMachineImpl, - VirtualMachine> { +class VirtualMachineExtensionsImpl extends + ExternalChildResourcesCachedImpl { private final VirtualMachineExtensionsClient client; /** @@ -46,8 +41,7 @@ public Map asMap() { /** @return an observable emits extensions in this collection as a map indexed by name. */ public Mono> asMapAsync() { - return listAsync() - .flatMapMany(Flux::fromIterable) + return listAsync().flatMapMany(Flux::fromIterable) .collect(Collectors.toMap(extension -> extension.name(), extension -> extension)) .map(map -> Collections.unmodifiableMap(map)); } @@ -56,19 +50,11 @@ public Mono> asMapAsync() { public Mono> listAsync() { Flux extensions = Flux.fromIterable(this.collection().values()); // Resolve reference getExtensions - Flux resolvedExtensionsStream = - extensions - .filter(extension -> extension.isReference()) - .flatMap( - extension -> - client - .getAsync(getParent().resourceGroupName(), getParent().name(), extension.name()) - .map( - extensionInner -> - new VirtualMachineExtensionImpl( - extension.name(), getParent(), extensionInner, client))); - return resolvedExtensionsStream - .concatWith(extensions.filter(extension -> !extension.isReference())) + Flux resolvedExtensionsStream = extensions.filter(extension -> extension.isReference()) + .flatMap(extension -> client.getAsync(getParent().resourceGroupName(), getParent().name(), extension.name()) + .map(extensionInner -> new VirtualMachineExtensionImpl(extension.name(), getParent(), extensionInner, + client))); + return resolvedExtensionsStream.concatWith(extensions.filter(extension -> !extension.isReference())) .collectList() .map(list -> Collections.unmodifiableList(list)); } @@ -120,10 +106,8 @@ protected List listChildResources() { if (inner.name() == null) { // This extension exists in the parent VM extension collection as a reference id. inner.withLocation(getParent().regionName()); - childResources - .add( - new VirtualMachineExtensionImpl( - ResourceUtils.nameFromResourceId(inner.id()), this.getParent(), inner, this.client)); + childResources.add(new VirtualMachineExtensionImpl(ResourceUtils.nameFromResourceId(inner.id()), + this.getParent(), inner, this.client)); } else { // This extension exists in the parent VM as a fully blown object childResources @@ -141,8 +125,8 @@ protected Flux listChildResourcesAsync() { @Override protected VirtualMachineExtensionImpl newChildResource(String name) { - VirtualMachineExtensionImpl extension = - VirtualMachineExtensionImpl.newVirtualMachineExtension(name, this.getParent(), this.client); + VirtualMachineExtensionImpl extension + = VirtualMachineExtensionImpl.newVirtualMachineExtension(name, this.getParent(), this.client); return extension; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImageImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImageImpl.java index f459caca35d1a..78fa65fb79ce2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImageImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImageImpl.java @@ -29,12 +29,7 @@ class VirtualMachineImageImpl extends IndexableWrapperImpl innerImages = - this.client.listWithResponse(region.name(), publisherName, offerName, skuName, - null, 1, "name desc", Context.NONE).getValue(); + List innerImages = this.client + .listWithResponse(region.name(), publisherName, offerName, skuName, null, 1, "name desc", Context.NONE) + .getValue(); if (innerImages != null && !innerImages.isEmpty()) { VirtualMachineImageResourceInner innerImageResource = innerImages.get(0); version = innerImageResource.name(); } } - VirtualMachineImageInner innerImage = - this.client.get(region.name(), publisherName, offerName, skuName, version); + VirtualMachineImageInner innerImage + = this.client.get(region.name(), publisherName, offerName, skuName, version); return (innerImage != null) ? new VirtualMachineImageImpl(region, publisherName, offerName, skuName, version, innerImage) : null; } @Override - public VirtualMachineImage getImage( - String region, String publisherName, String offerName, String skuName, String version) { + public VirtualMachineImage getImage(String region, String publisherName, String offerName, String skuName, + String version) { if ("latest".equalsIgnoreCase(version)) { - List innerImages = - this.client.listWithResponse(region, publisherName, offerName, skuName, - null, 1, "name desc", Context.NONE).getValue(); + List innerImages = this.client + .listWithResponse(region, publisherName, offerName, skuName, null, 1, "name desc", Context.NONE) + .getValue(); if (innerImages != null && !innerImages.isEmpty()) { VirtualMachineImageResourceInner innerImageResource = innerImages.get(0); version = innerImageResource.name(); @@ -61,8 +61,8 @@ public VirtualMachineImage getImage( } VirtualMachineImageInner innerImage = this.client.get(region, publisherName, offerName, skuName, version); return (innerImage != null) - ? new VirtualMachineImageImpl( - Region.fromName(region), publisherName, offerName, skuName, version, innerImage) + ? new VirtualMachineImageImpl(Region.fromName(region), publisherName, offerName, skuName, version, + innerImage) : null; } @@ -83,18 +83,13 @@ public PagedFlux listByRegionAsync(Region region) { @Override public PagedFlux listByRegionAsync(String regionName) { - return PagedConverter - .flatMapPage( - publishers().listByRegionAsync(regionName), - virtualMachinePublisher -> - virtualMachinePublisher - .offers() - .listAsync() - .onErrorResume( - ManagementException.class, - e -> e.getResponse().getStatusCode() == 404 ? Flux.empty() : Flux.error(e)) - .flatMap(virtualMachineOffer -> virtualMachineOffer.skus().listAsync()) - .flatMap(virtualMachineSku -> virtualMachineSku.images().listAsync())); + return PagedConverter.flatMapPage(publishers().listByRegionAsync(regionName), + virtualMachinePublisher -> virtualMachinePublisher.offers() + .listAsync() + .onErrorResume(ManagementException.class, + e -> e.getResponse().getStatusCode() == 404 ? Flux.empty() : Flux.error(e)) + .flatMap(virtualMachineOffer -> virtualMachineOffer.skus().listAsync()) + .flatMap(virtualMachineSku -> virtualMachineSku.images().listAsync())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImagesInSkuImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImagesInSkuImpl.java index 97a86f75eb856..1a58794cedfcc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImagesInSkuImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImagesInSkuImpl.java @@ -31,26 +31,14 @@ public PagedIterable list() { public PagedFlux listAsync() { final VirtualMachineImagesInSkuImpl self = this; PagedFlux virtualMachineImageResourcePagedFlux - = PagedConverter.convertListToPagedFlux(innerCollection.listWithResponseAsync( - sku.region().toString(), sku.publisher().name(), sku.offer().name(), sku.name(), - null, null, null)); + = PagedConverter.convertListToPagedFlux(innerCollection.listWithResponseAsync(sku.region().toString(), + sku.publisher().name(), sku.offer().name(), sku.name(), null, null, null)); return PagedConverter.flatMapPage(virtualMachineImageResourcePagedFlux, resourceInner -> innerCollection - .getAsync( - self.sku.region().toString(), - self.sku.publisher().name(), - self.sku.offer().name(), - self.sku.name(), - resourceInner.name()) - .map( - imageInner -> - (VirtualMachineImage) - new VirtualMachineImageImpl( - self.sku.region(), - self.sku.publisher().name(), - self.sku.offer().name(), - self.sku.name(), - resourceInner.name(), - imageInner))); + .getAsync(self.sku.region().toString(), self.sku.publisher().name(), self.sku.offer().name(), + self.sku.name(), resourceInner.name()) + .map(imageInner -> (VirtualMachineImage) new VirtualMachineImageImpl(self.sku.region(), + self.sku.publisher().name(), self.sku.offer().name(), self.sku.name(), resourceInner.name(), + imageInner))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImpl.java index a4ab60994462e..b233fc4178e31 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineImpl.java @@ -127,13 +127,10 @@ /** The implementation for VirtualMachine and its create and update interfaces. */ class VirtualMachineImpl extends GroupableResourceImpl - implements VirtualMachine, - VirtualMachine.DefinitionManagedOrUnmanaged, - VirtualMachine.DefinitionManaged, - VirtualMachine.DefinitionUnmanaged, - VirtualMachine.Update, - VirtualMachine.DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, - VirtualMachine.UpdateStages.WithSystemAssignedIdentityBasedAccessOrUpdate { + implements VirtualMachine, VirtualMachine.DefinitionManagedOrUnmanaged, VirtualMachine.DefinitionManaged, + VirtualMachine.DefinitionUnmanaged, VirtualMachine.Update, + VirtualMachine.DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, + VirtualMachine.UpdateStages.WithSystemAssignedIdentityBasedAccessOrUpdate { private final ClientLogger logger = new ClientLogger(VirtualMachineImpl.class); @@ -203,15 +200,11 @@ class VirtualMachineImpl // Snapshot of the updateParameter when update() is called, used to compare whether there is modification to VM during updateResourceAsync private VirtualMachineUpdateInner updateParameterSnapshotOnUpdate; - private static final SerializerAdapter SERIALIZER_ADAPTER = - SerializerFactory.createDefaultManagementSerializerAdapter(); - - VirtualMachineImpl( - String name, - VirtualMachineInner innerModel, - final ComputeManager computeManager, - final StorageManager storageManager, - final NetworkManager networkManager, + private static final SerializerAdapter SERIALIZER_ADAPTER + = SerializerFactory.createDefaultManagementSerializerAdapter(); + + VirtualMachineImpl(String name, VirtualMachineInner innerModel, final ComputeManager computeManager, + final StorageManager storageManager, final NetworkManager networkManager, final AuthorizationManager authorizationManager) { super(name, innerModel, computeManager); this.storageManager = storageManager; @@ -222,8 +215,8 @@ class VirtualMachineImpl this.namer = this.manager().resourceManager().internalContext().createIdentifierProvider(this.vmName); this.creatableSecondaryNetworkInterfaceKeys = new ArrayList<>(); this.existingSecondaryNetworkInterfacesToAssociate = new ArrayList<>(); - this.virtualMachineExtensions = - new VirtualMachineExtensionsImpl(computeManager.serviceClient().getVirtualMachineExtensions(), this); + this.virtualMachineExtensions + = new VirtualMachineExtensionsImpl(computeManager.serviceClient().getVirtualMachineExtensions(), this); this.managedDataDisks = new ManagedDataDiskCollection(this); initializeDataDisks(); @@ -243,20 +236,16 @@ public VirtualMachineImpl update() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - virtualMachine -> { - reset(virtualMachine.innerModel()); - virtualMachineExtensions.refresh(); - return virtualMachine; - }); + return super.refreshAsync().map(virtualMachine -> { + reset(virtualMachine.innerModel()); + virtualMachineExtensions.refresh(); + return virtualMachine; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -269,8 +258,7 @@ public void deallocate() { @Override public Mono deallocateAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .deallocateAsync(this.resourceGroupName(), this.name()) @@ -286,8 +274,7 @@ public void deallocate(boolean hibernate) { @Override public Mono deallocateAsync(boolean hibernate) { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .deallocateAsync(this.resourceGroupName(), this.name(), hibernate) @@ -303,8 +290,7 @@ public void generalize() { @Override public Mono generalizeAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .generalizeAsync(this.resourceGroupName(), this.name()); @@ -317,8 +303,7 @@ public void powerOff() { @Override public Mono powerOffAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .powerOffAsync(this.resourceGroupName(), this.name(), null); @@ -331,8 +316,7 @@ public void powerOff(boolean skipShutdown) { @Override public Mono powerOffAsync(boolean skipShutdown) { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .powerOffAsync(this.resourceGroupName(), this.name(), skipShutdown); @@ -375,8 +359,7 @@ public void simulateEviction() { @Override public Mono simulateEvictionAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .simulateEvictionAsync(this.resourceGroupName(), this.name()); @@ -384,8 +367,7 @@ public Mono simulateEvictionAsync() { @Override public void convertToManaged() { - this - .manager() + this.manager() .serviceClient() .getVirtualMachines() .convertToManagedDisks(this.resourceGroupName(), this.name()); @@ -394,8 +376,7 @@ public void convertToManaged() { @Override public Mono convertToManagedAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .convertToManagedDisksAsync(this.resourceGroupName(), this.name()) @@ -410,12 +391,10 @@ public VirtualMachineEncryption diskEncryption() { @Override public PagedIterable availableSizes() { - return PagedConverter.mapPage(this - .manager() + return PagedConverter.mapPage(this.manager() .serviceClient() .getVirtualMachines() - .listAvailableSizes(this.resourceGroupName(), this.name()), - VirtualMachineSizeImpl::new); + .listAvailableSizes(this.resourceGroupName(), this.name()), VirtualMachineSizeImpl::new); } @Override @@ -429,8 +408,7 @@ public Mono captureAsync(String containerName, String vhdPrefix, boolean parameters.withDestinationContainerName(containerName); parameters.withOverwriteVhds(overwriteVhd); parameters.withVhdPrefix(vhdPrefix); - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .captureAsync(this.resourceGroupName(), this.name(), parameters) @@ -444,57 +422,47 @@ public VirtualMachineInstanceView refreshInstanceView() { @Override public Mono refreshInstanceViewAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() - .getByResourceGroupWithResponseAsync( - this.resourceGroupName(), this.name(), InstanceViewTypes.INSTANCE_VIEW) - .map( - inner -> { - virtualMachineInstanceView = new VirtualMachineInstanceViewImpl(inner.getValue().instanceView()); - return virtualMachineInstanceView; - }) - .switchIfEmpty( - Mono - .defer( - () -> { - virtualMachineInstanceView = null; - return Mono.empty(); - })); - } - - @Override - public RunCommandResult runPowerShellScript( - List scriptLines, List scriptParameters) { - return this - .manager() + .getByResourceGroupWithResponseAsync(this.resourceGroupName(), this.name(), InstanceViewTypes.INSTANCE_VIEW) + .map(inner -> { + virtualMachineInstanceView = new VirtualMachineInstanceViewImpl(inner.getValue().instanceView()); + return virtualMachineInstanceView; + }) + .switchIfEmpty(Mono.defer(() -> { + virtualMachineInstanceView = null; + return Mono.empty(); + })); + } + + @Override + public RunCommandResult runPowerShellScript(List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachines() .runPowerShellScript(this.resourceGroupName(), this.name(), scriptLines, scriptParameters); } @Override - public Mono runPowerShellScriptAsync( - List scriptLines, List scriptParameters) { - return this - .manager() + public Mono runPowerShellScriptAsync(List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachines() .runPowerShellScriptAsync(this.resourceGroupName(), this.name(), scriptLines, scriptParameters); } @Override public RunCommandResult runShellScript(List scriptLines, List scriptParameters) { - return this - .manager() + return this.manager() .virtualMachines() .runShellScript(this.resourceGroupName(), this.name(), scriptLines, scriptParameters); } @Override - public Mono runShellScriptAsync( - List scriptLines, List scriptParameters) { - return this - .manager() + public Mono runShellScriptAsync(List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachines() .runShellScriptAsync(this.resourceGroupName(), this.name(), scriptLines, scriptParameters); } @@ -514,26 +482,22 @@ public Mono runCommandAsync(RunCommandInput inputCommand) { // Fluent methods for defining virtual network association for the new primary network interface @Override public VirtualMachineImpl withNewPrimaryNetwork(Creatable creatable) { - this.nicDefinitionWithPrivateIp = - this.preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)).withNewPrimaryNetwork(creatable); + this.nicDefinitionWithPrivateIp + = this.preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)).withNewPrimaryNetwork(creatable); return this; } @Override public VirtualMachineImpl withNewPrimaryNetwork(String addressSpace) { - this.nicDefinitionWithPrivateIp = - this - .preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)) - .withNewPrimaryNetwork(addressSpace); + this.nicDefinitionWithPrivateIp = this.preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)) + .withNewPrimaryNetwork(addressSpace); return this; } @Override public VirtualMachineImpl withExistingPrimaryNetwork(Network network) { - this.nicDefinitionWithSubnet = - this - .preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)) - .withExistingPrimaryNetwork(network); + this.nicDefinitionWithSubnet = this.preparePrimaryNetworkInterface(this.namer.getRandomName("nic", 20)) + .withExistingPrimaryNetwork(network); return this; } @@ -552,16 +516,16 @@ public VirtualMachineImpl withPrimaryPrivateIPAddressDynamic() { @Override public VirtualMachineImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { - this.nicDefinitionWithCreate = - this.nicDefinitionWithPrivateIp.withPrimaryPrivateIPAddressStatic(staticPrivateIPAddress); + this.nicDefinitionWithCreate + = this.nicDefinitionWithPrivateIp.withPrimaryPrivateIPAddressStatic(staticPrivateIPAddress); return this; } // Fluent methods for defining public IP association for the new primary network interface @Override public VirtualMachineImpl withNewPrimaryPublicIPAddress(Creatable creatable) { - Creatable nicCreatable = - this.nicDefinitionWithCreate.withNewPrimaryPublicIPAddress(creatable); + Creatable nicCreatable + = this.nicDefinitionWithCreate.withNewPrimaryPublicIPAddress(creatable); this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable); return this; } @@ -571,14 +535,11 @@ public VirtualMachineImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { return withNewPrimaryPublicIPAddress(leafDnsLabel, null); } -// @Override + // @Override public VirtualMachineImpl withNewPrimaryPublicIPAddress(String leafDnsLabel, DeleteOptions deleteOptions) { - PublicIpAddress.DefinitionStages.WithGroup definitionWithGroup = - this - .networkManager - .publicIpAddresses() - .define(this.namer.getRandomName("pip", 15)) - .withRegion(this.regionName()); + PublicIpAddress.DefinitionStages.WithGroup definitionWithGroup = this.networkManager.publicIpAddresses() + .define(this.namer.getRandomName("pip", 15)) + .withRegion(this.regionName()); PublicIpAddress.DefinitionStages.WithCreate definitionAfterGroup; if (this.creatableGroup != null) { definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -586,21 +547,21 @@ public VirtualMachineImpl withNewPrimaryPublicIPAddress(String leafDnsLabel, Del definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName()); } this.implicitPipCreatable = definitionAfterGroup.withLeafDomainLabel(leafDnsLabel); -// if (deleteOptions != null) { -// this.implicitPipCreatable = this.implicitPipCreatable.withDeleteOptions( -// com.azure.resourcemanager.network.models.DeleteOptions.fromString(deleteOptions.toString())); -// } + // if (deleteOptions != null) { + // this.implicitPipCreatable = this.implicitPipCreatable.withDeleteOptions( + // com.azure.resourcemanager.network.models.DeleteOptions.fromString(deleteOptions.toString())); + // } // Create NIC with creatable PIP - Creatable nicCreatable = - this.nicDefinitionWithCreate.withNewPrimaryPublicIPAddress(this.implicitPipCreatable); + Creatable nicCreatable + = this.nicDefinitionWithCreate.withNewPrimaryPublicIPAddress(this.implicitPipCreatable); this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable); return this; } @Override public VirtualMachineImpl withExistingPrimaryPublicIPAddress(PublicIpAddress publicIPAddress) { - Creatable nicCreatable = - this.nicDefinitionWithCreate.withExistingPrimaryPublicIPAddress(publicIPAddress); + Creatable nicCreatable + = this.nicDefinitionWithCreate.withExistingPrimaryPublicIPAddress(publicIPAddress); this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable); return this; } @@ -621,8 +582,8 @@ public VirtualMachineImpl withNewPrimaryNetworkInterface(Creatable definitionCreatable = - prepareNetworkInterface(name).withNewPrimaryPublicIPAddress(publicDnsNameLabel); + Creatable definitionCreatable + = prepareNetworkInterface(name).withNewPrimaryPublicIPAddress(publicDnsNameLabel); return withNewPrimaryNetworkInterface(definitionCreatable); } @@ -929,11 +890,8 @@ public VirtualMachineImpl withOSDiskVhdLocation(String containerName, String vhd VirtualHardDisk osVhd = new VirtualHardDisk(); try { URL sourceCustomImageUrl = new URL(osDisk.image().uri()); - URL destinationVhdUrl = - new URL( - sourceCustomImageUrl.getProtocol(), - sourceCustomImageUrl.getHost(), - "/" + containerName + "/" + vhdName); + URL destinationVhdUrl = new URL(sourceCustomImageUrl.getProtocol(), sourceCustomImageUrl.getHost(), + "/" + containerName + "/" + vhdName); osVhd.withUri(destinationVhdUrl.toString()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new RuntimeException(ex)); @@ -971,8 +929,7 @@ public VirtualMachineImpl withDataDiskDefaultDeleteOptions(DeleteOptions deleteO } @Override - public VirtualMachineImpl withDataDiskDefaultDiskEncryptionSet( - String diskEncryptionSetId) { + public VirtualMachineImpl withDataDiskDefaultDiskEncryptionSet(String diskEncryptionSetId) { this.managedDataDisks.setDefaultEncryptionSet(diskEncryptionSetId); return this; } @@ -997,7 +954,9 @@ public VirtualMachineImpl withOSDiskName(String name) { @Override public VirtualMachineImpl withOSDiskDeleteOptions(DeleteOptions deleteOptions) { - this.innerModel().storageProfile().osDisk() + this.innerModel() + .storageProfile() + .osDisk() .withDeleteOption(DiskDeleteOptionTypes.fromString(deleteOptions.toString())); return this; } @@ -1005,11 +964,13 @@ public VirtualMachineImpl withOSDiskDeleteOptions(DeleteOptions deleteOptions) { @Override public VirtualMachineImpl withOSDiskDiskEncryptionSet(String diskEncryptionSetId) { if (this.innerModel().storageProfile().osDisk().managedDisk() == null) { - this.innerModel().storageProfile().osDisk() - .withManagedDisk(new ManagedDiskParameters()); + this.innerModel().storageProfile().osDisk().withManagedDisk(new ManagedDiskParameters()); } if (this.innerModel().storageProfile().osDisk().managedDisk().diskEncryptionSet() == null) { - this.innerModel().storageProfile().osDisk().managedDisk() + this.innerModel() + .storageProfile() + .osDisk() + .managedDisk() .withDiskEncryptionSet(new DiskEncryptionSetParameters()); } this.innerModel().storageProfile().osDisk().managedDisk().diskEncryptionSet().withId(diskEncryptionSetId); @@ -1041,8 +1002,8 @@ public VirtualMachineImpl withNewUnmanagedDataDisk(Integer sizeInGB) { } @Override - public VirtualMachineImpl withExistingUnmanagedDataDisk( - String storageAccountName, String containerName, String vhdName) { + public VirtualMachineImpl withExistingUnmanagedDataDisk(String storageAccountName, String containerName, + String vhdName) { throwIfManagedDiskEnabled(ManagedUnmanagedDiskErrors.VM_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED); return defineUnmanagedDataDisk(null).withExistingVhd(storageAccountName, containerName, vhdName).attach(); } @@ -1099,10 +1060,8 @@ public VirtualMachineImpl withNewDataDisk(Creatable creatable) { @Override public VirtualMachineImpl withNewDataDisk(Creatable creatable, int lun, CachingTypes cachingType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); - this - .managedDataDisks - .newDisksToAttach - .put(this.addDependency(creatable), new DataDisk().withLun(lun).withCaching(cachingType)); + this.managedDataDisks.newDisksToAttach.put(this.addDependency(creatable), + new DataDisk().withLun(lun).withCaching(cachingType)); return this; } @@ -1116,28 +1075,21 @@ public VirtualMachineImpl withNewDataDisk(int sizeInGB) { @Override public VirtualMachineImpl withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); - this - .managedDataDisks - .implicitDisksToAssociate + this.managedDataDisks.implicitDisksToAssociate .add(new DataDisk().withLun(lun).withDiskSizeGB(sizeInGB).withCaching(cachingType)); return this; } @Override - public VirtualMachineImpl withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType) { + public VirtualMachineImpl withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withStorageAccountType(storageAccountType); - this - .managedDataDisks - .implicitDisksToAssociate - .add( - new DataDisk() - .withLun(lun) - .withDiskSizeGB(sizeInGB) - .withCaching(cachingType) - .withManagedDisk(managedDiskParameters)); + this.managedDataDisks.implicitDisksToAssociate.add(new DataDisk().withLun(lun) + .withDiskSizeGB(sizeInGB) + .withCaching(cachingType) + .withManagedDisk(managedDiskParameters)); return this; } @@ -1150,20 +1102,15 @@ public VirtualMachineImpl withNewDataDisk(int sizeInGB, int lun, VirtualMachineD managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withStorageAccountType(options.storageAccountType()); if (options.isDiskEncryptionSetConfigured()) { - managedDiskParameters.withDiskEncryptionSet( - new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); + managedDiskParameters + .withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); } } - this - .managedDataDisks - .implicitDisksToAssociate - .add( - new DataDisk() - .withLun(lun) - .withDiskSizeGB(sizeInGB) - .withCaching(options.cachingTypes()) - .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) - .withManagedDisk(managedDiskParameters)); + this.managedDataDisks.implicitDisksToAssociate.add(new DataDisk().withLun(lun) + .withDiskSizeGB(sizeInGB) + .withCaching(options.cachingTypes()) + .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) + .withManagedDisk(managedDiskParameters)); return this; } @@ -1172,9 +1119,7 @@ public VirtualMachineImpl withExistingDataDisk(Disk disk) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withId(disk.id()); - this - .managedDataDisks - .existingDisksToAttach + this.managedDataDisks.existingDisksToAttach .add(new DataDisk().withLun(-1).withManagedDisk(managedDiskParameters)); return this; } @@ -1184,9 +1129,7 @@ public VirtualMachineImpl withExistingDataDisk(Disk disk, int lun, CachingTypes throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withId(disk.id()); - this - .managedDataDisks - .existingDisksToAttach + this.managedDataDisks.existingDisksToAttach .add(new DataDisk().withLun(lun).withManagedDisk(managedDiskParameters).withCaching(cachingType)); return this; } @@ -1196,21 +1139,16 @@ public VirtualMachineImpl withExistingDataDisk(Disk disk, int newSizeInGB, int l throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withId(disk.id()); - this - .managedDataDisks - .existingDisksToAttach - .add( - new DataDisk() - .withLun(lun) - .withDiskSizeGB(newSizeInGB) - .withManagedDisk(managedDiskParameters) - .withCaching(cachingType)); + this.managedDataDisks.existingDisksToAttach.add(new DataDisk().withLun(lun) + .withDiskSizeGB(newSizeInGB) + .withManagedDisk(managedDiskParameters) + .withCaching(cachingType)); return this; } @Override - public VirtualMachineImpl withExistingDataDisk( - Disk disk, int newSizeInGB, int lun, VirtualMachineDiskOptions options) { + public VirtualMachineImpl withExistingDataDisk(Disk disk, int newSizeInGB, int lun, + VirtualMachineDiskOptions options) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); // storageAccountType is not allowed to be modified @@ -1218,19 +1156,14 @@ public VirtualMachineImpl withExistingDataDisk( ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withId(disk.id()); if (options.isDiskEncryptionSetConfigured()) { - managedDiskParameters.withDiskEncryptionSet( - new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); + managedDiskParameters + .withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); } - this - .managedDataDisks - .existingDisksToAttach - .add( - new DataDisk() - .withLun(lun) - .withDiskSizeGB(newSizeInGB) - .withCaching(options.cachingTypes()) - .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) - .withManagedDisk(managedDiskParameters)); + this.managedDataDisks.existingDisksToAttach.add(new DataDisk().withLun(lun) + .withDiskSizeGB(newSizeInGB) + .withCaching(options.cachingTypes()) + .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) + .withManagedDisk(managedDiskParameters)); return this; } @@ -1242,33 +1175,26 @@ public VirtualMachineImpl withNewDataDiskFromImage(int imageLun) { @Override public VirtualMachineImpl withNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType) { - this - .managedDataDisks - .newDisksFromImage + this.managedDataDisks.newDisksFromImage .add(new DataDisk().withLun(imageLun).withDiskSizeGB(newSizeInGB).withCaching(cachingType)); return this; } @Override - public VirtualMachineImpl withNewDataDiskFromImage( - int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) { + public VirtualMachineImpl withNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, + StorageAccountTypes storageAccountType) { ManagedDiskParameters managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withStorageAccountType(storageAccountType); - this - .managedDataDisks - .newDisksFromImage - .add( - new DataDisk() - .withLun(imageLun) - .withDiskSizeGB(newSizeInGB) - .withManagedDisk(managedDiskParameters) - .withCaching(cachingType)); + this.managedDataDisks.newDisksFromImage.add(new DataDisk().withLun(imageLun) + .withDiskSizeGB(newSizeInGB) + .withManagedDisk(managedDiskParameters) + .withCaching(cachingType)); return this; } @Override - public VirtualMachineImpl withNewDataDiskFromImage( - int imageLun, int newSizeInGB, VirtualMachineDiskOptions options) { + public VirtualMachineImpl withNewDataDiskFromImage(int imageLun, int newSizeInGB, + VirtualMachineDiskOptions options) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); ManagedDiskParameters managedDiskParameters = null; @@ -1276,20 +1202,15 @@ public VirtualMachineImpl withNewDataDiskFromImage( managedDiskParameters = new ManagedDiskParameters(); managedDiskParameters.withStorageAccountType(options.storageAccountType()); if (options.isDiskEncryptionSetConfigured()) { - managedDiskParameters.withDiskEncryptionSet( - new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); + managedDiskParameters + .withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(options.diskEncryptionSetId())); } } - this - .managedDataDisks - .implicitDisksToAssociate - .add( - new DataDisk() - .withLun(imageLun) - .withDiskSizeGB(newSizeInGB) - .withCaching(options.cachingTypes()) - .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) - .withManagedDisk(managedDiskParameters)); + this.managedDataDisks.implicitDisksToAssociate.add(new DataDisk().withLun(imageLun) + .withDiskSizeGB(newSizeInGB) + .withCaching(options.cachingTypes()) + .withDeleteOption(diskDeleteOptionsFromDeleteOptions(options.deleteOptions())) + .withManagedDisk(managedDiskParameters)); return this; } @@ -1314,8 +1235,8 @@ public VirtualMachineImpl withNewStorageAccount(Creatable creata @Override public VirtualMachineImpl withNewStorageAccount(String name) { - StorageAccount.DefinitionStages.WithGroup definitionWithGroup = - this.storageManager.storageAccounts().define(name).withRegion(this.regionName()); + StorageAccount.DefinitionStages.WithGroup definitionWithGroup + = this.storageManager.storageAccounts().define(name).withRegion(this.regionName()); Creatable definitionAfterGroup; if (this.creatableGroup != null) { definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -1350,8 +1271,8 @@ public VirtualMachineImpl withProximityPlacementGroup(String proximityPlacementG } @Override - public VirtualMachineImpl withNewProximityPlacementGroup( - String proximityPlacementGroupName, ProximityPlacementGroupType type) { + public VirtualMachineImpl withNewProximityPlacementGroup(String proximityPlacementGroupName, + ProximityPlacementGroupType type) { this.newProximityPlacementGroupName = proximityPlacementGroupName; this.newProximityPlacementGroupType = type; this.innerModel().withProximityPlacementGroup(null); @@ -1367,8 +1288,8 @@ public VirtualMachineImpl withoutProximityPlacementGroup() { @Override public VirtualMachineImpl withNewAvailabilitySet(String name) { - AvailabilitySet.DefinitionStages.WithGroup definitionWithGroup = - super.myManager.availabilitySets().define(name).withRegion(this.regionName()); + AvailabilitySet.DefinitionStages.WithGroup definitionWithGroup + = super.myManager.availabilitySets().define(name).withRegion(this.regionName()); AvailabilitySet.DefinitionStages.WithSku definitionWithSku; if (this.creatableGroup != null) { definitionWithSku = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -1398,7 +1319,7 @@ public VirtualMachineImpl withNewSecondaryNetworkInterface(Creatable creatable, - DeleteOptions deleteOptions) { + DeleteOptions deleteOptions) { String key = this.addDependency(creatable); this.creatableSecondaryNetworkInterfaceKeys.add(key); if (deleteOptions != null) { @@ -1736,7 +1657,8 @@ public DeleteOptions osDiskDeleteOptions() { @Override public String osDiskDiskEncryptionSetId() { - if (!isManagedDiskEnabled() || this.storageProfile().osDisk().managedDisk() == null + if (!isManagedDiskEnabled() + || this.storageProfile().osDisk().managedDisk() == null || this.storageProfile().osDisk().managedDisk().diskEncryptionSet() == null) { return null; } @@ -1745,12 +1667,14 @@ public String osDiskDiskEncryptionSetId() { @Override public boolean isOSDiskEphemeral() { - return this.storageProfile().osDisk().diffDiskSettings() != null && this.storageProfile().osDisk().diffDiskSettings().placement() != null; + return this.storageProfile().osDisk().diffDiskSettings() != null + && this.storageProfile().osDisk().diffDiskSettings().placement() != null; } @Override public boolean isEncryptionAtHost() { - return !Objects.isNull(this.innerModel().securityProfile()) && this.innerModel().securityProfile().encryptionAtHost(); + return !Objects.isNull(this.innerModel().securityProfile()) + && this.innerModel().securityProfile().encryptionAtHost(); } @Override @@ -1865,11 +1789,9 @@ public ProximityPlacementGroup proximityPlacementGroup() { return null; } else { ResourceId id = ResourceId.fromString(innerModel().proximityPlacementGroup().id()); - ProximityPlacementGroupInner plgInner = - manager() - .serviceClient() - .getProximityPlacementGroups() - .getByResourceGroup(id.resourceGroupName(), id.name()); + ProximityPlacementGroupInner plgInner = manager().serviceClient() + .getProximityPlacementGroups() + .getByResourceGroup(id.resourceGroupName(), id.name()); if (plgInner == null) { return null; } else { @@ -2014,14 +1936,18 @@ public SecurityTypes securityType() { @Override public boolean isSecureBootEnabled() { - return securityType() != null && this.innerModel().securityProfile().uefiSettings() != null - && ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().securityProfile().uefiSettings().secureBootEnabled()); + return securityType() != null + && this.innerModel().securityProfile().uefiSettings() != null + && ResourceManagerUtils + .toPrimitiveBoolean(this.innerModel().securityProfile().uefiSettings().secureBootEnabled()); } @Override public boolean isVTpmEnabled() { - return securityType() != null && this.innerModel().securityProfile().uefiSettings() != null - && ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().securityProfile().uefiSettings().vTpmEnabled()); + return securityType() != null + && this.innerModel().securityProfile().uefiSettings() != null + && ResourceManagerUtils + .toPrimitiveBoolean(this.innerModel().securityProfile().uefiSettings().vTpmEnabled()); } @Override @@ -2042,7 +1968,8 @@ public DeleteOptions networkInterfaceDeleteOptions(String networkInterfaceId) { || this.innerModel().networkProfile().networkInterfaces() == null) { return null; } - return this.innerModel().networkProfile() + return this.innerModel() + .networkProfile() .networkInterfaces() .stream() .filter(nic -> networkInterfaceId.equalsIgnoreCase(nic.id())) @@ -2074,21 +2001,15 @@ public void beforeGroupCreateOrUpdate() { if (osDiskRequiresImplicitStorageAccountCreation() || dataDisksRequiresImplicitStorageAccountCreation()) { Creatable storageAccountCreatable = null; if (this.creatableGroup != null) { - storageAccountCreatable = - this - .storageManager - .storageAccounts() - .define(this.namer.getRandomName("stg", 24).replace("-", "")) - .withRegion(this.regionName()) - .withNewResourceGroup(this.creatableGroup); + storageAccountCreatable = this.storageManager.storageAccounts() + .define(this.namer.getRandomName("stg", 24).replace("-", "")) + .withRegion(this.regionName()) + .withNewResourceGroup(this.creatableGroup); } else { - storageAccountCreatable = - this - .storageManager - .storageAccounts() - .define(this.namer.getRandomName("stg", 24).replace("-", "")) - .withRegion(this.regionName()) - .withExistingResourceGroup(this.resourceGroupName()); + storageAccountCreatable = this.storageManager.storageAccounts() + .define(this.namer.getRandomName("stg", 24).replace("-", "")) + .withRegion(this.regionName()) + .withExistingResourceGroup(this.resourceGroupName()); } this.creatableStorageAccountKey = this.addDependency(storageAccountCreatable); } @@ -2101,19 +2022,14 @@ public void beforeGroupCreateOrUpdate() { @Override public Mono createResourceAsync() { // -- set creation-time only properties - return prepareCreateResourceAsync() - .flatMap( - virtualMachine -> - this - .manager() - .serviceClient() - .getVirtualMachines() - .createOrUpdateAsync(resourceGroupName(), vmName, innerModel()) - .map( - virtualMachineInner -> { - reset(virtualMachineInner); - return this; - })); + return prepareCreateResourceAsync().flatMap(virtualMachine -> this.manager() + .serviceClient() + .getVirtualMachines() + .createOrUpdateAsync(resourceGroupName(), vmName, innerModel()) + .map(virtualMachineInner -> { + reset(virtualMachineInner); + return this; + })); } private Mono prepareCreateResourceAsync() { @@ -2128,49 +2044,32 @@ private Mono prepareCreateResourceAsync() { this.handleUnManagedOSAndDataDisksStorageSettings(); this.bootDiagnosticsHandler.handleDiagnosticsSettings(); this.handleNetworkSettings(); - return this - .createNewProximityPlacementGroupAsync() - .map( - virtualMachine -> { - this.handleAvailabilitySettings(); - this.virtualMachineMsiHandler.processCreatedExternalIdentities(); - this.virtualMachineMsiHandler.handleExternalIdentities(); - return virtualMachine; - }); + return this.createNewProximityPlacementGroupAsync().map(virtualMachine -> { + this.handleAvailabilitySettings(); + this.virtualMachineMsiHandler.processCreatedExternalIdentities(); + this.virtualMachineMsiHandler.handleExternalIdentities(); + return virtualMachine; + }); } public Accepted beginCreate() { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> - this - .manager() - .serviceClient() - .getVirtualMachines() - .createOrUpdateWithResponseAsync(resourceGroupName(), vmName, innerModel(), null, null) - .block(), - inner -> - new VirtualMachineImpl( - inner.name(), - inner, - this.manager(), - this.storageManager, - this.networkManager, - this.authorizationManager), - VirtualMachineInner.class, - () -> { - Flux dependencyTasksAsync = - taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); - dependencyTasksAsync.blockLast(); - - // same as createResourceAsync - prepareCreateResourceAsync().block(); - }, - this::reset, - Context.NONE); + return AcceptedImpl.newAccepted(logger, + this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), + () -> this.manager() + .serviceClient() + .getVirtualMachines() + .createOrUpdateWithResponseAsync(resourceGroupName(), vmName, innerModel(), null, null) + .block(), + inner -> new VirtualMachineImpl(inner.name(), inner, this.manager(), this.storageManager, + this.networkManager, this.authorizationManager), + VirtualMachineInner.class, () -> { + Flux dependencyTasksAsync + = taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); + dependencyTasksAsync.blockLast(); + + // same as createResourceAsync + prepareCreateResourceAsync().block(); + }, this::reset, Context.NONE); } @Override @@ -2192,19 +2091,16 @@ public Mono updateResourceAsync() { final boolean vmModified = this.isVirtualMachineModifiedDuringUpdate(updateParameter); if (vmModified) { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachines() .updateAsync(resourceGroupName(), vmName, updateParameter) - .onErrorResume(e -> refreshAsync() - .onErrorComplete() // ignore refresh error - .then(Mono.error(e))) - .map( - virtualMachineInner -> { - reset(virtualMachineInner); - return this; - }); + .onErrorResume(e -> refreshAsync().onErrorComplete() // ignore refresh error + .then(Mono.error(e))) + .map(virtualMachineInner -> { + reset(virtualMachineInner); + return this; + }); } else { return Mono.just(this); } @@ -2278,8 +2174,7 @@ public VirtualMachineImpl withAvailabilityZone(AvailabilityZoneId zoneId) { this.innerModel().zones().add(zoneId.toString()); // zone aware VM can be attached to only zone aware public IP. if (this.implicitPipCreatable != null) { - this.implicitPipCreatable - .withAvailabilityZone(zoneId) + this.implicitPipCreatable.withAvailabilityZone(zoneId) .withSku(PublicIPSkuType.STANDARD) // standard sku is required for zone resiliency .withStaticIP(); // static allocation is required for standard sku } @@ -2290,7 +2185,8 @@ public VirtualMachineImpl withAvailabilityZone(AvailabilityZoneId zoneId) { @Override public VirtualMachineImpl withOsDiskDeleteOptions(DeleteOptions deleteOptions) { if (deleteOptions == null - || this.innerModel().storageProfile() == null || this.innerModel().storageProfile().osDisk() == null) { + || this.innerModel().storageProfile() == null + || this.innerModel().storageProfile().osDisk() == null) { return null; } this.innerModel().storageProfile().osDisk().withDeleteOption(diskDeleteOptionsFromDeleteOptions(deleteOptions)); @@ -2308,23 +2204,20 @@ public VirtualMachineImpl withNetworkInterfacesDeleteOptions(DeleteOptions delet if (this.innerModel().networkProfile() != null && this.innerModel().networkProfile().networkInterfaces() != null) { // vararg "nicIds" will never be null, an array will always be created to hold the variables - Set nicIdSet = Arrays.stream(nicIds).map(nicId -> nicId.toLowerCase(Locale.ROOT)).collect(Collectors.toSet()); - this.innerModel().networkProfile().networkInterfaces().forEach( - nic -> { - if (nicIdSet.contains(nic.id().toLowerCase(Locale.ROOT))) { - nic.withDeleteOption(deleteOptions); - } + Set nicIdSet + = Arrays.stream(nicIds).map(nicId -> nicId.toLowerCase(Locale.ROOT)).collect(Collectors.toSet()); + this.innerModel().networkProfile().networkInterfaces().forEach(nic -> { + if (nicIdSet.contains(nic.id().toLowerCase(Locale.ROOT))) { + nic.withDeleteOption(deleteOptions); } - ); + }); } return this; } @Override public VirtualMachineImpl withNetworkInterfacesDeleteOptions(DeleteOptions deleteOptions) { - this.innerModel().networkProfile().networkInterfaces().forEach( - nic -> nic.withDeleteOption(deleteOptions) - ); + this.innerModel().networkProfile().networkInterfaces().forEach(nic -> nic.withDeleteOption(deleteOptions)); return this; } @@ -2333,22 +2226,21 @@ public VirtualMachineImpl withDataDisksDeleteOptions(DeleteOptions deleteOptions if (this.innerModel().storageProfile() != null && this.innerModel().storageProfile().dataDisks() != null) { // vararg "luns" will never be null, an array will always be created to hold the variables Set lunSet = Arrays.stream(luns).filter(Objects::nonNull).collect(Collectors.toSet()); - this.innerModel().storageProfile().dataDisks().forEach( - dataDisk -> { - if (lunSet.contains(dataDisk.lun())) { - dataDisk.withDeleteOption(diskDeleteOptionsFromDeleteOptions(deleteOptions)); - } + this.innerModel().storageProfile().dataDisks().forEach(dataDisk -> { + if (lunSet.contains(dataDisk.lun())) { + dataDisk.withDeleteOption(diskDeleteOptionsFromDeleteOptions(deleteOptions)); } - ); + }); } return this; } @Override public VirtualMachineImpl withDataDisksDeleteOptions(DeleteOptions deleteOptions) { - this.innerModel().storageProfile().dataDisks().forEach( - dataDisk -> dataDisk.withDeleteOption(diskDeleteOptionsFromDeleteOptions(deleteOptions)) - ); + this.innerModel() + .storageProfile() + .dataDisks() + .forEach(dataDisk -> dataDisk.withDeleteOption(diskDeleteOptionsFromDeleteOptions(deleteOptions))); return this; } @@ -2430,8 +2322,7 @@ private void setOSProfileDefaults() { if (osProfile.linuxConfiguration() == null) { osProfile.withLinuxConfiguration(new LinuxConfiguration()); } - this - .innerModel() + this.innerModel() .osProfile() .linuxConfiguration() .withDisablePasswordAuthentication(osProfile.adminPassword() == null); @@ -2480,13 +2371,11 @@ private void handleUnManagedOSAndDataDisksStorageSettings() { if (isInCreateMode()) { if (storageAccount != null) { if (isOSDiskFromPlatformImage(innerModel().storageProfile())) { - String uri = - innerModel() - .storageProfile() - .osDisk() - .vhd() - .uri() - .replaceFirst("\\{storage-base-url}", storageAccount.endPoints().primary().blob()); + String uri = innerModel().storageProfile() + .osDisk() + .vhd() + .uri() + .replaceFirst("\\{storage-base-url}", storageAccount.endPoints().primary().blob()); innerModel().storageProfile().osDisk().vhd().withUri(uri); } UnmanagedDataDiskImpl.ensureDisksVhdUri(unmanagedDataDisks, storageAccount, vmName); @@ -2506,18 +2395,14 @@ private Mono createNewProximityPlacementGroupAsync() { ProximityPlacementGroupInner plgInner = new ProximityPlacementGroupInner(); plgInner.withProximityPlacementGroupType(this.newProximityPlacementGroupType); plgInner.withLocation(this.innerModel().location()); - return this - .manager() + return this.manager() .serviceClient() .getProximityPlacementGroups() .createOrUpdateAsync(this.resourceGroupName(), this.newProximityPlacementGroupName, plgInner) - .map( - createdPlgInner -> { - this - .innerModel() - .withProximityPlacementGroup(new SubResource().withId(createdPlgInner.id())); - return this; - }); + .map(createdPlgInner -> { + this.innerModel().withProximityPlacementGroup(new SubResource().withId(createdPlgInner.id())); + return this; + }); } } return Mono.just(this); @@ -2544,7 +2429,10 @@ private void handleNetworkSettings() { if (this.primaryNetworkInterfaceDeleteOptions != null) { String primaryNetworkInterfaceId = primaryNetworkInterfaceId(); if (primaryNetworkInterfaceId != null) { - this.innerModel().networkProfile().networkInterfaces().stream() + this.innerModel() + .networkProfile() + .networkInterfaces() + .stream() .filter(nic -> primaryNetworkInterfaceId.equals(nic.id())) .forEach(nic -> nic.withDeleteOption(this.primaryNetworkInterfaceDeleteOptions)); } @@ -2722,8 +2610,8 @@ private String temporaryBlobUrl(String containerName, String blobName) { } private NetworkInterface.DefinitionStages.WithPrimaryPublicIPAddress prepareNetworkInterface(String name) { - NetworkInterface.DefinitionStages.WithGroup definitionWithGroup = - this.networkManager.networkInterfaces().define(name).withRegion(this.regionName()); + NetworkInterface.DefinitionStages.WithGroup definitionWithGroup + = this.networkManager.networkInterfaces().define(name).withRegion(this.regionName()); NetworkInterface.DefinitionStages.WithPrimaryNetwork definitionWithNetwork; if (this.creatableGroup != null) { definitionWithNetwork = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -2749,8 +2637,8 @@ private void initializeDataDisks() { } private NetworkInterface.DefinitionStages.WithPrimaryNetwork preparePrimaryNetworkInterface(String name) { - NetworkInterface.DefinitionStages.WithGroup definitionWithGroup = - this.networkManager.networkInterfaces().define(name).withRegion(this.regionName()); + NetworkInterface.DefinitionStages.WithGroup definitionWithGroup + = this.networkManager.networkInterfaces().define(name).withRegion(this.regionName()); NetworkInterface.DefinitionStages.WithPrimaryNetwork definitionAfterGroup; if (this.creatableGroup != null) { definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -2789,8 +2677,8 @@ boolean isVirtualMachineModifiedDuringUpdate(VirtualMachineUpdateInner updatePar return true; } else { try { - String jsonStrSnapshot = - SERIALIZER_ADAPTER.serialize(updateParameterSnapshotOnUpdate, SerializerEncoding.JSON); + String jsonStrSnapshot + = SERIALIZER_ADAPTER.serialize(updateParameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(updateParameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { @@ -2806,8 +2694,8 @@ VirtualMachineUpdateInner deepCopyInnerToUpdateParameter() { try { // deep copy via json String jsonStr = SERIALIZER_ADAPTER.serialize(updateParameter, SerializerEncoding.JSON); - updateParameter = - SERIALIZER_ADAPTER.deserialize(jsonStr, VirtualMachineUpdateInner.class, SerializerEncoding.JSON); + updateParameter + = SERIALIZER_ADAPTER.deserialize(jsonStr, VirtualMachineUpdateInner.class, SerializerEncoding.JSON); } catch (IOException e) { // ignored, null to signify not available return null; @@ -3046,15 +2934,14 @@ void setDataDisksDefaults() { } } // Func to get the next available lun - Callable nextLun = - () -> { - Integer lun = 0; - while (usedLuns.contains(lun)) { - lun++; - } - usedLuns.add(lun); - return lun; - }; + Callable nextLun = () -> { + Integer lun = 0; + while (usedLuns.contains(lun)) { + lun++; + } + usedLuns.add(lun); + return lun; + }; try { setAttachableNewDataDisks(nextLun); setAttachableExistingDataDisks(nextLun); @@ -3326,23 +3213,15 @@ void prepare() { String accountName = this.vmImpl.namer.getRandomName("stg", 24).replace("-", ""); Creatable storageAccountCreatable; if (this.vmImpl.creatableGroup != null) { - storageAccountCreatable = - this - .vmImpl - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.vmImpl.regionName()) - .withNewResourceGroup(this.vmImpl.creatableGroup); + storageAccountCreatable = this.vmImpl.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.vmImpl.regionName()) + .withNewResourceGroup(this.vmImpl.creatableGroup); } else { - storageAccountCreatable = - this - .vmImpl - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.vmImpl.regionName()) - .withExistingResourceGroup(this.vmImpl.resourceGroupName()); + storageAccountCreatable = this.vmImpl.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.vmImpl.regionName()) + .withExistingResourceGroup(this.vmImpl.resourceGroupName()); } this.creatableDiagnosticsStorageAccountKey = this.vmImpl.addDependency(storageAccountCreatable); } @@ -3371,13 +3250,10 @@ void handleDiagnosticsSettings() { storageAccount = this.vmImpl.existingStorageAccountToAssociate; } if (storageAccount == null) { - throw logger - .logExceptionAsError( - new IllegalStateException( - "Unable to retrieve expected storageAccount instance for BootDiagnostics")); + throw logger.logExceptionAsError(new IllegalStateException( + "Unable to retrieve expected storageAccount instance for BootDiagnostics")); } - vmInner() - .diagnosticsProfile() + vmInner().diagnosticsProfile() .bootDiagnostics() .withStorageUri(storageAccount.endPoints().primary().blob()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMsiHandler.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMsiHandler.java index 6923a8967cfeb..8ee114e4711fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMsiHandler.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMsiHandler.java @@ -73,9 +73,7 @@ VirtualMachineMsiHandler withoutLocalManagedServiceIdentity() { return this; } else if (this.virtualMachine.innerModel().identity().type().equals(ResourceIdentityType.SYSTEM_ASSIGNED)) { this.virtualMachine.innerModel().identity().withType(ResourceIdentityType.NONE); - } else if (this - .virtualMachine - .innerModel() + } else if (this.virtualMachine.innerModel() .identity() .type() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)) { @@ -210,15 +208,15 @@ private boolean handleRemoveAllExternalIdentitiesCase(VirtualMachineUpdateInner } } Set removeIds = new HashSet<>(); - for (Map.Entry entrySet - : this.userAssignedIdentities.entrySet()) { + for (Map.Entry entrySet : this.userAssignedIdentities + .entrySet()) { if (entrySet.getValue() == null) { removeIds.add(entrySet.getKey().toLowerCase(Locale.ROOT)); } } // If so check user want to remove all the identities - boolean removeAllCurrentIds = - currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); + boolean removeAllCurrentIds + = currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); if (removeAllCurrentIds) { // If so adjust the identity type [Setting type to SYSTEM_ASSIGNED orNONE will remove all the // identities] diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineOffersImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineOffersImpl.java index 40535a3ecd19d..253756aebbdb0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineOffersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineOffersImpl.java @@ -40,9 +40,9 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter - .convertListToPagedFlux(innerCollection.listOffersWithResponseAsync( - publisher.region().toString(), publisher.name())), + return PagedConverter.mapPage( + PagedConverter.convertListToPagedFlux( + innerCollection.listOffersWithResponseAsync(publisher.region().toString(), publisher.name())), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublisherImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublisherImpl.java index ab5af7e84b33f..ff1cd2c09c3ae 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublisherImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublisherImpl.java @@ -16,10 +16,7 @@ class VirtualMachinePublisherImpl implements VirtualMachinePublisher { private final VirtualMachineOffers offers; private final VirtualMachineExtensionImageTypes types; - VirtualMachinePublisherImpl( - Region location, - String publisher, - VirtualMachineImagesClient imagesClient, + VirtualMachinePublisherImpl(Region location, String publisher, VirtualMachineImagesClient imagesClient, VirtualMachineExtensionImagesClient extensionsClient) { this.location = location; this.publisher = publisher; diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublishersImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublishersImpl.java index 1961e4423522d..39dde030842de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublishersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinePublishersImpl.java @@ -21,8 +21,7 @@ public class VirtualMachinePublishersImpl private final VirtualMachineImagesClient imagesClientCollection; private final VirtualMachineExtensionImagesClient extensionsInnerCollection; - public VirtualMachinePublishersImpl( - VirtualMachineImagesClient imagesClientCollection, + public VirtualMachinePublishersImpl(VirtualMachineImagesClient imagesClientCollection, VirtualMachineExtensionImagesClient extensionsInnerCollection) { this.imagesClientCollection = imagesClientCollection; this.extensionsInnerCollection = extensionsInnerCollection; @@ -38,11 +37,8 @@ protected VirtualMachinePublisherImpl wrapModel(VirtualMachineImageResourceInner if (inner == null) { return null; } - return new VirtualMachinePublisherImpl( - Region.fromName(inner.location()), - inner.name(), - this.imagesClientCollection, - this.extensionsInnerCollection); + return new VirtualMachinePublisherImpl(Region.fromName(inner.location()), inner.name(), + this.imagesClientCollection, this.extensionsInnerCollection); } @Override @@ -57,8 +53,8 @@ public PagedFlux listByRegionAsync(Region region) { @Override public PagedFlux listByRegionAsync(String regionName) { - return PagedConverter.mapPage(PagedConverter - .convertListToPagedFlux(imagesClientCollection.listPublishersWithResponseAsync(regionName)), + return PagedConverter.mapPage( + PagedConverter.convertListToPagedFlux(imagesClientCollection.listPublishersWithResponseAsync(regionName)), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetExtensionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetExtensionImpl.java index 3242b179d2f9f..e7f9204e9a2d7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetExtensionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetExtensionImpl.java @@ -20,12 +20,12 @@ public class VirtualMachineScaleSetExtensionImpl extends ChildResourceImpl implements VirtualMachineScaleSetExtension, - VirtualMachineScaleSetExtension.Definition, - VirtualMachineScaleSetExtension.UpdateDefinition, - VirtualMachineScaleSetExtension.Update { + VirtualMachineScaleSetExtension.Definition, + VirtualMachineScaleSetExtension.UpdateDefinition, + VirtualMachineScaleSetExtension.Update { - protected VirtualMachineScaleSetExtensionImpl( - VirtualMachineScaleSetExtensionInner inner, VirtualMachineScaleSetImpl parent) { + protected VirtualMachineScaleSetExtensionImpl(VirtualMachineScaleSetExtensionInner inner, + VirtualMachineScaleSetImpl parent) { super(inner, parent); } @@ -97,8 +97,7 @@ public VirtualMachineScaleSetExtensionImpl withoutMinorVersionAutoUpgrade() { @Override public VirtualMachineScaleSetExtensionImpl withImage(VirtualMachineExtensionImage image) { - this - .innerModel() + this.innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetImpl.java index f69ebdf6ef252..22f575b0e9e3f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetImpl.java @@ -107,18 +107,14 @@ import java.util.concurrent.Callable; /** Implementation of VirtualMachineScaleSet. */ -public class VirtualMachineScaleSetImpl - extends GroupableParentResourceImpl< - VirtualMachineScaleSet, VirtualMachineScaleSetInner, VirtualMachineScaleSetImpl, ComputeManager> - implements VirtualMachineScaleSet, - VirtualMachineScaleSet.DefinitionManagedOrUnmanaged, - VirtualMachineScaleSet.DefinitionManaged, - VirtualMachineScaleSet.DefinitionUnmanaged, - VirtualMachineScaleSet.Update, - VirtualMachineScaleSet.DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, - VirtualMachineScaleSet.DefinitionStages.WithUserAssignedManagedServiceIdentity, - VirtualMachineScaleSet.UpdateStages.WithSystemAssignedIdentityBasedAccessOrApply, - VirtualMachineScaleSet.UpdateStages.WithUserAssignedManagedServiceIdentity { +public class VirtualMachineScaleSetImpl extends + GroupableParentResourceImpl + implements VirtualMachineScaleSet, VirtualMachineScaleSet.DefinitionManagedOrUnmanaged, + VirtualMachineScaleSet.DefinitionManaged, VirtualMachineScaleSet.DefinitionUnmanaged, VirtualMachineScaleSet.Update, + VirtualMachineScaleSet.DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, + VirtualMachineScaleSet.DefinitionStages.WithUserAssignedManagedServiceIdentity, + VirtualMachineScaleSet.UpdateStages.WithSystemAssignedIdentityBasedAccessOrApply, + VirtualMachineScaleSet.UpdateStages.WithUserAssignedManagedServiceIdentity { // Clients private final StorageManager storageManager; private final NetworkManager networkManager; @@ -170,12 +166,8 @@ public class VirtualMachineScaleSetImpl // Currently, it's only used in checking if the vm profile defaults has to be set. private boolean profileAttached = false; - VirtualMachineScaleSetImpl( - String name, - VirtualMachineScaleSetInner innerModel, - final ComputeManager computeManager, - final StorageManager storageManager, - final NetworkManager networkManager, + VirtualMachineScaleSetImpl(String name, VirtualMachineScaleSetInner innerModel, final ComputeManager computeManager, + final StorageManager storageManager, final NetworkManager networkManager, final AuthorizationManager authorizationManager) { super(name, innerModel, computeManager); this.storageManager = storageManager; @@ -195,8 +187,10 @@ protected void initializeChildrenFromInner() { && this.innerModel().virtualMachineProfile() != null && this.innerModel().virtualMachineProfile().extensionProfile() != null) { if (this.innerModel().virtualMachineProfile().extensionProfile().extensions() != null) { - for (VirtualMachineScaleSetExtensionInner inner - : this.innerModel().virtualMachineProfile().extensionProfile().extensions()) { + for (VirtualMachineScaleSetExtensionInner inner : this.innerModel() + .virtualMachineProfile() + .extensionProfile() + .extensions()) { this.extensions.put(inner.name(), new VirtualMachineScaleSetExtensionImpl(inner, this)); } } @@ -205,17 +199,14 @@ protected void initializeChildrenFromInner() { @Override public VirtualMachineScaleSetVMs virtualMachines() { - return new VirtualMachineScaleSetVMsImpl( - this, this.manager().serviceClient().getVirtualMachineScaleSetVMs(), this.myManager); + return new VirtualMachineScaleSetVMsImpl(this, this.manager().serviceClient().getVirtualMachineScaleSetVMs(), + this.myManager); } @Override public PagedIterable listAvailableSkus() { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getVirtualMachineScaleSets() - .listSkus(this.resourceGroupName(), this.name()), + return PagedConverter.mapPage( + this.manager().serviceClient().getVirtualMachineScaleSets().listSkus(this.resourceGroupName(), this.name()), VirtualMachineScaleSetSkuImpl::new); } @@ -226,8 +217,7 @@ public void deallocate() { @Override public Mono deallocateAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .deallocateAsync(this.resourceGroupName(), this.name(), null, null) @@ -242,8 +232,7 @@ public void powerOff() { @Override public Mono powerOffAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .powerOffAsync(this.resourceGroupName(), this.name(), null, null); @@ -256,8 +245,7 @@ public void restart() { @Override public Mono restartAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .restartAsync(this.resourceGroupName(), this.name(), null); @@ -270,8 +258,7 @@ public void start() { @Override public Mono startAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .startAsync(this.resourceGroupName(), this.name(), null); @@ -284,64 +271,57 @@ public void reimage() { @Override public Mono reimageAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .reimageAsync(this.resourceGroupName(), this.name(), null); } @Override - public RunCommandResult runPowerShellScriptInVMInstance( - String vmId, List scriptLines, List scriptParameters) { - return this - .manager() + public RunCommandResult runPowerShellScriptInVMInstance(String vmId, List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachineScaleSets() - .runPowerShellScriptInVMInstance( - this.resourceGroupName(), this.name(), vmId, scriptLines, scriptParameters); + .runPowerShellScriptInVMInstance(this.resourceGroupName(), this.name(), vmId, scriptLines, + scriptParameters); } @Override - public Mono runPowerShellScriptInVMInstanceAsync( - String vmId, List scriptLines, List scriptParameters) { - return this - .manager() + public Mono runPowerShellScriptInVMInstanceAsync(String vmId, List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachineScaleSets() - .runPowerShellScriptInVMInstanceAsync( - this.resourceGroupName(), this.name(), vmId, scriptLines, scriptParameters); + .runPowerShellScriptInVMInstanceAsync(this.resourceGroupName(), this.name(), vmId, scriptLines, + scriptParameters); } @Override - public RunCommandResult runShellScriptInVMInstance( - String vmId, List scriptLines, List scriptParameters) { - return this - .manager() + public RunCommandResult runShellScriptInVMInstance(String vmId, List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachineScaleSets() .runShellScriptInVMInstance(this.resourceGroupName(), this.name(), vmId, scriptLines, scriptParameters); } @Override - public Mono runShellScriptInVMInstanceAsync( - String vmId, List scriptLines, List scriptParameters) { - return this - .manager() + public Mono runShellScriptInVMInstanceAsync(String vmId, List scriptLines, + List scriptParameters) { + return this.manager() .virtualMachineScaleSets() - .runShellScriptInVMInstanceAsync( - this.resourceGroupName(), this.name(), vmId, scriptLines, scriptParameters); + .runShellScriptInVMInstanceAsync(this.resourceGroupName(), this.name(), vmId, scriptLines, + scriptParameters); } @Override public RunCommandResult runCommandInVMInstance(String vmId, RunCommandInput inputCommand) { - return this - .manager() + return this.manager() .virtualMachineScaleSets() .runCommandInVMInstance(this.resourceGroupName(), this.name(), vmId, inputCommand); } @Override public Mono runCommandVMInstanceAsync(String vmId, RunCommandInput inputCommand) { - return this - .manager() + return this.manager() .virtualMachineScaleSets() .runCommandVMInstanceAsync(this.resourceGroupName(), this.name(), vmId, inputCommand); } @@ -389,7 +369,8 @@ public boolean isEphemeralOSDisk() { && this.innerModel().virtualMachineProfile().storageProfile() != null && this.innerModel().virtualMachineProfile().storageProfile().osDisk() != null && this.innerModel().virtualMachineProfile().storageProfile().osDisk().diffDiskSettings() != null - && this.innerModel().virtualMachineProfile().storageProfile().osDisk().diffDiskSettings().placement() != null; + && this.innerModel().virtualMachineProfile().storageProfile().osDisk().diffDiskSettings().placement() + != null; } @Override @@ -438,8 +419,8 @@ public LoadBalancer getPrimaryInternetFacingLoadBalancer() throws IOException { @Override public Map listPrimaryInternetFacingLoadBalancerBackends() throws IOException { if (this.getPrimaryInternetFacingLoadBalancer() != null) { - return getBackendsAssociatedWithIpConfiguration( - this.primaryInternetFacingLoadBalancer, primaryNicDefaultIpConfiguration()); + return getBackendsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer, + primaryNicDefaultIpConfiguration()); } return new HashMap<>(); } @@ -448,8 +429,8 @@ public Map listPrimaryInternetFacingLoadBalancerBac public Map listPrimaryInternetFacingLoadBalancerInboundNatPools() throws IOException { if (this.getPrimaryInternetFacingLoadBalancer() != null) { - return getInboundNatPoolsAssociatedWithIpConfiguration( - this.primaryInternetFacingLoadBalancer, primaryNicDefaultIpConfiguration()); + return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer, + primaryNicDefaultIpConfiguration()); } return new HashMap<>(); } @@ -465,8 +446,8 @@ public LoadBalancer getPrimaryInternalLoadBalancer() throws IOException { @Override public Map listPrimaryInternalLoadBalancerBackends() throws IOException { if (this.getPrimaryInternalLoadBalancer() != null) { - return getBackendsAssociatedWithIpConfiguration( - this.primaryInternalLoadBalancer, primaryNicDefaultIpConfiguration()); + return getBackendsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer, + primaryNicDefaultIpConfiguration()); } return new HashMap<>(); } @@ -474,8 +455,8 @@ public Map listPrimaryInternalLoadBalancerBackends( @Override public Map listPrimaryInternalLoadBalancerInboundNatPools() throws IOException { if (this.getPrimaryInternalLoadBalancer() != null) { - return getInboundNatPoolsAssociatedWithIpConfiguration( - this.primaryInternalLoadBalancer, primaryNicDefaultIpConfiguration()); + return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer, + primaryNicDefaultIpConfiguration()); } return new HashMap<>(); } @@ -637,11 +618,9 @@ public ProximityPlacementGroup proximityPlacementGroup() { return null; } else { ResourceId id = ResourceId.fromString(innerModel().proximityPlacementGroup().id()); - ProximityPlacementGroupInner plgInner = - manager() - .serviceClient() - .getProximityPlacementGroups() - .getByResourceGroup(id.resourceGroupName(), id.name()); + ProximityPlacementGroupInner plgInner = manager().serviceClient() + .getProximityPlacementGroups() + .getByResourceGroup(id.resourceGroupName(), id.name()); if (plgInner == null) { return null; } else { @@ -662,51 +641,43 @@ public Plan plan() { @Override public OrchestrationMode orchestrationMode() { - return this.innerModel().orchestrationMode() == null ? OrchestrationMode.UNIFORM : this.innerModel().orchestrationMode(); + return this.innerModel().orchestrationMode() == null + ? OrchestrationMode.UNIFORM + : this.innerModel().orchestrationMode(); } @Override public VirtualMachineScaleSetNetworkInterface getNetworkInterfaceByInstanceId(String instanceId, String name) { - return this - .networkManager - .networkInterfaces() + return this.networkManager.networkInterfaces() .getByVirtualMachineScaleSetInstanceId(this.resourceGroupName(), this.name(), instanceId, name); } @Override public Mono getNetworkInterfaceByInstanceIdAsync(String instanceId, - String name) { - return this - .networkManager - .networkInterfaces() + String name) { + return this.networkManager.networkInterfaces() .getByVirtualMachineScaleSetInstanceIdAsync(this.resourceGroupName(), this.name(), instanceId, name); } @Override public PagedIterable listNetworkInterfaces() { - return this - .networkManager - .networkInterfaces() + return this.networkManager.networkInterfaces() .listByVirtualMachineScaleSet(this.resourceGroupName(), this.name()); } @Override - public PagedIterable listNetworkInterfacesByInstanceId( - String virtualMachineInstanceId) { - return this - .networkManager - .networkInterfaces() + public PagedIterable + listNetworkInterfacesByInstanceId(String virtualMachineInstanceId) { + return this.networkManager.networkInterfaces() .listByVirtualMachineScaleSetInstanceId(this.resourceGroupName(), this.name(), virtualMachineInstanceId); } @Override - public PagedFlux listNetworkInterfacesByInstanceIdAsync( - String virtualMachineInstanceId) { - return this - .networkManager - .networkInterfaces() - .listByVirtualMachineScaleSetInstanceIdAsync( - this.resourceGroupName(), this.name(), virtualMachineInstanceId); + public PagedFlux + listNetworkInterfacesByInstanceIdAsync(String virtualMachineInstanceId) { + return this.networkManager.networkInterfaces() + .listByVirtualMachineScaleSetInstanceIdAsync(this.resourceGroupName(), this.name(), + virtualMachineInstanceId); } // Fluent setters @@ -745,15 +716,14 @@ public VirtualMachineScaleSetImpl withExistingPrimaryNetworkSubnet(Network netwo @Override public VirtualMachineScaleSetImpl withExistingPrimaryInternetFacingLoadBalancer(LoadBalancer loadBalancer) { if (loadBalancer.publicIpAddressIds().isEmpty()) { - throw logger - .logExceptionAsError( - new IllegalArgumentException("Parameter loadBalancer must be an Internet facing load balancer")); + throw logger.logExceptionAsError( + new IllegalArgumentException("Parameter loadBalancer must be an Internet facing load balancer")); } initVMProfileIfNecessary(); if (isInCreateMode()) { this.primaryInternetFacingLoadBalancer = loadBalancer; - associateLoadBalancerToIpConfiguration( - this.primaryInternetFacingLoadBalancer, this.primaryNicDefaultIpConfiguration()); + associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancer, + this.primaryNicDefaultIpConfiguration()); } else { this.primaryInternetFacingLoadBalancerToAttachOnUpdate = loadBalancer; } @@ -765,10 +735,10 @@ public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerBackends( initVMProfileIfNecessary(); if (this.isInCreateMode()) { VirtualMachineScaleSetIpConfiguration defaultPrimaryIpConfig = this.primaryNicDefaultIpConfiguration(); - removeAllBackendAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancer, defaultPrimaryIpConfig); - associateBackEndsToIpConfiguration( - this.primaryInternetFacingLoadBalancer.id(), defaultPrimaryIpConfig, backendNames); + removeAllBackendAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, + defaultPrimaryIpConfig); + associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(), defaultPrimaryIpConfig, + backendNames); } else { addToList(this.primaryInternetFacingLBBackendsToAddOnUpdate, backendNames); } @@ -780,10 +750,10 @@ public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerInboundNa initVMProfileIfNecessary(); if (this.isInCreateMode()) { VirtualMachineScaleSetIpConfiguration defaultPrimaryIpConfig = this.primaryNicDefaultIpConfiguration(); - removeAllInboundNatPoolAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancer, defaultPrimaryIpConfig); - associateInboundNATPoolsToIpConfiguration( - this.primaryInternetFacingLoadBalancer.id(), defaultPrimaryIpConfig, natPoolNames); + removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, + defaultPrimaryIpConfig); + associateInboundNATPoolsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(), + defaultPrimaryIpConfig, natPoolNames); } else { addToList(this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate, natPoolNames); } @@ -793,9 +763,8 @@ public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerInboundNa @Override public VirtualMachineScaleSetImpl withExistingPrimaryInternalLoadBalancer(LoadBalancer loadBalancer) { if (!loadBalancer.publicIpAddressIds().isEmpty()) { - throw logger - .logExceptionAsError( - new IllegalArgumentException("Parameter loadBalancer must be an internal load balancer")); + throw logger.logExceptionAsError( + new IllegalArgumentException("Parameter loadBalancer must be an internal load balancer")); } String lbNetworkId = null; for (LoadBalancerPrivateFrontend frontEnd : loadBalancer.privateFrontends().values()) { @@ -805,43 +774,30 @@ public VirtualMachineScaleSetImpl withExistingPrimaryInternalLoadBalancer(LoadBa } initVMProfileIfNecessary(); if (isInCreateMode()) { - String vmNICNetworkId = - ResourceUtils.parentResourceIdFromResourceId(this.existingPrimaryNetworkSubnetNameToAssociate); + String vmNICNetworkId + = ResourceUtils.parentResourceIdFromResourceId(this.existingPrimaryNetworkSubnetNameToAssociate); // Azure has a really wired BUG that - it throws exception when vnet of VMSS and LB are not same // (code: NetworkInterfaceAndInternalLoadBalancerMustUseSameVnet) but at the same time Azure update // the VMSS's network section to refer this invalid internal LB. This makes VMSS un-usable and portal // will show a error above VMSS profile page. // if (!vmNICNetworkId.equalsIgnoreCase(lbNetworkId)) { - throw logger - .logExceptionAsError( - new IllegalArgumentException( - "Virtual network associated with scale set virtual machines" - + " and internal load balancer must be same. " - + "'" - + vmNICNetworkId - + "'" - + "'" - + lbNetworkId)); + throw logger.logExceptionAsError( + new IllegalArgumentException("Virtual network associated with scale set virtual machines" + + " and internal load balancer must be same. " + "'" + vmNICNetworkId + "'" + "'" + + lbNetworkId)); } this.primaryInternalLoadBalancer = loadBalancer; - associateLoadBalancerToIpConfiguration( - this.primaryInternalLoadBalancer, this.primaryNicDefaultIpConfiguration()); + associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancer, + this.primaryNicDefaultIpConfiguration()); } else { - String vmNicVnetId = - ResourceUtils.parentResourceIdFromResourceId(primaryNicDefaultIpConfiguration().subnet().id()); + String vmNicVnetId + = ResourceUtils.parentResourceIdFromResourceId(primaryNicDefaultIpConfiguration().subnet().id()); if (!vmNicVnetId.equalsIgnoreCase(lbNetworkId)) { - throw logger - .logExceptionAsError( - new IllegalArgumentException( - "Virtual network associated with scale set virtual machines" - + " and internal load balancer must be same. " - + "'" - + vmNicVnetId - + "'" - + "'" - + lbNetworkId)); + throw logger.logExceptionAsError( + new IllegalArgumentException("Virtual network associated with scale set virtual machines" + + " and internal load balancer must be same. " + "'" + vmNicVnetId + "'" + "'" + lbNetworkId)); } this.primaryInternalLoadBalancerToAttachOnUpdate = loadBalancer; } @@ -854,8 +810,8 @@ public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerBackends(String if (this.isInCreateMode()) { VirtualMachineScaleSetIpConfiguration defaultPrimaryIpConfig = primaryNicDefaultIpConfiguration(); removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, defaultPrimaryIpConfig); - associateBackEndsToIpConfiguration( - this.primaryInternalLoadBalancer.id(), defaultPrimaryIpConfig, backendNames); + associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancer.id(), defaultPrimaryIpConfig, + backendNames); } else { addToList(this.primaryInternalLBBackendsToAddOnUpdate, backendNames); } @@ -867,10 +823,10 @@ public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerInboundNatPools initVMProfileIfNecessary(); if (this.isInCreateMode()) { VirtualMachineScaleSetIpConfiguration defaultPrimaryIpConfig = this.primaryNicDefaultIpConfiguration(); - removeAllInboundNatPoolAssociationFromIpConfiguration( - this.primaryInternalLoadBalancer, defaultPrimaryIpConfig); - associateInboundNATPoolsToIpConfiguration( - this.primaryInternalLoadBalancer.id(), defaultPrimaryIpConfig, natPoolNames); + removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, + defaultPrimaryIpConfig); + associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancer.id(), defaultPrimaryIpConfig, + natPoolNames); } else { addToList(this.primaryInternalLBInboundNatPoolsToAddOnUpdate, natPoolNames); } @@ -924,16 +880,15 @@ public VirtualMachineScaleSetImpl withPopularWindowsImage(KnownWindowsVirtualMac @Override public VirtualMachineScaleSetImpl withLatestWindowsImage(String publisher, String offer, String sku) { - ImageReference imageReference = - new ImageReference().withPublisher(publisher).withOffer(offer).withSku(sku).withVersion("latest"); + ImageReference imageReference + = new ImageReference().withPublisher(publisher).withOffer(offer).withSku(sku).withVersion("latest"); return withSpecificWindowsImageVersion(imageReference); } @Override public VirtualMachineScaleSetImpl withSpecificWindowsImageVersion(ImageReference imageReference) { initVMProfileIfNecessary(); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -951,8 +906,7 @@ public VirtualMachineScaleSetImpl withGeneralizedWindowsCustomImage(String custo initVMProfileIfNecessary(); ImageReference imageReferenceInner = new ImageReference(); imageReferenceInner.withId(customImageId); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -977,8 +931,7 @@ public VirtualMachineScaleSetImpl withStoredWindowsImage(String imageUrl) { initVMProfileIfNecessary(); VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.withUri(imageUrl); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1000,16 +953,15 @@ public VirtualMachineScaleSetImpl withPopularLinuxImage(KnownLinuxVirtualMachine @Override public VirtualMachineScaleSetImpl withLatestLinuxImage(String publisher, String offer, String sku) { - ImageReference imageReference = - new ImageReference().withPublisher(publisher).withOffer(offer).withSku(sku).withVersion("latest"); + ImageReference imageReference + = new ImageReference().withPublisher(publisher).withOffer(offer).withSku(sku).withVersion("latest"); return withSpecificLinuxImageVersion(imageReference); } @Override public VirtualMachineScaleSetImpl withSpecificLinuxImageVersion(ImageReference imageReference) { initVMProfileIfNecessary(); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1025,8 +977,7 @@ public VirtualMachineScaleSetImpl withGeneralizedLinuxCustomImage(String customI initVMProfileIfNecessary(); ImageReference imageReferenceInner = new ImageReference(); imageReferenceInner.withId(customImageId); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1049,8 +1000,7 @@ public VirtualMachineScaleSetImpl withStoredLinuxImage(String imageUrl) { initVMProfileIfNecessary(); VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.withUri(imageUrl); - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1219,8 +1169,8 @@ public VirtualMachineScaleSetImpl withCapacity(long capacity) { @Override public VirtualMachineScaleSetImpl withNewStorageAccount(String name) { - StorageAccount.DefinitionStages.WithGroup definitionWithGroup = - this.storageManager.storageAccounts().define(name).withRegion(this.regionName()); + StorageAccount.DefinitionStages.WithGroup definitionWithGroup + = this.storageManager.storageAccounts().define(name).withRegion(this.regionName()); Creatable definitionAfterGroup; if (this.creatableGroup != null) { definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -1291,8 +1241,8 @@ public boolean isManagedDiskEnabled() { if (this.innerModel() == null || this.innerModel().virtualMachineProfile() == null) { return false; } - VirtualMachineScaleSetStorageProfile storageProfile = - this.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.innerModel().virtualMachineProfile().storageProfile(); if (isOsDiskFromCustomImage(storageProfile)) { return true; } @@ -1378,8 +1328,7 @@ public StorageAccountTypes managedOSDiskStorageAccountType() { && this.innerModel().virtualMachineProfile().storageProfile() != null && this.innerModel().virtualMachineProfile().storageProfile().osDisk() != null && this.innerModel().virtualMachineProfile().storageProfile().osDisk().managedDisk() != null) { - return this - .innerModel() + return this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1398,9 +1347,7 @@ public VirtualMachineScaleSetImpl withUnmanagedDisks() { @Override public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); - this - .managedDataDisks - .implicitDisksToAssociate + this.managedDataDisks.implicitDisksToAssociate .add(new VirtualMachineScaleSetDataDisk().withLun(-1).withDiskSizeGB(sizeInGB)); return this; } @@ -1408,29 +1355,22 @@ public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB) { @Override public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); - this - .managedDataDisks - .implicitDisksToAssociate + this.managedDataDisks.implicitDisksToAssociate .add(new VirtualMachineScaleSetDataDisk().withLun(lun).withDiskSizeGB(sizeInGB).withCaching(cachingType)); return this; } @Override - public VirtualMachineScaleSetImpl withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType) { + public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED); - VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = - new VirtualMachineScaleSetManagedDiskParameters(); + VirtualMachineScaleSetManagedDiskParameters managedDiskParameters + = new VirtualMachineScaleSetManagedDiskParameters(); managedDiskParameters.withStorageAccountType(storageAccountType); - this - .managedDataDisks - .implicitDisksToAssociate - .add( - new VirtualMachineScaleSetDataDisk() - .withLun(lun) - .withDiskSizeGB(sizeInGB) - .withCaching(cachingType) - .withManagedDisk(managedDiskParameters)); + this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk().withLun(lun) + .withDiskSizeGB(sizeInGB) + .withCaching(cachingType) + .withManagedDisk(managedDiskParameters)); return this; } @@ -1455,7 +1395,7 @@ public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB) .withDiskSizeGB(newSizeInGB); return this; } - + @Override public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, CachingTypes cachingType) { throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE); @@ -1468,7 +1408,7 @@ public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, .withCaching(cachingType); return this; } - + @Override public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, @@ -1486,7 +1426,7 @@ public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, .withStorageAccountType(storageAccountType); return this; } - + private VirtualMachineScaleSetDataDisk getDataDiskInner(int lun) { VirtualMachineScaleSetStorageProfile storageProfile = this .inner() @@ -1513,34 +1453,24 @@ public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun) { } @Override - public VirtualMachineScaleSetImpl withNewDataDiskFromImage( - int imageLun, int newSizeInGB, CachingTypes cachingType) { - this - .managedDataDisks - .newDisksFromImage - .add( - new VirtualMachineScaleSetDataDisk() - .withLun(imageLun) - .withDiskSizeGB(newSizeInGB) - .withCaching(cachingType)); + public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun, int newSizeInGB, + CachingTypes cachingType) { + this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk().withLun(imageLun) + .withDiskSizeGB(newSizeInGB) + .withCaching(cachingType)); return this; } @Override - public VirtualMachineScaleSetImpl withNewDataDiskFromImage( - int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) { - VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = - new VirtualMachineScaleSetManagedDiskParameters(); + public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, + StorageAccountTypes storageAccountType) { + VirtualMachineScaleSetManagedDiskParameters managedDiskParameters + = new VirtualMachineScaleSetManagedDiskParameters(); managedDiskParameters.withStorageAccountType(storageAccountType); - this - .managedDataDisks - .newDisksFromImage - .add( - new VirtualMachineScaleSetDataDisk() - .withLun(imageLun) - .withDiskSizeGB(newSizeInGB) - .withManagedDisk(managedDiskParameters) - .withCaching(cachingType)); + this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk().withLun(imageLun) + .withDiskSizeGB(newSizeInGB) + .withManagedDisk(managedDiskParameters) + .withCaching(cachingType)); return this; } @@ -1548,8 +1478,7 @@ public VirtualMachineScaleSetImpl withNewDataDiskFromImage( public VirtualMachineScaleSetImpl withOSDiskStorageAccountType(StorageAccountTypes accountType) { initVMProfileIfNecessary(); // withers is limited to VMSS based on ManagedDisk. - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .osDisk() @@ -1600,8 +1529,8 @@ public VirtualMachineScaleSetImpl withSystemAssignedIdentityBasedAccessTo(String } @Override - public VirtualMachineScaleSetImpl withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId) { + public VirtualMachineScaleSetImpl + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId) { this.virtualMachineScaleSetMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId); return this; } @@ -1644,28 +1573,25 @@ && isVMProfileNotSet()) { this.setOSDiskDefault(); } this.setPrimaryIpConfigurationSubnet(); - return this - .setPrimaryIpConfigurationBackendsAndInboundNatPoolsAsync() - .flatMap( - virtualMachineScaleSet -> { - if (isManagedDiskEnabled()) { - this.managedDataDisks.setDataDisksDefaults(); - } else { - List dataDisks = - this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); - VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name()); - } - this.handleUnManagedOSDiskContainers(); - this.bootDiagnosticsHandler.handleDiagnosticsSettings(); - this.virtualMachineScaleSetMsiHandler.processCreatedExternalIdentities(); - this.virtualMachineScaleSetMsiHandler.handleExternalIdentities(); - this.adjustProfileForFlexibleMode(); - return this.createNewProximityPlacementGroupAsync() - .then(this.manager() - .serviceClient() - .getVirtualMachineScaleSets() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); - }); + return this.setPrimaryIpConfigurationBackendsAndInboundNatPoolsAsync().flatMap(virtualMachineScaleSet -> { + if (isManagedDiskEnabled()) { + this.managedDataDisks.setDataDisksDefaults(); + } else { + List dataDisks + = this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); + VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name()); + } + this.handleUnManagedOSDiskContainers(); + this.bootDiagnosticsHandler.handleDiagnosticsSettings(); + this.virtualMachineScaleSetMsiHandler.processCreatedExternalIdentities(); + this.virtualMachineScaleSetMsiHandler.handleExternalIdentities(); + this.adjustProfileForFlexibleMode(); + return this.createNewProximityPlacementGroupAsync() + .then(this.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); + }); } @Override @@ -1688,69 +1614,55 @@ public Mono updateResourceAsync() { this.setOSDiskDefault(); } this.setPrimaryIpConfigurationSubnet(); - return this - .setPrimaryIpConfigurationBackendsAndInboundNatPoolsAsync() - .map( - virtualMachineScaleSet -> { - if (isManagedDiskEnabled()) { - this.managedDataDisks.setDataDisksDefaults(); - } else if (this.innerModel() != null - && this.innerModel().virtualMachineProfile() != null) { - List dataDisks = - this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); - VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name()); - } - this.handleUnManagedOSDiskContainers(); - this.bootDiagnosticsHandler.handleDiagnosticsSettings(); - this.virtualMachineScaleSetMsiHandler.processCreatedExternalIdentities(); - this.adjustProfileForFlexibleMode(); - // - VirtualMachineScaleSetUpdate updateParameter = VMSSPatchPayload.preparePatchPayload(this); - // - this.virtualMachineScaleSetMsiHandler.handleExternalIdentities(updateParameter); - return updateParameter; - }) - .flatMap( - updateParameter -> - this - .manager() - .serviceClient() - .getVirtualMachineScaleSets() - .updateAsync(resourceGroupName(), name(), updateParameter) - .map( - vmssInner -> { - setInner(vmssInner); - self.clearCachedProperties(); - self.initializeChildrenFromInner(); - self.virtualMachineScaleSetMsiHandler.clear(); - return self; - })); + return this.setPrimaryIpConfigurationBackendsAndInboundNatPoolsAsync().map(virtualMachineScaleSet -> { + if (isManagedDiskEnabled()) { + this.managedDataDisks.setDataDisksDefaults(); + } else if (this.innerModel() != null && this.innerModel().virtualMachineProfile() != null) { + List dataDisks + = this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); + VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name()); + } + this.handleUnManagedOSDiskContainers(); + this.bootDiagnosticsHandler.handleDiagnosticsSettings(); + this.virtualMachineScaleSetMsiHandler.processCreatedExternalIdentities(); + this.adjustProfileForFlexibleMode(); + // + VirtualMachineScaleSetUpdate updateParameter = VMSSPatchPayload.preparePatchPayload(this); + // + this.virtualMachineScaleSetMsiHandler.handleExternalIdentities(updateParameter); + return updateParameter; + }) + .flatMap(updateParameter -> this.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .updateAsync(resourceGroupName(), name(), updateParameter) + .map(vmssInner -> { + setInner(vmssInner); + self.clearCachedProperties(); + self.initializeChildrenFromInner(); + self.virtualMachineScaleSetMsiHandler.clear(); + return self; + })); } @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - scaleSet -> { - VirtualMachineScaleSetImpl impl = (VirtualMachineScaleSetImpl) scaleSet; - impl.clearCachedProperties(); - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(scaleSet -> { + VirtualMachineScaleSetImpl impl = (VirtualMachineScaleSetImpl) scaleSet; + impl.clearCachedProperties(); + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualMachineScaleSets() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } - - // Helpers // @@ -1761,19 +1673,25 @@ private boolean isVMProfileNotSet() { private void adjustProfileForFlexibleMode() { if (this.orchestrationMode() == OrchestrationMode.FLEXIBLE) { if (this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations() != null) { - this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations().forEach(virtualMachineScaleSetNetworkConfiguration -> { - if (virtualMachineScaleSetNetworkConfiguration.ipConfigurations() != null) { - virtualMachineScaleSetNetworkConfiguration.ipConfigurations().forEach(virtualMachineScaleSetIpConfiguration -> { - // this property is not allowed to appear when creating vmss in flexible mode, though it's defined in the swagger file - virtualMachineScaleSetIpConfiguration.withLoadBalancerInboundNatPools(null); - }); - } - }); + this.innerModel() + .virtualMachineProfile() + .networkProfile() + .networkInterfaceConfigurations() + .forEach(virtualMachineScaleSetNetworkConfiguration -> { + if (virtualMachineScaleSetNetworkConfiguration.ipConfigurations() != null) { + virtualMachineScaleSetNetworkConfiguration.ipConfigurations() + .forEach(virtualMachineScaleSetIpConfiguration -> { + // this property is not allowed to appear when creating vmss in flexible mode, though it's defined in the swagger file + virtualMachineScaleSetIpConfiguration.withLoadBalancerInboundNatPools(null); + }); + } + }); } this.innerModel() // upgradePolicy is not supported in flexible vmss .withUpgradePolicy(null) - .virtualMachineProfile().networkProfile() + .virtualMachineProfile() + .networkProfile() // NetworkApiVersion must be specified when creating in flexible mode .withNetworkApiVersion(NetworkApiVersion.TWO_ZERO_TWO_ZERO_ONE_ONE_ZERO_ONE); } @@ -1781,25 +1699,22 @@ private void adjustProfileForFlexibleMode() { private Mono createInnerNoProfile() { this.innerModel().withVirtualMachineProfile(null); - return manager() - .serviceClient() - .getVirtualMachineScaleSets() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); + return manager().serviceClient() + .getVirtualMachineScaleSets() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); } private Mono updateResourceAsyncNoProfile(VirtualMachineScaleSetImpl self) { - return manager() - .serviceClient() + return manager().serviceClient() .getVirtualMachineScaleSets() .updateAsync(resourceGroupName(), name(), VMSSPatchPayload.preparePatchPayload(this)) - .map( - vmssInner -> { - setInner(vmssInner); - self.clearCachedProperties(); - self.initializeChildrenFromInner(); - self.virtualMachineScaleSetMsiHandler.clear(); - return self; - }); + .map(vmssInner -> { + setInner(vmssInner); + self.clearCachedProperties(); + self.initializeChildrenFromInner(); + self.virtualMachineScaleSetMsiHandler.clear(); + return self; + }); } private void initVMProfileIfNecessary() { @@ -1810,9 +1725,8 @@ private void initVMProfileIfNecessary() { } private VirtualMachineScaleSetVMProfile initDefaultVMProfile() { - VirtualMachineScaleSetImpl impl = (VirtualMachineScaleSetImpl) this.manager() - .virtualMachineScaleSets() - .define(this.name()); + VirtualMachineScaleSetImpl impl + = (VirtualMachineScaleSetImpl) this.manager().virtualMachineScaleSets().define(this.name()); if (this.orchestrationMode() == OrchestrationMode.FLEXIBLE) { if (this.innerModel().platformFaultDomainCount() != null) { impl.withFlexibleOrchestrationMode(this.innerModel().platformFaultDomainCount()); @@ -1862,8 +1776,8 @@ private void setOSProfileDefaults() { } private void setOSDiskDefault() { - VirtualMachineScaleSetStorageProfile storageProfile = - this.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.innerModel().virtualMachineProfile().storageProfile(); VirtualMachineScaleSetOSDisk osDisk = storageProfile.osDisk(); if (isOSDiskFromImage(osDisk)) { // ODDisk CreateOption: FROM_IMAGE @@ -1907,16 +1821,14 @@ private void setOSDiskDefault() { * @return */ private boolean shouldSetProfileDefaults() { - return isInCreateMode() - || (this.orchestrationMode() == OrchestrationMode.FLEXIBLE && this.profileAttached); + return isInCreateMode() || (this.orchestrationMode() == OrchestrationMode.FLEXIBLE && this.profileAttached); } private void setExtensions() { if (this.extensions.size() > 0 && this.innerModel() != null && this.innerModel().virtualMachineProfile() != null) { - this - .innerModel() + this.innerModel() .virtualMachineProfile() .withExtensionProfile(new VirtualMachineScaleSetExtensionProfile()) .extensionProfile() @@ -1936,8 +1848,8 @@ protected void prepareOSDiskContainers() { if (this.innerModel() == null || this.innerModel().virtualMachineProfile() == null || isManagedDiskEnabled()) { return; } - final VirtualMachineScaleSetStorageProfile storageProfile = - innerModel().virtualMachineProfile().storageProfile(); + final VirtualMachineScaleSetStorageProfile storageProfile + = innerModel().virtualMachineProfile().storageProfile(); if (isOSDiskFromStoredImage(storageProfile)) { // There is a restriction currently that virtual machine's disk cannot be stored in multiple storage // accounts if scale set is based on stored image. Remove this check once azure start supporting it. @@ -1950,21 +1862,15 @@ protected void prepareOSDiskContainers() { String accountName = this.namer.getRandomName("stg", 24).replace("-", ""); Creatable storageAccountCreatable; if (this.creatableGroup != null) { - storageAccountCreatable = - this - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.regionName()) - .withNewResourceGroup(this.creatableGroup); + storageAccountCreatable = this.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.regionName()) + .withNewResourceGroup(this.creatableGroup); } else { - storageAccountCreatable = - this - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.regionName()) - .withExistingResourceGroup(this.resourceGroupName()); + storageAccountCreatable = this.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.regionName()) + .withExistingResourceGroup(this.resourceGroupName()); } this.creatableStorageAccountKeys.add(this.addDependency(storageAccountCreatable)); } @@ -1974,8 +1880,8 @@ private void handleUnManagedOSDiskContainers() { if (this.innerModel() == null || this.innerModel().virtualMachineProfile() == null) { return; } - final VirtualMachineScaleSetStorageProfile storageProfile = - innerModel().virtualMachineProfile().storageProfile(); + final VirtualMachineScaleSetStorageProfile storageProfile + = innerModel().virtualMachineProfile().storageProfile(); if (isManagedDiskEnabled()) { storageProfile.osDisk().withVhdContainers(null); return; @@ -2001,22 +1907,19 @@ private void handleUnManagedOSDiskContainers() { if (isInCreateMode() && this.creatableStorageAccountKeys.isEmpty() && this.existingStorageAccountsToAssociate.isEmpty()) { - throw logger - .logExceptionAsError( - new IllegalStateException("Expected storage account(s) for VMSS OS disk containers not found")); + throw logger.logExceptionAsError( + new IllegalStateException("Expected storage account(s) for VMSS OS disk containers not found")); } for (String storageAccountKey : this.creatableStorageAccountKeys) { StorageAccount storageAccount = this.taskResult(storageAccountKey); - storageProfile - .osDisk() + storageProfile.osDisk() .vhdContainers() .add(mergePath(storageAccount.endPoints().primary().blob(), containerName)); } for (StorageAccount storageAccount : this.existingStorageAccountsToAssociate) { - storageProfile - .osDisk() + storageProfile.osDisk() .vhdContainers() .add(mergePath(storageAccount.endPoints().primary().blob(), containerName)); } @@ -2040,135 +1943,110 @@ private Mono setPrimaryIpConfigurationBackendsAndInb } try { - return this - .loadCurrentPrimaryLoadBalancersIfAvailableAsync() - .map( - virtualMachineScaleSet -> { - initVMProfileIfNecessary(); - VirtualMachineScaleSetIpConfiguration primaryIpConfig = primaryNicDefaultIpConfiguration(); - if (this.primaryInternetFacingLoadBalancer != null) { - removeBackendsFromIpConfiguration( - this.primaryInternetFacingLoadBalancer.id(), - primaryIpConfig, - this.primaryInternetFacingLBBackendsToRemoveOnUpdate.toArray(new String[0])); - - associateBackEndsToIpConfiguration( - primaryInternetFacingLoadBalancer.id(), - primaryIpConfig, - this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0])); - - removeInboundNatPoolsFromIpConfiguration( - this.primaryInternetFacingLoadBalancer.id(), - primaryIpConfig, - this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0])); - - associateInboundNATPoolsToIpConfiguration( - primaryInternetFacingLoadBalancer.id(), - primaryIpConfig, - this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); - } + return this.loadCurrentPrimaryLoadBalancersIfAvailableAsync().map(virtualMachineScaleSet -> { + initVMProfileIfNecessary(); + VirtualMachineScaleSetIpConfiguration primaryIpConfig = primaryNicDefaultIpConfiguration(); + if (this.primaryInternetFacingLoadBalancer != null) { + removeBackendsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(), primaryIpConfig, + this.primaryInternetFacingLBBackendsToRemoveOnUpdate.toArray(new String[0])); + + associateBackEndsToIpConfiguration(primaryInternetFacingLoadBalancer.id(), primaryIpConfig, + this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0])); + + removeInboundNatPoolsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(), + primaryIpConfig, + this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0])); + + associateInboundNATPoolsToIpConfiguration(primaryInternetFacingLoadBalancer.id(), primaryIpConfig, + this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); + } - if (this.primaryInternalLoadBalancer != null) { - removeBackendsFromIpConfiguration( - this.primaryInternalLoadBalancer.id(), - primaryIpConfig, - this.primaryInternalLBBackendsToRemoveOnUpdate.toArray(new String[0])); - - associateBackEndsToIpConfiguration( - primaryInternalLoadBalancer.id(), - primaryIpConfig, - this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0])); - - removeInboundNatPoolsFromIpConfiguration( - this.primaryInternalLoadBalancer.id(), - primaryIpConfig, - this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0])); - - associateInboundNATPoolsToIpConfiguration( - primaryInternalLoadBalancer.id(), - primaryIpConfig, - this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); - } + if (this.primaryInternalLoadBalancer != null) { + removeBackendsFromIpConfiguration(this.primaryInternalLoadBalancer.id(), primaryIpConfig, + this.primaryInternalLBBackendsToRemoveOnUpdate.toArray(new String[0])); - if (this.removePrimaryInternetFacingLoadBalancerOnUpdate) { - if (this.primaryInternetFacingLoadBalancer != null) { - removeLoadBalancerAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancer, primaryIpConfig); - } - } + associateBackEndsToIpConfiguration(primaryInternalLoadBalancer.id(), primaryIpConfig, + this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0])); - if (this.removePrimaryInternalLoadBalancerOnUpdate) { - if (this.primaryInternalLoadBalancer != null) { - removeLoadBalancerAssociationFromIpConfiguration( - this.primaryInternalLoadBalancer, primaryIpConfig); - } - } + removeInboundNatPoolsFromIpConfiguration(this.primaryInternalLoadBalancer.id(), primaryIpConfig, + this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0])); - if (this.primaryInternetFacingLoadBalancerToAttachOnUpdate != null) { - if (this.primaryInternetFacingLoadBalancer != null) { - removeLoadBalancerAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancer, primaryIpConfig); - } - associateLoadBalancerToIpConfiguration( - this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig); - if (!this.primaryInternetFacingLBBackendsToAddOnUpdate.isEmpty()) { - removeAllBackendAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig); - associateBackEndsToIpConfiguration( - this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(), - primaryIpConfig, - this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0])); - } - if (!this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.isEmpty()) { - removeAllInboundNatPoolAssociationFromIpConfiguration( - this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig); - associateInboundNATPoolsToIpConfiguration( - this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(), - primaryIpConfig, - this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); - } - } + associateInboundNATPoolsToIpConfiguration(primaryInternalLoadBalancer.id(), primaryIpConfig, + this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); + } - if (this.primaryInternalLoadBalancerToAttachOnUpdate != null) { - if (this.primaryInternalLoadBalancer != null) { - removeLoadBalancerAssociationFromIpConfiguration( - this.primaryInternalLoadBalancer, primaryIpConfig); - } - associateLoadBalancerToIpConfiguration( - this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig); - if (!this.primaryInternalLBBackendsToAddOnUpdate.isEmpty()) { - removeAllBackendAssociationFromIpConfiguration( - this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig); - associateBackEndsToIpConfiguration( - this.primaryInternalLoadBalancerToAttachOnUpdate.id(), - primaryIpConfig, - this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0])); - } - - if (!this.primaryInternalLBInboundNatPoolsToAddOnUpdate.isEmpty()) { - removeAllInboundNatPoolAssociationFromIpConfiguration( - this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig); - associateInboundNATPoolsToIpConfiguration( - this.primaryInternalLoadBalancerToAttachOnUpdate.id(), - primaryIpConfig, - this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); - } - } + if (this.removePrimaryInternetFacingLoadBalancerOnUpdate) { + if (this.primaryInternetFacingLoadBalancer != null) { + removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, + primaryIpConfig); + } + } - this.removePrimaryInternetFacingLoadBalancerOnUpdate = false; - this.removePrimaryInternalLoadBalancerOnUpdate = false; - this.primaryInternetFacingLoadBalancerToAttachOnUpdate = null; - this.primaryInternalLoadBalancerToAttachOnUpdate = null; - this.primaryInternetFacingLBBackendsToRemoveOnUpdate.clear(); - this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.clear(); - this.primaryInternalLBBackendsToRemoveOnUpdate.clear(); - this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.clear(); - this.primaryInternetFacingLBBackendsToAddOnUpdate.clear(); - this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.clear(); - this.primaryInternalLBBackendsToAddOnUpdate.clear(); - this.primaryInternalLBInboundNatPoolsToAddOnUpdate.clear(); - return this; - }); + if (this.removePrimaryInternalLoadBalancerOnUpdate) { + if (this.primaryInternalLoadBalancer != null) { + removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, + primaryIpConfig); + } + } + + if (this.primaryInternetFacingLoadBalancerToAttachOnUpdate != null) { + if (this.primaryInternetFacingLoadBalancer != null) { + removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, + primaryIpConfig); + } + associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, + primaryIpConfig); + if (!this.primaryInternetFacingLBBackendsToAddOnUpdate.isEmpty()) { + removeAllBackendAssociationFromIpConfiguration( + this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig); + associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(), + primaryIpConfig, this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0])); + } + if (!this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.isEmpty()) { + removeAllInboundNatPoolAssociationFromIpConfiguration( + this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig); + associateInboundNATPoolsToIpConfiguration( + this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(), primaryIpConfig, + this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); + } + } + + if (this.primaryInternalLoadBalancerToAttachOnUpdate != null) { + if (this.primaryInternalLoadBalancer != null) { + removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, + primaryIpConfig); + } + associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, + primaryIpConfig); + if (!this.primaryInternalLBBackendsToAddOnUpdate.isEmpty()) { + removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, + primaryIpConfig); + associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(), + primaryIpConfig, this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0])); + } + + if (!this.primaryInternalLBInboundNatPoolsToAddOnUpdate.isEmpty()) { + removeAllInboundNatPoolAssociationFromIpConfiguration( + this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig); + associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(), + primaryIpConfig, this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0])); + } + } + + this.removePrimaryInternetFacingLoadBalancerOnUpdate = false; + this.removePrimaryInternalLoadBalancerOnUpdate = false; + this.primaryInternetFacingLoadBalancerToAttachOnUpdate = null; + this.primaryInternalLoadBalancerToAttachOnUpdate = null; + this.primaryInternetFacingLBBackendsToRemoveOnUpdate.clear(); + this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.clear(); + this.primaryInternalLBBackendsToRemoveOnUpdate.clear(); + this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.clear(); + this.primaryInternetFacingLBBackendsToAddOnUpdate.clear(); + this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.clear(); + this.primaryInternalLBBackendsToAddOnUpdate.clear(); + this.primaryInternalLBInboundNatPoolsToAddOnUpdate.clear(); + return this; + }); } catch (IOException ioException) { throw logger.logExceptionAsError(new RuntimeException(ioException)); } @@ -2192,41 +2070,28 @@ private Mono loadCurrentPrimaryLoadBalancersIfAvaila return self; } if (!ipConfig.loadBalancerBackendAddressPools().isEmpty()) { - firstLoadBalancerId = - ResourceUtils.parentResourceIdFromResourceId(ipConfig.loadBalancerBackendAddressPools().get(0).id()); + firstLoadBalancerId + = ResourceUtils.parentResourceIdFromResourceId(ipConfig.loadBalancerBackendAddressPools().get(0).id()); } if (firstLoadBalancerId == null && !ipConfig.loadBalancerInboundNatPools().isEmpty()) { - firstLoadBalancerId = - ResourceUtils.parentResourceIdFromResourceId(ipConfig.loadBalancerInboundNatPools().get(0).id()); + firstLoadBalancerId + = ResourceUtils.parentResourceIdFromResourceId(ipConfig.loadBalancerInboundNatPools().get(0).id()); } if (firstLoadBalancerId == null) { return self; } - self = - self - .concatWith( - Mono - .just(firstLoadBalancerId) - .flatMap( - id -> - this - .networkManager - .loadBalancers() - .getByIdAsync(id) - .map( - loadBalancer1 -> { - if (loadBalancer1.publicIpAddressIds() != null - && loadBalancer1.publicIpAddressIds().size() > 0) { - this.primaryInternetFacingLoadBalancer = loadBalancer1; - } else { - this.primaryInternalLoadBalancer = loadBalancer1; - } - return this; - }))) - .last(); + self = self.concatWith(Mono.just(firstLoadBalancerId) + .flatMap(id -> this.networkManager.loadBalancers().getByIdAsync(id).map(loadBalancer1 -> { + if (loadBalancer1.publicIpAddressIds() != null && loadBalancer1.publicIpAddressIds().size() > 0) { + this.primaryInternetFacingLoadBalancer = loadBalancer1; + } else { + this.primaryInternalLoadBalancer = loadBalancer1; + } + return this; + }))).last(); String secondLoadBalancerId = null; for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) { @@ -2238,8 +2103,7 @@ private Mono loadCurrentPrimaryLoadBalancersIfAvaila if (secondLoadBalancerId == null) { for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) { - if (!subResource - .id() + if (!subResource.id() .toLowerCase(Locale.ROOT) .startsWith(firstLoadBalancerId.toLowerCase(Locale.ROOT))) { secondLoadBalancerId = ResourceUtils.parentResourceIdFromResourceId(subResource.id()); @@ -2252,34 +2116,23 @@ private Mono loadCurrentPrimaryLoadBalancersIfAvaila return self; } - return self - .concatWith( - Mono - .just(secondLoadBalancerId) - .flatMap( - id -> - networkManager - .loadBalancers() - .getByIdAsync(id) - .map( - loadBalancer2 -> { - if (loadBalancer2.publicIpAddressIds() != null - && loadBalancer2.publicIpAddressIds().size() > 0) { - this.primaryInternetFacingLoadBalancer = loadBalancer2; - } else { - this.primaryInternalLoadBalancer = loadBalancer2; - } - return this; - }))) - .last(); + return self.concatWith(Mono.just(secondLoadBalancerId) + .flatMap(id -> networkManager.loadBalancers().getByIdAsync(id).map(loadBalancer2 -> { + if (loadBalancer2.publicIpAddressIds() != null && loadBalancer2.publicIpAddressIds().size() > 0) { + this.primaryInternetFacingLoadBalancer = loadBalancer2; + } else { + this.primaryInternalLoadBalancer = loadBalancer2; + } + return this; + }))).last(); } private VirtualMachineScaleSetIpConfiguration primaryNicDefaultIpConfiguration() { if (this.innerModel() == null || this.innerModel().virtualMachineProfile() == null) { return null; } - List nicConfigurations = - this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations(); + List nicConfigurations + = this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations(); for (VirtualMachineScaleSetNetworkConfiguration nicConfiguration : nicConfigurations) { if (nicConfiguration.primary()) { @@ -2295,17 +2148,16 @@ private VirtualMachineScaleSetIpConfiguration primaryNicDefaultIpConfiguration() } } } - throw logger - .logExceptionAsError( - new RuntimeException("Could not find the primary nic configuration or an IP configuration in it")); + throw logger.logExceptionAsError( + new RuntimeException("Could not find the primary nic configuration or an IP configuration in it")); } private VirtualMachineScaleSetNetworkConfiguration primaryNicConfiguration() { if (this.innerModel() == null || this.innerModel().virtualMachineProfile() == null) { return null; } - List nicConfigurations = - this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations(); + List nicConfigurations + = this.innerModel().virtualMachineProfile().networkProfile().networkInterfaceConfigurations(); for (VirtualMachineScaleSetNetworkConfiguration nicConfiguration : nicConfigurations) { if (nicConfiguration.primary()) { @@ -2315,8 +2167,8 @@ private VirtualMachineScaleSetNetworkConfiguration primaryNicConfiguration() { throw logger.logExceptionAsError(new RuntimeException("Could not find the primary nic configuration")); } - private static void associateBackEndsToIpConfiguration( - String loadBalancerId, VirtualMachineScaleSetIpConfiguration ipConfig, String... backendNames) { + private static void associateBackEndsToIpConfiguration(String loadBalancerId, + VirtualMachineScaleSetIpConfiguration ipConfig, String... backendNames) { if (ipConfig == null || ipConfig.loadBalancerBackendAddressPools() == null) { return; } @@ -2341,8 +2193,8 @@ private static void associateBackEndsToIpConfiguration( } } - private static void associateInboundNATPoolsToIpConfiguration( - String loadBalancerId, VirtualMachineScaleSetIpConfiguration ipConfig, String... inboundNatPools) { + private static void associateInboundNATPoolsToIpConfiguration(String loadBalancerId, + VirtualMachineScaleSetIpConfiguration ipConfig, String... inboundNatPools) { List inboundNatPoolSubResourcesToAssociate = new ArrayList<>(); for (String inboundNatPool : inboundNatPools) { String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", inboundNatPool); @@ -2363,8 +2215,8 @@ private static void associateInboundNATPoolsToIpConfiguration( } } - private static Map getBackendsAssociatedWithIpConfiguration( - LoadBalancer loadBalancer, VirtualMachineScaleSetIpConfiguration ipConfig) { + private static Map getBackendsAssociatedWithIpConfiguration(LoadBalancer loadBalancer, + VirtualMachineScaleSetIpConfiguration ipConfig) { if (ipConfig == null || ipConfig.loadBalancerBackendAddressPools() == null) { return Collections.emptyMap(); } @@ -2401,8 +2253,8 @@ private static Map getInboundNatPoolsAssocia return attachedInboundNatPools; } - private static void associateLoadBalancerToIpConfiguration( - LoadBalancer loadBalancer, VirtualMachineScaleSetIpConfiguration ipConfig) { + private static void associateLoadBalancerToIpConfiguration(LoadBalancer loadBalancer, + VirtualMachineScaleSetIpConfiguration ipConfig) { Collection backends = loadBalancer.backends().values(); String[] backendNames = new String[backends.size()]; int i = 0; @@ -2424,21 +2276,20 @@ private static void associateLoadBalancerToIpConfiguration( associateInboundNATPoolsToIpConfiguration(loadBalancer.id(), ipConfig, natPoolNames); } - private static void removeLoadBalancerAssociationFromIpConfiguration( - LoadBalancer loadBalancer, VirtualMachineScaleSetIpConfiguration ipConfig) { + private static void removeLoadBalancerAssociationFromIpConfiguration(LoadBalancer loadBalancer, + VirtualMachineScaleSetIpConfiguration ipConfig) { removeAllBackendAssociationFromIpConfiguration(loadBalancer, ipConfig); removeAllInboundNatPoolAssociationFromIpConfiguration(loadBalancer, ipConfig); } - private static void removeAllBackendAssociationFromIpConfiguration( - LoadBalancer loadBalancer, VirtualMachineScaleSetIpConfiguration ipConfig) { + private static void removeAllBackendAssociationFromIpConfiguration(LoadBalancer loadBalancer, + VirtualMachineScaleSetIpConfiguration ipConfig) { if (ipConfig == null || ipConfig.loadBalancerBackendAddressPools() == null) { return; } List toRemove = new ArrayList<>(); for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) { - if (subResource - .id() + if (subResource.id() .toLowerCase(Locale.ROOT) .startsWith(loadBalancer.id().toLowerCase(Locale.ROOT) + "/")) { toRemove.add(subResource); @@ -2450,15 +2301,14 @@ private static void removeAllBackendAssociationFromIpConfiguration( } } - private static void removeAllInboundNatPoolAssociationFromIpConfiguration( - LoadBalancer loadBalancer, VirtualMachineScaleSetIpConfiguration ipConfig) { + private static void removeAllInboundNatPoolAssociationFromIpConfiguration(LoadBalancer loadBalancer, + VirtualMachineScaleSetIpConfiguration ipConfig) { if (ipConfig == null || ipConfig.loadBalancerInboundNatPools() == null) { return; } List toRemove = new ArrayList<>(); for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) { - if (subResource - .id() + if (subResource.id() .toLowerCase(Locale.ROOT) .startsWith(loadBalancer.id().toLowerCase(Locale.ROOT) + "/")) { toRemove.add(subResource); @@ -2470,8 +2320,8 @@ private static void removeAllInboundNatPoolAssociationFromIpConfiguration( } } - private static void removeBackendsFromIpConfiguration( - String loadBalancerId, VirtualMachineScaleSetIpConfiguration ipConfig, String... backendNames) { + private static void removeBackendsFromIpConfiguration(String loadBalancerId, + VirtualMachineScaleSetIpConfiguration ipConfig, String... backendNames) { if (ipConfig == null || ipConfig.loadBalancerBackendAddressPools() == null) { return; } @@ -2491,8 +2341,8 @@ private static void removeBackendsFromIpConfiguration( } } - private static void removeInboundNatPoolsFromIpConfiguration( - String loadBalancerId, VirtualMachineScaleSetIpConfiguration ipConfig, String... inboundNatPoolNames) { + private static void removeInboundNatPoolsFromIpConfiguration(String loadBalancerId, + VirtualMachineScaleSetIpConfiguration ipConfig, String... inboundNatPoolNames) { if (ipConfig == null || ipConfig.loadBalancerInboundNatPools() == null) { return; } @@ -2558,18 +2408,17 @@ public String resourceId() { }; } - protected VirtualMachineScaleSetImpl withUnmanagedDataDisk( - VirtualMachineScaleSetUnmanagedDataDiskImpl unmanagedDisk) { + protected VirtualMachineScaleSetImpl + withUnmanagedDataDisk(VirtualMachineScaleSetUnmanagedDataDiskImpl unmanagedDisk) { initVMProfileIfNecessary(); if (this.innerModel().virtualMachineProfile().storageProfile().dataDisks() == null) { - this - .innerModel() + this.innerModel() .virtualMachineProfile() .storageProfile() .withDataDisks(new ArrayList()); } - List dataDisks = - this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); + List dataDisks + = this.innerModel().virtualMachineProfile().storageProfile().dataDisks(); dataDisks.add(unmanagedDisk.innerModel()); return this; } @@ -2724,8 +2573,8 @@ public VirtualMachineScaleSetImpl withVirtualMachinePublicIp() { if (nicIpConfig.publicIpAddressConfiguration() != null) { return this; } else { - VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig = - new VirtualMachineScaleSetPublicIpAddressConfiguration(); + VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig + = new VirtualMachineScaleSetPublicIpAddressConfiguration(); pipConfig.withName("pip1"); pipConfig.withIdleTimeoutInMinutes(15); // @@ -2742,14 +2591,13 @@ public VirtualMachineScaleSetImpl withVirtualMachinePublicIp(String leafDomainLa if (nicIpConfig.publicIpAddressConfiguration().dnsSettings() != null) { nicIpConfig.publicIpAddressConfiguration().dnsSettings().withDomainNameLabel(leafDomainLabel); } else { - nicIpConfig - .publicIpAddressConfiguration() + nicIpConfig.publicIpAddressConfiguration() .withDnsSettings(new VirtualMachineScaleSetPublicIpAddressConfigurationDnsSettings()); nicIpConfig.publicIpAddressConfiguration().dnsSettings().withDomainNameLabel(leafDomainLabel); } } else { - VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig = - new VirtualMachineScaleSetPublicIpAddressConfiguration(); + VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig + = new VirtualMachineScaleSetPublicIpAddressConfiguration(); pipConfig.withName("pip1"); pipConfig.withIdleTimeoutInMinutes(15); pipConfig.withDnsSettings(new VirtualMachineScaleSetPublicIpAddressConfigurationDnsSettings()); @@ -2760,8 +2608,8 @@ public VirtualMachineScaleSetImpl withVirtualMachinePublicIp(String leafDomainLa } @Override - public VirtualMachineScaleSetImpl withVirtualMachinePublicIp( - VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig) { + public VirtualMachineScaleSetImpl + withVirtualMachinePublicIp(VirtualMachineScaleSetPublicIpAddressConfiguration pipConfig) { initVMProfileIfNecessary(); VirtualMachineScaleSetIpConfiguration nicIpConfig = this.primaryNicDefaultIpConfiguration(); nicIpConfig.withPublicIpAddressConfiguration(pipConfig); @@ -2883,8 +2731,8 @@ public VirtualMachineScaleSetImpl withoutApplicationGatewayBackendPool(String ba } @Override - public VirtualMachineScaleSetImpl withExistingApplicationSecurityGroup( - ApplicationSecurityGroup applicationSecurityGroup) { + public VirtualMachineScaleSetImpl + withExistingApplicationSecurityGroup(ApplicationSecurityGroup applicationSecurityGroup) { return withExistingApplicationSecurityGroupId(applicationSecurityGroup.id()); } @@ -2938,8 +2786,8 @@ public VirtualMachineScaleSetImpl withProximityPlacementGroup(String proximityPl } @Override - public VirtualMachineScaleSetImpl withNewProximityPlacementGroup( - String proximityPlacementGroupName, ProximityPlacementGroupType type) { + public VirtualMachineScaleSetImpl withNewProximityPlacementGroup(String proximityPlacementGroupName, + ProximityPlacementGroupType type) { this.newProximityPlacementGroupName = proximityPlacementGroupName; this.newProximityPlacementGroupType = type; @@ -2949,8 +2797,8 @@ public VirtualMachineScaleSetImpl withNewProximityPlacementGroup( } @Override - public VirtualMachineScaleSetImpl withDoNotRunExtensionsOnOverprovisionedVMs( - Boolean doNotRunExtensionsOnOverprovisionedVMs) { + public VirtualMachineScaleSetImpl + withDoNotRunExtensionsOnOverprovisionedVMs(Boolean doNotRunExtensionsOnOverprovisionedVMs) { this.innerModel().withDoNotRunExtensionsOnOverprovisionedVMs(doNotRunExtensionsOnOverprovisionedVMs); return this; } @@ -2967,8 +2815,7 @@ private Mono createNewProximityPlacementGroupAsync() ProximityPlacementGroupInner plgInner = new ProximityPlacementGroupInner(); plgInner.withProximityPlacementGroupType(this.newProximityPlacementGroupType); plgInner.withLocation(this.innerModel().location()); - return this - .manager() + return this.manager() .serviceClient() .getProximityPlacementGroups() .createOrUpdateAsync(this.resourceGroupName(), this.newProximityPlacementGroupName, plgInner) @@ -3021,8 +2868,8 @@ void setDataDisksDefaults() { if (this.vmss.innerModel() == null || this.vmss.innerModel().virtualMachineProfile() == null) { return; } - VirtualMachineScaleSetStorageProfile storageProfile = - this.vmss.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.vmss.innerModel().virtualMachineProfile().storageProfile(); if (isPending()) { if (storageProfile.dataDisks() == null) { storageProfile.withDataDisks(new ArrayList<>()); @@ -3048,15 +2895,14 @@ void setDataDisksDefaults() { } // Func to get the next available lun // - Callable nextLun = - () -> { - Integer lun = 0; - while (usedLuns.contains(lun)) { - lun++; - } - usedLuns.add(lun); - return lun; - }; + Callable nextLun = () -> { + Integer lun = 0; + while (usedLuns.contains(lun)) { + lun++; + } + usedLuns.add(lun); + return lun; + }; try { setImplicitDataDisks(nextLun); } catch (Exception ex) { @@ -3091,8 +2937,8 @@ private void setImplicitDataDisks(Callable nextLun) throws Exception { if (this.vmss.innerModel() == null || this.vmss.innerModel().virtualMachineProfile() == null) { return; } - VirtualMachineScaleSetStorageProfile storageProfile = - this.vmss.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.vmss.innerModel().virtualMachineProfile().storageProfile(); List dataDisks = storageProfile.dataDisks(); for (VirtualMachineScaleSetDataDisk dataDisk : this.implicitDisksToAssociate) { dataDisk.withCreateOption(DiskCreateOptionTypes.EMPTY); @@ -3117,8 +2963,8 @@ private void setImageBasedDataDisks() { if (this.vmss.innerModel() == null || this.vmss.innerModel().virtualMachineProfile() == null) { return; } - VirtualMachineScaleSetStorageProfile storageProfile = - this.vmss.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.vmss.innerModel().virtualMachineProfile().storageProfile(); List dataDisks = storageProfile.dataDisks(); for (VirtualMachineScaleSetDataDisk dataDisk : this.newDisksFromImage) { dataDisk.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE); @@ -3133,8 +2979,8 @@ private void removeDataDisks() { if (this.vmss.innerModel() == null || this.vmss.innerModel().virtualMachineProfile() == null) { return; } - VirtualMachineScaleSetStorageProfile storageProfile = - this.vmss.innerModel().virtualMachineProfile().storageProfile(); + VirtualMachineScaleSetStorageProfile storageProfile + = this.vmss.innerModel().virtualMachineProfile().storageProfile(); List dataDisks = storageProfile.dataDisks(); for (Integer lun : this.diskLunsToRemove) { int indexToRemove = 0; @@ -3176,8 +3022,8 @@ private class BootDiagnosticsHandler { if (isBootDiagnosticsEnabled() && this.vmssInner() != null && this.vmssInner().virtualMachineProfile() != null - && this.vmssInner().virtualMachineProfile() - .diagnosticsProfile().bootDiagnostics().storageUri() == null) { + && this.vmssInner().virtualMachineProfile().diagnosticsProfile().bootDiagnostics().storageUri() + == null) { this.useManagedStorageAccount = true; } } @@ -3230,8 +3076,7 @@ BootDiagnosticsHandler withBootDiagnostics(String storageAccountBlobEndpointUri) } this.enableDisable(true); this.useManagedStorageAccount = false; - this - .vmssInner() + this.vmssInner() .virtualMachineProfile() .diagnosticsProfile() .bootDiagnostics() @@ -3285,23 +3130,15 @@ void prepare() { String accountName = this.vmssImpl.namer.getRandomName("stg", 24).replace("-", ""); Creatable storageAccountCreatable; if (this.vmssImpl.creatableGroup != null) { - storageAccountCreatable = - this - .vmssImpl - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.vmssImpl.regionName()) - .withNewResourceGroup(this.vmssImpl.creatableGroup); + storageAccountCreatable = this.vmssImpl.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.vmssImpl.regionName()) + .withNewResourceGroup(this.vmssImpl.creatableGroup); } else { - storageAccountCreatable = - this - .vmssImpl - .storageManager - .storageAccounts() - .define(accountName) - .withRegion(this.vmssImpl.regionName()) - .withExistingResourceGroup(this.vmssImpl.resourceGroupName()); + storageAccountCreatable = this.vmssImpl.storageManager.storageAccounts() + .define(accountName) + .withRegion(this.vmssImpl.regionName()) + .withExistingResourceGroup(this.vmssImpl.resourceGroupName()); } this.creatableDiagnosticsStorageAccountKey = this.vmssImpl.addDependency(storageAccountCreatable); } @@ -3334,13 +3171,10 @@ void handleDiagnosticsSettings() { storageAccount = this.existingStorageAccountToAssociate; } if (storageAccount == null) { - throw logger - .logExceptionAsError( - new IllegalStateException( - "Unable to retrieve expected storageAccount instance for BootDiagnostics")); + throw logger.logExceptionAsError(new IllegalStateException( + "Unable to retrieve expected storageAccount instance for BootDiagnostics")); } - vmssInner() - .virtualMachineProfile() + vmssInner().virtualMachineProfile() .diagnosticsProfile() .bootDiagnostics() .withStorageUri(storageAccount.endPoints().primary().blob()); @@ -3360,8 +3194,7 @@ private void enableDisable(boolean enable) { this.vmssInner().virtualMachineProfile().withDiagnosticsProfile(new DiagnosticsProfile()); } if (this.vmssInner().virtualMachineProfile().diagnosticsProfile().bootDiagnostics() == null) { - this - .vmssInner() + this.vmssInner() .virtualMachineProfile() .diagnosticsProfile() .withBootDiagnostics(new BootDiagnostics()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetMsiHandler.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetMsiHandler.java index 94867895404c3..2f0f9e304de6c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetMsiHandler.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetMsiHandler.java @@ -71,9 +71,7 @@ VirtualMachineScaleSetMsiHandler withoutLocalManagedServiceIdentity() { return this; } else if (this.scaleSet.innerModel().identity().type().equals(ResourceIdentityType.SYSTEM_ASSIGNED)) { this.scaleSet.innerModel().identity().withType(ResourceIdentityType.NONE); - } else if (this - .scaleSet - .innerModel() + } else if (this.scaleSet.innerModel() .identity() .type() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)) { @@ -207,15 +205,15 @@ private boolean handleRemoveAllExternalIdentitiesCase(VirtualMachineScaleSetUpda } } Set removeIds = new HashSet<>(); - for (Map.Entry entrySet - : this.userAssignedIdentities.entrySet()) { + for (Map.Entry entrySet : this.userAssignedIdentities + .entrySet()) { if (entrySet.getValue() == null) { removeIds.add(entrySet.getKey().toLowerCase(Locale.ROOT)); } } // If so check user want to remove all the identities - boolean removeAllCurrentIds = - currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); + boolean removeAllCurrentIds + = currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); if (removeAllCurrentIds) { // If so adjust the identity type [Setting type to SYSTEM_ASSIGNED orNONE will remove all the // identities] diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetUnmanagedDataDiskImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetUnmanagedDataDiskImpl.java index 1a8f33ff70aaa..754ddfdbd3c11 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetUnmanagedDataDiskImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetUnmanagedDataDiskImpl.java @@ -13,23 +13,20 @@ import java.util.List; /** The implementation for {@link VirtualMachineScaleSetUnmanagedDataDisk} and its create and update interfaces. */ -class VirtualMachineScaleSetUnmanagedDataDiskImpl - extends ChildResourceImpl - implements VirtualMachineScaleSetUnmanagedDataDisk.DefinitionWithNewVhd< - VirtualMachineScaleSet.DefinitionStages.WithUnmanagedCreate>, - VirtualMachineScaleSetUnmanagedDataDisk.DefinitionWithImage< - VirtualMachineScaleSet.DefinitionStages.WithUnmanagedCreate>, - VirtualMachineScaleSetUnmanagedDataDisk.UpdateDefinition, - VirtualMachineScaleSetUnmanagedDataDisk.Update, - VirtualMachineScaleSetUnmanagedDataDisk { +class VirtualMachineScaleSetUnmanagedDataDiskImpl extends + ChildResourceImpl implements + VirtualMachineScaleSetUnmanagedDataDisk.DefinitionWithNewVhd, + VirtualMachineScaleSetUnmanagedDataDisk.DefinitionWithImage, + VirtualMachineScaleSetUnmanagedDataDisk.UpdateDefinition, + VirtualMachineScaleSetUnmanagedDataDisk.Update, VirtualMachineScaleSetUnmanagedDataDisk { - protected VirtualMachineScaleSetUnmanagedDataDiskImpl( - VirtualMachineScaleSetDataDisk innerObject, VirtualMachineScaleSetImpl parent) { + protected VirtualMachineScaleSetUnmanagedDataDiskImpl(VirtualMachineScaleSetDataDisk innerObject, + VirtualMachineScaleSetImpl parent) { super(innerObject, parent); } - protected static VirtualMachineScaleSetUnmanagedDataDiskImpl prepareDataDisk( - String name, VirtualMachineScaleSetImpl parent) { + protected static VirtualMachineScaleSetUnmanagedDataDiskImpl prepareDataDisk(String name, + VirtualMachineScaleSetImpl parent) { VirtualMachineScaleSetDataDisk dataDiskInner = new VirtualMachineScaleSetDataDisk(); dataDiskInner.withLun(-1).withName(name); return new VirtualMachineScaleSetUnmanagedDataDiskImpl(dataDiskInner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMImpl.java index b8ebefe42927f..6ae0d842a944e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMImpl.java @@ -69,11 +69,8 @@ class VirtualMachineScaleSetVMImpl // To track the managed data disks private final ManagedDataDiskCollection managedDataDisks = new ManagedDataDiskCollection(); - VirtualMachineScaleSetVMImpl( - VirtualMachineScaleSetVMInner inner, - final VirtualMachineScaleSetImpl parent, - final VirtualMachineScaleSetVMsClient client, - final ComputeManager computeManager) { + VirtualMachineScaleSetVMImpl(VirtualMachineScaleSetVMInner inner, final VirtualMachineScaleSetImpl parent, + final VirtualMachineScaleSetVMsClient client, final ComputeManager computeManager) { super(inner, parent); this.client = client; this.computeManager = computeManager; @@ -187,14 +184,8 @@ public ImageReference platformImageReference() { public VirtualMachineImage getOSPlatformImage() { if (this.isOSBasedOnPlatformImage()) { ImageReference imageReference = this.platformImageReference(); - return this - .computeManager - .virtualMachineImages() - .getImage( - this.region(), - imageReference.publisher(), - imageReference.offer(), - imageReference.sku(), + return this.computeManager.virtualMachineImages() + .getImage(this.region(), imageReference.publisher(), imageReference.offer(), imageReference.sku(), imageReference.version()); } return null; @@ -377,9 +368,8 @@ public Map extensions() { Map extensions = new LinkedHashMap<>(); if (this.innerModel().resources() != null) { for (VirtualMachineExtensionInner extensionInner : this.innerModel().resources()) { - extensions - .put( - extensionInner.name(), new VirtualMachineScaleSetVMInstanceExtensionImpl(extensionInner, this)); + extensions.put(extensionInner.name(), + new VirtualMachineScaleSetVMInstanceExtensionImpl(extensionInner, this)); } } return Collections.unmodifiableMap(extensions); @@ -401,18 +391,16 @@ public DiagnosticsProfile diagnosticsProfile() { } private void updateInstanceView(VirtualMachineScaleSetVMInstanceViewInner instanceViewInner) { - this.virtualMachineInstanceView = - new VirtualMachineInstanceViewImpl( - new VirtualMachineInstanceViewInner() - .withBootDiagnostics(instanceViewInner.bootDiagnostics()) - .withDisks(instanceViewInner.disks()) - .withExtensions(instanceViewInner.extensions()) - .withPlatformFaultDomain(instanceViewInner.platformFaultDomain()) - .withPlatformUpdateDomain(instanceViewInner.platformUpdateDomain()) - .withRdpThumbPrint(instanceViewInner.rdpThumbPrint()) - .withStatuses(instanceViewInner.statuses()) - .withVmAgent(instanceViewInner.vmAgent()) - .withMaintenanceRedeployStatus(instanceViewInner.maintenanceRedeployStatus())); + this.virtualMachineInstanceView = new VirtualMachineInstanceViewImpl( + new VirtualMachineInstanceViewInner().withBootDiagnostics(instanceViewInner.bootDiagnostics()) + .withDisks(instanceViewInner.disks()) + .withExtensions(instanceViewInner.extensions()) + .withPlatformFaultDomain(instanceViewInner.platformFaultDomain()) + .withPlatformUpdateDomain(instanceViewInner.platformUpdateDomain()) + .withRdpThumbPrint(instanceViewInner.rdpThumbPrint()) + .withStatuses(instanceViewInner.statuses()) + .withVmAgent(instanceViewInner.vmAgent()) + .withMaintenanceRedeployStatus(instanceViewInner.maintenanceRedeployStatus())); // hyperVGeneration is not in spec // vmHealth and assignedHost } @@ -431,14 +419,12 @@ public VirtualMachineInstanceView refreshInstanceView() { } public Mono refreshInstanceViewAsync() { - return this - .client + return this.client .getInstanceViewAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId()) - .map( - instanceViewInner -> { - updateInstanceView(instanceViewInner); - return virtualMachineInstanceView; - }) + .map(instanceViewInner -> { + updateInstanceView(instanceViewInner); + return virtualMachineInstanceView; + }) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } @@ -464,9 +450,8 @@ public void reimage() { @Override public Mono reimageAsync() { - return this - .client - .reimageAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), null); + return this.client.reimageAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), + null); } @Override @@ -486,9 +471,8 @@ public void powerOff() { @Override public Mono powerOffAsync() { - return this - .client - .powerOffAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), null); + return this.client.powerOffAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), + null); } @Override @@ -498,8 +482,8 @@ public void powerOff(boolean skipShutdown) { @Override public Mono powerOffAsync(boolean skipShutdown) { - return this.client - .powerOffAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), skipShutdown); + return this.client.powerOffAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), + skipShutdown); } @Override @@ -539,22 +523,20 @@ public VirtualMachineScaleSetVM refresh() { @Override public Mono refreshAsync() { - return this - .client + return this.client .getWithResponseAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), InstanceViewTypes.INSTANCE_VIEW) .map(Response::getValue) - .map( - vmInner -> { - this.setInner(vmInner); - this.clearCachedRelatedResources(); - if (vmInner.instanceView() != null) { - // load instance view - updateInstanceView(vmInner.instanceView()); - } - this.initializeDataDisks(); - return this; - }); + .map(vmInner -> { + this.setInner(vmInner); + this.clearCachedRelatedResources(); + if (vmInner.instanceView() != null) { + // load instance view + updateInstanceView(vmInner.instanceView()); + } + this.initializeDataDisks(); + return this; + }); } @Override @@ -620,47 +602,39 @@ public boolean isManagedDiskEnabled() { @Override public Update withExistingDataDisk(Disk dataDisk, int lun, CachingTypes cachingTypes) { - return this - .withExistingDataDisk( - dataDisk, lun, cachingTypes, StorageAccountTypes.fromString(dataDisk.sku().accountType().toString())); + return this.withExistingDataDisk(dataDisk, lun, cachingTypes, + StorageAccountTypes.fromString(dataDisk.sku().accountType().toString())); } @Override - public Update withExistingDataDisk( - Disk dataDisk, int lun, CachingTypes cachingTypes, StorageAccountTypes storageAccountTypes) { + public Update withExistingDataDisk(Disk dataDisk, int lun, CachingTypes cachingTypes, + StorageAccountTypes storageAccountTypes) { if (!this.isManagedDiskEnabled()) { - throw logger - .logExceptionAsError( - new IllegalStateException( - ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED)); + throw logger.logExceptionAsError( + new IllegalStateException(ManagedUnmanagedDiskErrors.VM_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED)); } if (dataDisk.innerModel().diskState() != DiskState.UNATTACHED) { throw logger.logExceptionAsError(new IllegalStateException("Disk need to be in unattached state")); } - ManagedDiskParameters managedDiskParameters = - new ManagedDiskParameters().withStorageAccountType(storageAccountTypes); + ManagedDiskParameters managedDiskParameters + = new ManagedDiskParameters().withStorageAccountType(storageAccountTypes); managedDiskParameters.withId(dataDisk.id()); - DataDisk attachDataDisk = - new DataDisk() - .withCreateOption(DiskCreateOptionTypes.ATTACH) - .withLun(lun) - .withCaching(cachingTypes) - .withManagedDisk(managedDiskParameters); + DataDisk attachDataDisk = new DataDisk().withCreateOption(DiskCreateOptionTypes.ATTACH) + .withLun(lun) + .withCaching(cachingTypes) + .withManagedDisk(managedDiskParameters); return this.withExistingDataDisk(attachDataDisk, lun); } private Update withExistingDataDisk(DataDisk dataDisk, int lun) { if (this.tryFindDataDisk(lun, this.innerModel().storageProfile().dataDisks()) != null) { - throw logger - .logExceptionAsError( - new IllegalStateException(String.format("A data disk with lun '%d' already attached", lun))); + throw logger.logExceptionAsError( + new IllegalStateException(String.format("A data disk with lun '%d' already attached", lun))); } else if (this.tryFindDataDisk(lun, this.managedDataDisks.existingDisksToAttach) != null) { - throw logger - .logExceptionAsError( - new IllegalStateException( - String.format("A data disk with lun '%d' already scheduled to be attached", lun))); + throw logger.logExceptionAsError(new IllegalStateException( + String.format("A data disk with lun '%d' already scheduled to be attached", lun))); } this.managedDataDisks.existingDisksToAttach.add(dataDisk); return this; @@ -670,15 +644,12 @@ private Update withExistingDataDisk(DataDisk dataDisk, int lun) { public Update withoutDataDisk(int lun) { DataDisk dataDisk = this.tryFindDataDisk(lun, this.innerModel().storageProfile().dataDisks()); if (dataDisk == null) { - throw logger - .logExceptionAsError( - new IllegalStateException(String.format("A data disk with lun '%d' not found", lun))); + throw logger.logExceptionAsError( + new IllegalStateException(String.format("A data disk with lun '%d' not found", lun))); } if (dataDisk.createOption() != DiskCreateOptionTypes.ATTACH) { String exceptionMessage = String.format( - "A data disk with lun '%d' cannot be detached, as it is part of Virtual Machine Scale Set model", - lun - ); + "A data disk with lun '%d' cannot be detached, as it is part of Virtual Machine Scale Set model", lun); throw logger.logExceptionAsError(new IllegalStateException(exceptionMessage)); } this.managedDataDisks.diskLunsToRemove.add(lun); @@ -704,20 +675,18 @@ public VirtualMachineScaleSetVM apply(Context context) { public Mono applyAsync(Context context) { final VirtualMachineScaleSetVMImpl self = this; this.managedDataDisks.syncToVMDataDisks(this.innerModel().storageProfile()); - return this - .parent() + return this.parent() .manager() .serviceClient() .getVirtualMachineScaleSetVMs() .updateAsync(this.parent().resourceGroupName(), this.parent().name(), this.instanceId(), this.innerModel()) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map( - vmInner -> { - self.setInner(vmInner); - self.clearCachedRelatedResources(); - self.initializeDataDisks(); - return self; - }); + .map(vmInner -> { + self.setInner(vmInner); + self.clearCachedRelatedResources(); + self.initializeDataDisks(); + return self; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMInstanceExtensionImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMInstanceExtensionImpl.java index 4db23ce6b8a9a..b37cd33a6cb25 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMInstanceExtensionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMInstanceExtensionImpl.java @@ -20,8 +20,8 @@ class VirtualMachineScaleSetVMInstanceExtensionImpl private HashMap publicSettings; private HashMap protectedSettings; - VirtualMachineScaleSetVMInstanceExtensionImpl( - VirtualMachineExtensionInner inner, VirtualMachineScaleSetVMImpl parent) { + VirtualMachineScaleSetVMInstanceExtensionImpl(VirtualMachineExtensionInner inner, + VirtualMachineScaleSetVMImpl parent) { super(inner, parent); initializeSettings(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMsImpl.java index 06b52fb7691f4..25f37d6cd41a0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetVMsImpl.java @@ -33,8 +33,8 @@ class VirtualMachineScaleSetVMsImpl private final VirtualMachineScaleSetVMsClient client; private final ComputeManager computeManager; - VirtualMachineScaleSetVMsImpl( - VirtualMachineScaleSetImpl scaleSet, VirtualMachineScaleSetVMsClient client, ComputeManager computeManager) { + VirtualMachineScaleSetVMsImpl(VirtualMachineScaleSetImpl scaleSet, VirtualMachineScaleSetVMsClient client, + ComputeManager computeManager) { this.scaleSet = scaleSet; this.client = client; this.computeManager = computeManager; @@ -64,7 +64,8 @@ public PagedFlux listAsync() { @Override public Mono deleteInstancesAsync(Collection instanceIds) { - return this.scaleSet.manager().virtualMachineScaleSets() + return this.scaleSet.manager() + .virtualMachineScaleSets() .deleteInstancesAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), instanceIds, false); } @@ -80,8 +81,9 @@ public void deleteInstances(String... instanceIds) { @Override public Mono deleteInstancesAsync(Collection instanceIds, boolean forceDeletion) { - return this.scaleSet.manager().virtualMachineScaleSets().deleteInstancesAsync(this.scaleSet.resourceGroupName(), - this.scaleSet.name(), instanceIds, forceDeletion); + return this.scaleSet.manager() + .virtualMachineScaleSets() + .deleteInstancesAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), instanceIds, forceDeletion); } @Override @@ -96,9 +98,11 @@ public void deallocateInstances(Collection instanceIds) { @Override public Mono deallocateInstancesAsync(Collection instanceIds) { - return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().deallocateAsync( - this.scaleSet.resourceGroupName(), this.scaleSet.name(), null, - new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); + return this.scaleSet.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .deallocateAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), null, + new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); } @Override @@ -108,9 +112,11 @@ public void powerOffInstances(Collection instanceIds, boolean skipShutdo @Override public Mono powerOffInstancesAsync(Collection instanceIds, boolean skipShutdown) { - return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().powerOffAsync( - this.scaleSet.resourceGroupName(), this.scaleSet.name(), skipShutdown, - new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); + return this.scaleSet.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .powerOffAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), skipShutdown, + new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); } @Override @@ -120,9 +126,11 @@ public void startInstances(Collection instanceIds) { @Override public Mono startInstancesAsync(Collection instanceIds) { - return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().startAsync( - this.scaleSet.resourceGroupName(), this.scaleSet.name(), - new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); + return this.scaleSet.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .startAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), + new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); } @Override @@ -132,9 +140,11 @@ public void restartInstances(Collection instanceIds) { @Override public Mono restartInstancesAsync(Collection instanceIds) { - return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().restartAsync( - this.scaleSet.resourceGroupName(), this.scaleSet.name(), - new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); + return this.scaleSet.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .restartAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), + new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); } @Override @@ -144,22 +154,24 @@ public void redeployInstances(Collection instanceIds) { @Override public Mono redeployInstancesAsync(Collection instanceIds) { - return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().redeployAsync( - this.scaleSet.resourceGroupName(), this.scaleSet.name(), - new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); - } - -// @Override -// public void reimageInstances(Collection instanceIds) { -// this.reimageInstancesAsync(instanceIds).block(); -// } -// -// @Override -// public Mono reimageInstancesAsync(Collection instanceIds) { -// return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().reimageAsync( -// this.scaleSet.resourceGroupName(), this.scaleSet.name(), -// new VirtualMachineScaleSetReimageParameters().withInstanceIds(new ArrayList<>(instanceIds))); -// } + return this.scaleSet.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .redeployAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), + new VirtualMachineScaleSetVMInstanceIDs().withInstanceIds(new ArrayList<>(instanceIds))); + } + + // @Override + // public void reimageInstances(Collection instanceIds) { + // this.reimageInstancesAsync(instanceIds).block(); + // } + // + // @Override + // public Mono reimageInstancesAsync(Collection instanceIds) { + // return this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets().reimageAsync( + // this.scaleSet.resourceGroupName(), this.scaleSet.name(), + // new VirtualMachineScaleSetReimageParameters().withInstanceIds(new ArrayList<>(instanceIds))); + // } @Override public VirtualMachineScaleSetVM getInstance(String instanceId) { @@ -168,8 +180,7 @@ public VirtualMachineScaleSetVM getInstance(String instanceId) { @Override public Mono getInstanceAsync(String instanceId) { - return this - .client + return this.client .getWithResponseAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), instanceId, InstanceViewTypes.INSTANCE_VIEW) .map(Response::getValue) @@ -185,11 +196,10 @@ public Mono updateInstancesAsync(Collection instanceIds) { for (String instanceId : instanceIds) { instanceIdList.add(instanceId); } - VirtualMachineScaleSetsClient scaleSetInnerManager = - this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets(); - return scaleSetInnerManager - .updateInstancesAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), - new VirtualMachineScaleSetVMInstanceRequiredIDs().withInstanceIds(instanceIdList)); + VirtualMachineScaleSetsClient scaleSetInnerManager + = this.scaleSet.manager().serviceClient().getVirtualMachineScaleSets(); + return scaleSetInnerManager.updateInstancesAsync(this.scaleSet.resourceGroupName(), this.scaleSet.name(), + new VirtualMachineScaleSetVMInstanceRequiredIDs().withInstanceIds(instanceIdList)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetsImpl.java index 2bea22edf3c18..1a27cba276855 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineScaleSetsImpl.java @@ -29,23 +29,15 @@ import reactor.core.publisher.Mono; /** The implementation for VirtualMachineScaleSets. */ -public class VirtualMachineScaleSetsImpl - extends TopLevelModifiableResourcesImpl< - VirtualMachineScaleSet, - VirtualMachineScaleSetImpl, - VirtualMachineScaleSetInner, - VirtualMachineScaleSetsClient, - ComputeManager> +public class VirtualMachineScaleSetsImpl extends + TopLevelModifiableResourcesImpl implements VirtualMachineScaleSets { private final StorageManager storageManager; private final NetworkManager networkManager; private final AuthorizationManager authorizationManager; - public VirtualMachineScaleSetsImpl( - ComputeManager computeManager, - StorageManager storageManager, - NetworkManager networkManager, - AuthorizationManager authorizationManager) { + public VirtualMachineScaleSetsImpl(ComputeManager computeManager, StorageManager storageManager, + NetworkManager networkManager, AuthorizationManager authorizationManager) { super(computeManager.serviceClient().getVirtualMachineScaleSets(), computeManager); this.storageManager = storageManager; this.networkManager = networkManager; @@ -103,24 +95,15 @@ public Mono reimageAsync(String groupName, String name) { } @Override - public RunCommandResult runPowerShellScriptInVMInstance( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters) { - return this - .runPowerShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters) + public RunCommandResult runPowerShellScriptInVMInstance(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters) { + return this.runPowerShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters) .block(); } @Override - public Mono runPowerShellScriptInVMInstanceAsync( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters) { + public Mono runPowerShellScriptInVMInstanceAsync(String groupName, String scaleSetName, + String vmId, List scriptLines, List scriptParameters) { RunCommandInput inputCommand = new RunCommandInput(); inputCommand.withCommandId("RunPowerShellScript"); inputCommand.withScript(scriptLines); @@ -129,24 +112,15 @@ public Mono runPowerShellScriptInVMInstanceAsync( } @Override - public RunCommandResult runShellScriptInVMInstance( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters) { - return this - .runShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters) + public RunCommandResult runShellScriptInVMInstance(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters) { + return this.runShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters) .block(); } @Override - public Mono runShellScriptInVMInstanceAsync( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters) { + public Mono runShellScriptInVMInstanceAsync(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters) { RunCommandInput inputCommand = new RunCommandInput(); inputCommand.withCommandId("RunShellScript"); inputCommand.withScript(scriptLines); @@ -155,16 +129,15 @@ public Mono runShellScriptInVMInstanceAsync( } @Override - public RunCommandResult runCommandInVMInstance( - String groupName, String scaleSetName, String vmId, RunCommandInput inputCommand) { + public RunCommandResult runCommandInVMInstance(String groupName, String scaleSetName, String vmId, + RunCommandInput inputCommand) { return this.runCommandVMInstanceAsync(groupName, scaleSetName, vmId, inputCommand).block(); } @Override - public Mono runCommandVMInstanceAsync( - String groupName, String scaleSetName, String vmId, RunCommandInput inputCommand) { - return this - .manager() + public Mono runCommandVMInstanceAsync(String groupName, String scaleSetName, String vmId, + RunCommandInput inputCommand) { + return this.manager() .serviceClient() .getVirtualMachineScaleSetVMs() .runCommandAsync(groupName, scaleSetName, vmId, inputCommand) @@ -172,18 +145,23 @@ public Mono runCommandVMInstanceAsync( } @Override - public void deleteInstances(String groupName, String scaleSetName, Collection instanceIds, boolean forceDeletion) { + public void deleteInstances(String groupName, String scaleSetName, Collection instanceIds, + boolean forceDeletion) { this.deleteInstancesAsync(groupName, scaleSetName, instanceIds, forceDeletion).block(); } @Override - public Mono deleteInstancesAsync(String groupName, String scaleSetName, Collection instanceIds, boolean forceDeletion) { + public Mono deleteInstancesAsync(String groupName, String scaleSetName, Collection instanceIds, + boolean forceDeletion) { if (instanceIds == null || instanceIds.isEmpty()) { return Mono.empty(); } - return this.manager().serviceClient().getVirtualMachineScaleSets().deleteInstancesAsync(groupName, scaleSetName, - new VirtualMachineScaleSetVMInstanceRequiredIDs().withInstanceIds(new ArrayList<>(instanceIds)), - forceDeletion); + return this.manager() + .serviceClient() + .getVirtualMachineScaleSets() + .deleteInstancesAsync(groupName, scaleSetName, + new VirtualMachineScaleSetVMInstanceRequiredIDs().withInstanceIds(new ArrayList<>(instanceIds)), + forceDeletion); } @Override @@ -196,37 +174,31 @@ protected VirtualMachineScaleSetImpl wrapModel(String name) { VirtualMachineScaleSetInner inner = new VirtualMachineScaleSetInner(); inner.withVirtualMachineProfile(new VirtualMachineScaleSetVMProfile()); - inner - .virtualMachineProfile() - .withStorageProfile( - new VirtualMachineScaleSetStorageProfile() - .withOsDisk(new VirtualMachineScaleSetOSDisk().withVhdContainers(new ArrayList()))); + inner.virtualMachineProfile() + .withStorageProfile(new VirtualMachineScaleSetStorageProfile() + .withOsDisk(new VirtualMachineScaleSetOSDisk().withVhdContainers(new ArrayList()))); inner.virtualMachineProfile().withOsProfile(new VirtualMachineScaleSetOSProfile()); inner.virtualMachineProfile().withNetworkProfile(new VirtualMachineScaleSetNetworkProfile()); - inner - .virtualMachineProfile() + inner.virtualMachineProfile() .networkProfile() .withNetworkInterfaceConfigurations(new ArrayList()); - VirtualMachineScaleSetNetworkConfiguration primaryNetworkInterfaceConfiguration = - new VirtualMachineScaleSetNetworkConfiguration() - .withPrimary(true) + VirtualMachineScaleSetNetworkConfiguration primaryNetworkInterfaceConfiguration + = new VirtualMachineScaleSetNetworkConfiguration().withPrimary(true) .withName("primary-nic-cfg") .withIpConfigurations(new ArrayList()); - primaryNetworkInterfaceConfiguration - .ipConfigurations() + primaryNetworkInterfaceConfiguration.ipConfigurations() .add(new VirtualMachineScaleSetIpConfiguration().withName("primary-nic-ip-cfg")); - inner - .virtualMachineProfile() + inner.virtualMachineProfile() .networkProfile() .networkInterfaceConfigurations() .add(primaryNetworkInterfaceConfiguration); - return new VirtualMachineScaleSetImpl( - name, inner, this.manager(), this.storageManager, this.networkManager, this.authorizationManager); + return new VirtualMachineScaleSetImpl(name, inner, this.manager(), this.storageManager, this.networkManager, + this.authorizationManager); } @Override @@ -234,8 +206,8 @@ protected VirtualMachineScaleSetImpl wrapModel(VirtualMachineScaleSetInner inner if (inner == null) { return null; } - return new VirtualMachineScaleSetImpl( - inner.name(), inner, this.manager(), this.storageManager, this.networkManager, this.authorizationManager); + return new VirtualMachineScaleSetImpl(inner.name(), inner, this.manager(), this.storageManager, + this.networkManager, this.authorizationManager); } @Override @@ -245,8 +217,8 @@ public void deleteById(String id, boolean forceDeletion) { @Override public Mono deleteByIdAsync(String id, boolean forceDeletion) { - return deleteByResourceGroupAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), forceDeletion); + return deleteByResourceGroupAsync(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), + forceDeletion); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineSkusImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineSkusImpl.java index f37cc2589a444..beef19f05ed0e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineSkusImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachineSkusImpl.java @@ -40,10 +40,10 @@ protected VirtualMachineSkuImpl wrapModel(VirtualMachineImageResourceInner inner @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter - .convertListToPagedFlux( - innerCollection.listSkusWithResponseAsync( - offer.region().toString(), offer.publisher().name(), offer.name())), - this::wrapModel); + return PagedConverter + .mapPage( + PagedConverter.convertListToPagedFlux(innerCollection + .listSkusWithResponseAsync(offer.region().toString(), offer.publisher().name(), offer.name())), + this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinesImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinesImpl.java index 4a87c42ece1ba..475e500b8bae4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/VirtualMachinesImpl.java @@ -42,9 +42,8 @@ import java.util.function.Function; /** The implementation for VirtualMachines. */ -public class VirtualMachinesImpl - extends TopLevelModifiableResourcesImpl< - VirtualMachine, VirtualMachineImpl, VirtualMachineInner, VirtualMachinesClient, ComputeManager> +public class VirtualMachinesImpl extends + TopLevelModifiableResourcesImpl implements VirtualMachines { private final StorageManager storageManager; private final NetworkManager networkManager; @@ -52,11 +51,8 @@ public class VirtualMachinesImpl private final VirtualMachineSizesImpl vmSizes; private final ClientLogger logger = new ClientLogger(VirtualMachinesImpl.class); - public VirtualMachinesImpl( - ComputeManager computeManager, - StorageManager storageManager, - NetworkManager networkManager, - AuthorizationManager authorizationManager) { + public VirtualMachinesImpl(ComputeManager computeManager, StorageManager storageManager, + NetworkManager networkManager, AuthorizationManager authorizationManager) { super(computeManager.serviceClient().getVirtualMachines(), computeManager); this.storageManager = storageManager; this.networkManager = networkManager; @@ -147,14 +143,13 @@ public String capture(String groupName, String name, String containerName, Strin } @Override - public Mono captureAsync( - String groupName, String name, String containerName, String vhdPrefix, boolean overwriteVhd) { + public Mono captureAsync(String groupName, String name, String containerName, String vhdPrefix, + boolean overwriteVhd) { VirtualMachineCaptureParameters parameters = new VirtualMachineCaptureParameters(); parameters.withDestinationContainerName(containerName); parameters.withOverwriteVhds(overwriteVhd); parameters.withVhdPrefix(vhdPrefix); - return this - .inner() + return this.inner() .captureAsync(groupName, name, parameters) .map(captureResult -> VirtualMachineImpl.serializeCaptureResult(captureResult, logger)); } @@ -170,14 +165,14 @@ public Mono migrateToManagedAsync(String groupName, String name) { } @Override - public RunCommandResult runPowerShellScript( - String groupName, String name, List scriptLines, List scriptParameters) { + public RunCommandResult runPowerShellScript(String groupName, String name, List scriptLines, + List scriptParameters) { return this.runPowerShellScriptAsync(groupName, name, scriptLines, scriptParameters).block(); } @Override - public Mono runPowerShellScriptAsync( - String groupName, String name, List scriptLines, List scriptParameters) { + public Mono runPowerShellScriptAsync(String groupName, String name, List scriptLines, + List scriptParameters) { RunCommandInput inputCommand = new RunCommandInput(); inputCommand.withCommandId("RunPowerShellScript"); inputCommand.withScript(scriptLines); @@ -186,14 +181,14 @@ public Mono runPowerShellScriptAsync( } @Override - public RunCommandResult runShellScript( - String groupName, String name, List scriptLines, List scriptParameters) { + public RunCommandResult runShellScript(String groupName, String name, List scriptLines, + List scriptParameters) { return this.runShellScriptAsync(groupName, name, scriptLines, scriptParameters).block(); } @Override - public Mono runShellScriptAsync( - String groupName, String name, List scriptLines, List scriptParameters) { + public Mono runShellScriptAsync(String groupName, String name, List scriptLines, + List scriptParameters) { RunCommandInput inputCommand = new RunCommandInput(); inputCommand.withCommandId("RunShellScript"); inputCommand.withScript(scriptLines); @@ -218,16 +213,10 @@ public Accepted beginDeleteById(String id) { @Override public Accepted beginDeleteByResourceGroup(String resourceGroupName, String name) { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteWithResponseAsync(resourceGroupName, name, null).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.inner().deleteWithResponseAsync(resourceGroupName, name, null).block(), Function.identity(), + Void.class, null, Context.NONE); } @Override @@ -237,8 +226,8 @@ public void deleteById(String id, boolean forceDeletion) { @Override public Mono deleteByIdAsync(String id, boolean forceDeletion) { - return deleteByResourceGroupAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), forceDeletion); + return deleteByResourceGroupAsync(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), + forceDeletion); } @Override @@ -253,22 +242,16 @@ public Mono deleteByResourceGroupAsync(String resourceGroupName, String na @Override public Accepted beginDeleteById(String id, boolean forceDeletion) { - return beginDeleteByResourceGroup( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), forceDeletion); + return beginDeleteByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), + forceDeletion); } @Override public Accepted beginDeleteByResourceGroup(String resourceGroupName, String name, boolean forceDeletion) { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteWithResponseAsync(resourceGroupName, name, forceDeletion).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.inner().deleteWithResponseAsync(resourceGroupName, name, forceDeletion).block(), + Function.identity(), Void.class, null, Context.NONE); } @Override @@ -277,24 +260,27 @@ public PagedIterable listByVirtualMachineScaleSetId(String vmssI } @Override - @SuppressWarnings({"unchecked", "removal"}) + @SuppressWarnings({ "unchecked", "removal" }) public PagedFlux listByVirtualMachineScaleSetIdAsync(String vmssId) { if (CoreUtils.isNullOrEmpty(vmssId)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'vmssId' is required and cannot be null."))); + return new PagedFlux<>( + () -> Mono.error(new IllegalArgumentException("Parameter 'vmssId' is required and cannot be null."))); } // Hack in nextLink encoding by using reflection. // Replace below hack with "listAsync()" once backend fix "nextLink" encoding issue: // https://github.com/Azure/azure-rest-api-specs/issues/25640 Method listSinglePageAsync; try { - listSinglePageAsync = inner().getClass().getDeclaredMethod("listByResourceGroupSinglePageAsync", String.class, String.class, ExpandTypeForListVMs.class); + listSinglePageAsync = inner().getClass() + .getDeclaredMethod("listByResourceGroupSinglePageAsync", String.class, String.class, + ExpandTypeForListVMs.class); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } Method listNextSinglePageAsync; try { - listNextSinglePageAsync = inner().getClass().getDeclaredMethod("listNextSinglePageAsync", String.class, Context.class); + listNextSinglePageAsync + = inner().getClass().getDeclaredMethod("listNextSinglePageAsync", String.class, Context.class); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } @@ -303,24 +289,23 @@ public PagedFlux listByVirtualMachineScaleSetIdAsync(String vmss listNextSinglePageAsync.setAccessible(true); return null; }); - return wrapPageAsync(new PagedFlux<>( - () -> { - try { - return (Mono>) - listSinglePageAsync.invoke(inner(), ResourceUtils.groupFromResourceId(vmssId), String.format("'virtualMachineScaleSet/id' eq '%s'", vmssId), null); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - }, - nextLink -> { - try { - return (Mono>) - // encode nextLink - listNextSinglePageAsync.invoke(inner(), ResourceUtils.encodeResourceId(nextLink), Context.NONE); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - })); + return wrapPageAsync(new PagedFlux<>(() -> { + try { + return (Mono>) listSinglePageAsync.invoke(inner(), + ResourceUtils.groupFromResourceId(vmssId), + String.format("'virtualMachineScaleSet/id' eq '%s'", vmssId), null); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }, nextLink -> { + try { + return (Mono>) + // encode nextLink + listNextSinglePageAsync.invoke(inner(), ResourceUtils.encodeResourceId(nextLink), Context.NONE); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + })); } @Override @@ -331,8 +316,8 @@ public PagedIterable listByVirtualMachineScaleSet(VirtualMachine @Override public PagedFlux listByVirtualMachineScaleSetAsync(VirtualMachineScaleSet vmss) { if (vmss == null) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'vmss' is required and cannot be null."))); + return new PagedFlux<>( + () -> Mono.error(new IllegalArgumentException("Parameter 'vmss' is required and cannot be null."))); } return listByVirtualMachineScaleSetIdAsync(vmss.id()); } @@ -352,8 +337,8 @@ protected VirtualMachineImpl wrapModel(String name) { inner.withOsProfile(new OSProfile()); inner.withHardwareProfile(new HardwareProfile()); inner.withNetworkProfile(new NetworkProfile().withNetworkInterfaces(new ArrayList<>())); - return new VirtualMachineImpl( - name, inner, this.manager(), this.storageManager, this.networkManager, this.authorizationManager); + return new VirtualMachineImpl(name, inner, this.manager(), this.storageManager, this.networkManager, + this.authorizationManager); } @Override @@ -361,12 +346,7 @@ protected VirtualMachineImpl wrapModel(VirtualMachineInner virtualMachineInner) if (virtualMachineInner == null) { return null; } - return new VirtualMachineImpl( - virtualMachineInner.name(), - virtualMachineInner, - this.manager(), - this.storageManager, - this.networkManager, - this.authorizationManager); + return new VirtualMachineImpl(virtualMachineInner.name(), virtualMachineInner, this.manager(), + this.storageManager, this.networkManager, this.authorizationManager); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeLegacyEncryptionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeLegacyEncryptionMonitorImpl.java index f499c5030334f..97b69b290cd7f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeLegacyEncryptionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeLegacyEncryptionMonitorImpl.java @@ -125,23 +125,20 @@ public DiskVolumeEncryptionMonitor refresh() { public Mono refreshAsync() { final WindowsVolumeLegacyEncryptionMonitorImpl self = this; // Refreshes the cached Windows virtual machine and installed encryption extension - return retrieveVirtualMachineAsync() - .map( - virtualMachine -> { - self.virtualMachine = virtualMachine; - if (virtualMachine.resources() != null) { - for (VirtualMachineExtensionInner extension : virtualMachine.resources()) { - if (EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisher()) - && EncryptionExtensionIdentifier - .isEncryptionTypeName( - extension.typePropertiesType(), OperatingSystemTypes.WINDOWS)) { - self.encryptionExtension = extension; - break; - } - } + return retrieveVirtualMachineAsync().map(virtualMachine -> { + self.virtualMachine = virtualMachine; + if (virtualMachine.resources() != null) { + for (VirtualMachineExtensionInner extension : virtualMachine.resources()) { + if (EncryptionExtensionIdentifier.isEncryptionPublisherName(extension.publisher()) + && EncryptionExtensionIdentifier.isEncryptionTypeName(extension.typePropertiesType(), + OperatingSystemTypes.WINDOWS)) { + self.encryptionExtension = extension; + break; } - return self; - }); + } + } + return self; + }); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeNoAADEncryptionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeNoAADEncryptionMonitorImpl.java index 5d18446d13a73..564b271c9b9bc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeNoAADEncryptionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/implementation/WindowsVolumeNoAADEncryptionMonitorImpl.java @@ -139,12 +139,10 @@ public DiskVolumeEncryptionMonitor refresh() { public Mono refreshAsync() { final WindowsVolumeNoAADEncryptionMonitorImpl self = this; // Refreshes the cached virtual machine and installed encryption extension - return retrieveVirtualMachineAsync() - .map( - virtualMachine -> { - self.virtualMachine = virtualMachine; - return self; - }); + return retrieveVirtualMachineAsync().map(virtualMachine -> { + self.virtualMachine = virtualMachine; + return self; + }); } /** @@ -153,7 +151,8 @@ public Mono refreshAsync() { * @return the retrieved virtual machine */ private Mono retrieveVirtualMachineAsync() { - return this.computeManager.serviceClient().getVirtualMachines() + return this.computeManager.serviceClient() + .getVirtualMachines() .getByResourceGroupWithResponseAsync(rgName, vmName, InstanceViewTypes.INSTANCE_VIEW) .map(Response::getValue); // Exception if vm not found diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySet.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySet.java index 09d9715e0446c..c4a8149d24bcf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySet.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySet.java @@ -17,10 +17,8 @@ /** An immutable client-side representation of an Azure availability set. */ @Fluent -public interface AvailabilitySet - extends GroupableResource, - Refreshable, - Updatable { +public interface AvailabilitySet extends GroupableResource, + Refreshable, Updatable { /** @return the update domain count of this availability set */ int updateDomainCount(); @@ -114,21 +112,16 @@ interface WithProximityPlacementGroup { * @param type the type of the group * @return the next stage of the definition. */ - WithCreate withNewProximityPlacementGroup( - String proximityPlacementGroupName, ProximityPlacementGroupType type); + WithCreate withNewProximityPlacementGroup(String proximityPlacementGroupName, + ProximityPlacementGroupType type); } /** * The stage of an availability set definition which contains all the minimum required inputs for the resource * to be created but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithUpdateDomainCount, - WithFaultDomainCount, - WithSku, - WithProximityPlacementGroup { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + WithUpdateDomainCount, WithFaultDomainCount, WithSku, WithProximityPlacementGroup { } } @@ -163,11 +156,9 @@ interface WithProximityPlacementGroup { Update withoutProximityPlacementGroup(); } } + /** The template for an availability set update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithProximityPlacementGroup { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithProximityPlacementGroup { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySets.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySets.java index 442c45f6f69f9..fd6d46bd64fe9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySets.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/AvailabilitySets.java @@ -17,14 +17,8 @@ /** Entry point to availability set management API. */ @Fluent -public interface AvailabilitySets - extends SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - HasManager { +public interface AvailabilitySets extends SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsListing, SupportsCreating, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsBatchCreation, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeRoles.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeRoles.java index 8755b26bc55aa..1ccfd486106e0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeRoles.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeRoles.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.compute.models; - /** Defines values for ComputeRoles. */ public enum ComputeRoles { /** Enum value PaaS. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeSku.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeSku.java index 6c9b79fa49b8b..9da0be40e6651 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeSku.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ComputeSku.java @@ -17,10 +17,13 @@ public interface ComputeSku extends HasInnerModel { /** @return the sku name */ ComputeSkuName name(); + /** @return the sku tier */ ComputeSkuTier tier(); + /** @return the compute resource type that the sku describes */ ComputeResourceType resourceType(); + /** * The virtual machine size type if the sku describes sku for virtual machine resource type. * @@ -30,6 +33,7 @@ public interface ComputeSku extends HasInnerModel { * @return the virtual machine size type */ VirtualMachineSizeTypes virtualMachineSizeType(); + /** * The managed disk or snapshot sku type if the sku describes sku for disk or snapshot resource type. * @@ -39,6 +43,7 @@ public interface ComputeSku extends HasInnerModel { * @return the managed disk or snapshot sku type */ DiskSkuTypes diskSkuType(); + /** * The availability set sku type if the sku describes sku for availability set resource type. * @@ -48,18 +53,25 @@ public interface ComputeSku extends HasInnerModel { * @return the availability set sku type */ AvailabilitySetSkuTypes availabilitySetSkuType(); + /** @return the regions that the sku is available */ List regions(); + /** @return the availability zones supported for this sku, index by region */ Map> zones(); + /** @return the scaling information of the sku */ ResourceSkuCapacity capacity(); + /** @return the api versions that this sku supports */ List apiVersions(); + /** @return the metadata for querying the sku pricing information */ List costs(); + /** @return the capabilities of the sku */ List capabilities(); + /** @return the restrictions because of which SKU cannot be used */ List restrictions(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disk.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disk.java index efa3ce7697608..b213b75e51b64 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disk.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disk.java @@ -100,21 +100,12 @@ public interface Disk extends GroupableResource, Refr PublicNetworkAccess publicNetworkAccess(); /** The entirety of the managed disk definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithDiskSource, - DefinitionStages.WithWindowsDiskSource, - DefinitionStages.WithLinuxDiskSource, - DefinitionStages.WithData, - DefinitionStages.WithDataDiskSource, - DefinitionStages.WithDataDiskFromVhd, - DefinitionStages.WithDataDiskFromUpload, - DefinitionStages.WithDataDiskFromDisk, - DefinitionStages.WithDataDiskFromSnapshot, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithCreateAndSize, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithDiskSource, + DefinitionStages.WithWindowsDiskSource, DefinitionStages.WithLinuxDiskSource, DefinitionStages.WithData, + DefinitionStages.WithDataDiskSource, DefinitionStages.WithDataDiskFromVhd, + DefinitionStages.WithDataDiskFromUpload, DefinitionStages.WithDataDiskFromDisk, + DefinitionStages.WithDataDiskFromSnapshot, DefinitionStages.WithStorageAccount, + DefinitionStages.WithCreateAndSize, DefinitionStages.WithCreate { } /** Grouping of managed disk definition stages. */ @@ -327,6 +318,7 @@ interface WithOSDiskFromImage { */ WithCreateAndSize fromImage(VirtualMachineCustomImage image); } + /** The stage of the managed disk definition allowing to choose source data disk image. */ interface WithDataDiskFromImage { /** @@ -479,16 +471,9 @@ interface WithPublicNetworkAccess { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithSku, - WithAvailabilityZone, - WithDiskEncryption, - WithHibernationSupport, - WithLogicalSectorSize, - WithHyperVGeneration, - WithPublicNetworkAccess { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + WithSku, WithAvailabilityZone, WithDiskEncryption, WithHibernationSupport, WithLogicalSectorSize, + WithHyperVGeneration, WithPublicNetworkAccess { /** * Begins creating the disk resource. @@ -581,6 +566,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the disk. * @@ -591,15 +577,8 @@ interface WithPublicNetworkAccess { } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithSize, - UpdateStages.WithOSSettings, - UpdateStages.WithDiskEncryption, - UpdateStages.WithHibernationSupport, - UpdateStages.WithHyperVGeneration, - UpdateStages.WithPublicNetworkAccess { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithSize, UpdateStages.WithOSSettings, UpdateStages.WithDiskEncryption, + UpdateStages.WithHibernationSupport, UpdateStages.WithHyperVGeneration, UpdateStages.WithPublicNetworkAccess { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSet.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSet.java index cd0eeba24947b..f0b2701ed1e44 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSet.java @@ -16,10 +16,8 @@ /** An immutable client-side representation of an Azure disk encryption set. */ @Fluent -public interface DiskEncryptionSet - extends GroupableResource, - Updatable, - Refreshable { +public interface DiskEncryptionSet extends GroupableResource, + Updatable, Refreshable { /** @return resource id of the Azure key vault containing the key or secret */ String keyVaultId(); @@ -42,23 +40,21 @@ public interface DiskEncryptionSet DiskEncryptionSetType encryptionType(); /** The entirety of the disk encryption set definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithEncryptionType, - DefinitionStages.WithKeyVault, - DefinitionStages.WithKeyVaultKey, + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, + DefinitionStages.WithEncryptionType, DefinitionStages.WithKeyVault, DefinitionStages.WithKeyVaultKey, DefinitionStages.WithSystemAssignedManagedServiceIdentity, - DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, - DefinitionStages.WithCreate { } + DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, DefinitionStages.WithCreate { + } /** Grouping of disk encryption set definition stages */ interface DefinitionStages { /** The first stage of a disk encryption set definition. */ - interface Blank extends DefinitionWithRegion { } + interface Blank extends DefinitionWithRegion { + } /** The stage of a disk encryption set definition allowing to specify the resource group. */ - interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { } + interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { + } /** * The stage of a disk encryption set definition allowing to set the disk encryption set type. @@ -158,17 +154,13 @@ interface WithAutomaticKeyRotation { * but also allows for any other optional settings to be specified. */ interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithAutomaticKeyRotation { } + extends Creatable, Resource.DefinitionWithTags, WithAutomaticKeyRotation { + } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSystemAssignedManagedServiceIdentity, - UpdateStages.WithAutomaticKeyRotation { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithSystemAssignedManagedServiceIdentity, UpdateStages.WithAutomaticKeyRotation { } /** Grouping of disk encryption set update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSets.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSets.java index 3e5af7b22d045..9e842472af8cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSets.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskEncryptionSets.java @@ -11,11 +11,7 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsDeletingById; /** Entry point to disk encryption set management API. */ -public interface DiskEncryptionSets - extends SupportsCreating, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsDeletingById { +public interface DiskEncryptionSets extends SupportsCreating, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsDeletingById { } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskVolumeEncryptionMonitor.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskVolumeEncryptionMonitor.java index 7f277a5a12c95..35839dcf45599 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskVolumeEncryptionMonitor.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/DiskVolumeEncryptionMonitor.java @@ -11,10 +11,13 @@ public interface DiskVolumeEncryptionMonitor extends Refreshable { /** @return operating system type of the virtual machine */ OperatingSystemTypes osType(); + /** @return the encryption progress message */ String progressMessage(); + /** @return operating system disk encryption status */ EncryptionStatus osDiskStatus(); + /** @return data disks encryption status */ EncryptionStatus dataDiskStatus(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disks.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disks.java index 3444c92c73a29..addedaf6c66c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disks.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Disks.java @@ -21,16 +21,9 @@ /** Entry point to managed disk management API in Azure. */ @Fluent public interface Disks - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Grants access to a disk. @@ -52,8 +45,8 @@ public interface Disks * @param accessDuration access duration * @return a representation of the deferred computation of this call returning a read-only SAS URI to the disk */ - Mono grantAccessAsync( - String resourceGroupName, String diskName, AccessLevel accessLevel, int accessDuration); + Mono grantAccessAsync(String resourceGroupName, String diskName, AccessLevel accessLevel, + int accessDuration); /** * Revoke access granted to a disk. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Galleries.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Galleries.java index 82422c9aa5c87..69e50e3fd69ff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Galleries.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Galleries.java @@ -14,10 +14,6 @@ /** Entry point to galleries management API in Azure. */ @Fluent public interface Galleries - extends SupportsCreating, - SupportsDeletingByResourceGroup, - SupportsBatchDeletion, - SupportsGettingByResourceGroup, - SupportsListingByResourceGroup, - SupportsListing { + extends SupportsCreating, SupportsDeletingByResourceGroup, SupportsBatchDeletion, + SupportsGettingByResourceGroup, SupportsListingByResourceGroup, SupportsListing { } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Gallery.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Gallery.java index 030e1427e6d88..930b983f00117 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Gallery.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Gallery.java @@ -21,14 +21,8 @@ /** An immutable client-side representation of an Azure gallery. */ @Fluent -public interface Gallery - extends HasInnerModel, - Resource, - GroupableResource, - HasResourceGroup, - Refreshable, - Updatable, - HasManager { +public interface Gallery extends HasInnerModel, Resource, GroupableResource, + HasResourceGroup, Refreshable, Updatable, HasManager { /** @return description for the gallery resource. */ String description(); @@ -103,6 +97,7 @@ interface WithCreate extends Creatable, Resource.DefinitionWithTags, DefinitionStages.WithDescription { } } + /** The template for a Gallery update operation, containing all the settings that can be modified. */ interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithDescription { } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImage.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImage.java index ed1ffc00f7dd4..294bb810e5fe3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImage.java @@ -26,12 +26,8 @@ * multiple versions of the same image. */ @Fluent -public interface GalleryImage - extends HasInnerModel, - Indexable, - Refreshable, - Updatable, - HasManager { +public interface GalleryImage extends HasInnerModel, Indexable, Refreshable, + Updatable, HasManager { /** @return the description of the image. */ String description(); @@ -125,13 +121,8 @@ public interface GalleryImage PagedIterable listVersions(); /** The entirety of the gallery image definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGallery, - DefinitionStages.WithLocation, - DefinitionStages.WithIdentifier, - DefinitionStages.WithOsTypeAndState, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGallery, DefinitionStages.WithLocation, + DefinitionStages.WithIdentifier, DefinitionStages.WithOsTypeAndState, DefinitionStages.WithCreate { } /** Grouping of gallery image definition stages. */ @@ -446,33 +437,19 @@ interface WithTags { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithDescription, - DefinitionStages.WithDisallowed, - DefinitionStages.WithEndOfLifeDate, - DefinitionStages.WithEula, - DefinitionStages.WithPrivacyStatementUri, - DefinitionStages.WithPurchasePlan, - DefinitionStages.WithRecommendedVMConfiguration, - DefinitionStages.WithReleaseNoteUri, - DefinitionStages.WithHyperVGeneration, - DefinitionStages.WithSecurityTypes, - DefinitionStages.WithTags { + interface WithCreate extends Creatable, DefinitionStages.WithDescription, + DefinitionStages.WithDisallowed, DefinitionStages.WithEndOfLifeDate, DefinitionStages.WithEula, + DefinitionStages.WithPrivacyStatementUri, DefinitionStages.WithPurchasePlan, + DefinitionStages.WithRecommendedVMConfiguration, DefinitionStages.WithReleaseNoteUri, + DefinitionStages.WithHyperVGeneration, DefinitionStages.WithSecurityTypes, DefinitionStages.WithTags { } } + /** The template for a gallery image update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithDescription, - UpdateStages.WithDisallowed, - UpdateStages.WithEndOfLifeDate, - UpdateStages.WithEula, - UpdateStages.WithOsState, - UpdateStages.WithPrivacyStatementUri, - UpdateStages.WithRecommendedVMConfiguration, - UpdateStages.WithReleaseNoteUri, - UpdateStages.WithTags { + interface Update extends Appliable, UpdateStages.WithDescription, UpdateStages.WithDisallowed, + UpdateStages.WithEndOfLifeDate, UpdateStages.WithEula, UpdateStages.WithOsState, + UpdateStages.WithPrivacyStatementUri, UpdateStages.WithRecommendedVMConfiguration, + UpdateStages.WithReleaseNoteUri, UpdateStages.WithTags { } /** Grouping of gallery image update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersion.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersion.java index ba97bf03032ef..705283ec2d4e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersion.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersion.java @@ -20,12 +20,8 @@ /** An immutable client-side representation of an Azure gallery image version. */ @Fluent -public interface GalleryImageVersion - extends HasInnerModel, - Indexable, - Refreshable, - Updatable, - HasManager { +public interface GalleryImageVersion extends HasInnerModel, Indexable, + Refreshable, Updatable, HasManager { /** @return the ARM id of the image version. */ String id(); @@ -66,12 +62,8 @@ public interface GalleryImageVersion String type(); /** The entirety of the gallery image version definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithImage, - DefinitionStages.WithLocation, - DefinitionStages.WithSource, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithImage, DefinitionStages.WithLocation, + DefinitionStages.WithSource, DefinitionStages.WithCreate { } /** Grouping of gallery image version definition stages. */ @@ -209,21 +201,14 @@ interface WithTags { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithAvailableRegion, - DefinitionStages.WithEndOfLifeDate, - DefinitionStages.WithExcludeFromLatest, - DefinitionStages.WithTags { + interface WithCreate extends Creatable, DefinitionStages.WithAvailableRegion, + DefinitionStages.WithEndOfLifeDate, DefinitionStages.WithExcludeFromLatest, DefinitionStages.WithTags { } } + /** The template for a gallery image version update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithAvailableRegion, - UpdateStages.WithEndOfLifeDate, - UpdateStages.WithExcludeFromLatest, - UpdateStages.WithTags { + interface Update extends Appliable, UpdateStages.WithAvailableRegion, + UpdateStages.WithEndOfLifeDate, UpdateStages.WithExcludeFromLatest, UpdateStages.WithTags { } /** Grouping of gallery image version update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersions.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersions.java index ef9e758ab7ec3..7f9a2ac8c7ad3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersions.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImageVersions.java @@ -22,8 +22,8 @@ public interface GalleryImageVersions extends SupportsCreating getByGalleryImageAsync( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName); + Mono getByGalleryImageAsync(String resourceGroupName, String galleryName, + String galleryImageName, String galleryImageVersionName); /** * Retrieves information about a gallery image version. @@ -35,8 +35,8 @@ Mono getByGalleryImageAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the gallery image version resource */ - GalleryImageVersion getByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName); + GalleryImageVersion getByGalleryImage(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName); /** * List gallery image versions under a gallery image. @@ -47,8 +47,8 @@ GalleryImageVersion getByGalleryImage( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - PagedFlux listByGalleryImageAsync( - String resourceGroupName, String galleryName, String galleryImageName); + PagedFlux listByGalleryImageAsync(String resourceGroupName, String galleryName, + String galleryImageName); /** * List gallery image versions under a gallery image. @@ -59,8 +59,8 @@ PagedFlux listByGalleryImageAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return list of gallery image versions */ - PagedIterable listByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName); + PagedIterable listByGalleryImage(String resourceGroupName, String galleryName, + String galleryImageName); /** * Delete a gallery image version. @@ -72,8 +72,8 @@ PagedIterable listByGalleryImage( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the completable for the request */ - Mono deleteByGalleryImageAsync( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName); + Mono deleteByGalleryImageAsync(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName); /** * Delete a gallery image version. @@ -84,6 +84,6 @@ Mono deleteByGalleryImageAsync( * @param galleryImageVersionName The name of the gallery image version. * @throws IllegalArgumentException thrown if parameters fail the validation */ - void deleteByGalleryImage( - String resourceGroupName, String galleryName, String galleryImageName, String galleryImageVersionName); + void deleteByGalleryImage(String resourceGroupName, String galleryName, String galleryImageName, + String galleryImageVersionName); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownLinuxVirtualMachineImage.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownLinuxVirtualMachineImage.java index c53a43eac519a..c97bd154eb7f2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownLinuxVirtualMachineImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownLinuxVirtualMachineImage.java @@ -43,7 +43,6 @@ public enum KnownLinuxVirtualMachineImage { /** Oracle Linux 8.1. */ ORACLE_LINUX_8_1("Oracle", "Oracle-Linux", "81"), - /** UbuntuServer 18.04LTS Gen2. */ UBUNTU_SERVER_18_04_LTS_GEN2("Canonical", "UbuntuServer", "18_04-lts-gen2"), /** UbuntuServer 20.04LTS. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownWindowsVirtualMachineImage.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownWindowsVirtualMachineImage.java index 52de4a4717067..c401dcc882997 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownWindowsVirtualMachineImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/KnownWindowsVirtualMachineImage.java @@ -17,8 +17,8 @@ public enum KnownWindowsVirtualMachineImage { * @deprecated On May 23rd, 2023, Microsoft was contractually obligated to remove all “*-with-Containers-*” VM images from Azure image gallery. */ @Deprecated - WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS( - "MicrosoftWindowsServer", "WindowsServer", "2019-Datacenter-with-Containers"), + WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS("MicrosoftWindowsServer", "WindowsServer", + "2019-Datacenter-with-Containers"), /** Windows Server 2016 Data center. */ WINDOWS_SERVER_2016_DATACENTER("MicrosoftWindowsServer", "WindowsServer", "2016-Datacenter"), /** Windows Server 2012 R2 Data center. */ @@ -30,8 +30,8 @@ public enum KnownWindowsVirtualMachineImage { * @deprecated On May 23rd, 2023, Microsoft was contractually obligated to remove all “*-with-Containers-*” VM images from Azure image gallery. */ @Deprecated - WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS_GEN2( - "MicrosoftWindowsServer", "WindowsServer", "2019-datacenter-with-containers-g2"), + WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS_GEN2("MicrosoftWindowsServer", "WindowsServer", + "2019-datacenter-with-containers-g2"), /** Windows Server 2016 Data center gen2. */ WINDOWS_SERVER_2016_DATACENTER_GEN2("MicrosoftWindowsServer", "WindowsServer", "2016-datacenter-gensecond"), /** Windows 10 2021 H2 Pro gen2. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/LinuxVMDiskEncryptionConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/LinuxVMDiskEncryptionConfiguration.java index 09e9d08ad6312..04528e3656cde 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/LinuxVMDiskEncryptionConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/LinuxVMDiskEncryptionConfiguration.java @@ -29,10 +29,8 @@ public LinuxVMDiskEncryptionConfiguration(String keyVaultId, String aadClientId, * @param aadClientId client ID of an AAD application which has permission to the KeyVault * @param aadSecret client secret corresponding to the client ID */ - public LinuxVMDiskEncryptionConfiguration(String keyVaultId, - String vaultUri, - String aadClientId, - String aadSecret) { + public LinuxVMDiskEncryptionConfiguration(String keyVaultId, String vaultUri, String aadClientId, + String aadSecret) { super(keyVaultId, vaultUri, aadClientId, aadSecret, null); } @@ -46,10 +44,8 @@ public LinuxVMDiskEncryptionConfiguration(String keyVaultId, * @param aadSecret client secret corresponding to the client ID * @param azureEnvironment Azure environment */ - public LinuxVMDiskEncryptionConfiguration(String keyVaultId, - String aadClientId, - String aadSecret, - AzureEnvironment azureEnvironment) { + public LinuxVMDiskEncryptionConfiguration(String keyVaultId, String aadClientId, String aadSecret, + AzureEnvironment azureEnvironment) { super(keyVaultId, null, aadClientId, aadSecret, azureEnvironment); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshot.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshot.java index 274cc89ccbbbb..538fa95b624c0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshot.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshot.java @@ -110,17 +110,11 @@ public interface Snapshot Mono awaitCopyStartCompletionAsync(); /** The entirety of the managed snapshot definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSnapshotSource, - DefinitionStages.WithWindowsSnapshotSource, - DefinitionStages.WithLinuxSnapshotSource, - DefinitionStages.WithDataSnapshotSource, - DefinitionStages.WithDataSnapshotFromVhd, - DefinitionStages.WithDataSnapshotFromDisk, - DefinitionStages.WithDataSnapshotFromSnapshot, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, + DefinitionStages.WithSnapshotSource, DefinitionStages.WithWindowsSnapshotSource, + DefinitionStages.WithLinuxSnapshotSource, DefinitionStages.WithDataSnapshotSource, + DefinitionStages.WithDataSnapshotFromVhd, DefinitionStages.WithDataSnapshotFromDisk, + DefinitionStages.WithDataSnapshotFromSnapshot, DefinitionStages.WithCreate { } /** Grouping of managed snapshot definition stages. */ @@ -350,6 +344,7 @@ interface WithOSSnapshotFromImage { */ WithCreate fromImage(VirtualMachineCustomImage image); } + /** The stage of the managed disk definition allowing to choose source data disk image. */ interface WithDataSnapshotFromImage { /** @@ -428,13 +423,8 @@ interface WithPublicNetworkAccess { * but also allows for any other optional settings to be specified. */ interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithSize, - WithSku, - WithIncremental, - WithCopyStart, - WithPublicNetworkAccess { + extends Creatable, Resource.DefinitionWithTags, WithSize, + WithSku, WithIncremental, WithCopyStart, WithPublicNetworkAccess { } } @@ -470,6 +460,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the snapshot. * @@ -480,11 +471,7 @@ interface WithPublicNetworkAccess { } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithOSSettings, - UpdateStages.WithPublicNetworkAccess { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithOSSettings, UpdateStages.WithPublicNetworkAccess { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshots.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshots.java index 1849503a8fe96..333dcb5b92495 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshots.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Snapshots.java @@ -19,17 +19,10 @@ /** Entry point to managed snapshot management API in Azure. */ @Fluent -public interface Snapshots - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface Snapshots extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, + HasManager { /** * Grants access to the snapshot asynchronously. * @@ -39,8 +32,8 @@ public interface Snapshots * @param accessDuration access duration * @return a representation of the deferred computation of this call returning a read-only SAS URI to the snapshot */ - Mono grantAccessAsync( - String resourceGroupName, String snapshotName, AccessLevel accessLevel, int accessDuration); + Mono grantAccessAsync(String resourceGroupName, String snapshotName, AccessLevel accessLevel, + int accessDuration); /** * Grants access to a snapshot. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachine.java index a1e0959057f6e..fb1f87fe67b9e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachine.java @@ -32,11 +32,8 @@ /** An immutable client-side representation of an Azure virtual machine. */ @Fluent -public interface VirtualMachine - extends GroupableResource, - Refreshable, - Updatable, - HasNetworkInterfaces { +public interface VirtualMachine extends GroupableResource, + Refreshable, Updatable, HasNetworkInterfaces { // Actions /** Shuts down the virtual machine and releases the compute resources. */ void deallocate(); @@ -213,8 +210,8 @@ public interface VirtualMachine * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runPowerShellScriptAsync( - List scriptLines, List scriptParameters); + Mono runPowerShellScriptAsync(List scriptLines, + List scriptParameters); /** * Run shell script in the virtual machine. @@ -232,8 +229,8 @@ Mono runPowerShellScriptAsync( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runShellScriptAsync( - List scriptLines, List scriptParameters); + Mono runShellScriptAsync(List scriptLines, + List scriptParameters); /** * Run commands in the virtual machine. @@ -462,65 +459,40 @@ Mono runShellScriptAsync( // /** The virtual machine scale set stages shared between managed and unmanaged based virtual machine definitions. */ - interface DefinitionShared - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithNetwork, - DefinitionStages.WithSubnet, - DefinitionStages.WithPrivateIP, - DefinitionStages.WithPublicIPAddress, - DefinitionStages.WithPrimaryNetworkInterface, - DefinitionStages.WithOS, - DefinitionStages.WithProximityPlacementGroup, - DefinitionStages.WithSecurityFeatures, - DefinitionStages.WithCreate { + interface DefinitionShared extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithNetwork, + DefinitionStages.WithSubnet, DefinitionStages.WithPrivateIP, DefinitionStages.WithPublicIPAddress, + DefinitionStages.WithPrimaryNetworkInterface, DefinitionStages.WithOS, + DefinitionStages.WithProximityPlacementGroup, DefinitionStages.WithSecurityFeatures, + DefinitionStages.WithCreate { } /** The entirety of the virtual machine definition. */ interface DefinitionManagedOrUnmanaged - extends DefinitionShared, - DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged, - DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged, - DefinitionStages.WithWindowsAdminPasswordManagedOrUnmanaged, - DefinitionStages.WithFromImageCreateOptionsManagedOrUnmanaged, - DefinitionStages.WithLinuxCreateManagedOrUnmanaged, - DefinitionStages.WithWindowsCreateManagedOrUnmanaged, - DefinitionStages.WithManagedCreate, - DefinitionStages.WithUnmanagedCreate { + extends DefinitionShared, DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged, + DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged, + DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged, + DefinitionStages.WithWindowsAdminPasswordManagedOrUnmanaged, + DefinitionStages.WithFromImageCreateOptionsManagedOrUnmanaged, + DefinitionStages.WithLinuxCreateManagedOrUnmanaged, DefinitionStages.WithWindowsCreateManagedOrUnmanaged, + DefinitionStages.WithManagedCreate, DefinitionStages.WithUnmanagedCreate { } /** The entirety of the managed disk based virtual machine definition. */ - interface DefinitionManaged - extends DefinitionShared, - DefinitionStages.WithLinuxRootUsernameManaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged, - DefinitionStages.WithWindowsAdminUsernameManaged, - DefinitionStages.WithWindowsAdminPasswordManaged, - DefinitionStages.WithFromImageCreateOptionsManaged, - DefinitionStages.WithLinuxCreateManaged, - DefinitionStages.WithWindowsCreateManaged, - DefinitionStages.WithManagedCreate { + interface DefinitionManaged extends DefinitionShared, DefinitionStages.WithLinuxRootUsernameManaged, + DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged, DefinitionStages.WithWindowsAdminUsernameManaged, + DefinitionStages.WithWindowsAdminPasswordManaged, DefinitionStages.WithFromImageCreateOptionsManaged, + DefinitionStages.WithLinuxCreateManaged, DefinitionStages.WithWindowsCreateManaged, + DefinitionStages.WithManagedCreate { } /** The entirety of the unmanaged disk based virtual machine definition. */ - interface DefinitionUnmanaged - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithNetwork, - DefinitionStages.WithSubnet, - DefinitionStages.WithPrivateIP, - DefinitionStages.WithPublicIPAddress, - DefinitionStages.WithPrimaryNetworkInterface, - DefinitionStages.WithOS, - DefinitionStages.WithLinuxRootUsernameUnmanaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged, - DefinitionStages.WithWindowsAdminUsernameUnmanaged, - DefinitionStages.WithWindowsAdminPasswordUnmanaged, - DefinitionStages.WithFromImageCreateOptionsUnmanaged, - DefinitionStages.WithLinuxCreateUnmanaged, - DefinitionStages.WithWindowsCreateUnmanaged, - DefinitionStages.WithUnmanagedCreate { + interface DefinitionUnmanaged extends DefinitionStages.Blank, DefinitionStages.WithGroup, + DefinitionStages.WithNetwork, DefinitionStages.WithSubnet, DefinitionStages.WithPrivateIP, + DefinitionStages.WithPublicIPAddress, DefinitionStages.WithPrimaryNetworkInterface, DefinitionStages.WithOS, + DefinitionStages.WithLinuxRootUsernameUnmanaged, DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged, + DefinitionStages.WithWindowsAdminUsernameUnmanaged, DefinitionStages.WithWindowsAdminPasswordUnmanaged, + DefinitionStages.WithFromImageCreateOptionsUnmanaged, DefinitionStages.WithLinuxCreateUnmanaged, + DefinitionStages.WithWindowsCreateUnmanaged, DefinitionStages.WithUnmanagedCreate { } /** Grouping of virtual machine definition stages. */ @@ -629,17 +601,17 @@ interface WithPublicIPAddress { */ WithProximityPlacementGroup withNewPrimaryPublicIPAddress(String leafDnsLabel); -// /** -// * Creates a new public IP address in the same region and resource group as the resource, with the specified -// * DNS label and associates it with the VM's primary network interface. -// * -// *

The internal name for the public IP address will be derived from the DNS label. -// * -// * @param leafDnsLabel a leaf domain label -// * @param deleteOptions the delete options for the IP address -// * @return the next stage of the definition -// */ -// WithProximityPlacementGroup withNewPrimaryPublicIPAddress(String leafDnsLabel, DeleteOptions deleteOptions); + // /** + // * Creates a new public IP address in the same region and resource group as the resource, with the specified + // * DNS label and associates it with the VM's primary network interface. + // * + // *

The internal name for the public IP address will be derived from the DNS label. + // * + // * @param leafDnsLabel a leaf domain label + // * @param deleteOptions the delete options for the IP address + // * @return the next stage of the definition + // */ + // WithProximityPlacementGroup withNewPrimaryPublicIPAddress(String leafDnsLabel, DeleteOptions deleteOptions); /** * Associates an existing public IP address with the VM's primary network interface. @@ -709,8 +681,8 @@ interface WithOS { * @param knownImage a known market-place image * @return the next stage of the definition */ - WithWindowsAdminUsernameManagedOrUnmanaged withPopularWindowsImage( - KnownWindowsVirtualMachineImage knownImage); + WithWindowsAdminUsernameManagedOrUnmanaged + withPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage); /** * Specifies that the latest version of a marketplace Windows image should to be used as the virtual @@ -721,8 +693,8 @@ WithWindowsAdminUsernameManagedOrUnmanaged withPopularWindowsImage( * @param sku specifies the SKU of the image * @return the next stage of the definition */ - WithWindowsAdminUsernameManagedOrUnmanaged withLatestWindowsImage( - String publisher, String offer, String sku); + WithWindowsAdminUsernameManagedOrUnmanaged withLatestWindowsImage(String publisher, String offer, + String sku); /** * Specifies a version of a marketplace Windows image to be used as the virtual machine's OS. @@ -1319,8 +1291,8 @@ interface WithUnmanagedDataDisk { * @param vhdName the name for the VHD file * @return the next stage of the definition */ - WithUnmanagedCreate withExistingUnmanagedDataDisk( - String storageAccountName, String containerName, String vhdName); + WithUnmanagedCreate withExistingUnmanagedDataDisk(String storageAccountName, String containerName, + String vhdName); /** * Begins definition of an unmanaged data disk to be attached to the virtual machine. @@ -1328,8 +1300,8 @@ WithUnmanagedCreate withExistingUnmanagedDataDisk( * @param name the name for the data disk * @return the first stage of an unmanaged data disk definition */ - VirtualMachineUnmanagedDataDisk.DefinitionStages.Blank defineUnmanagedDataDisk( - String name); + VirtualMachineUnmanagedDataDisk.DefinitionStages.Blank + defineUnmanagedDataDisk(String name); } /** The stage of a virtual machine definition allowing to specify a managed data disk. */ @@ -1381,8 +1353,8 @@ interface WithManagedDataDisk { * @param storageAccountType the storage account type * @return the next stage of the definition */ - WithManagedCreate withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType); + WithManagedCreate withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType); /** * Specifies that a managed disk needs to be created implicitly with the given settings. @@ -1422,7 +1394,7 @@ WithManagedCreate withNewDataDisk( * @return the next stage of the definition */ WithManagedCreate withExistingDataDisk(Disk disk, int newSizeInGB, int lun, - VirtualMachineDiskOptions options); + VirtualMachineDiskOptions options); /** * Associates an existing source managed disk with the virtual machine and specifies additional settings. @@ -1462,8 +1434,8 @@ WithManagedCreate withExistingDataDisk(Disk disk, int newSizeInGB, int lun, * @param storageAccountType a storage account type * @return the next stage of the definition */ - WithManagedCreate withNewDataDiskFromImage( - int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType); + WithManagedCreate withNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, + StorageAccountTypes storageAccountType); /** * Specifies the data disk to be created from the data disk image in the virtual machine image. @@ -1473,8 +1445,8 @@ WithManagedCreate withNewDataDiskFromImage( * @param options the disk options * @return the next stage of the definition */ - WithManagedCreate withNewDataDiskFromImage( - int imageLun, int newSizeInGB, VirtualMachineDiskOptions options); + WithManagedCreate withNewDataDiskFromImage(int imageLun, int newSizeInGB, + VirtualMachineDiskOptions options); } /** The stage of the virtual machine definition allowing to specify availability set. */ @@ -1565,7 +1537,7 @@ interface WithSecondaryNetworkInterface { * @return the next stage of the definition */ WithCreate withNewSecondaryNetworkInterface(Creatable creatable, - DeleteOptions deleteOptions); + DeleteOptions deleteOptions); /** * Associates an existing network interface with the virtual machine. @@ -1736,8 +1708,8 @@ interface WithSystemAssignedIdentityBasedAccessOrCreate extends WithCreate { * @param role access role to assigned to the virtual machine's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + BuiltInRole role); /** * Specifies that virtual machine's system assigned (local) identity should have the given access (described @@ -1747,8 +1719,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param role access role to assigned to the virtual machine's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /** * Specifies that virtual machine's system assigned (local) identity should have the access (described by @@ -1759,8 +1731,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the virtual machine's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + String roleDefinitionId); /** * Specifies that virtual machine's system assigned (local) identity should have the access (described by @@ -1770,8 +1742,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the virtual machine's local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId); } /** @@ -1984,29 +1956,16 @@ interface WithUserData { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithOSDiskSettings, - DefinitionStages.WithVMSize, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithAvailabilitySet, - DefinitionStages.WithSecondaryNetworkInterface, - DefinitionStages.WithExtension, - DefinitionStages.WithPlan, - DefinitionStages.WithBootDiagnostics, - DefinitionStages.WithPriority, - DefinitionStages.WithBillingProfile, - DefinitionStages.WithSystemAssignedManagedServiceIdentity, - DefinitionStages.WithUserAssignedManagedServiceIdentity, - DefinitionStages.WithLicenseType, - DefinitionStages.WithAdditionalCapacities, - DefinitionStages.WithNetworkInterfaceDeleteOptions, - DefinitionStages.WithEphemeralOSDisk, - DefinitionStages.WithScaleSet, - DefinitionStages.WithSecurityTypes, - DefinitionStages.WithSecurityProfile, - DefinitionStages.WithUserData { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithOSDiskSettings, DefinitionStages.WithVMSize, DefinitionStages.WithStorageAccount, + DefinitionStages.WithAvailabilitySet, DefinitionStages.WithSecondaryNetworkInterface, + DefinitionStages.WithExtension, DefinitionStages.WithPlan, DefinitionStages.WithBootDiagnostics, + DefinitionStages.WithPriority, DefinitionStages.WithBillingProfile, + DefinitionStages.WithSystemAssignedManagedServiceIdentity, + DefinitionStages.WithUserAssignedManagedServiceIdentity, DefinitionStages.WithLicenseType, + DefinitionStages.WithAdditionalCapacities, DefinitionStages.WithNetworkInterfaceDeleteOptions, + DefinitionStages.WithEphemeralOSDisk, DefinitionStages.WithScaleSet, DefinitionStages.WithSecurityTypes, + DefinitionStages.WithSecurityProfile, DefinitionStages.WithUserData { /** * Begins creating the virtual machine resource. @@ -2158,8 +2117,8 @@ interface WithManagedDataDisk { * @param storageAccountType a storage account type * @return the next stage of the update */ - Update withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType); + Update withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType); /** * Specifies that a managed disk needs to be created implicitly with the given settings. @@ -2243,8 +2202,7 @@ interface WithSecondaryNetworkInterface { * @param deleteOptions the delete options for the secondary network interface * @return the next stage of the definition */ - Update withNewSecondaryNetworkInterface(Creatable creatable, - DeleteOptions deleteOptions); + Update withNewSecondaryNetworkInterface(Creatable creatable, DeleteOptions deleteOptions); /** * Associates an existing network interface with the virtual machine. @@ -2376,8 +2334,8 @@ interface WithSystemAssignedIdentityBasedAccessOrUpdate extends Update { * @param role access role to assigned to the virtual machine's local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessTo(String resourceId, + BuiltInRole role); /** * Specifies that virtual machine's system assigned (local) identity should have the given access (described @@ -2387,8 +2345,8 @@ WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAcc * @param role access role to assigned to the virtual machine's local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrUpdate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /** * Specifies that virtual machine's system assigned (local) identity should have the access (described by @@ -2399,8 +2357,8 @@ WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the virtual machine's local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessTo(String resourceId, + String roleDefinitionId); /** * Specifies that virtual machine's system assigned (local) identity should have the access (described by @@ -2410,8 +2368,8 @@ WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the virtual machine's local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrUpdate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrUpdate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId); } /** @@ -2662,25 +2620,13 @@ interface WithUserData { } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithProximityPlacementGroup, - UpdateStages.WithUnmanagedDataDisk, - UpdateStages.WithManagedDataDisk, - UpdateStages.WithSecondaryNetworkInterface, - UpdateStages.WithExtension, - UpdateStages.WithBootDiagnostics, - UpdateStages.WithBillingProfile, - UpdateStages.WithSystemAssignedManagedServiceIdentity, - UpdateStages.WithUserAssignedManagedServiceIdentity, - UpdateStages.WithLicenseType, - UpdateStages.WithAdditionalCapacities, - UpdateStages.WithOSDisk, - UpdateStages.WithSecurityFeatures, - UpdateStages.WithDeleteOptions, - UpdateStages.WithSecurityProfile, - UpdateStages.WithUserData { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithProximityPlacementGroup, UpdateStages.WithUnmanagedDataDisk, UpdateStages.WithManagedDataDisk, + UpdateStages.WithSecondaryNetworkInterface, UpdateStages.WithExtension, UpdateStages.WithBootDiagnostics, + UpdateStages.WithBillingProfile, UpdateStages.WithSystemAssignedManagedServiceIdentity, + UpdateStages.WithUserAssignedManagedServiceIdentity, UpdateStages.WithLicenseType, + UpdateStages.WithAdditionalCapacities, UpdateStages.WithOSDisk, UpdateStages.WithSecurityFeatures, + UpdateStages.WithDeleteOptions, UpdateStages.WithSecurityProfile, UpdateStages.WithUserData { /** * Specifies the encryption settings for the OS Disk. * diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImage.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImage.java index f74fb1ac42e82..52c5c98209098 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImage.java @@ -36,13 +36,9 @@ public interface VirtualMachineCustomImage /** The entirety of the image definition. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithHyperVGeneration, - DefinitionStages.WithOSDiskImageSourceAltVirtualMachineSource, - DefinitionStages.WithOSDiskImageSource, - DefinitionStages.WithSourceVirtualMachine, - DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings { + extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithHyperVGeneration, + DefinitionStages.WithOSDiskImageSourceAltVirtualMachineSource, DefinitionStages.WithOSDiskImageSource, + DefinitionStages.WithSourceVirtualMachine, DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings { } /** Grouping of image definition stages. */ @@ -85,8 +81,8 @@ interface WithOSDiskImageSource { * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withWindowsFromVhd( - String sourceVhdUrl, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withWindowsFromVhd(String sourceVhdUrl, + OperatingSystemStateTypes osState); /** * Specifies the Linux source native VHD for the OS disk image. @@ -95,8 +91,8 @@ WithCreateAndDataDiskImageOSDiskSettings withWindowsFromVhd( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withLinuxFromVhd( - String sourceVhdUrl, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withLinuxFromVhd(String sourceVhdUrl, + OperatingSystemStateTypes osState); /** * Specifies the Windows source snapshot for the OS disk image. @@ -105,8 +101,8 @@ WithCreateAndDataDiskImageOSDiskSettings withLinuxFromVhd( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot( - Snapshot sourceSnapshot, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot(Snapshot sourceSnapshot, + OperatingSystemStateTypes osState); /** * Specifies the Linux source snapshot for the OS disk image. @@ -115,8 +111,8 @@ WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot( - Snapshot sourceSnapshot, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot(Snapshot sourceSnapshot, + OperatingSystemStateTypes osState); /** * Specifies the Windows source snapshot for the OS disk image. @@ -125,8 +121,8 @@ WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot( - String sourceSnapshotId, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot(String sourceSnapshotId, + OperatingSystemStateTypes osState); /** * Specifies the Linux source snapshot for the OS disk image. @@ -135,8 +131,8 @@ WithCreateAndDataDiskImageOSDiskSettings withWindowsFromSnapshot( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot( - String sourceSnapshotId, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot(String sourceSnapshotId, + OperatingSystemStateTypes osState); /** * Specifies the Windows source managed disk for the OS disk image. @@ -145,8 +141,8 @@ WithCreateAndDataDiskImageOSDiskSettings withLinuxFromSnapshot( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk( - String sourceManagedDiskId, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk(String sourceManagedDiskId, + OperatingSystemStateTypes osState); /** * Specifies the Linux source managed disk for the OS disk image. @@ -155,8 +151,8 @@ WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withLinuxFromDisk( - String sourceManagedDiskId, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withLinuxFromDisk(String sourceManagedDiskId, + OperatingSystemStateTypes osState); /** * Specifies the Windows source managed disk for the OS disk image. @@ -165,8 +161,8 @@ WithCreateAndDataDiskImageOSDiskSettings withLinuxFromDisk( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk( - Disk sourceManagedDisk, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk(Disk sourceManagedDisk, + OperatingSystemStateTypes osState); /** * Specifies the Linux source managed disk for the OS disk image. @@ -175,8 +171,8 @@ WithCreateAndDataDiskImageOSDiskSettings withWindowsFromDisk( * @param osState operating system state * @return the next stage of the definition */ - WithCreateAndDataDiskImageOSDiskSettings withLinuxFromDisk( - Disk sourceManagedDisk, OperatingSystemStateTypes osState); + WithCreateAndDataDiskImageOSDiskSettings withLinuxFromDisk(Disk sourceManagedDisk, + OperatingSystemStateTypes osState); } /** The stage of the image definition allowing to choose source virtual machine. */ @@ -277,10 +273,8 @@ interface WithZoneResilient { * The stage of an image definition containing all the required inputs for the resource to be created, but also * allowing for any other optional settings to be specified. */ - interface WithCreate - extends DefinitionStages.WithZoneResilient, - Creatable, - Resource.DefinitionWithTags { + interface WithCreate extends DefinitionStages.WithZoneResilient, Creatable, + Resource.DefinitionWithTags { } } @@ -392,12 +386,9 @@ interface WithAttach extends Attachable.InDefinition, WithDisk * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithDiskLun, - DefinitionStages.WithImageSource, - DefinitionStages.WithDiskSettings, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithDiskLun, + DefinitionStages.WithImageSource, DefinitionStages.WithDiskSettings, + DefinitionStages.WithAttach { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImages.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImages.java index 5e71661ff4fc5..d9beb53763e6a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineCustomImages.java @@ -18,15 +18,10 @@ /** Entry point to custom virtual machine image management. */ @Fluent -public interface VirtualMachineCustomImages - extends SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface VirtualMachineCustomImages extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, + HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineEncryptionConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineEncryptionConfiguration.java index 4a7610cbc6e33..897cb4b4f4791 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineEncryptionConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineEncryptionConfiguration.java @@ -75,23 +75,14 @@ public abstract class VirtualMachineEncryptionConfiguration { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - WithAutoUpgradeMinorVersion, - WithSettings, - WithTags { + interface WithAttach extends Attachable.InDefinition, WithAutoUpgradeMinorVersion, + WithSettings, WithTags { } /** @@ -204,12 +201,9 @@ interface WithTags { * @param the stage of the parent definition to return to after attaching this definition */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithImageOrPublisher, - DefinitionStages.WithPublisher, - DefinitionStages.WithType, - DefinitionStages.WithVersion, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithImageOrPublisher, + DefinitionStages.WithPublisher, DefinitionStages.WithType, + DefinitionStages.WithVersion, DefinitionStages.WithAttach { } /** Grouping of virtual machine extension definition stages as part of parent virtual machine update. */ @@ -291,11 +285,8 @@ interface WithVersion { * * @param the stage of the parent update to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - WithAutoUpgradeMinorVersion, - WithSettings, - WithTags { + interface WithAttach extends Attachable.InUpdate, WithAutoUpgradeMinorVersion, + WithSettings, WithTags { } /** @@ -392,12 +383,9 @@ interface WithTags { * @param the stage of the parent update to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithImageOrPublisher, - UpdateDefinitionStages.WithPublisher, - UpdateDefinitionStages.WithType, - UpdateDefinitionStages.WithVersion, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithImageOrPublisher, + UpdateDefinitionStages.WithPublisher, UpdateDefinitionStages.WithType, + UpdateDefinitionStages.WithVersion, UpdateDefinitionStages.WithAttach { } /** Grouping of virtual machine extension update stages. */ @@ -489,10 +477,7 @@ interface WithTags { } /** The entirety of virtual machine extension update as a part of parent virtual machine update. */ - interface Update - extends Settable, - UpdateStages.WithAutoUpgradeMinorVersion, - UpdateStages.WithSettings, - UpdateStages.WithTags { + interface Update extends Settable, UpdateStages.WithAutoUpgradeMinorVersion, + UpdateStages.WithSettings, UpdateStages.WithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSet.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSet.java index 4da16fc94f0c4..19c50b472c7cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSet.java @@ -34,10 +34,8 @@ /** An immutable client-side representation of an Azure virtual machine scale set. */ @Fluent -public interface VirtualMachineScaleSet - extends GroupableResource, - Refreshable, - Updatable { +public interface VirtualMachineScaleSet extends GroupableResource, + Refreshable, Updatable { // Actions /** @return entry point to manage virtual machine instances in the scale set. */ VirtualMachineScaleSetVMs virtualMachines(); @@ -107,8 +105,8 @@ public interface VirtualMachineScaleSet * @param scriptParameters script parameters * @return result of PowerShell script execution */ - RunCommandResult runPowerShellScriptInVMInstance( - String vmId, List scriptLines, List scriptParameters); + RunCommandResult runPowerShellScriptInVMInstance(String vmId, List scriptLines, + List scriptParameters); /** * Run PowerShell in a virtual machine instance in a scale set asynchronously. @@ -118,8 +116,8 @@ RunCommandResult runPowerShellScriptInVMInstance( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runPowerShellScriptInVMInstanceAsync( - String vmId, List scriptLines, List scriptParameters); + Mono runPowerShellScriptInVMInstanceAsync(String vmId, List scriptLines, + List scriptParameters); /** * Run shell script in a virtual machine instance in a scale set. @@ -129,8 +127,8 @@ Mono runPowerShellScriptInVMInstanceAsync( * @param scriptParameters script parameters * @return result of shell script execution */ - RunCommandResult runShellScriptInVMInstance( - String vmId, List scriptLines, List scriptParameters); + RunCommandResult runShellScriptInVMInstance(String vmId, List scriptLines, + List scriptParameters); /** * Run shell script in a virtual machine instance in a scale set asynchronously. @@ -140,8 +138,8 @@ RunCommandResult runShellScriptInVMInstance( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runShellScriptInVMInstanceAsync( - String vmId, List scriptLines, List scriptParameters); + Mono runShellScriptInVMInstanceAsync(String vmId, List scriptLines, + List scriptParameters); /** * Run commands in a virtual machine instance in a scale set. @@ -295,8 +293,8 @@ Mono runShellScriptInVMInstanceAsync( * @param virtualMachineInstanceId the instance ID * @return the network interfaces */ - PagedIterable listNetworkInterfacesByInstanceId( - String virtualMachineInstanceId); + PagedIterable + listNetworkInterfacesByInstanceId(String virtualMachineInstanceId); /** * Lists the network interface associated with a specific virtual machine instance in the scale set asynchronously. @@ -304,8 +302,8 @@ PagedIterable listNetworkInterfacesByIns * @param virtualMachineInstanceId the instance ID * @return the network interfaces */ - PagedFlux listNetworkInterfacesByInstanceIdAsync( - String virtualMachineInstanceId); + PagedFlux + listNetworkInterfacesByInstanceIdAsync(String virtualMachineInstanceId); /** @return true if managed disk is used for the virtual machine scale set's disks (os, data) */ boolean isManagedDiskEnabled(); @@ -410,57 +408,37 @@ PagedFlux listNetworkInterfacesByInstanc * The virtual machine scale set stages shared between managed and unmanaged based virtual machine scale set * definitions. */ - interface DefinitionShared - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSku, - DefinitionStages.WithProximityPlacementGroup, - DefinitionStages.WithNetworkSubnet, - DefinitionStages.WithPrimaryInternetFacingLoadBalancer, - DefinitionStages.WithPrimaryInternalLoadBalancer, - DefinitionStages.WithPrimaryInternetFacingLoadBalancerBackendOrNatPool, - DefinitionStages.WithInternalLoadBalancerBackendOrNatPool, - DefinitionStages.WithPrimaryInternetFacingLoadBalancerNatPool, - DefinitionStages.WithInternalInternalLoadBalancerNatPool, - DefinitionStages.WithOS, - DefinitionStages.WithCreate { + interface DefinitionShared extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSku, + DefinitionStages.WithProximityPlacementGroup, DefinitionStages.WithNetworkSubnet, + DefinitionStages.WithPrimaryInternetFacingLoadBalancer, DefinitionStages.WithPrimaryInternalLoadBalancer, + DefinitionStages.WithPrimaryInternetFacingLoadBalancerBackendOrNatPool, + DefinitionStages.WithInternalLoadBalancerBackendOrNatPool, + DefinitionStages.WithPrimaryInternetFacingLoadBalancerNatPool, + DefinitionStages.WithInternalInternalLoadBalancerNatPool, DefinitionStages.WithOS, DefinitionStages.WithCreate { } /** The entirety of the virtual machine scale set definition. */ interface DefinitionManagedOrUnmanaged - extends DefinitionShared, - DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged, - DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged, - DefinitionStages.WithWindowsAdminPasswordManagedOrUnmanaged, - DefinitionStages.WithLinuxCreateManagedOrUnmanaged, - DefinitionStages.WithWindowsCreateManagedOrUnmanaged, - DefinitionStages.WithManagedCreate, - DefinitionStages.WithUnmanagedCreate { + extends DefinitionShared, DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged, + DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged, + DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged, + DefinitionStages.WithWindowsAdminPasswordManagedOrUnmanaged, DefinitionStages.WithLinuxCreateManagedOrUnmanaged, + DefinitionStages.WithWindowsCreateManagedOrUnmanaged, DefinitionStages.WithManagedCreate, + DefinitionStages.WithUnmanagedCreate { } /** The entirety of the managed disk based virtual machine scale set definition. */ - interface DefinitionManaged - extends DefinitionShared, - DefinitionStages.WithLinuxRootUsernameManaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged, - DefinitionStages.WithWindowsAdminUsernameManaged, - DefinitionStages.WithWindowsAdminPasswordManaged, - DefinitionStages.WithLinuxCreateManaged, - DefinitionStages.WithWindowsCreateManaged, - DefinitionStages.WithManagedCreate { + interface DefinitionManaged extends DefinitionShared, DefinitionStages.WithLinuxRootUsernameManaged, + DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged, DefinitionStages.WithWindowsAdminUsernameManaged, + DefinitionStages.WithWindowsAdminPasswordManaged, DefinitionStages.WithLinuxCreateManaged, + DefinitionStages.WithWindowsCreateManaged, DefinitionStages.WithManagedCreate { } /** The entirety of the unmanaged disk based virtual machine scale set definition. */ - interface DefinitionUnmanaged - extends DefinitionShared, - DefinitionStages.WithLinuxRootUsernameUnmanaged, - DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged, - DefinitionStages.WithWindowsAdminUsernameUnmanaged, - DefinitionStages.WithWindowsAdminPasswordUnmanaged, - DefinitionStages.WithLinuxCreateUnmanaged, - DefinitionStages.WithWindowsCreateUnmanaged, - DefinitionStages.WithUnmanagedCreate { + interface DefinitionUnmanaged extends DefinitionShared, DefinitionStages.WithLinuxRootUsernameUnmanaged, + DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged, DefinitionStages.WithWindowsAdminUsernameUnmanaged, + DefinitionStages.WithWindowsAdminPasswordUnmanaged, DefinitionStages.WithLinuxCreateUnmanaged, + DefinitionStages.WithWindowsCreateUnmanaged, DefinitionStages.WithUnmanagedCreate { } /** Grouping of virtual machine scale set definition stages. */ @@ -537,8 +515,8 @@ interface WithProximityPlacementGroup extends WithDoNotRunExtensionsOnOverprovis * @param type the type of the group * @return the next stage of the definition. */ - WithDoNotRunExtensionsOnOverprovisionedVms withNewProximityPlacementGroup( - String proximityPlacementGroupName, ProximityPlacementGroupType type); + WithDoNotRunExtensionsOnOverprovisionedVms + withNewProximityPlacementGroup(String proximityPlacementGroupName, ProximityPlacementGroupType type); } /** @@ -554,8 +532,8 @@ interface WithDoNotRunExtensionsOnOverprovisionedVms extends WithAdditionalCapab * @param doNotRunExtensionsOnOverprovisionedVMs the doNotRunExtensionsOnOverprovisionedVMs value to set * @return the next stage of the definition. */ - WithAdditionalCapabilities withDoNotRunExtensionsOnOverprovisionedVMs( - Boolean doNotRunExtensionsOnOverprovisionedVMs); + WithAdditionalCapabilities + withDoNotRunExtensionsOnOverprovisionedVMs(Boolean doNotRunExtensionsOnOverprovisionedVMs); } /** @@ -574,7 +552,6 @@ interface WithAdditionalCapabilities extends WithNetworkSubnet { WithNetworkSubnet withAdditionalCapabilities(AdditionalCapabilities additionalCapabilities); } - /** * The stage of a virtual machine scale set definition allowing to specify the virtual network subnet for the * primary network configuration. @@ -606,8 +583,8 @@ interface WithPrimaryInternetFacingLoadBalancer { * @param loadBalancer an existing Internet-facing load balancer * @return the next stage of the definition */ - WithPrimaryInternetFacingLoadBalancerBackendOrNatPool withExistingPrimaryInternetFacingLoadBalancer( - LoadBalancer loadBalancer); + WithPrimaryInternetFacingLoadBalancerBackendOrNatPool + withExistingPrimaryInternetFacingLoadBalancer(LoadBalancer loadBalancer); /** * Specifies that no public load balancer should be associated with the virtual machine scale set. @@ -658,8 +635,8 @@ interface WithPrimaryInternetFacingLoadBalancerBackendOrNatPool * @param backendNames the names of existing backends in the selected load balancer * @return the next stage of the definition */ - WithPrimaryInternetFacingLoadBalancerNatPool withPrimaryInternetFacingLoadBalancerBackends( - String... backendNames); + WithPrimaryInternetFacingLoadBalancerNatPool + withPrimaryInternetFacingLoadBalancerBackends(String... backendNames); } /** @@ -674,8 +651,8 @@ interface WithPrimaryInternetFacingLoadBalancerNatPool extends WithPrimaryIntern * @param natPoolNames inbound NAT pools names existing on the selected load balancer * @return the next stage of the definition */ - WithPrimaryInternalLoadBalancer withPrimaryInternetFacingLoadBalancerInboundNatPools( - String... natPoolNames); + WithPrimaryInternalLoadBalancer + withPrimaryInternetFacingLoadBalancerInboundNatPools(String... natPoolNames); } /** @@ -718,8 +695,8 @@ interface WithOS { * @param knownImage a known market-place image * @return the next stage of the definition */ - WithWindowsAdminUsernameManagedOrUnmanaged withPopularWindowsImage( - KnownWindowsVirtualMachineImage knownImage); + WithWindowsAdminUsernameManagedOrUnmanaged + withPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage); /** * Specifies that the latest version of the specified marketplace Windows image should be used. @@ -729,8 +706,8 @@ WithWindowsAdminUsernameManagedOrUnmanaged withPopularWindowsImage( * @param sku specifies the SKU of the image * @return the next stage of the definition */ - WithWindowsAdminUsernameManagedOrUnmanaged withLatestWindowsImage( - String publisher, String offer, String sku); + WithWindowsAdminUsernameManagedOrUnmanaged withLatestWindowsImage(String publisher, String offer, + String sku); /** * Specifies the specific version of a marketplace Windows image needs to be used. @@ -1202,8 +1179,8 @@ interface WithManagedDataDisk { * @param storageAccountType the storage account type * @return the next stage of virtual machine definition */ - WithManagedCreate withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType); + WithManagedCreate withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType); /** * Specifies the data disk to be created from the data disk image in the virtual machine image. @@ -1232,8 +1209,8 @@ WithManagedCreate withNewDataDisk( * @param storageAccountType the storage account type * @return the next stage of virtual machine definition */ - WithManagedCreate withNewDataDiskFromImage( - int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType); + WithManagedCreate withNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, + StorageAccountTypes storageAccountType); } /** The optionals applicable only for managed disks. */ @@ -1472,8 +1449,8 @@ interface WithSystemAssignedIdentityBasedAccessOrCreate extends WithCreate { * @param role access role to assigned to the scale set local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + BuiltInRole role); /** * Specifies that virtual machine scale set's local identity should have the given access (described by the @@ -1483,8 +1460,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param role access role to assigned to the scale set local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /** * Specifies that virtual machine scale set's system assigned (local) identity should have the access @@ -1495,8 +1472,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the scale set local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + String roleDefinitionId); /** * Specifies that virtual machine scale set's system assigned (local) identity should have the access @@ -1506,8 +1483,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId access role definition to assigned to the scale set local identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId); } /** @@ -1788,32 +1765,18 @@ interface WithEphemeralOSDisk { * The stage of a virtual machine scale set definition containing all the required inputs for the resource to be * created, but also allowing for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithOSDiskSettings, - DefinitionStages.WithComputerNamePrefix, - DefinitionStages.WithCapacity, - DefinitionStages.WithUpgradePolicy, - DefinitionStages.WithOverProvision, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithCustomData, - DefinitionStages.WithExtension, - DefinitionStages.WithSystemAssignedManagedServiceIdentity, - DefinitionStages.WithUserAssignedManagedServiceIdentity, - DefinitionStages.WithBootDiagnostics, - DefinitionStages.WithBillingProfile, - DefinitionStages.WithVMPriority, - DefinitionStages.WithVirtualMachinePublicIp, - DefinitionStages.WithAcceleratedNetworking, - DefinitionStages.WithIpForwarding, - DefinitionStages.WithNetworkSecurityGroup, - DefinitionStages.WithSinglePlacementGroup, - DefinitionStages.WithApplicationGateway, - DefinitionStages.WithApplicationSecurityGroup, - DefinitionStages.WithSecrets, - DefinitionStages.WithPlan, - DefinitionStages.WithEphemeralOSDisk, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, DefinitionStages.WithOSDiskSettings, + DefinitionStages.WithComputerNamePrefix, DefinitionStages.WithCapacity, DefinitionStages.WithUpgradePolicy, + DefinitionStages.WithOverProvision, DefinitionStages.WithStorageAccount, DefinitionStages.WithCustomData, + DefinitionStages.WithExtension, DefinitionStages.WithSystemAssignedManagedServiceIdentity, + DefinitionStages.WithUserAssignedManagedServiceIdentity, DefinitionStages.WithBootDiagnostics, + DefinitionStages.WithBillingProfile, DefinitionStages.WithVMPriority, + DefinitionStages.WithVirtualMachinePublicIp, DefinitionStages.WithAcceleratedNetworking, + DefinitionStages.WithIpForwarding, DefinitionStages.WithNetworkSecurityGroup, + DefinitionStages.WithSinglePlacementGroup, DefinitionStages.WithApplicationGateway, + DefinitionStages.WithApplicationSecurityGroup, DefinitionStages.WithSecrets, DefinitionStages.WithPlan, + DefinitionStages.WithEphemeralOSDisk, + Resource.DefinitionWithTags { } } @@ -1836,8 +1799,8 @@ interface WithPrimaryLoadBalancer extends WithPrimaryInternalLoadBalancer { * @param loadBalancer the primary Internet-facing load balancer * @return the next stage of the update */ - WithPrimaryInternetFacingLoadBalancerBackendOrNatPool withExistingPrimaryInternetFacingLoadBalancer( - LoadBalancer loadBalancer); + WithPrimaryInternetFacingLoadBalancerBackendOrNatPool + withExistingPrimaryInternetFacingLoadBalancer(LoadBalancer loadBalancer); } /** @@ -1854,8 +1817,8 @@ interface WithPrimaryInternetFacingLoadBalancerBackendOrNatPool * @param backendNames the backend names * @return the next stage of the update */ - WithPrimaryInternetFacingLoadBalancerNatPool withPrimaryInternetFacingLoadBalancerBackends( - String... backendNames); + WithPrimaryInternetFacingLoadBalancerNatPool + withPrimaryInternetFacingLoadBalancerBackends(String... backendNames); } /** @@ -1870,8 +1833,8 @@ interface WithPrimaryInternetFacingLoadBalancerNatPool extends WithPrimaryIntern * @param natPoolNames the names of existing inbound NAT pools on the selected load balancer * @return the next stage of the update */ - WithPrimaryInternalLoadBalancer withPrimaryInternetFacingLoadBalancerInboundNatPools( - String... natPoolNames); + WithPrimaryInternalLoadBalancer + withPrimaryInternetFacingLoadBalancerInboundNatPools(String... natPoolNames); } /** @@ -1891,8 +1854,8 @@ interface WithPrimaryInternalLoadBalancer extends WithApply { * @param loadBalancer the primary Internet-facing load balancer * @return the next stage of the update */ - WithPrimaryInternalLoadBalancerBackendOrNatPool withExistingPrimaryInternalLoadBalancer( - LoadBalancer loadBalancer); + WithPrimaryInternalLoadBalancerBackendOrNatPool + withExistingPrimaryInternalLoadBalancer(LoadBalancer loadBalancer); } /** @@ -2148,8 +2111,8 @@ interface WithSystemAssignedIdentityBasedAccessOrApply extends WithApply { * @param role access role to assigned to the scale set local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessTo(String resourceId, + BuiltInRole role); /** * Specifies that virtual machine scale set's system assigned (local) identity should have the given access @@ -2159,8 +2122,8 @@ WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAcce * @param role access role to assigned to the scale set local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrApply + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /** * Specifies that virtual machine scale set 's system assigned (local) identity should have the access @@ -2171,8 +2134,8 @@ WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAcce * @param roleDefinitionId access role definition to assigned to the scale set local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessTo(String resourceId, + String roleDefinitionId); /** * Specifies that virtual machine scale set's system assigned (local) identity should have the access @@ -2182,8 +2145,8 @@ WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAcce * @param roleDefinitionId access role definition to assigned to the scale set local identity * @return the next stage of the update */ - WithSystemAssignedIdentityBasedAccessOrApply withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrApply + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId); } /** @@ -2310,8 +2273,8 @@ interface WithManagedDataDisk { * @param storageAccountType the storage account type * @return the next stage of virtual machine scale set update */ - WithApply withNewDataDisk( - int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType); + WithApply withNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, + StorageAccountTypes storageAccountType); /** * Detaches managed data disk with the given LUN from the virtual machine scale set instances. @@ -2521,39 +2484,22 @@ interface WithApplicationSecurityGroup { } /** The stage of a virtual machine scale set update containing inputs for the resource to be updated. */ - interface WithApply - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithManagedDataDisk, - UpdateStages.WithUnmanagedDataDisk, - UpdateStages.WithSku, - UpdateStages.WithAdditionalCapabilities, - UpdateStages.WithCapacity, - UpdateStages.WithCustomData, - UpdateStages.WithSecrets, - UpdateStages.WithExtension, - UpdateStages.WithoutPrimaryLoadBalancer, - UpdateStages.WithoutPrimaryLoadBalancerBackend, - UpdateStages.WithoutPrimaryLoadBalancerNatPool, - UpdateStages.WithSystemAssignedManagedServiceIdentity, - UpdateStages.WithUserAssignedManagedServiceIdentity, - UpdateStages.WithBootDiagnostics, - UpdateStages.WithBillingProfile, - UpdateStages.WithAvailabilityZone, - UpdateStages.WithVirtualMachinePublicIp, - UpdateStages.WithAcceleratedNetworking, - UpdateStages.WithIpForwarding, - UpdateStages.WithNetworkSecurityGroup, - UpdateStages.WithSinglePlacementGroup, - UpdateStages.WithApplicationGateway, - UpdateStages.WithApplicationSecurityGroup { + interface WithApply extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithManagedDataDisk, UpdateStages.WithUnmanagedDataDisk, UpdateStages.WithSku, + UpdateStages.WithAdditionalCapabilities, UpdateStages.WithCapacity, UpdateStages.WithCustomData, + UpdateStages.WithSecrets, UpdateStages.WithExtension, UpdateStages.WithoutPrimaryLoadBalancer, + UpdateStages.WithoutPrimaryLoadBalancerBackend, UpdateStages.WithoutPrimaryLoadBalancerNatPool, + UpdateStages.WithSystemAssignedManagedServiceIdentity, UpdateStages.WithUserAssignedManagedServiceIdentity, + UpdateStages.WithBootDiagnostics, UpdateStages.WithBillingProfile, UpdateStages.WithAvailabilityZone, + UpdateStages.WithVirtualMachinePublicIp, UpdateStages.WithAcceleratedNetworking, + UpdateStages.WithIpForwarding, UpdateStages.WithNetworkSecurityGroup, UpdateStages.WithSinglePlacementGroup, + UpdateStages.WithApplicationGateway, UpdateStages.WithApplicationSecurityGroup { } } /** The entirety of the virtual machine scale set update. */ - interface Update - extends UpdateStages.WithPrimaryLoadBalancer, - UpdateStages.WithPrimaryInternetFacingLoadBalancerBackendOrNatPool, - UpdateStages.WithPrimaryInternalLoadBalancerBackendOrNatPool { + interface Update extends UpdateStages.WithPrimaryLoadBalancer, + UpdateStages.WithPrimaryInternetFacingLoadBalancerBackendOrNatPool, + UpdateStages.WithPrimaryInternalLoadBalancerBackendOrNatPool { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetExtension.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetExtension.java index cc39b30b9026d..db9a06f94d286 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetExtension.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetExtension.java @@ -46,12 +46,9 @@ public interface VirtualMachineScaleSetExtension * @param the stage of the parent definition to return to after attaching this definition */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithImageOrPublisher, - DefinitionStages.WithPublisher, - DefinitionStages.WithType, - DefinitionStages.WithVersion, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithImageOrPublisher, + DefinitionStages.WithPublisher, DefinitionStages.WithType, + DefinitionStages.WithVersion, DefinitionStages.WithAttach { } /** @@ -362,12 +359,9 @@ interface WithSettings { * @param the stage of the parent update to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithImageOrPublisher, - UpdateDefinitionStages.WithPublisher, - UpdateDefinitionStages.WithType, - UpdateDefinitionStages.WithVersion, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithImageOrPublisher, + UpdateDefinitionStages.WithPublisher, UpdateDefinitionStages.WithType, + UpdateDefinitionStages.WithVersion, UpdateDefinitionStages.WithAttach { } /** Grouping of virtual machine extension update stages. */ @@ -436,9 +430,7 @@ interface WithSettings { /** * The entirety of virtual machine scale set extension update as a part of parent virtual machine scale set update. */ - interface Update - extends Settable, - UpdateStages.WithAutoUpgradeMinorVersion, - UpdateStages.WithSettings { + interface Update extends Settable, UpdateStages.WithAutoUpgradeMinorVersion, + UpdateStages.WithSettings { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetSkuTypes.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetSkuTypes.java index feea4364cc7d3..8c22a4f84fd95 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetSkuTypes.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetSkuTypes.java @@ -15,236 +15,236 @@ public class VirtualMachineScaleSetSkuTypes { private static final Map VALUES_BY_NAME = new HashMap<>(); /** Static value Standard_A0 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A0 = - new VirtualMachineScaleSetSkuTypes("Standard_A0", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A0 + = new VirtualMachineScaleSetSkuTypes("Standard_A0", "Standard"); /** Static value Standard_A1 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A1 = - new VirtualMachineScaleSetSkuTypes("Standard_A1", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A1 + = new VirtualMachineScaleSetSkuTypes("Standard_A1", "Standard"); /** Static value Standard_A2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A2 = - new VirtualMachineScaleSetSkuTypes("Standard_A2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A2 + = new VirtualMachineScaleSetSkuTypes("Standard_A2", "Standard"); /** Static value Standard_A3 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A3 = - new VirtualMachineScaleSetSkuTypes("Standard_A3", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A3 + = new VirtualMachineScaleSetSkuTypes("Standard_A3", "Standard"); /** Static value Standard_A4 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A4 = - new VirtualMachineScaleSetSkuTypes("Standard_A4", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A4 + = new VirtualMachineScaleSetSkuTypes("Standard_A4", "Standard"); /** Static value Standard_A5 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A5 = - new VirtualMachineScaleSetSkuTypes("Standard_A5", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A5 + = new VirtualMachineScaleSetSkuTypes("Standard_A5", "Standard"); /** Static value Standard_A6 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A6 = - new VirtualMachineScaleSetSkuTypes("Standard_A6", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A6 + = new VirtualMachineScaleSetSkuTypes("Standard_A6", "Standard"); /** Static value Standard_A7 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A7 = - new VirtualMachineScaleSetSkuTypes("Standard_A7", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A7 + = new VirtualMachineScaleSetSkuTypes("Standard_A7", "Standard"); /** Static value Standard_A8 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A8 = - new VirtualMachineScaleSetSkuTypes("Standard_A8", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A8 + = new VirtualMachineScaleSetSkuTypes("Standard_A8", "Standard"); /** Static value Standard_A9 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A9 = - new VirtualMachineScaleSetSkuTypes("Standard_A9", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A9 + = new VirtualMachineScaleSetSkuTypes("Standard_A9", "Standard"); /** Static value Standard_A10 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A10 = - new VirtualMachineScaleSetSkuTypes("Standard_A10", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A10 + = new VirtualMachineScaleSetSkuTypes("Standard_A10", "Standard"); /** Static value Standard_A11 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_A11 = - new VirtualMachineScaleSetSkuTypes("Standard_A11", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_A11 + = new VirtualMachineScaleSetSkuTypes("Standard_A11", "Standard"); /** Static value Standard_D1 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D1 = - new VirtualMachineScaleSetSkuTypes("Standard_D1", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D1 + = new VirtualMachineScaleSetSkuTypes("Standard_D1", "Standard"); /** Static value Standard_D2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D2 = - new VirtualMachineScaleSetSkuTypes("Standard_D2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D2 + = new VirtualMachineScaleSetSkuTypes("Standard_D2", "Standard"); /** Static value Standard_D3 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D3 = - new VirtualMachineScaleSetSkuTypes("Standard_D3", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D3 + = new VirtualMachineScaleSetSkuTypes("Standard_D3", "Standard"); /** Static value Standard_D4 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D4 = - new VirtualMachineScaleSetSkuTypes("Standard_D4", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D4 + = new VirtualMachineScaleSetSkuTypes("Standard_D4", "Standard"); /** Static value Standard_D11 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D11 = - new VirtualMachineScaleSetSkuTypes("Standard_D11", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D11 + = new VirtualMachineScaleSetSkuTypes("Standard_D11", "Standard"); /** Static value Standard_D12 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D12 = - new VirtualMachineScaleSetSkuTypes("Standard_D12", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D12 + = new VirtualMachineScaleSetSkuTypes("Standard_D12", "Standard"); /** Static value Standard_D13 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D13 = - new VirtualMachineScaleSetSkuTypes("Standard_D13", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D13 + = new VirtualMachineScaleSetSkuTypes("Standard_D13", "Standard"); /** Static value Standard_D14 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D14 = - new VirtualMachineScaleSetSkuTypes("Standard_D14", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D14 + = new VirtualMachineScaleSetSkuTypes("Standard_D14", "Standard"); /** Static value Standard_D1_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D1_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D1_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D1_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D1_v2", "Standard"); /** Static value Standard_D2_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D2_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D2_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D2_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D2_v2", "Standard"); /** Static value Standard_D3_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D3_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D3_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D3_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D3_v2", "Standard"); /** Static value Standard_D4_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D4_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D4_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D4_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D4_v2", "Standard"); /** Static value Standard_D5_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D5_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D5_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D5_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D5_v2", "Standard"); /** Static value Standard_D11_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D11_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D11_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D11_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D11_v2", "Standard"); /** Static value Standard_D12_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D12_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D12_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D12_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D12_v2", "Standard"); /** Static value Standard_D13_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D13_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D13_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D13_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D13_v2", "Standard"); /** Static value Standard_D14_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D14_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D14_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D14_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D14_v2", "Standard"); /** Static value Standard_D15_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_D15_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_D15_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_D15_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_D15_v2", "Standard"); /** Static value Standard_DS1 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS1 = - new VirtualMachineScaleSetSkuTypes("Standard_DS1", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS1 + = new VirtualMachineScaleSetSkuTypes("Standard_DS1", "Standard"); /** Static value Standard_DS2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS2", "Standard"); /** Static value Standard_DS3 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS3 = - new VirtualMachineScaleSetSkuTypes("Standard_DS3", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS3 + = new VirtualMachineScaleSetSkuTypes("Standard_DS3", "Standard"); /** Static value Standard_DS4 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS4 = - new VirtualMachineScaleSetSkuTypes("Standard_DS4", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS4 + = new VirtualMachineScaleSetSkuTypes("Standard_DS4", "Standard"); /** Static value Standard_DS11 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS11 = - new VirtualMachineScaleSetSkuTypes("Standard_DS11", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS11 + = new VirtualMachineScaleSetSkuTypes("Standard_DS11", "Standard"); /** Static value Standard_DS12 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS12 = - new VirtualMachineScaleSetSkuTypes("Standard_DS12", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS12 + = new VirtualMachineScaleSetSkuTypes("Standard_DS12", "Standard"); /** Static value Standard_DS13 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS13 = - new VirtualMachineScaleSetSkuTypes("Standard_DS13", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS13 + = new VirtualMachineScaleSetSkuTypes("Standard_DS13", "Standard"); /** Static value Standard_DS14 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS14 = - new VirtualMachineScaleSetSkuTypes("Standard_DS14", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS14 + = new VirtualMachineScaleSetSkuTypes("Standard_DS14", "Standard"); /** Static value Standard_DS1_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS1_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS1_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS1_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS1_v2", "Standard"); /** Static value Standard_DS2_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS2_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS2_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS2_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS2_v2", "Standard"); /** Static value Standard_DS3_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS3_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS3_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS3_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS3_v2", "Standard"); /** Static value Standard_DS4_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS4_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS4_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS4_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS4_v2", "Standard"); /** Static value Standard_DS5_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS5_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS5_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS5_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS5_v2", "Standard"); /** Static value Standard_DS11_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS11_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS11_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS11_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS11_v2", "Standard"); /** Static value Standard_DS12_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS12_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS12_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS12_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS12_v2", "Standard"); /** Static value Standard_DS13_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS13_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS13_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS13_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS13_v2", "Standard"); /** Static value Standard_DS14_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS14_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS14_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS14_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS14_v2", "Standard"); /** Static value Standard_DS15_v2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_DS15_V2 = - new VirtualMachineScaleSetSkuTypes("Standard_DS15_v2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_DS15_V2 + = new VirtualMachineScaleSetSkuTypes("Standard_DS15_v2", "Standard"); /** Static value STANDARD_F1S for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F1S = - new VirtualMachineScaleSetSkuTypes("STANDARD_F1S", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F1S + = new VirtualMachineScaleSetSkuTypes("STANDARD_F1S", "Standard"); /** Static value STANDARD_F2S for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F2S = - new VirtualMachineScaleSetSkuTypes("STANDARD_F2S", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F2S + = new VirtualMachineScaleSetSkuTypes("STANDARD_F2S", "Standard"); /** Static value STANDARD_F4S for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F4S = - new VirtualMachineScaleSetSkuTypes("STANDARD_F4S", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F4S + = new VirtualMachineScaleSetSkuTypes("STANDARD_F4S", "Standard"); /** Static value STANDARD_F8S for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F8S = - new VirtualMachineScaleSetSkuTypes("STANDARD_F8S", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F8S + = new VirtualMachineScaleSetSkuTypes("STANDARD_F8S", "Standard"); /** Static value STANDARD_F16S for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F16S = - new VirtualMachineScaleSetSkuTypes("STANDARD_F16S", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F16S + = new VirtualMachineScaleSetSkuTypes("STANDARD_F16S", "Standard"); /** Static value STANDARD_F1 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F1 = - new VirtualMachineScaleSetSkuTypes("STANDARD_F1", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F1 + = new VirtualMachineScaleSetSkuTypes("STANDARD_F1", "Standard"); /** Static value STANDARD_F2 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F2 = - new VirtualMachineScaleSetSkuTypes("STANDARD_F2", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F2 + = new VirtualMachineScaleSetSkuTypes("STANDARD_F2", "Standard"); /** Static value STANDARD_F4 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F4 = - new VirtualMachineScaleSetSkuTypes("STANDARD_F4", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F4 + = new VirtualMachineScaleSetSkuTypes("STANDARD_F4", "Standard"); /** Static value STANDARD_F8 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F8 = - new VirtualMachineScaleSetSkuTypes("STANDARD_F8", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F8 + = new VirtualMachineScaleSetSkuTypes("STANDARD_F8", "Standard"); /** Static value STANDARD_F16 for VirtualMachineScaleSetSkuTypes. */ - public static final VirtualMachineScaleSetSkuTypes STANDARD_F16 = - new VirtualMachineScaleSetSkuTypes("STANDARD_F16", "Standard"); + public static final VirtualMachineScaleSetSkuTypes STANDARD_F16 + = new VirtualMachineScaleSetSkuTypes("STANDARD_F16", "Standard"); /** the SKU corresponding to this size. */ private final Sku sku; diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetUnmanagedDataDisk.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetUnmanagedDataDisk.java index 8e8727ec448fb..2ee618add3ea9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetUnmanagedDataDisk.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetUnmanagedDataDisk.java @@ -108,10 +108,8 @@ interface WithAttach extends Attachable.InDefinition { * @param the stage of the parent definition to return to after attaching this definition */ interface DefinitionWithNewVhd - extends DefinitionStages.Blank, - DefinitionStages.WithDiskSource, - DefinitionStages.WithNewVhdDiskSettings, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithDiskSource, + DefinitionStages.WithNewVhdDiskSettings, DefinitionStages.WithAttach { } /** @@ -120,10 +118,8 @@ interface DefinitionWithNewVhd * @param the stage of the parent definition to return to after attaching this definition */ interface DefinitionWithImage - extends DefinitionStages.Blank, - DefinitionStages.WithDiskSource, - DefinitionStages.WithFromImageDiskSettings, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithDiskSource, + DefinitionStages.WithFromImageDiskSettings, DefinitionStages.WithAttach { } /** Grouping of unamanged data disk definition stages applicable as part of a virtual machine scale set update. */ @@ -189,10 +185,8 @@ interface WithAttach extends Attachable.InUpdate { * @param the stage of the parent update to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithDiskSource, - UpdateDefinitionStages.WithNewVhdDiskSettings, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithDiskSource, + UpdateDefinitionStages.WithNewVhdDiskSettings, UpdateDefinitionStages.WithAttach { } /** Grouping of unmanaged data disk update stages. */ @@ -232,10 +226,7 @@ interface WithDiskCaching { } /** The entirety of a unmanaged data disk update as part of a virtual machine scale set update. */ - interface Update - extends UpdateStages.WithDiskSize, - UpdateStages.WithDiskLun, - UpdateStages.WithDiskCaching, - Settable { + interface Update extends UpdateStages.WithDiskSize, UpdateStages.WithDiskLun, UpdateStages.WithDiskCaching, + Settable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVM.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVM.java index 57d8068811f0f..e598a3be038af 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVM.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVM.java @@ -23,11 +23,8 @@ /** An immutable client-side representation of a virtual machine instance in an Azure virtual machine scale set. */ @Fluent public interface VirtualMachineScaleSetVM - extends Resource, - ChildResource, - Refreshable, - Updatable, - HasInnerModel { + extends Resource, ChildResource, Refreshable, + Updatable, HasInnerModel { /** @return the instance ID assigned to this virtual machine instance */ String instanceId(); @@ -317,8 +314,8 @@ interface Update extends Appliable { * @param storageAccountTypes the storage account type * @return the next stage of the update */ - Update withExistingDataDisk( - Disk dataDisk, int lun, CachingTypes cachingTypes, StorageAccountTypes storageAccountTypes); + Update withExistingDataDisk(Disk dataDisk, int lun, CachingTypes cachingTypes, + StorageAccountTypes storageAccountTypes); /** * Detaches an existing data disk from this VMSS virtual machine. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVMs.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVMs.java index c795d6612ba8d..375d17095097e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVMs.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetVMs.java @@ -169,20 +169,20 @@ public interface VirtualMachineScaleSetVMs extends SupportsListing redeployInstancesAsync(Collection instanceIds); -// /** -// * Updates the version of the installed operating system in the virtual machine instances. -// * -// * @param instanceIds instance IDs of the virtual machine scale set instances -// */ -// void reimageInstances(Collection instanceIds); -// -// /** -// * Updates the version of the installed operating system in the virtual machine instances. -// * -// * @param instanceIds instance IDs of the virtual machine scale set instances -// * @return a representation of the deferred computation of this call. -// */ -// Mono reimageInstancesAsync(Collection instanceIds); + // /** + // * Updates the version of the installed operating system in the virtual machine instances. + // * + // * @param instanceIds instance IDs of the virtual machine scale set instances + // */ + // void reimageInstances(Collection instanceIds); + // + // /** + // * Updates the version of the installed operating system in the virtual machine instances. + // * + // * @param instanceIds instance IDs of the virtual machine scale set instances + // * @return a representation of the deferred computation of this call. + // */ + // Mono reimageInstancesAsync(Collection instanceIds); /** * Simulates the eviction of the specified spot virtual machine in the scale set asynchronously. The eviction will diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSets.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSets.java index 157e15e7f6db4..75b32c924cfe1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSets.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSets.java @@ -24,17 +24,11 @@ /** Entry point to virtual machine scale set management API. */ @Fluent -public interface VirtualMachineScaleSets - extends SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsCreating, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface VirtualMachineScaleSets extends SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsCreating, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { /** * Shuts down the virtual machines in the scale set and releases the compute resources. * @@ -146,12 +140,8 @@ public interface VirtualMachineScaleSets * @param scriptParameters script parameters * @return result of PowerShell script execution */ - RunCommandResult runPowerShellScriptInVMInstance( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters); + RunCommandResult runPowerShellScriptInVMInstance(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters); /** * Run PowerShell in a virtual machine instance in a scale set asynchronously. @@ -163,12 +153,8 @@ RunCommandResult runPowerShellScriptInVMInstance( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runPowerShellScriptInVMInstanceAsync( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters); + Mono runPowerShellScriptInVMInstanceAsync(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters); /** * Run shell script in a virtual machine instance in a scale set. @@ -180,12 +166,8 @@ Mono runPowerShellScriptInVMInstanceAsync( * @param scriptParameters script parameters * @return result of shell script execution */ - RunCommandResult runShellScriptInVMInstance( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters); + RunCommandResult runShellScriptInVMInstance(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters); /** * Run shell script in a virtual machine instance in a scale set asynchronously. @@ -197,12 +179,8 @@ RunCommandResult runShellScriptInVMInstance( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runShellScriptInVMInstanceAsync( - String groupName, - String scaleSetName, - String vmId, - List scriptLines, - List scriptParameters); + Mono runShellScriptInVMInstanceAsync(String groupName, String scaleSetName, String vmId, + List scriptLines, List scriptParameters); /** * Run commands in a virtual machine instance in a scale set. @@ -213,8 +191,8 @@ Mono runShellScriptInVMInstanceAsync( * @param inputCommand command input * @return result of execution */ - RunCommandResult runCommandInVMInstance( - String groupName, String scaleSetName, String vmId, RunCommandInput inputCommand); + RunCommandResult runCommandInVMInstance(String groupName, String scaleSetName, String vmId, + RunCommandInput inputCommand); /** * Run commands in a virtual machine instance in a scale set asynchronously. @@ -225,8 +203,8 @@ RunCommandResult runCommandInVMInstance( * @param inputCommand command input * @return handle to the asynchronous execution */ - Mono runCommandVMInstanceAsync( - String groupName, String scaleSetName, String vmId, RunCommandInput inputCommand); + Mono runCommandVMInstanceAsync(String groupName, String scaleSetName, String vmId, + RunCommandInput inputCommand); /** * Delete virtual machine instances. @@ -236,8 +214,7 @@ Mono runCommandVMInstanceAsync( * @param instanceIds instance IDs * @param forceDeletion force delete without graceful shutdown */ - void deleteInstances(String groupName, String scaleSetName, - Collection instanceIds, boolean forceDeletion); + void deleteInstances(String groupName, String scaleSetName, Collection instanceIds, boolean forceDeletion); /** * Delete virtual machine instances. @@ -248,8 +225,8 @@ void deleteInstances(String groupName, String scaleSetName, * @param forceDeletion force delete without graceful shutdown * @return a representation of the deferred computation of this call */ - Mono deleteInstancesAsync(String groupName, String scaleSetName, - Collection instanceIds, boolean forceDeletion); + Mono deleteInstancesAsync(String groupName, String scaleSetName, Collection instanceIds, + boolean forceDeletion); /** * Force delete a resource from Azure, identifying it by its resource ID. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineUnmanagedDataDisk.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineUnmanagedDataDisk.java index b79f9ba5903cb..0e1f08aff0d29 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineUnmanagedDataDisk.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineUnmanagedDataDisk.java @@ -66,8 +66,9 @@ interface WithDiskSource { * @param vhdName the name of the VHD file to attach * @return the next stage of data disk definition */ - WithVhdAttachedDiskSettings withExistingVhd( - String storageAccountName, String containerName, String vhdName); + WithVhdAttachedDiskSettings withExistingVhd(String storageAccountName, String containerName, + String vhdName); + /** * specifies that disk needs to be created with a new VHD of given size. * @@ -197,10 +198,8 @@ interface WithAttach extends Attachable.InDefinition { * @param the stage of the parent definition to return to after attaching this definition */ interface DefinitionWithExistingVhd - extends DefinitionStages.Blank, - DefinitionStages.WithDiskSource, - DefinitionStages.WithVhdAttachedDiskSettings, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithDiskSource, + DefinitionStages.WithVhdAttachedDiskSettings, DefinitionStages.WithAttach { } /** @@ -209,10 +208,8 @@ interface DefinitionWithExistingVhd * @param the stage of the parent definition to return to after attaching this definition */ interface DefinitionWithNewVhd - extends DefinitionStages.Blank, - DefinitionStages.WithDiskSource, - DefinitionStages.WithNewVhdDiskSettings, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithDiskSource, + DefinitionStages.WithNewVhdDiskSettings, DefinitionStages.WithAttach { } /** @@ -221,10 +218,8 @@ interface DefinitionWithNewVhd * @param the stage of the parent definition to return to after attaching this definition */ interface DefinitionWithImage - extends DefinitionStages.Blank, - DefinitionStages.WithDiskSource, - DefinitionStages.WithFromImageDiskSettings, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithDiskSource, + DefinitionStages.WithFromImageDiskSettings, DefinitionStages.WithAttach { } /** Grouping of data disk definition stages applicable as part of a virtual machine update. */ @@ -251,8 +246,8 @@ interface WithDiskSource { * @param vhdName the name of the VHD file to attach * @return the next stage of data disk definition */ - WithVhdAttachedDiskSettings withExistingVhd( - String storageAccountName, String containerName, String vhdName); + WithVhdAttachedDiskSettings withExistingVhd(String storageAccountName, String containerName, + String vhdName); /** * specifies that disk needs to be created with a new VHD of given size. @@ -342,10 +337,8 @@ interface WithAttach extends Attachable.InUpdate { * @param the stage of the parent update to return to after attaching this definition */ interface UpdateDefinitionWithExistingVhd - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithDiskSource, - UpdateDefinitionStages.WithVhdAttachedDiskSettings, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithDiskSource, + UpdateDefinitionStages.WithVhdAttachedDiskSettings, UpdateDefinitionStages.WithAttach { } /** @@ -354,10 +347,8 @@ interface UpdateDefinitionWithExistingVhd * @param the stage of the parent update to return to after attaching this definition */ interface UpdateDefinitionWithNewVhd - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithDiskSource, - UpdateDefinitionStages.WithNewVhdDiskSettings, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithDiskSource, + UpdateDefinitionStages.WithNewVhdDiskSettings, UpdateDefinitionStages.WithAttach { } /** Grouping of data disk update stages. */ @@ -397,10 +388,7 @@ interface WithDiskCaching { } /** The entirety of a data disk update as part of a virtual machine update. */ - interface Update - extends UpdateStages.WithDiskSize, - UpdateStages.WithDiskLun, - UpdateStages.WithDiskCaching, - Settable { + interface Update extends UpdateStages.WithDiskSize, UpdateStages.WithDiskLun, UpdateStages.WithDiskCaching, + Settable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachines.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachines.java index e38608bda0180..1fb68dfab7372 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachines.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachines.java @@ -22,16 +22,10 @@ /** Entry point to virtual machine management API. */ public interface VirtualMachines - extends SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsCreating, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsCreating, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** @return available virtual machine sizes */ VirtualMachineSizes sizes(); @@ -180,8 +174,8 @@ public interface VirtualMachines * @param overwriteVhd whether to overwrites destination VHD if it exists * @return a representation of the deferred computation of this call */ - Mono captureAsync( - String groupName, String name, String containerName, String vhdPrefix, boolean overwriteVhd); + Mono captureAsync(String groupName, String name, String containerName, String vhdPrefix, + boolean overwriteVhd); /** * Migrates the virtual machine with unmanaged disks to use managed disks. @@ -209,8 +203,8 @@ Mono captureAsync( * @param scriptParameters script parameters * @return result of PowerShell script execution */ - RunCommandResult runPowerShellScript( - String groupName, String name, List scriptLines, List scriptParameters); + RunCommandResult runPowerShellScript(String groupName, String name, List scriptLines, + List scriptParameters); /** * Run shell script in a virtual machine asynchronously. @@ -221,8 +215,8 @@ RunCommandResult runPowerShellScript( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runPowerShellScriptAsync( - String groupName, String name, List scriptLines, List scriptParameters); + Mono runPowerShellScriptAsync(String groupName, String name, List scriptLines, + List scriptParameters); /** * Run shell script in a virtual machine. @@ -233,8 +227,8 @@ Mono runPowerShellScriptAsync( * @param scriptParameters script parameters * @return result of shell script execution */ - RunCommandResult runShellScript( - String groupName, String name, List scriptLines, List scriptParameters); + RunCommandResult runShellScript(String groupName, String name, List scriptLines, + List scriptParameters); /** * Run shell script in a virtual machine asynchronously. @@ -245,8 +239,8 @@ RunCommandResult runShellScript( * @param scriptParameters script parameters * @return handle to the asynchronous execution */ - Mono runShellScriptAsync( - String groupName, String name, List scriptLines, List scriptParameters); + Mono runShellScriptAsync(String groupName, String name, List scriptLines, + List scriptParameters); /** * Run commands in a virtual machine. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/WindowsVMDiskEncryptionConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/WindowsVMDiskEncryptionConfiguration.java index 0e8d89bf0537c..f668bf62ec16e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/WindowsVMDiskEncryptionConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/WindowsVMDiskEncryptionConfiguration.java @@ -29,10 +29,8 @@ public WindowsVMDiskEncryptionConfiguration(String keyVaultId, String aadClientI * @param aadClientId client ID of an AAD application which has permission to the key vault * @param aadSecret client secret corresponding to the aadClientId */ - public WindowsVMDiskEncryptionConfiguration(String keyVaultId, - String vaultUri, - String aadClientId, - String aadSecret) { + public WindowsVMDiskEncryptionConfiguration(String keyVaultId, String vaultUri, String aadClientId, + String aadSecret) { super(keyVaultId, vaultUri, aadClientId, aadSecret, null); } @@ -46,10 +44,8 @@ public WindowsVMDiskEncryptionConfiguration(String keyVaultId, * @param aadSecret client secret corresponding to the aadClientId * @param azureEnvironment Azure environment */ - public WindowsVMDiskEncryptionConfiguration(String keyVaultId, - String aadClientId, - String aadSecret, - AzureEnvironment azureEnvironment) { + public WindowsVMDiskEncryptionConfiguration(String keyVaultId, String aadClientId, String aadSecret, + AzureEnvironment azureEnvironment) { super(keyVaultId, null, aadClientId, aadSecret, azureEnvironment); } @@ -70,8 +66,7 @@ public WindowsVMDiskEncryptionConfiguration(String keyVaultId) { * @param keyVaultId the resource ID of the key vault to store the disk encryption key * @param vaultUri URI of the key vault data-plane endpoint */ - public WindowsVMDiskEncryptionConfiguration(String keyVaultId, - String vaultUri) { + public WindowsVMDiskEncryptionConfiguration(String keyVaultId, String vaultUri) { super(keyVaultId, vaultUri, null); } @@ -83,8 +78,7 @@ public WindowsVMDiskEncryptionConfiguration(String keyVaultId, * @param keyVaultId the resource ID of the key vault to store the disk encryption key * @param azureEnvironment Azure environment */ - public WindowsVMDiskEncryptionConfiguration(String keyVaultId, - AzureEnvironment azureEnvironment) { + public WindowsVMDiskEncryptionConfiguration(String keyVaultId, AzureEnvironment azureEnvironment) { super(keyVaultId, null, azureEnvironment); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeManagementTest.java index 911084d9f6f33..40d895391d656 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeManagementTest.java @@ -50,21 +50,10 @@ public abstract class ComputeManagementTest extends ResourceManagerTestProxyTest protected MsiManager msiManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -89,11 +78,12 @@ protected void cleanUpResources() { protected void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { System.out.println("Trying to de-provision"); - virtualMachine.manager().serviceClient().getVirtualMachines().beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); + virtualMachine.manager() + .serviceClient() + .getVirtualMachines() + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunShellScript") + .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); // wait as above command will not return as sync ResourceManagerUtils.sleep(Duration.ofMinutes(1)); @@ -131,21 +121,21 @@ protected void sleep(long milli) { } } - protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup resourceGroup, String id) throws Exception { - return createHttpLoadBalancers(region, resourceGroup, id, LoadBalancerSkuType.BASIC, PublicIPSkuType.BASIC, false); + protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup resourceGroup, String id) + throws Exception { + return createHttpLoadBalancers(region, resourceGroup, id, LoadBalancerSkuType.BASIC, PublicIPSkuType.BASIC, + false); } - protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup resourceGroup, String id, LoadBalancerSkuType loadBalancerSkuType, PublicIPSkuType publicIPSkuType, boolean staticIp) - throws Exception { + protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup resourceGroup, String id, + LoadBalancerSkuType loadBalancerSkuType, PublicIPSkuType publicIPSkuType, boolean staticIp) throws Exception { final String loadBalancerName = generateRandomResourceName("extlb" + id + "-", 18); final String publicIpName = "pip-" + loadBalancerName; final String frontendName = loadBalancerName + "-FE1"; final String backendPoolName = loadBalancerName + "-BAP1"; final String natPoolName = loadBalancerName + "-INP1"; - PublicIpAddress.DefinitionStages.WithCreate pipCreate = this - .networkManager - .publicIpAddresses() + PublicIpAddress.DefinitionStages.WithCreate pipCreate = this.networkManager.publicIpAddresses() .define(publicIpName) .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -156,46 +146,41 @@ protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup reso pipCreate.withStaticIP(); } - PublicIpAddress publicIPAddress = - pipCreate - .create(); - - LoadBalancer loadBalancer = - this - .networkManager - .loadBalancers() - .define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule("httpRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName) - .withProbe("httpProbe") - .attach() - .defineInboundNatPool(natPoolName) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) - .attach() - // Add an HTTP probe - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - .withSku(loadBalancerSkuType) - .create(); + PublicIpAddress publicIPAddress = pipCreate.create(); + + LoadBalancer loadBalancer = this.networkManager.loadBalancers() + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule("httpRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName) + .withProbe("httpProbe") + .attach() + .defineInboundNatPool(natPoolName) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) + .attach() + // Add an HTTP probe + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + .withSku(loadBalancerSkuType) + .create(); return loadBalancer; } - protected LoadBalancer createInternetFacingLoadBalancer( - Region region, ResourceGroup resourceGroup, String id, LoadBalancerSkuType lbSkuType) throws Exception { + protected LoadBalancer createInternetFacingLoadBalancer(Region region, ResourceGroup resourceGroup, String id, + LoadBalancerSkuType lbSkuType) throws Exception { final String loadBalancerName = generateRandomResourceName("extlb" + id + "-", 18); final String publicIPName = "pip-" + loadBalancerName; final String frontendName = loadBalancerName + "-FE1"; @@ -206,80 +191,74 @@ protected LoadBalancer createInternetFacingLoadBalancer( // Sku of PublicIP and LoadBalancer must match // - PublicIPSkuType publicIPSkuType = - lbSkuType.equals(LoadBalancerSkuType.BASIC) ? PublicIPSkuType.BASIC : PublicIPSkuType.STANDARD; - - PublicIpAddress publicIPAddress = - this - .networkManager - .publicIpAddresses() - .define(publicIPName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(publicIPName) - // Optionals - .withStaticIP() - .withSku(publicIPSkuType) - // Create - .create(); - - LoadBalancer loadBalancer = - this - .networkManager - .loadBalancers() - .define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule("httpRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe("httpProbe") - .attach() - .defineLoadBalancingRule("httpsRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe("httpsProbe") - .attach() - - // Add two nat pools to enable direct VM connectivity to port SSH and 23 - .defineInboundNatPool(natPoolName1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPoolName2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer - .attach() - - // Add two probes one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - .defineHttpProbe("httpsProbe") - .withRequestPath("/") - .attach() - .withSku(lbSkuType) - .create(); + PublicIPSkuType publicIPSkuType + = lbSkuType.equals(LoadBalancerSkuType.BASIC) ? PublicIPSkuType.BASIC : PublicIPSkuType.STANDARD; + + PublicIpAddress publicIPAddress = this.networkManager.publicIpAddresses() + .define(publicIPName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(publicIPName) + // Optionals + .withStaticIP() + .withSku(publicIPSkuType) + // Create + .create(); + + LoadBalancer loadBalancer = this.networkManager.loadBalancers() + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule("httpRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe("httpProbe") + .attach() + .defineLoadBalancingRule("httpsRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe("httpsProbe") + .attach() + + // Add two nat pools to enable direct VM connectivity to port SSH and 23 + .defineInboundNatPool(natPoolName1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPoolName2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer + .attach() + + // Add two probes one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + .defineHttpProbe("httpsProbe") + .withRequestPath("/") + .attach() + .withSku(lbSkuType) + .create(); return loadBalancer; } - protected LoadBalancer createInternalLoadBalancer( - Region region, ResourceGroup resourceGroup, Network network, String id) throws Exception { + protected LoadBalancer createInternalLoadBalancer(Region region, ResourceGroup resourceGroup, Network network, + String id) throws Exception { final String loadBalancerName = generateRandomResourceName("InternalLb" + id + "-", 18); final String privateFrontEndName = loadBalancerName + "-FE1"; final String backendPoolName1 = loadBalancerName + "-BAP1"; @@ -288,56 +267,53 @@ protected LoadBalancer createInternalLoadBalancer( final String natPoolName2 = loadBalancerName + "-INP2"; final String subnetName = "subnet1"; - LoadBalancer loadBalancer = - this - .networkManager - .loadBalancers() - .define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule("httpRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(1000) - .toBackend(backendPoolName1) - .withProbe("httpProbe") - .attach() - .defineLoadBalancingRule("httpsRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(1001) - .toBackend(backendPoolName2) - .withProbe("httpsProbe") - .attach() - - // Add two NAT pools to enable direct VM connectivity to port 44 and 45 - .defineInboundNatPool(natPoolName1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPortRange(8000, 8099) - .toBackendPort(44) - .attach() - .defineInboundNatPool(natPoolName2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPortRange(9000, 9099) - .toBackendPort(45) - .attach() - - // Explicitly define the frontend - .definePrivateFrontend(privateFrontEndName) - .withExistingSubnet(network, subnetName) // Frontend with VNET means internal load-balancer - .attach() - - // Add two probes one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - .defineHttpProbe("httpsProbe") - .withRequestPath("/") - .attach() - .create(); + LoadBalancer loadBalancer = this.networkManager.loadBalancers() + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule("httpRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(1000) + .toBackend(backendPoolName1) + .withProbe("httpProbe") + .attach() + .defineLoadBalancingRule("httpsRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(1001) + .toBackend(backendPoolName2) + .withProbe("httpsProbe") + .attach() + + // Add two NAT pools to enable direct VM connectivity to port 44 and 45 + .defineInboundNatPool(natPoolName1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPortRange(8000, 8099) + .toBackendPort(44) + .attach() + .defineInboundNatPool(natPoolName2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPortRange(9000, 9099) + .toBackendPort(45) + .attach() + + // Explicitly define the frontend + .definePrivateFrontend(privateFrontEndName) + .withExistingSubnet(network, subnetName) // Frontend with VNET means internal load-balancer + .attach() + + // Add two probes one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + .defineHttpProbe("httpsProbe") + .withRequestPath("/") + .attach() + .create(); return loadBalancer; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeSkuTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeSkuTests.java index d83f409f52377..7d5a443f17e68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeSkuTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ComputeSkuTests.java @@ -24,14 +24,14 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile super.initializeClients(httpPipeline, profile); } -// @Test -// public void foo() { -// HashSet s = new HashSet<>(); -// s.add(EncryptionStatus.NOT_ENCRYPTED); -// s.add(EncryptionStatus.NOT_ENCRYPTED); -// -// System.out.println(s.contains(EncryptionStatus.fromString("notEncrypted"))); -// } + // @Test + // public void foo() { + // HashSet s = new HashSet<>(); + // s.add(EncryptionStatus.NOT_ENCRYPTED); + // s.add(EncryptionStatus.NOT_ENCRYPTED); + // + // System.out.println(s.contains(EncryptionStatus.fromString("notEncrypted"))); + // } @Test @DoNotRecord(skipInPlayback = true) @@ -48,9 +48,8 @@ public void canListSkus() throws Exception { Assertions.assertNotNull(sku.regions()); if (sku.resourceType().equals(ComputeResourceType.VIRTUALMACHINES)) { Assertions.assertNotNull(sku.virtualMachineSizeType()); - Assertions - .assertEquals( - sku.virtualMachineSizeType().toString().toLowerCase(), sku.name().toString().toLowerCase()); + Assertions.assertEquals(sku.virtualMachineSizeType().toString().toLowerCase(), + sku.name().toString().toLowerCase()); Assertions.assertNull(sku.availabilitySetSkuType()); Assertions.assertNull(sku.diskSkuType()); atleastOneVirtualMachineResourceSku = true; @@ -66,25 +65,24 @@ public void canListSkus() throws Exception { } if (sku.resourceType().equals(ComputeResourceType.AVAILABILITYSETS)) { Assertions.assertNotNull(sku.availabilitySetSkuType()); - Assertions - .assertEquals( - sku.availabilitySetSkuType().toString().toLowerCase(), sku.name().toString().toLowerCase()); + Assertions.assertEquals(sku.availabilitySetSkuType().toString().toLowerCase(), + sku.name().toString().toLowerCase()); Assertions.assertNull(sku.virtualMachineSizeType()); Assertions.assertNull(sku.diskSkuType()); atleastOneAvailabilitySetResourceSku = true; } if (sku.resourceType().equals(ComputeResourceType.DISKS)) { Assertions.assertNotNull(sku.diskSkuType().toString()); - Assertions - .assertEquals(sku.diskSkuType().toString().toLowerCase(), sku.name().toString().toLowerCase()); + Assertions.assertEquals(sku.diskSkuType().toString().toLowerCase(), + sku.name().toString().toLowerCase()); Assertions.assertNull(sku.virtualMachineSizeType()); Assertions.assertNull(sku.availabilitySetSkuType()); atleastOneDiskResourceSku = true; } if (sku.resourceType().equals(ComputeResourceType.SNAPSHOTS)) { Assertions.assertNotNull(sku.diskSkuType()); - Assertions - .assertEquals(sku.diskSkuType().toString().toLowerCase(), sku.name().toString().toLowerCase()); + Assertions.assertEquals(sku.diskSkuType().toString().toLowerCase(), + sku.name().toString().toLowerCase()); Assertions.assertNull(sku.virtualMachineSizeType()); Assertions.assertNull(sku.availabilitySetSkuType()); atleastOneSnapshotResourceSku = true; @@ -113,8 +111,8 @@ public void canListSkusByRegion() throws Exception { @Test @DoNotRecord(skipInPlayback = true) public void canListSkusByResourceType() throws Exception { - PagedIterable skus = - this.computeManager.computeSkus().listByResourceType(ComputeResourceType.VIRTUALMACHINES); + PagedIterable skus + = this.computeManager.computeSkus().listByResourceType(ComputeResourceType.VIRTUALMACHINES); for (ComputeSku sku : skus) { Assertions.assertTrue(sku.resourceType().equals(ComputeResourceType.VIRTUALMACHINES)); } @@ -127,21 +125,15 @@ public void canListSkusByResourceType() throws Exception { @DoNotRecord(skipInPlayback = true) public void canListSkusByRegionAndResourceType() throws Exception { // LiveOnly because "test timing out after latest test proxy update" - PagedIterable skus = - this - .computeManager - .computeSkus() - .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.VIRTUALMACHINES); + PagedIterable skus = this.computeManager.computeSkus() + .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.VIRTUALMACHINES); for (ComputeSku sku : skus) { Assertions.assertTrue(sku.resourceType().equals(ComputeResourceType.VIRTUALMACHINES)); Assertions.assertTrue(sku.regions().contains(Region.US_EAST2)); } - skus = - this - .computeManager - .computeSkus() - .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.fromString("Unknown")); + skus = this.computeManager.computeSkus() + .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.fromString("Unknown")); Assertions.assertNotNull(skus); Assertions.assertEquals(0, TestUtilities.getSize(skus)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/DiskEncryptionSetTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/DiskEncryptionSetTests.java index efea42c18b1d0..5000ee8e850b2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/DiskEncryptionSetTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/DiskEncryptionSetTests.java @@ -43,10 +43,10 @@ protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { if (!testContextManager.doNotRecordTest()) { // don't match api-version when matching url - interceptorManager.addMatchers(new CustomMatcher() - .setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) - .setExcludedHeaders(Collections.singletonList("Accept-Language")) - .setIgnoredQueryParameters(Collections.singletonList("api-version"))); + interceptorManager + .addMatchers(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) + .setExcludedHeaders(Collections.singletonList("Accept-Language")) + .setIgnoredQueryParameters(Collections.singletonList("api-version"))); } } } @@ -74,12 +74,10 @@ public void canCRUDDiskEncryptionSet() { Assertions.assertEquals(vaultAndKey.key.id(), diskEncryptionSet.encryptionKeyId()); Assertions.assertNotNull(diskEncryptionSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertTrue(diskEncryptionSet.isAutomaticKeyRotationEnabled()); - Assertions.assertEquals(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, diskEncryptionSet.encryptionType()); + Assertions.assertEquals(DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, + diskEncryptionSet.encryptionType()); - diskEncryptionSet.update() - .withoutSystemAssignedManagedServiceIdentity() - .withoutAutomaticKeyRotation() - .apply(); + diskEncryptionSet.update().withoutSystemAssignedManagedServiceIdentity().withoutAutomaticKeyRotation().apply(); Assertions.assertNull(diskEncryptionSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertFalse(diskEncryptionSet.isAutomaticKeyRotationEnabled()); } @@ -96,7 +94,8 @@ private VaultAndKey(Vault vault, Key key) { VaultAndKey createVaultAndKey(Region region, String rgName, String name, String signedInUser) { // create vault - Vault vault = keyVaultManager.vaults().define(name) + Vault vault = keyVaultManager.vaults() + .define(name) .withRegion(region) .withNewResourceGroup(rgName) .withRoleBasedAccessControl() @@ -105,7 +104,8 @@ VaultAndKey createVaultAndKey(Region region, String rgName, String name, String // RBAC for this app String rbacName = generateRandomUuid(); - authorizationManager.roleAssignments().define(rbacName) + authorizationManager.roleAssignments() + .define(rbacName) .forUser(signedInUser) .withBuiltInRole(BuiltInRole.KEY_VAULT_ADMINISTRATOR) .withResourceScope(vault) @@ -120,9 +120,6 @@ VaultAndKey createVaultAndKey(Region region, String rgName, String name, String } Key createKey(Vault vault) { - return vault.keys().define("key1") - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + return vault.keys().define("key1").withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ManagedDiskOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ManagedDiskOperationsTests.java index b9b217c47fc00..ef3d6bf6566f3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ManagedDiskOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/ManagedDiskOperationsTests.java @@ -52,19 +52,17 @@ public void canOperateOnEmptyManagedDisk() { // Create an empty managed disk // - Disk disk = - computeManager - .disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .withSizeInGB(100) - // Start option - .withSku(DiskSkuTypes.STANDARD_LRS) - .withTag("tkey1", "tval1") - // End option - .create(); + Disk disk = computeManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .withSizeInGB(100) + // Start option + .withSku(DiskSkuTypes.STANDARD_LRS) + .withTag("tkey1", "tval1") + // End option + .create(); Assertions.assertNotNull(disk.id()); Assertions.assertTrue(disk.name().equalsIgnoreCase(diskName)); @@ -109,31 +107,27 @@ public void canOperateOnManagedDiskFromDisk() { // Create an empty managed disk // - Disk emptyDisk = - computeManager - .disks() - .define(diskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .withSizeInGB(100) - .create(); + Disk emptyDisk = computeManager.disks() + .define(diskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .withSizeInGB(100) + .create(); // Create a managed disk from existing managed disk // - Disk disk = - computeManager - .disks() - .define(diskName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .fromDisk(emptyDisk) - // Start Option - .withSizeInGB(200) - .withSku(DiskSkuTypes.STANDARD_LRS) - // End Option - .create(); + Disk disk = computeManager.disks() + .define(diskName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .fromDisk(emptyDisk) + // Start Option + .withSizeInGB(200) + .withSku(DiskSkuTypes.STANDARD_LRS) + // End Option + .create(); disk = computeManager.disks().getById(disk.id()); @@ -160,17 +154,15 @@ public void canOperateOnManagedDiskFromUpload() { // Create a managed disk from upload // - Disk disk = - computeManager - .disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .withUploadSizeInMB(1000) - .withSku(DiskSkuTypes.STANDARD_LRS) - // End Option - .create(); + Disk disk = computeManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .withUploadSizeInMB(1000) + .withSku(DiskSkuTypes.STANDARD_LRS) + // End Option + .create(); disk = computeManager.disks().getById(disk.id()); @@ -195,26 +187,22 @@ public void canOperateOnManagedDiskFromSnapshot() { ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Disk emptyDisk = - computeManager - .disks() - .define(emptyDiskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(100) - .create(); - - Snapshot snapshot = - computeManager - .snapshots() - .define(snapshotName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withDataFromDisk(emptyDisk) - .withSizeInGB(200) - .withSku(SnapshotSkuType.STANDARD_LRS) - .create(); + Disk emptyDisk = computeManager.disks() + .define(emptyDiskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(100) + .create(); + + Snapshot snapshot = computeManager.snapshots() + .define(snapshotName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withDataFromDisk(emptyDisk) + .withSizeInGB(200) + .withSku(SnapshotSkuType.STANDARD_LRS) + .create(); Assertions.assertNotNull(snapshot.id()); Assertions.assertTrue(snapshot.name().equalsIgnoreCase(snapshotName)); @@ -226,16 +214,14 @@ public void canOperateOnManagedDiskFromSnapshot() { Assertions.assertEquals(snapshot.source().type(), CreationSourceType.COPIED_FROM_DISK); assertResourceIdEquals(snapshot.source().sourceId(), emptyDisk.id()); - Disk fromSnapshotDisk = - computeManager - .disks() - .define(snapshotBasedDiskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .fromSnapshot(snapshot) - .withSizeInGB(300) - .create(); + Disk fromSnapshotDisk = computeManager.disks() + .define(snapshotBasedDiskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .fromSnapshot(snapshot) + .withSizeInGB(300) + .create(); Assertions.assertNotNull(fromSnapshotDisk.id()); Assertions.assertTrue(fromSnapshotDisk.name().equalsIgnoreCase(snapshotBasedDiskName)); @@ -264,27 +250,23 @@ public void canCopyStartIncrementalSnapshot() { ResourceGroup resourceGroup2 = resourceManager.resourceGroups().define(rgName2).withRegion(region2).create(); // create disk to copy - Disk emptyDisk = - computeManager - .disks() - .define(emptyDiskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(100) - .create(); + Disk emptyDisk = computeManager.disks() + .define(emptyDiskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(100) + .create(); // create incremental snapshot from the disk - Snapshot snapshot = - computeManager - .snapshots() - .define(snapshotName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withDataFromDisk(emptyDisk) - .withSku(SnapshotSkuType.STANDARD_LRS) - .withIncremental(true) - .create(); + Snapshot snapshot = computeManager.snapshots() + .define(snapshotName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withDataFromDisk(emptyDisk) + .withSku(SnapshotSkuType.STANDARD_LRS) + .withIncremental(true) + .create(); Assertions.assertTrue(snapshot.incremental()); Assertions.assertEquals(CreationSourceType.COPIED_FROM_DISK, snapshot.source().type()); @@ -292,16 +274,14 @@ public void canCopyStartIncrementalSnapshot() { Assertions.assertThrows(IllegalStateException.class, snapshot::awaitCopyStartCompletion); // copy the snapshot to the same region - Snapshot snapshotSameRegion = - computeManager - .snapshots() - .define(snapshotName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withDataFromSnapshot(snapshot) - .withCopyStart() - .withIncremental(true) - .create(); + Snapshot snapshotSameRegion = computeManager.snapshots() + .define(snapshotName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withDataFromSnapshot(snapshot) + .withCopyStart() + .withIncremental(true) + .create(); Assertions.assertTrue(snapshotSameRegion.incremental()); Assertions.assertEquals(CreationSourceType.COPIED_FROM_SNAPSHOT, snapshotSameRegion.source().type()); @@ -310,12 +290,9 @@ public void canCopyStartIncrementalSnapshot() { // we don't wait for CopyStart to finish, so it should be in progress Assertions.assertNotEquals(100, snapshotSameRegion.copyCompletionPercent()); - computeManager - .snapshots() - .deleteById(snapshotSameRegion.id()); + computeManager.snapshots().deleteById(snapshotSameRegion.id()); - Snapshot snapshotSameRegion2 = computeManager - .snapshots() + Snapshot snapshotSameRegion2 = computeManager.snapshots() .define(snapshotName2) .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -327,16 +304,14 @@ public void canCopyStartIncrementalSnapshot() { Assertions.assertTrue(snapshotSameRegion2.awaitCopyStartCompletion(Duration.ofHours(24))); // copy the snapshot to a new region - Snapshot snapshotNewRegion = - computeManager - .snapshots() - .define(newRegionSnapshotName) - .withRegion(region2) - .withExistingResourceGroup(resourceGroup2) - .withDataFromSnapshot(snapshot) - .withCopyStart() - .withIncremental(true) - .create(); + Snapshot snapshotNewRegion = computeManager.snapshots() + .define(newRegionSnapshotName) + .withRegion(region2) + .withExistingResourceGroup(resourceGroup2) + .withDataFromSnapshot(snapshot) + .withCopyStart() + .withIncremental(true) + .create(); snapshotNewRegion.awaitCopyStartCompletion(); Assertions.assertTrue(snapshotNewRegion.incremental()); @@ -346,16 +321,14 @@ public void canCopyStartIncrementalSnapshot() { Assertions.assertNull(snapshotNewRegion.copyCompletionError()); // create disk from snapshot in the new region - Disk fromSnapshotDisk = - computeManager - .disks() - .define(snapshotBasedDiskName) - .withRegion(region2) - .withExistingResourceGroup(resourceGroup2) - .withData() - .fromSnapshot(snapshotNewRegion) - .withSizeInGB(300) - .create(); + Disk fromSnapshotDisk = computeManager.disks() + .define(snapshotBasedDiskName) + .withRegion(region2) + .withExistingResourceGroup(resourceGroup2) + .withData() + .fromSnapshot(snapshotNewRegion) + .withSizeInGB(300) + .create(); Assertions.assertNotNull(fromSnapshotDisk.id()); Assertions.assertTrue(fromSnapshotDisk.name().equalsIgnoreCase(snapshotBasedDiskName)); @@ -373,33 +346,29 @@ public void canCreateWithLogicalSectorSize() { String diskName = generateRandomResourceName("disk", 15); // logical sector size is null for standard SKU - Disk defaultDisk = - computeManager - .disks() - .define("default_disk") - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withData() - .withSizeInGB(1) - .withSku(DiskSkuTypes.STANDARD_LRS) - .create(); + Disk defaultDisk = computeManager.disks() + .define("default_disk") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withData() + .withSizeInGB(1) + .withSku(DiskSkuTypes.STANDARD_LRS) + .create(); defaultDisk.refresh(); Assertions.assertNull(defaultDisk.logicalSectorSizeInBytes()); // can specify logical sector size on PREMIUM_V2_LRS - Disk disk = - computeManager - .disks() - .define(diskName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(10) - .withSku(DiskSkuTypes.PREMIUM_V2_LRS) - .withLogicalSectorSizeInBytes(512) - .create(); + Disk disk = computeManager.disks() + .define(diskName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(10) + .withSku(DiskSkuTypes.PREMIUM_V2_LRS) + .withLogicalSectorSizeInBytes(512) + .create(); disk.refresh(); @@ -409,17 +378,15 @@ public void canCreateWithLogicalSectorSize() { @Test public void canCreateAndUpdateManagedDiskWithHyperVGeneration() { - Disk disk = - computeManager - .disks() - .define(generateRandomResourceName("disk", 15)) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withData() - .withSizeInGB(1) - .withSku(DiskSkuTypes.STANDARD_LRS) - .withHyperVGeneration(HyperVGeneration.V1) - .create(); + Disk disk = computeManager.disks() + .define(generateRandomResourceName("disk", 15)) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withData() + .withSizeInGB(1) + .withSku(DiskSkuTypes.STANDARD_LRS) + .withHyperVGeneration(HyperVGeneration.V1) + .create(); disk.refresh(); Assertions.assertEquals(disk.hyperVGeneration(), HyperVGeneration.V1); @@ -435,16 +402,14 @@ public void canCreateAndUpdatePublicNetworkAccess() { // Create an empty managed disk // - Disk disk = - computeManager - .disks() - .define(diskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .withSizeInGB(100) - .disablePublicNetworkAccess() - .create(); + Disk disk = computeManager.disks() + .define(diskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .withSizeInGB(100) + .disablePublicNetworkAccess() + .create(); disk.refresh(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, disk.publicNetworkAccess()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SharedGalleryImageTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SharedGalleryImageTests.java index 434819a386700..ba750b27154ee 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SharedGalleryImageTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SharedGalleryImageTests.java @@ -51,17 +51,14 @@ protected void cleanUpResources() { public void canCreateUpdateListGetDeleteGallery() { // Create a gallery // - Gallery javaGallery = - this - .computeManager - .galleries() - .define("JavaImageGallery") - .withRegion(region) - .withNewResourceGroup(rgName) - // Optionals - Start - .withDescription("java's image gallery") - // Optionals - End - .create(); + Gallery javaGallery = this.computeManager.galleries() + .define("JavaImageGallery") + .withRegion(region) + .withNewResourceGroup(rgName) + // Optionals - Start + .withDescription("java's image gallery") + // Optionals - End + .create(); Assertions.assertNotNull(javaGallery.uniqueName()); Assertions.assertEquals("JavaImageGallery", javaGallery.name()); @@ -93,34 +90,28 @@ public void canCreateUpdateGetDeleteGalleryImage() { // Create a gallery // - Gallery javaGallery = - this - .computeManager - .galleries() - .define(galleryName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDescription("java's image gallery") - .create(); + Gallery javaGallery = this.computeManager.galleries() + .define(galleryName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDescription("java's image gallery") + .create(); // // Create an image in the gallery // - GalleryImage galleryImage = - this - .computeManager - .galleryImages() - .define(galleryImageName) - .withExistingGallery(javaGallery) - .withLocation(region) - .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") - .withGeneralizedWindows() - // Optionals - Start - .withUnsupportedDiskType(DiskSkuTypes.STANDARD_LRS) - .withUnsupportedDiskType(DiskSkuTypes.PREMIUM_LRS) - .withRecommendedMaximumCPUsCountForVirtualMachine(25) - .withRecommendedMaximumMemoryForVirtualMachine(3200) - // Options - End - .create(); + GalleryImage galleryImage = this.computeManager.galleryImages() + .define(galleryImageName) + .withExistingGallery(javaGallery) + .withLocation(region) + .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") + .withGeneralizedWindows() + // Optionals - Start + .withUnsupportedDiskType(DiskSkuTypes.STANDARD_LRS) + .withUnsupportedDiskType(DiskSkuTypes.PREMIUM_LRS) + .withRecommendedMaximumCPUsCountForVirtualMachine(25) + .withRecommendedMaximumMemoryForVirtualMachine(3200) + // Options - End + .create(); Assertions.assertNotNull(galleryImage); Assertions.assertNotNull(galleryImage.innerModel()); @@ -142,8 +133,7 @@ public void canCreateUpdateGetDeleteGalleryImage() { // // Update an image in the gallery // - galleryImage - .update() + galleryImage.update() .withoutUnsupportedDiskType(DiskSkuTypes.PREMIUM_LRS) .withRecommendedMinimumCPUsCountForVirtualMachine(15) .withRecommendedMemoryForVirtualMachine(2200, 3200) @@ -167,15 +157,14 @@ public void canCreateUpdateGetDeleteGalleryImage() { OffsetDateTime offsetDateTime = OffsetDateTime.now().plusDays(10); Map tags = new HashMap<>(); tags.put("tag1", "myTag1"); - galleryImage - .update() + galleryImage.update() .withDescription(description) .withReleaseNoteUri(releaseURI) .withEndOfLifeDate(offsetDateTime) .withRecommendedCPUsCountForVirtualMachine(10, 20) .withRecommendedMemoryForVirtualMachine(10, 20) .withUnsupportedDiskType(DiskSkuTypes.PREMIUM_LRS) -// .withOsState(OperatingSystemStateTypes.SPECIALIZED) // changing of osState is not allowed + // .withOsState(OperatingSystemStateTypes.SPECIALIZED) // changing of osState is not allowed .withTags(tags) .apply(); @@ -189,7 +178,7 @@ public void canCreateUpdateGetDeleteGalleryImage() { Assertions.assertEquals(10, galleryImage.recommendedVirtualMachineConfiguration().memory().min()); Assertions.assertEquals(20, galleryImage.recommendedVirtualMachineConfiguration().memory().max()); Assertions.assertTrue(galleryImage.disallowed().diskTypes().contains(DiskSkuTypes.PREMIUM_LRS.toString())); -// Assertions.assertEquals(galleryImage.osState(), OperatingSystemStateTypes.SPECIALIZED); + // Assertions.assertEquals(galleryImage.osState(), OperatingSystemStateTypes.SPECIALIZED); // // List images in the gallery @@ -214,30 +203,24 @@ public void canCreateUpdateGetDeleteGalleryImage() { public void canCreateUpdateGetDeleteGalleryImageVersion() { final String galleryName = generateRandomResourceName("jsim", 15); // "jsim94f154754"; - Gallery gallery = - this - .computeManager - .galleries() - .define(galleryName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withDescription("java's image gallery") - .create(); + Gallery gallery = this.computeManager.galleries() + .define(galleryName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDescription("java's image gallery") + .create(); // // Create an image in the gallery (a container to hold custom linux image) // final String galleryImageName = "SampleImages"; - GalleryImage galleryImage = - this - .computeManager - .galleryImages() - .define(galleryImageName) - .withExistingGallery(gallery) - .withLocation(region) - .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") - .withGeneralizedLinux() - .create(); + GalleryImage galleryImage = this.computeManager.galleryImages() + .define(galleryImageName) + .withExistingGallery(gallery) + .withLocation(region) + .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") + .withGeneralizedLinux() + .create(); // // Create a custom image to base the version on // @@ -250,18 +233,15 @@ public void canCreateUpdateGetDeleteGalleryImageVersion() { final String versionName = "0.0.4"; - GalleryImageVersion imageVersion = - this - .computeManager - .galleryImageVersions() - .define(versionName) - .withExistingImage(rgName, gallery.name(), galleryImage.name()) - .withLocation(region.toString()) - .withSourceCustomImage(customImage) - // Options - Start - .withRegionAvailability(Region.US_WEST2, 1) - // Options - End - .create(); + GalleryImageVersion imageVersion = this.computeManager.galleryImageVersions() + .define(versionName) + .withExistingImage(rgName, gallery.name(), galleryImage.name()) + .withLocation(region.toString()) + .withSourceCustomImage(customImage) + // Options - Start + .withRegionAvailability(Region.US_WEST2, 1) + // Options - End + .create(); Assertions.assertNotNull(imageVersion); Assertions.assertNotNull(imageVersion.innerModel()); @@ -298,9 +278,7 @@ public void canCreateUpdateGetDeleteGalleryImageVersion() { // // Delete the image version // - this - .computeManager - .galleryImageVersions() + this.computeManager.galleryImageVersions() .deleteByGalleryImage(rgName, galleryName, galleryImageName, versionName); } @@ -308,29 +286,23 @@ public void canCreateUpdateGetDeleteGalleryImageVersion() { public void canCreateTrustedLaunchVMsFromGalleryImage() { final String galleryName = generateRandomResourceName("jsim", 15); - Gallery gallery = - this - .computeManager - .galleries() - .define(galleryName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withDescription("java's image gallery") - .create(); + Gallery gallery = this.computeManager.galleries() + .define(galleryName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDescription("java's image gallery") + .create(); final String galleryImageName = "SampleImages"; - GalleryImage galleryImage = - this - .computeManager - .galleryImages() - .define(galleryImageName) - .withExistingGallery(gallery) - .withLocation(region) - .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") - .withGeneralizedLinux() - .withHyperVGeneration(HyperVGeneration.V2) - .withTrustedLaunch() - .create(); + GalleryImage galleryImage = this.computeManager.galleryImages() + .define(galleryImageName) + .withExistingGallery(gallery) + .withLocation(region) + .withIdentifier("JavaSDKTeam", "JDK", "Jdk-9") + .withGeneralizedLinux() + .withHyperVGeneration(HyperVGeneration.V2) + .withTrustedLaunch() + .create(); Assertions.assertEquals(HyperVGeneration.V2, galleryImage.hyperVGeneration()); Assertions.assertEquals(SecurityTypes.TRUSTED_LAUNCH, galleryImage.securityType()); @@ -339,21 +311,17 @@ public void canCreateTrustedLaunchVMsFromGalleryImage() { final String versionName = "0.0.1"; - GalleryImageVersion imageVersion = - this - .computeManager - .galleryImageVersions() - .define(versionName) - .withExistingImage(rgName, gallery.name(), galleryImage.name()) - .withLocation(region.toString()) - .withSourceVirtualMachine(virtualMachine) - .withRegionAvailability(Region.US_WEST2, 1) - .create(); + GalleryImageVersion imageVersion = this.computeManager.galleryImageVersions() + .define(versionName) + .withExistingImage(rgName, gallery.name(), galleryImage.name()) + .withLocation(region.toString()) + .withSourceVirtualMachine(virtualMachine) + .withRegionAvailability(Region.US_WEST2, 1) + .create(); final String trustedLaunchVmName = generateRandomResourceName("tlvm", 15); - VirtualMachine trustedLaunchVm = computeManager - .virtualMachines() + VirtualMachine trustedLaunchVm = computeManager.virtualMachines() .define(trustedLaunchVmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -382,27 +350,25 @@ private VirtualMachine prepareTrustedLaunchVM(String rgName, Region region, Comp final KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UBUNTU_SERVER_20_04_LTS_GEN2; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withNewDataDisk(1) - .withNewDataDisk(1, 2, CachingTypes.READ_WRITE) - .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) - .withNewStorageAccount(generateRandomResourceName("stg", 17)) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withTrustedLaunch() - .withSecureBoot() - .withVTpm() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withNewDataDisk(1) + .withNewDataDisk(1, 2, CachingTypes.READ_WRITE) + .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) + .withNewStorageAccount(generateRandomResourceName("stg", 17)) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withTrustedLaunch() + .withSecureBoot() + .withVTpm() + .create(); virtualMachine.deallocate(); virtualMachine.generalize(); @@ -411,23 +377,20 @@ private VirtualMachine prepareTrustedLaunchVM(String rgName, Region region, Comp } private VirtualMachineCustomImage prepareCustomImage(String rgName, Region region, ComputeManager computeManager) { - VirtualMachine linuxVM = - prepareGeneralizedVmWith2EmptyDataDisks( - rgName, generateRandomResourceName("muldvm", 15), region, computeManager); + VirtualMachine linuxVM = prepareGeneralizedVmWith2EmptyDataDisks(rgName, + generateRandomResourceName("muldvm", 15), region, computeManager); final String vhdBasedImageName = generateRandomResourceName("img", 20); // - VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDisk = - computeManager - .virtualMachineCustomImages() + VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDisk + = computeManager.virtualMachineCustomImages() .define(vhdBasedImageName) .withRegion(region) .withNewResourceGroup(rgName) .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED) .withOSDiskCaching(linuxVM.osDiskCachingType()); for (VirtualMachineUnmanagedDataDisk disk : linuxVM.unmanagedDataDisks().values()) { - creatableDisk - .defineDataDiskImage() + creatableDisk.defineDataDiskImage() .withLun(disk.lun()) .fromVhd(disk.vhdUri()) .withDiskCaching(disk.cachingType()) @@ -439,38 +402,36 @@ private VirtualMachineCustomImage prepareCustomImage(String rgName, Region regio return customImage; } - private VirtualMachine prepareGeneralizedVmWith2EmptyDataDisks( - String rgName, String vmName, Region region, ComputeManager computeManager) { + private VirtualMachine prepareGeneralizedVmWith2EmptyDataDisks(String rgName, String vmName, Region region, + ComputeManager computeManager) { final String uname = "javauser"; final String password = password(); final KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(30) - .withCaching(CachingTypes.READ_WRITE) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(60) - .withCaching(CachingTypes.READ_ONLY) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_D2_V3) - .withNewStorageAccount(generateRandomResourceName("stg", 17)) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(30) + .withCaching(CachingTypes.READ_WRITE) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(60) + .withCaching(CachingTypes.READ_ONLY) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_D2_V3) + .withNewStorageAccount(generateRandomResourceName("stg", 17)) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); // deprovisionAgentInLinuxVM(virtualMachine); virtualMachine.deallocate(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SnapshotOptionsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SnapshotOptionsTests.java index 088505ed49296..8536639847713 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SnapshotOptionsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/SnapshotOptionsTests.java @@ -34,16 +34,14 @@ public void canCreateAndUpdatePublicNetworkAccess() { final String diskName1 = generateRandomResourceName("md-1", 20); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Disk disk = - computeManager - .disks() - .define(diskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup.name()) - .withData() - .withSizeInGB(100) - .disablePublicNetworkAccess() - .create(); + Disk disk = computeManager.disks() + .define(diskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup.name()) + .withData() + .withSizeInGB(100) + .disablePublicNetworkAccess() + .create(); Snapshot snapshot = computeManager.snapshots() .define(snapshotName) diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineAvailabilityZoneOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineAvailabilityZoneOperationsTests.java index 3f3fad62dfd39..1fa25cbe942c6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineAvailabilityZoneOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineAvailabilityZoneOperationsTests.java @@ -56,25 +56,23 @@ public void canCreateZonedVirtualMachineWithImplicitZoneForRelatedResources() th final String proxyGroupName = "plg1Test"; // Create a zoned virtual machine // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipDnsLabel) - .withNewProximityPlacementGroup(proxyGroupName, ProximityPlacementGroupType.STANDARD) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // Optionals - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - // Create VM - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipDnsLabel) + .withNewProximityPlacementGroup(proxyGroupName, ProximityPlacementGroupType.STANDARD) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // Optionals + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + // Create VM + .create(); // Checks the zone assigned to the virtual machine // @@ -84,16 +82,11 @@ public void canCreateZonedVirtualMachineWithImplicitZoneForRelatedResources() th // Check the proximity placement group information Assertions.assertNotNull(virtualMachine.proximityPlacementGroup()); - Assertions - .assertEquals( - ProximityPlacementGroupType.STANDARD, - virtualMachine.proximityPlacementGroup().proximityPlacementGroupType()); + Assertions.assertEquals(ProximityPlacementGroupType.STANDARD, + virtualMachine.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(virtualMachine.proximityPlacementGroup().virtualMachineIds()); - Assertions - .assertTrue( - virtualMachine - .id() - .equalsIgnoreCase(virtualMachine.proximityPlacementGroup().virtualMachineIds().get(0))); + Assertions.assertTrue( + virtualMachine.id().equalsIgnoreCase(virtualMachine.proximityPlacementGroup().virtualMachineIds().get(0))); // Checks the zone assigned to the implicitly created public IP address. // Implicitly created PIP will be BASIC @@ -121,57 +114,48 @@ public void canCreateZonedVirtualMachineWithExplicitZoneForRelatedResources() th // Create zoned public IP for the virtual machine // final String pipDnsLabel = generateRandomResourceName("pip", 10); - PublicIpAddress publicIPAddress = - networkManager - .publicIpAddresses() - .define(pipDnsLabel) - .withRegion(region) - .withNewResourceGroup(rgName) - .withStaticIP() - // Optionals - .withAvailabilityZone( - AvailabilityZoneId.ZONE_1) // since the SKU is STANDARD and VM is zoned, PIP must be zoned - .withSku( - PublicIPSkuType - .STANDARD) // Only standard sku supports zone resiliency, so if you want it zoned, specify explicitly as - // above. - // Create PIP - .create(); + PublicIpAddress publicIPAddress = networkManager.publicIpAddresses() + .define(pipDnsLabel) + .withRegion(region) + .withNewResourceGroup(rgName) + .withStaticIP() + // Optionals + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) // since the SKU is STANDARD and VM is zoned, PIP must be zoned + .withSku(PublicIPSkuType.STANDARD) // Only standard sku supports zone resiliency, so if you want it zoned, specify explicitly as + // above. + // Create PIP + .create(); // Create a zoned data disk for the virtual machine // final String diskName = generateRandomResourceName("dsk", 10); - Disk dataDisk = - computeManager - .disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100) - // Optionals - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - // Create Disk - .create(); + Disk dataDisk = computeManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100) + // Optionals + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + // Create Disk + .create(); // Create a zoned virtual machine // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIPAddress) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // Optionals - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withExistingDataDisk(dataDisk) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - // Create VM - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIPAddress) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // Optionals + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withExistingDataDisk(dataDisk) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + // Create VM + .create(); // Checks the zone assigned to the virtual machine // Assertions.assertNotNull(virtualMachine.availabilityZones()); @@ -216,40 +200,34 @@ public void canCreateZonedVirtualMachineWithZoneResilientPublicIP() throws Excep // Create zone resilient public IP for the virtual machine // final String pipDnsLabel = generateRandomResourceName("pip", 10); - PublicIpAddress publicIPAddress = - networkManager - .publicIpAddresses() - .define(pipDnsLabel) - .withRegion(region) - .withNewResourceGroup(rgName) - .withStaticIP() - // Optionals - .withSku( - PublicIPSkuType - .STANDARD) // No zone selected, STANDARD SKU is zone resilient [zone resilient: resources - // deployed in all zones by the service and it will be served by all AZs all the - // time] - // Create PIP - .create(); + PublicIpAddress publicIPAddress = networkManager.publicIpAddresses() + .define(pipDnsLabel) + .withRegion(region) + .withNewResourceGroup(rgName) + .withStaticIP() + // Optionals + .withSku(PublicIPSkuType.STANDARD) // No zone selected, STANDARD SKU is zone resilient [zone resilient: resources + // deployed in all zones by the service and it will be served by all AZs all the + // time] + // Create PIP + .create(); // Create a zoned virtual machine // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIPAddress) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // Optionals - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - // Create VM - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIPAddress) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // Optionals + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + // Create VM + .create(); // Checks the zone assigned to the virtual machine // Assertions.assertNotNull(virtualMachine.availabilityZones()); @@ -260,10 +238,7 @@ public void canCreateZonedVirtualMachineWithZoneResilientPublicIP() throws Excep publicIPAddress = virtualMachine.getPrimaryPublicIPAddress(); Assertions.assertNotNull(publicIPAddress.sku()); Assertions.assertTrue(publicIPAddress.sku().equals(PublicIPSkuType.STANDARD)); - Assertions - .assertNotNull( - publicIPAddress - .availabilityZones()); // Though zone-resilient, this property won't be populated by the service. + Assertions.assertNotNull(publicIPAddress.availabilityZones()); // Though zone-resilient, this property won't be populated by the service. Assertions.assertTrue(publicIPAddress.availabilityZones().isEmpty()); } @@ -274,58 +249,52 @@ public void canCreateZonedVirtualMachineWithZoneResilientPublicIP() throws Excep canCreateRegionalNonAvailSetVirtualMachinesAndAssociateThemWithSingleBackendPoolOfZoneResilientLoadBalancer() throws Exception { final String networkName = generateRandomResourceName("net", 10); - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); // create two regional virtual machine, which does not belongs to any availability set // Iterator subnets = network.subnets().values().iterator(); // Define first regional virtual machine // - Creatable creatableVM1 = - computeManager - .virtualMachines() - .define(generateRandomResourceName("vm1", 10)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(subnets.next().name()) // Put VM in first subnet - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // Optionals - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable creatableVM1 = computeManager.virtualMachines() + .define(generateRandomResourceName("vm1", 10)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnets.next().name()) // Put VM in first subnet + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // Optionals + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); // Define second regional virtual machine // - Creatable creatableVM2 = - computeManager - .virtualMachines() - .define(generateRandomResourceName("vm2", 10)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(subnets.next().name()) // Put VM in second subnet - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // Optionals - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); - - CreatedResources createdVMs = - computeManager.virtualMachines().create(creatableVM1, creatableVM2); + Creatable creatableVM2 = computeManager.virtualMachines() + .define(generateRandomResourceName("vm2", 10)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnets.next().name()) // Put VM in second subnet + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // Optionals + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + + CreatedResources createdVMs + = computeManager.virtualMachines().create(creatableVM1, creatableVM2); VirtualMachine firstVirtualMachine = createdVMs.get(creatableVM1.key()); VirtualMachine secondVirtualMachine = createdVMs.get(creatableVM2.key()); @@ -342,49 +311,42 @@ public void canCreateZonedVirtualMachineWithZoneResilientPublicIP() throws Excep // Creates a public IP address for the internet-facing load-balancer // final String pipDnsLabel = generateRandomResourceName("pip", 10); - PublicIpAddress publicIPAddress = - networkManager - .publicIpAddresses() - .define(pipDnsLabel) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withStaticIP() - // Optionals - .withSku(PublicIPSkuType.STANDARD) // STANDARD LB requires STANDARD PIP - // Create PIP - .create(); + PublicIpAddress publicIPAddress = networkManager.publicIpAddresses() + .define(pipDnsLabel) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withStaticIP() + // Optionals + .withSku(PublicIPSkuType.STANDARD) // STANDARD LB requires STANDARD PIP + // Create PIP + .create(); // Creates a Internet-Facing LoadBalancer with one front-end IP configuration and // two backend pool associated with this IP Config // final String lbName = generateRandomResourceName("lb", 10); - LoadBalancer lb = - this - .networkManager - .loadBalancers() - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .defineLoadBalancingRule("rule-1") - .withProtocol(TransportProtocol.TCP) - .fromFrontend("front-end-1") - .fromFrontendPort(80) - .toExistingVirtualMachines(firstVirtualMachine, secondVirtualMachine) - .withProbe("tcpProbe-1") - .attach() - .definePublicFrontend("front-end-1") // Define the frontend IP configuration used by the LB rule - .withExistingPublicIpAddress(publicIPAddress) - .attach() - .defineTcpProbe("tcpProbe-1") // Define the Probe used by the LB rule - .withPort(25) - .withIntervalInSeconds(15) - .withNumberOfProbes(5) - .attach() - .withSku( - LoadBalancerSkuType - .STANDARD) // "zone-resilient LB" which don't have the constraint that all VMs needs to be in - // the same availability set - .create(); + LoadBalancer lb = this.networkManager.loadBalancers() + .define(lbName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineLoadBalancingRule("rule-1") + .withProtocol(TransportProtocol.TCP) + .fromFrontend("front-end-1") + .fromFrontendPort(80) + .toExistingVirtualMachines(firstVirtualMachine, secondVirtualMachine) + .withProbe("tcpProbe-1") + .attach() + .definePublicFrontend("front-end-1") // Define the frontend IP configuration used by the LB rule + .withExistingPublicIpAddress(publicIPAddress) + .attach() + .defineTcpProbe("tcpProbe-1") // Define the Probe used by the LB rule + .withPort(25) + .withIntervalInSeconds(15) + .withNumberOfProbes(5) + .attach() + .withSku(LoadBalancerSkuType.STANDARD) // "zone-resilient LB" which don't have the constraint that all VMs needs to be in + // the same availability set + .create(); // Zone resilient LB does not care VMs are zoned or regional, in the above cases VMs are regional. // @@ -428,75 +390,67 @@ public void canCreateZonedVirtualMachineWithZoneResilientPublicIP() throws Excep public void canCreateZonedVirtualMachinesAndAssociateThemWithSingleBackendPoolOfZoneResilientLoadBalancer() throws Exception { final String networkName = generateRandomResourceName("net", 10); - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); // create two regional virtual machine, which does not belongs to any availability set // Iterator subnets = network.subnets().values().iterator(); // Define first regional virtual machine // - Creatable creatableVM1 = - computeManager - .virtualMachines() - .define(generateRandomResourceName("vm1", 10)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(subnets.next().name()) // Put VM in first subnet - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - // Optionals - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable creatableVM1 = computeManager.virtualMachines() + .define(generateRandomResourceName("vm1", 10)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnets.next().name()) // Put VM in first subnet + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + // Optionals + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); // Define second regional virtual machine // - Creatable creatableVM2 = - computeManager - .virtualMachines() - .define(generateRandomResourceName("vm2", 10)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(subnets.next().name()) // Put VM in second subnet - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - // Optionals - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); - - CreatedResources createdVMs = - computeManager.virtualMachines().create(creatableVM1, creatableVM2); + Creatable creatableVM2 = computeManager.virtualMachines() + .define(generateRandomResourceName("vm2", 10)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnets.next().name()) // Put VM in second subnet + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + // Optionals + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + + CreatedResources createdVMs + = computeManager.virtualMachines().create(creatableVM1, creatableVM2); // Creates a public IP address for the internet-facing load-balancer // final String pipDnsLabel = generateRandomResourceName("pip", 10); - PublicIpAddress publicIPAddress = - networkManager - .publicIpAddresses() - .define(pipDnsLabel) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withStaticIP() - // Optionals - .withSku(PublicIPSkuType.STANDARD) // STANDARD LB requires STANDARD PIP - // Create PIP - .create(); + PublicIpAddress publicIPAddress = networkManager.publicIpAddresses() + .define(pipDnsLabel) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withStaticIP() + // Optionals + .withSku(PublicIPSkuType.STANDARD) // STANDARD LB requires STANDARD PIP + // Create PIP + .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(network.resourceGroupName()); @@ -510,57 +464,51 @@ public void canCreateZonedVirtualMachinesAndAssociateThemWithSingleBackendPoolOf // Sku of PublicIP and LoadBalancer must match // - PublicIpAddress lbPip = - this - .networkManager - .publicIpAddresses() - .define(publicIPName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(publicIPName) - // Optionals - .withStaticIP() - .withSku(PublicIPSkuType.STANDARD) - // Create - .create(); - - LoadBalancer loadBalancer = - this - .networkManager - .loadBalancers() - .define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule("httpRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toExistingVirtualMachines(createdVMs.get(creatableVM1.key())) - .withProbe("httpProbe") - .attach() - .defineLoadBalancingRule("httpsRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toExistingVirtualMachines(createdVMs.get(creatableVM2.key())) - .withProbe("httpsProbe") - .attach() - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer - .attach() - - // Add two probes one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - .defineHttpProbe("httpsProbe") - .withRequestPath("/") - .attach() - .withSku(LoadBalancerSkuType.STANDARD) - .create(); + PublicIpAddress lbPip = this.networkManager.publicIpAddresses() + .define(publicIPName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(publicIPName) + // Optionals + .withStaticIP() + .withSku(PublicIPSkuType.STANDARD) + // Create + .create(); + + LoadBalancer loadBalancer = this.networkManager.loadBalancers() + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule("httpRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toExistingVirtualMachines(createdVMs.get(creatableVM1.key())) + .withProbe("httpProbe") + .attach() + .defineLoadBalancingRule("httpsRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toExistingVirtualMachines(createdVMs.get(creatableVM2.key())) + .withProbe("httpsProbe") + .attach() + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer + .attach() + + // Add two probes one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + .defineHttpProbe("httpsProbe") + .withRequestPath("/") + .attach() + .withSku(LoadBalancerSkuType.STANDARD) + .create(); // Zone resilient LB does not care VMs are zoned or regional, in the above cases VMs are zoned. // diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineBootDiagnosticsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineBootDiagnosticsTests.java index a716ce8114c43..60cf871acd577 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineBootDiagnosticsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineBootDiagnosticsTests.java @@ -33,20 +33,18 @@ protected void cleanUpResources() { @Test public void canEnableBootDiagnosticsWithImplicitStorageOnManagedVMCreation() { - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withBootDiagnostics() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); @@ -56,23 +54,21 @@ public void canEnableBootDiagnosticsWithImplicitStorageOnManagedVMCreation() { @Test public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMCreation() { final String storageName = generateRandomResourceName("st", 14); - Creatable creatableStorageAccount = - storageManager.storageAccounts().define(storageName).withRegion(region).withNewResourceGroup(rgName); + Creatable creatableStorageAccount + = storageManager.storageAccounts().define(storageName).withRegion(region).withNewResourceGroup(rgName); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withBootDiagnostics(creatableStorageAccount) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withBootDiagnostics(creatableStorageAccount) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); Assertions.assertNotNull(virtualMachine.bootDiagnosticsStorageUri()); @@ -82,28 +78,24 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMCreation() { @Test public void canEnableBootDiagnosticsWithExplicitStorageOnManagedVMCreation() { final String storageName = generateRandomResourceName("st", 14); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .create(); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withBootDiagnostics(storageAccount) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withBootDiagnostics(storageAccount) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); @@ -113,20 +105,18 @@ public void canEnableBootDiagnosticsWithExplicitStorageOnManagedVMCreation() { @Test public void canDisableBootDiagnostics() { - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withBootDiagnostics() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); @@ -141,63 +131,53 @@ public void canDisableBootDiagnostics() { @Test public void bootDiagnosticsShouldUsesOSUnManagedDiskImplicitStorage() { - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() // The implicit storage account for OS disk should be used for boot diagnostics as - // well - .withBootDiagnostics() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() // The implicit storage account for OS disk should be used for boot diagnostics as + // well + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); Assertions.assertNotNull(virtualMachine.bootDiagnosticsStorageUri()); Assertions.assertNotNull(virtualMachine.osUnmanagedDiskVhdUri()); - Assertions - .assertTrue( - virtualMachine - .osUnmanagedDiskVhdUri() - .toLowerCase() - .startsWith(virtualMachine.bootDiagnosticsStorageUri().toLowerCase())); + Assertions.assertTrue(virtualMachine.osUnmanagedDiskVhdUri() + .toLowerCase() + .startsWith(virtualMachine.bootDiagnosticsStorageUri().toLowerCase())); } @Test public void bootDiagnosticsShouldUseUnManagedDisksExplicitStorage() { final String storageName = generateRandomResourceName("st", 14); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .create(); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withBootDiagnostics() - .withExistingStorageAccount( - storageAccount) // This storage account must be shared by disk and boot diagnostics - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withBootDiagnostics() + .withExistingStorageAccount(storageAccount) // This storage account must be shared by disk and boot diagnostics + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); @@ -207,112 +187,95 @@ public void bootDiagnosticsShouldUseUnManagedDisksExplicitStorage() { @Test public void canEnableBootDiagnosticsWithImplicitStorageOnUnManagedVMCreation() { - VirtualMachine virtualMachine1 = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .create(); + VirtualMachine virtualMachine1 = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .create(); String osDiskVhd = virtualMachine1.osUnmanagedDiskVhdUri(); Assertions.assertNotNull(osDiskVhd); computeManager.virtualMachines().deleteById(virtualMachine1.id()); - VirtualMachine virtualMachine2 = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSUnmanagedDisk(osDiskVhd, OperatingSystemTypes.LINUX) - .withBootDiagnostics() // A new storage account should be created and used - .create(); + VirtualMachine virtualMachine2 = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSUnmanagedDisk(osDiskVhd, OperatingSystemTypes.LINUX) + .withBootDiagnostics() // A new storage account should be created and used + .create(); Assertions.assertNotNull(virtualMachine2); Assertions.assertTrue(virtualMachine2.isBootDiagnosticsEnabled()); Assertions.assertNotNull(virtualMachine2.bootDiagnosticsStorageUri()); Assertions.assertNotNull(virtualMachine2.osUnmanagedDiskVhdUri()); - Assertions - .assertFalse( - virtualMachine2 - .osUnmanagedDiskVhdUri() - .toLowerCase() - .startsWith(virtualMachine2.bootDiagnosticsStorageUri().toLowerCase())); + Assertions.assertFalse(virtualMachine2.osUnmanagedDiskVhdUri() + .toLowerCase() + .startsWith(virtualMachine2.bootDiagnosticsStorageUri().toLowerCase())); } @Test public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMCreation() { final String storageName = generateRandomResourceName("st", 14); - Creatable creatableStorageAccount = - storageManager.storageAccounts().define(storageName).withRegion(region).withNewResourceGroup(rgName); + Creatable creatableStorageAccount + = storageManager.storageAccounts().define(storageName).withRegion(region).withNewResourceGroup(rgName); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withBootDiagnostics( - creatableStorageAccount) // This storage account should be used for BDiagnostics not OS disk storage - // account - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withBootDiagnostics(creatableStorageAccount) // This storage account should be used for BDiagnostics not OS disk storage + // account + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); Assertions.assertNotNull(virtualMachine.bootDiagnosticsStorageUri()); Assertions.assertTrue(virtualMachine.bootDiagnosticsStorageUri().contains(storageName)); // There should be a different storage account created for the OS Disk - Assertions - .assertFalse( - virtualMachine - .osUnmanagedDiskVhdUri() - .toLowerCase() - .startsWith(virtualMachine.bootDiagnosticsStorageUri().toLowerCase())); + Assertions.assertFalse(virtualMachine.osUnmanagedDiskVhdUri() + .toLowerCase() + .startsWith(virtualMachine.bootDiagnosticsStorageUri().toLowerCase())); } @Test public void canEnableBootDiagnosticsOnManagedStorageAccount() { - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnosticsOnManagedStorageAccount() - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnosticsOnManagedStorageAccount() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); Assertions.assertNull(virtualMachine.bootDiagnosticsStorageUri()); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); - virtualMachine.update() - .withNewDataDisk(10) - .apply(); + virtualMachine.update().withNewDataDisk(10).apply(); Assertions.assertTrue(virtualMachine.isBootDiagnosticsEnabled()); Assertions.assertNull(virtualMachine.bootDiagnosticsStorageUri()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineCustomImageOperationsTest.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineCustomImageOperationsTest.java index b90c6ad9ffa8e..91e803acb8051 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineCustomImageOperationsTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineCustomImageOperationsTest.java @@ -47,21 +47,18 @@ protected void cleanUpResources() { public void canCreateImageFromNativeVhd() throws IOException { final String vhdBasedImageName = generateRandomResourceName("img", 20); - VirtualMachine linuxVM = - prepareGeneralizedVmWith2EmptyDataDisks( - rgName, generateRandomResourceName("muldvm", 15), region, computeManager); + VirtualMachine linuxVM = prepareGeneralizedVmWith2EmptyDataDisks(rgName, + generateRandomResourceName("muldvm", 15), region, computeManager); // - VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDisk = - computeManager - .virtualMachineCustomImages() + VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDisk + = computeManager.virtualMachineCustomImages() .define(vhdBasedImageName) .withRegion(region) .withNewResourceGroup(rgName) .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED) .withOSDiskCaching(linuxVM.osDiskCachingType()); for (VirtualMachineUnmanagedDataDisk disk : linuxVM.unmanagedDataDisks().values()) { - creatableDisk - .defineDataDiskImage() + creatableDisk.defineDataDiskImage() .withLun(disk.lun()) .fromVhd(disk.vhdUri()) .withDiskCaching(disk.cachingType()) @@ -94,39 +91,36 @@ public void canCreateImageFromNativeVhd() throws IOException { Assertions.assertEquals(matchedDisk.vhdUri(), diskImage.blobUri()); Assertions.assertEquals((long) matchedDisk.size() + 10, (long) diskImage.diskSizeGB()); } - VirtualMachineCustomImage image = - computeManager.virtualMachineCustomImages().getByResourceGroup(rgName, vhdBasedImageName); + VirtualMachineCustomImage image + = computeManager.virtualMachineCustomImages().getByResourceGroup(rgName, vhdBasedImageName); Assertions.assertNotNull(image); - PagedIterable images = - computeManager.virtualMachineCustomImages().listByResourceGroup(rgName); + PagedIterable images + = computeManager.virtualMachineCustomImages().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.getSize(images) > 0); // Create virtual machine from custom image // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(generateRandomResourceName("cusvm", 15)) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(image.id()) - .withRootUsername("javauser") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(generateRandomResourceName("cusvm", 15)) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(image.id()) + .withRootUsername("javauser") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Map dataDisks = virtualMachine.dataDisks(); Assertions.assertNotNull(dataDisks); Assertions.assertEquals(dataDisks.size(), image.dataDiskImages().size()); // Create a hyperv Gen2 image - VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDiskGen2 = - computeManager - .virtualMachineCustomImages() + VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings creatableDiskGen2 + = computeManager.virtualMachineCustomImages() .define(vhdBasedImageName + "Gen2") .withRegion(region) .withNewResourceGroup(rgName) @@ -134,8 +128,7 @@ public void canCreateImageFromNativeVhd() throws IOException { .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED) .withOSDiskCaching(linuxVM.osDiskCachingType()); for (VirtualMachineUnmanagedDataDisk disk : linuxVM.unmanagedDataDisks().values()) { - creatableDisk - .defineDataDiskImage() + creatableDisk.defineDataDiskImage() .withLun(disk.lun()) .fromVhd(disk.vhdUri()) .withDiskCaching(disk.cachingType()) @@ -167,15 +160,13 @@ public void canCreateImageByCapturingVM() { VirtualMachine vm = prepareGeneralizedVmWith2EmptyDataDisks(rgName, vmName, region, computeManager); // - VirtualMachineCustomImage customImage = - computeManager - .virtualMachineCustomImages() - .define(imageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withHyperVGeneration(HyperVGenerationTypes.V1) - .fromVirtualMachine(vm.id()) - .create(); + VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages() + .define(imageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withHyperVGeneration(HyperVGenerationTypes.V1) + .fromVirtualMachine(vm.id()) + .create(); Assertions.assertTrue(customImage.name().equalsIgnoreCase(imageName)); Assertions.assertNotNull(customImage.osDiskImage()); @@ -208,28 +199,26 @@ public void canCreateImageFromManagedDisk() { final String storageAccountName = generateRandomResourceName("stg", 17); final String uname = "juser"; - VirtualMachine nativeVm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ - .defineUnmanagedDataDisk("disk1") - .withNewVhd(100) - .withCaching(CachingTypes.READ_ONLY) - .attach() - .withNewUnmanagedDataDisk(100) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(storageAccountName) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine nativeVm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ + .defineUnmanagedDataDisk("disk1") + .withNewVhd(100) + .withCaching(CachingTypes.READ_ONLY) + .attach() + .withNewUnmanagedDataDisk(100) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(storageAccountName) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Assertions.assertFalse(nativeVm.isManagedDiskEnabled()); String osVhdUri = nativeVm.osUnmanagedDiskVhdUri(); @@ -242,72 +231,63 @@ public void canCreateImageFromManagedDisk() { final String osDiskName = generateRandomResourceName("dsk", 15); // Create managed disk with Os from vm's Os disk // - Disk managedOsDisk = - computeManager - .disks() - .define(osDiskName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinuxFromVhd(osVhdUri) - .withStorageAccountName(storageAccountName) - .create(); + Disk managedOsDisk = computeManager.disks() + .define(osDiskName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinuxFromVhd(osVhdUri) + .withStorageAccountName(storageAccountName) + .create(); // Create managed disk with Data from vm's lun0 data disk // - StorageAccount storageAccount = - storageManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); + StorageAccount storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); final String dataDiskName1 = generateRandomResourceName("dsk", 15); VirtualMachineUnmanagedDataDisk vmNativeDataDisk1 = dataDisks.get(0); - Disk managedDataDisk1 = - computeManager - .disks() - .define(dataDiskName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withData() - .fromVhd(vmNativeDataDisk1.vhdUri()) - .withStorageAccount(storageAccount) - .create(); + Disk managedDataDisk1 = computeManager.disks() + .define(dataDiskName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withData() + .fromVhd(vmNativeDataDisk1.vhdUri()) + .withStorageAccount(storageAccount) + .create(); // Create managed disk with Data from vm's lun1 data disk // final String dataDiskName2 = generateRandomResourceName("dsk", 15); VirtualMachineUnmanagedDataDisk vmNativeDataDisk2 = dataDisks.get(1); - Disk managedDataDisk2 = - computeManager - .disks() - .define(dataDiskName2) - .withRegion(region) - .withNewResourceGroup(rgName) - .withData() - .fromVhd(vmNativeDataDisk2.vhdUri()) - .withStorageAccountId(storageAccount.id()) - .create(); + Disk managedDataDisk2 = computeManager.disks() + .define(dataDiskName2) + .withRegion(region) + .withNewResourceGroup(rgName) + .withData() + .fromVhd(vmNativeDataDisk2.vhdUri()) + .withStorageAccountId(storageAccount.id()) + .create(); // Create an image from the above managed disks // Note that this is not a direct user scenario, but including this as per CRP team request // final String imageName = generateRandomResourceName("img", 15); - VirtualMachineCustomImage customImage = - computeManager - .virtualMachineCustomImages() - .define(imageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinuxFromDisk(managedOsDisk, OperatingSystemStateTypes.GENERALIZED) - .defineDataDiskImage() - .withLun(vmNativeDataDisk1.lun()) - .fromManagedDisk(managedDataDisk1) - .withDiskCaching(vmNativeDataDisk1.cachingType()) - .withDiskSizeInGB(vmNativeDataDisk1.size() + 10) - .attach() - .defineDataDiskImage() - .withLun(vmNativeDataDisk2.lun()) - .fromManagedDisk(managedDataDisk2) - .withDiskSizeInGB(vmNativeDataDisk2.size() + 10) - .attach() - .create(); + VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages() + .define(imageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinuxFromDisk(managedOsDisk, OperatingSystemStateTypes.GENERALIZED) + .defineDataDiskImage() + .withLun(vmNativeDataDisk1.lun()) + .fromManagedDisk(managedDataDisk1) + .withDiskCaching(vmNativeDataDisk1.cachingType()) + .withDiskSizeInGB(vmNativeDataDisk1.size() + 10) + .attach() + .defineDataDiskImage() + .withLun(vmNativeDataDisk2.lun()) + .fromManagedDisk(managedDataDisk2) + .withDiskSizeInGB(vmNativeDataDisk2.size() + 10) + .attach() + .create(); Assertions.assertNotNull(customImage); Assertions.assertTrue(customImage.name().equalsIgnoreCase(imageName)); @@ -320,9 +300,8 @@ public void canCreateImageFromManagedDisk() { Assertions.assertNull(customImage.sourceVirtualMachineId()); Assertions.assertTrue(customImage.dataDiskImages().containsKey(vmNativeDataDisk1.lun())); - Assertions - .assertEquals( - customImage.dataDiskImages().get(vmNativeDataDisk1.lun()).caching(), vmNativeDataDisk1.cachingType()); + Assertions.assertEquals(customImage.dataDiskImages().get(vmNativeDataDisk1.lun()).caching(), + vmNativeDataDisk1.cachingType()); Assertions.assertTrue(customImage.dataDiskImages().containsKey(vmNativeDataDisk2.lun())); Assertions.assertEquals(customImage.dataDiskImages().get(vmNativeDataDisk2.lun()).caching(), CachingTypes.NONE); @@ -332,10 +311,8 @@ public void canCreateImageFromManagedDisk() { Assertions.assertEquals((long) diskImage.diskSizeGB(), vmDisk.size() + 10); Assertions.assertNull(diskImage.blobUri()); Assertions.assertNotNull(diskImage.managedDisk()); - Assertions - .assertTrue( - diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk1.id()) - || diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk2.id())); + Assertions.assertTrue(diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk1.id()) + || diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk2.id())); } computeManager.disks().deleteById(managedOsDisk.id()); computeManager.disks().deleteById(managedDataDisk1.id()); @@ -343,37 +320,35 @@ public void canCreateImageFromManagedDisk() { computeManager.virtualMachineCustomImages().deleteById(customImage.id()); } - private VirtualMachine prepareGeneralizedVmWith2EmptyDataDisks( - String rgName, String vmName, Region region, ComputeManager computeManager) { + private VirtualMachine prepareGeneralizedVmWith2EmptyDataDisks(String rgName, String vmName, Region region, + ComputeManager computeManager) { final String uname = "javauser"; final KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS; final String publicIpDnsLabel = generateRandomResourceName("pip", 20); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(30) - .withCaching(CachingTypes.READ_WRITE) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(60) - .withCaching(CachingTypes.READ_ONLY) - .attach() - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(generateRandomResourceName("stg", 17)) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(30) + .withCaching(CachingTypes.READ_WRITE) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(60) + .withCaching(CachingTypes.READ_ONLY) + .attach() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(generateRandomResourceName("stg", 17)) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); // ResourceManagerUtils.sleep(Duration.ofMinutes(1)); deprovisionAgentInLinuxVM(virtualMachine); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEMSILMSIOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEMSILMSIOperationsTests.java index cd039814df195..523f3696e9da1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEMSILMSIOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEMSILMSIOperationsTests.java @@ -51,51 +51,48 @@ public void canCreateUpdateVirtualMachineWithEMSI() { // Create a virtual network residing in the above RG // - final Network network = - networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); + final Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .create(); // Create an "User Assigned (External) MSI" residing in the above RG and assign reader access to the virtual // network // - final Identity createdIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withNewResourceGroup(creatableRG) - .withAccessTo(network, BuiltInRole.READER) - .create(); + final Identity createdIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .withAccessTo(network, BuiltInRole.READER) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName2) - .withRegion(region) - .withNewResourceGroup(creatableRG) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName2) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create a virtual machine and associate it with existing and yet-t-be-created identities // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .withSize(VirtualMachineSizeTypes.STANDARD_A0) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .withSize(VirtualMachineSizeTypes.STANDARD_A0) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); @@ -115,9 +112,8 @@ public void canCreateUpdateVirtualMachineWithEMSI() { for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); - Assertions - .assertTrue( - identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); + Assertions.assertTrue( + identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { @@ -128,8 +124,8 @@ public void canCreateUpdateVirtualMachineWithEMSI() { // Ensure expected role assignment exists for explicitly created EMSI // - PagedIterable roleAssignmentsForNetwork = - this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); + PagedIterable roleAssignmentsForNetwork + = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null @@ -138,26 +134,22 @@ public void canCreateUpdateVirtualMachineWithEMSI() { break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); + Assertions.assertTrue(found, + "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); - RoleAssignment assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) - .block(); + RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, + createdIdentity.principalId()).block(); - Assertions - .assertNotNull( - assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the virtual network for identity"); // Ensure expected role assignment exists for explicitly created EMSI // ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); - PagedIterable roleAssignmentsForResourceGroup = - this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); + PagedIterable roleAssignmentsForResourceGroup + = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null @@ -166,26 +158,19 @@ public void canCreateUpdateVirtualMachineWithEMSI() { break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the resource group for identity" - + implicitlyCreatedIdentity.name()); + Assertions.assertTrue(found, "Expected role assignment not found for the resource group for identity" + + implicitlyCreatedIdentity.name()); - assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) - .block(); + assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(resourceGroup.id(), BuiltInRole.CONTRIBUTOR, + implicitlyCreatedIdentity.principalId()).block(); - Assertions - .assertNotNull( - assignment, "Expected role assignment with ROLE not found for the resource group for identity"); + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator itr = emsiIds.iterator(); // Remove both (all) identities - virtualMachine - .update() + virtualMachine.update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); @@ -207,8 +192,7 @@ public void canCreateUpdateVirtualMachineWithEMSI() { Identity identity2 = msiManager.identities().getById(itr.next()); // // Update VM by enabling System-MSI and add two identities - virtualMachine - .update() + virtualMachine.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) @@ -217,9 +201,8 @@ public void canCreateUpdateVirtualMachineWithEMSI() { Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue( + virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); // Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); @@ -228,9 +211,8 @@ public void canCreateUpdateVirtualMachineWithEMSI() { Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue( + virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); // Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); @@ -242,9 +224,8 @@ public void canCreateUpdateVirtualMachineWithEMSI() { Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue( + virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); // Remove identities one by one (second one) @@ -270,45 +251,39 @@ public void canCreateVirtualMachineWithLMSIAndEMSI() { // Create a virtual network // - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create a virtual machine and associate it with existing and yet-to-be-created identities // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .withSize(VirtualMachineSizeTypes.STANDARD_A0) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .withSize(VirtualMachineSizeTypes.STANDARD_A0) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); @@ -328,43 +303,33 @@ public void canCreateVirtualMachineWithLMSIAndEMSI() { // Ensure expected role assignment exists for LMSI // - PagedIterable roleAssignmentsForNetwork = - this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); + PagedIterable roleAssignmentsForNetwork + = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the virtual network for local identity" - + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); - - RoleAssignment assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - network.id(), - BuiltInRole.CONTRIBUTOR, - virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) - .block(); - - Assertions - .assertNotNull( - assignment, - "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); + Assertions.assertTrue(found, "Expected role assignment not found for the virtual network for local identity" + + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); + + RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.CONTRIBUTOR, + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()).block(); + + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); // Ensure expected role assignment exists for EMSI // ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); - PagedIterable roleAssignmentsForResourceGroup = - this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); + PagedIterable roleAssignmentsForResourceGroup + = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null @@ -373,19 +338,14 @@ public void canCreateVirtualMachineWithLMSIAndEMSI() { break; } } - Assertions - .assertTrue( - found, "Expected role assignment not found for the resource group for identity" + identity.name()); - - assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) - .block(); - - Assertions - .assertNotNull( - assignment, - "Expected role assignment with ROLE not found for the resource group for system assigned identity"); + Assertions.assertTrue(found, + "Expected role assignment not found for the resource group for identity" + identity.name()); + + assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, + identity.principalId()).block(); + + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the resource group for system assigned identity"); } @Test @@ -396,32 +356,28 @@ public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { // Create a virtual machine with no EMSI & LMSI // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.STANDARD_A0) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.STANDARD_A0) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withExistingResourceGroup(virtualMachine.resourceGroupName()) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(virtualMachine.resourceGroupName()) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Update virtual machine so that it depends on the EMSI // @@ -431,7 +387,8 @@ public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { // Set emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); - Optional emsiIdOptional = emsiIds.stream().filter(emsiId -> emsiId.endsWith("/" + identityName1)).findAny(); + Optional emsiIdOptional + = emsiIds.stream().filter(emsiId -> emsiId.endsWith("/" + identityName1)).findAny(); Assertions.assertTrue(emsiIdOptional.isPresent()); Identity identity = msiManager.identities().getById(emsiIdOptional.get()); @@ -439,32 +396,26 @@ public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); // Update VM without modify MSI - virtualMachine.update() - .withNewDataDisk(10) - .apply(); + virtualMachine.update().withNewDataDisk(10).apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); // Creates an EMSI // - Identity createdIdentity = - msiManager - .identities() - .define(identityName2) - .withRegion(region) - .withExistingResourceGroup(virtualMachine.resourceGroupName()) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .create(); + Identity createdIdentity = msiManager.identities() + .define(identityName2) + .withRegion(region) + .withExistingResourceGroup(virtualMachine.resourceGroupName()) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .create(); // Update the virtual machine by removing the an EMSI and adding existing EMSI // - virtualMachine = - virtualMachine - .update() - .withoutUserAssignedManagedServiceIdentity(identity.id()) - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .apply(); + virtualMachine = virtualMachine.update() + .withoutUserAssignedManagedServiceIdentity(identity.id()) + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .apply(); // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine // @@ -485,9 +436,8 @@ public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue( + virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); @@ -511,24 +461,17 @@ public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } - private Mono lookupRoleAssignmentUsingScopeAndRoleAsync( - final String scope, BuiltInRole role, final String principalId) { - return this - .msiManager - .authorizationManager() + private Mono lookupRoleAssignmentUsingScopeAndRoleAsync(final String scope, BuiltInRole role, + final String principalId) { + return this.msiManager.authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) - .flatMap( - roleDefinition -> - msiManager - .authorizationManager() - .roleAssignments() - .listByScopeAsync(scope) - .filter( - roleAssignment -> - roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) - && roleAssignment.principalId().equalsIgnoreCase(principalId)) - .singleOrEmpty()) + .flatMap(roleDefinition -> msiManager.authorizationManager() + .roleAssignments() + .listByScopeAsync(scope) + .filter(roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) + && roleAssignment.principalId().equalsIgnoreCase(principalId)) + .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEncryptionOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEncryptionOperationsTests.java index d80a9bba7538a..dae404c0fbce8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEncryptionOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineEncryptionOperationsTests.java @@ -47,21 +47,19 @@ public void canEncryptVirtualMachineLegacy() { final String vmName1 = "myvm1"; final String uname = "juser"; - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); DiskVolumeEncryptionMonitor monitor1 = virtualMachine.diskEncryption().getMonitor(); Assertions.assertNotNull(monitor1); @@ -69,8 +67,8 @@ public void canEncryptVirtualMachineLegacy() { Assertions.assertNotNull(monitor1.dataDiskStatus()); Assertions.assertEquals(EncryptionStatus.NOT_ENCRYPTED, monitor1.osDiskStatus()); Assertions.assertEquals(EncryptionStatus.NOT_ENCRYPTED, monitor1.dataDiskStatus()); - DiskVolumeEncryptionMonitor monitor2 = - virtualMachine.diskEncryption().enable(keyVaultId, aadClientId, aadSecret); + DiskVolumeEncryptionMonitor monitor2 + = virtualMachine.diskEncryption().enable(keyVaultId, aadClientId, aadSecret); Assertions.assertNotNull(monitor2); Assertions.assertNotNull(monitor2.osDiskStatus()); Assertions.assertNotNull(monitor2.dataDiskStatus()); @@ -81,7 +79,6 @@ public void canEncryptVirtualMachineLegacy() { Assertions.assertNotEquals(EncryptionStatus.NOT_ENCRYPTED, monitor2.osDiskStatus()); } - @Test public void canEncryptVirtualMachine() { // https://docs.microsoft.com/azure/virtual-machines/linux/disk-encryption-overview @@ -103,7 +100,8 @@ public void canEncryptVirtualMachine() { .create(); final String vaultName = generateRandomResourceName("vault", 20); - Vault vault = keyVaultManager.vaults().define(vaultName) + Vault vault = keyVaultManager.vaults() + .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .withEmptyAccessPolicy() @@ -118,9 +116,8 @@ public void canEncryptVirtualMachine() { Assertions.assertNotNull(monitor1.dataDiskStatus()); Assertions.assertEquals(EncryptionStatus.NOT_ENCRYPTED, monitor1.osDiskStatus()); Assertions.assertEquals(EncryptionStatus.NOT_ENCRYPTED, monitor1.dataDiskStatus()); - DiskVolumeEncryptionMonitor monitor2 = virtualMachine - .diskEncryption() - .enable(new LinuxVMDiskEncryptionConfiguration(vaultId, vaultUri)); + DiskVolumeEncryptionMonitor monitor2 + = virtualMachine.diskEncryption().enable(new LinuxVMDiskEncryptionConfiguration(vaultId, vaultUri)); Assertions.assertNotNull(monitor2); Assertions.assertNotNull(monitor2.osDiskStatus()); Assertions.assertNotNull(monitor2.dataDiskStatus()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionImageOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionImageOperationsTests.java index 608b25ce554b0..924fe2a25b23a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionImageOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionImageOperationsTests.java @@ -24,8 +24,8 @@ public class VirtualMachineExtensionImageOperationsTests extends ComputeManageme public void canListExtensionImages() throws Exception { final int maxListing = 20; int count = 0; - PagedIterable extensionImages = - computeManager.virtualMachineExtensionImages().listByRegion(Region.US_EAST); + PagedIterable extensionImages + = computeManager.virtualMachineExtensionImages().listByRegion(Region.US_EAST); // Lazy listing for (VirtualMachineExtensionImage extensionImage : extensionImages) { Assertions.assertNotNull(extensionImage); @@ -39,16 +39,16 @@ public void canListExtensionImages() throws Exception { @Test public void canGetExtensionTypeVersionAndImage() throws Exception { - PagedIterable extensionImages = - computeManager.virtualMachineExtensionImages().listByRegion(Region.US_EAST); + PagedIterable extensionImages + = computeManager.virtualMachineExtensionImages().listByRegion(Region.US_EAST); final String dockerExtensionPublisherName = "Microsoft.Azure.Extensions"; final String dockerExtensionImageTypeName = "DockerExtension"; // Lookup Azure docker extension publisher // - PagedIterable publishers = - computeManager.virtualMachineExtensionImages().publishers().listByRegion(Region.US_EAST); + PagedIterable publishers + = computeManager.virtualMachineExtensionImages().publishers().listByRegion(Region.US_EAST); VirtualMachinePublisher azureDockerExtensionPublisher = null; for (VirtualMachinePublisher publisher : publishers) { @@ -76,14 +76,11 @@ public void canGetExtensionTypeVersionAndImage() throws Exception { Assertions.assertNotNull(dockerExtensionImageType.id()); Assertions.assertTrue(dockerExtensionImageType.name().equalsIgnoreCase(dockerExtensionImageTypeName)); Assertions.assertTrue(dockerExtensionImageType.regionName().equalsIgnoreCase(Region.US_EAST.toString())); - Assertions - .assertTrue( - dockerExtensionImageType - .id() - .toLowerCase() - .endsWith( - "/Providers/Microsoft.Compute/Locations/eastus/Publishers/Microsoft.Azure.Extensions/ArtifactTypes/VMExtension/Types/DockerExtension" - .toLowerCase())); + Assertions.assertTrue(dockerExtensionImageType.id() + .toLowerCase() + .endsWith( + "/Providers/Microsoft.Compute/Locations/eastus/Publishers/Microsoft.Azure.Extensions/ArtifactTypes/VMExtension/Types/DockerExtension" + .toLowerCase())); Assertions.assertNotNull(dockerExtensionImageType.publisher()); Assertions .assertTrue(dockerExtensionImageType.publisher().name().equalsIgnoreCase(dockerExtensionPublisherName)); @@ -101,15 +98,11 @@ public void canGetExtensionTypeVersionAndImage() throws Exception { Assertions.assertNotNull(extensionImageFirstVersion); String versionName = extensionImageFirstVersion.name(); - Assertions - .assertTrue( - extensionImageFirstVersion - .id() - .toLowerCase() - .endsWith( - ("/Providers/Microsoft.Compute/Locations/eastus/Publishers/Microsoft.Azure.Extensions/ArtifactTypes/VMExtension/Types/DockerExtension/Versions/" - + versionName) - .toLowerCase())); + Assertions.assertTrue(extensionImageFirstVersion.id() + .toLowerCase() + .endsWith( + ("/Providers/Microsoft.Compute/Locations/eastus/Publishers/Microsoft.Azure.Extensions/ArtifactTypes/VMExtension/Types/DockerExtension/Versions/" + + versionName).toLowerCase())); Assertions.assertNotNull(extensionImageFirstVersion.type()); // Fetch the Azure docker extension image @@ -120,9 +113,7 @@ public void canGetExtensionTypeVersionAndImage() throws Exception { Assertions.assertTrue(dockerExtensionImage.publisherName().equalsIgnoreCase(dockerExtensionPublisherName)); Assertions.assertTrue(dockerExtensionImage.typeName().equalsIgnoreCase(dockerExtensionImageTypeName)); Assertions.assertTrue(dockerExtensionImage.versionName().equalsIgnoreCase(versionName)); - Assertions - .assertTrue( - dockerExtensionImage.osType() == OperatingSystemTypes.LINUX - || dockerExtensionImage.osType() == OperatingSystemTypes.WINDOWS); + Assertions.assertTrue(dockerExtensionImage.osType() == OperatingSystemTypes.LINUX + || dockerExtensionImage.osType() == OperatingSystemTypes.WINDOWS); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionOperationsTests.java index 512a583cd47f0..f43232a8b1865 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineExtensionOperationsTests.java @@ -49,45 +49,37 @@ public void canEnableDiagnosticsExtension() throws Exception { final String vmName = "javavm1"; // Creates a storage account - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageAccountName) - .withRegion(region) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageAccountName) + .withRegion(region) + .withNewResourceGroup(rgName) + .create(); // Create a Linux VM // - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withExistingStorageAccount(storageAccount) - .create(); - - final InputStream embeddedJsonConfig = - VirtualMachineExtensionOperationsTests.class.getResourceAsStream("/linux_diagnostics_public_config.json"); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withExistingStorageAccount(storageAccount) + .create(); + + final InputStream embeddedJsonConfig + = VirtualMachineExtensionOperationsTests.class.getResourceAsStream("/linux_diagnostics_public_config.json"); String jsonConfig = SerializerFactory.createDefaultManagementSerializerAdapter() - .serialize( - SerializerFactory.createDefaultManagementSerializerAdapter() - .deserialize(embeddedJsonConfig, Object.class, SerializerEncoding.JSON), - SerializerEncoding.JSON - ); + .serialize(SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize(embeddedJsonConfig, Object.class, SerializerEncoding.JSON), SerializerEncoding.JSON); jsonConfig = jsonConfig.replace("%VirtualMachineResourceId%", vm.id()); // Update Linux VM to enable Diagnostics - vm - .update() + vm.update() .defineNewExtension("LinuxDiagnostic") .withPublisher("Microsoft.OSTCExtensions") .withType("LinuxDiagnostic") @@ -124,26 +116,23 @@ public void canResetPasswordUsingVMAccessExtension() throws Exception { // Create a Linux VM // - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); // Using VMAccess Linux extension to reset the password for the existing user 'Foo12' // https://github.com/Azure/azure-linux-extensions/blob/master/VMAccess/README.md // - vm - .update() + vm.update() .defineNewExtension("VMAccessForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("VMAccessForLinux") @@ -159,8 +148,7 @@ public void canResetPasswordUsingVMAccessExtension() throws Exception { // Update the VMAccess Linux extension to reset password again for the user 'Foo12' // - vm - .update() + vm.update() .updateExtension("VMAccessForLinux") .withProtectedSetting("username", "Foo12") .withProtectedSetting("password", "muy!234OR") @@ -177,27 +165,25 @@ public void canInstallUninstallCustomExtension() throws Exception { // Create Linux VM with a custom extension to install MySQL // - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_A1_v2")) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("commandToExecute", installCommand) - .attach() - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_A1_v2")) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("commandToExecute", installCommand) + .attach() + .create(); Assertions.assertTrue(vm.listExtensions().size() > 0); Assertions.assertTrue(vm.listExtensions().containsKey("CustomScriptForLinux")); @@ -222,28 +208,26 @@ public void canHandleExtensionReference() throws Exception { // Create a Linux VM // - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .defineNewExtension("VMAccessForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("VMAccessForLinux") - .withVersion("1.4") - .withProtectedSetting("username", "Foo12") - .withProtectedSetting("password", "B12a6@12xyz!") - .withProtectedSetting("reset_ssh", "true") - .attach() - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .defineNewExtension("VMAccessForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("VMAccessForLinux") + .withVersion("1.4") + .withProtectedSetting("username", "Foo12") + .withProtectedSetting("password", "B12a6@12xyz!") + .withProtectedSetting("reset_ssh", "true") + .attach() + .create(); Assertions.assertTrue(vm.listExtensions().size() > 0); @@ -260,15 +244,13 @@ public void canHandleExtensionReference() throws Exception { Assertions.assertNotNull(vmWithExtensionReference); // Update the extension - VirtualMachine vmWithExtensionUpdated = - vmWithExtensionReference - .update() - .updateExtension("VMAccessForLinux") - .withProtectedSetting("username", "Foo12") - .withProtectedSetting("password", "muy!234OR") - .withProtectedSetting("reset_ssh", "true") - .parent() - .apply(); + VirtualMachine vmWithExtensionUpdated = vmWithExtensionReference.update() + .updateExtension("VMAccessForLinux") + .withProtectedSetting("username", "Foo12") + .withProtectedSetting("password", "muy!234OR") + .withProtectedSetting("reset_ssh", "true") + .parent() + .apply(); // Again getting VM with extension reference virtualMachines = computeManager.virtualMachines().listByResourceGroup(rgName); @@ -297,37 +279,37 @@ public void canHandleExtensionReference() throws Exception { public void canGetInstanceViewInDeallocatedState() { // Create a Linux VM String vmName = generateRandomResourceName("javavm", 15); - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .defineNewExtension("VMAccessForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("VMAccessForLinux") - .withVersion("1.4") - .withProtectedSetting("username", "Foo12") - .withProtectedSetting("password", "B12a6@12xyz!") - .withProtectedSetting("reset_ssh", "true") - .attach() - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .defineNewExtension("VMAccessForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("VMAccessForLinux") + .withVersion("1.4") + .withProtectedSetting("username", "Foo12") + .withProtectedSetting("password", "B12a6@12xyz!") + .withProtectedSetting("reset_ssh", "true") + .attach() + .create(); Assertions.assertTrue(vm.listExtensions().size() > 0); - Assertions.assertTrue(vm.listExtensions().values().stream().noneMatch(extension -> extension.getInstanceView() == null)); + Assertions.assertTrue( + vm.listExtensions().values().stream().noneMatch(extension -> extension.getInstanceView() == null)); vm.deallocate(); // In deallocated state, we can get VM's extensions but not their instance views. Assertions.assertTrue(vm.listExtensions().size() > 0); - Assertions.assertTrue(vm.listExtensions().values().stream().allMatch(extension -> extension.getInstanceView() == null)); + Assertions.assertTrue( + vm.listExtensions().values().stream().allMatch(extension -> extension.getInstanceView() == null)); } @Test @@ -336,21 +318,17 @@ public void canIgnoreInvalidJson() throws IOException { String vaultName = generateRandomResourceName("javavt", 15); final String secretName = generateRandomResourceName("srt", 10); - Vault vault = - this - .keyVaultManager - .vaults() - .define(vaultName) - .withRegion(region) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowSecretAllPermissions() - .attach() - .withDeploymentEnabled() - .create(); - final InputStream embeddedJsonConfig = - this.getClass().getResourceAsStream("/myTest.txt"); + Vault vault = this.keyVaultManager.vaults() + .define(vaultName) + .withRegion(region) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowSecretAllPermissions() + .attach() + .withDeploymentEnabled() + .create(); + final InputStream embeddedJsonConfig = this.getClass().getResourceAsStream("/myTest.txt"); String secretValue = IOUtils.toString(embeddedJsonConfig, StandardCharsets.UTF_8); Secret secret = vault.secrets().define(secretName).withValue(secretValue).create(); @@ -358,26 +336,24 @@ public void canIgnoreInvalidJson() throws IOException { extensionSecretSettings.put("pollingIntervalInS", "3600"); extensionSecretSettings.put("observedCertificates", Collections.singletonList(secret.id())); - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .defineNewExtension("KeyVaultForLinux") - .withPublisher("Microsoft.Azure.KeyVault") - .withType("KeyVaultForLinux") - .withVersion("1.0") - .withPublicSetting("secretsManagementSettings", extensionSecretSettings) - .attach() - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .defineNewExtension("KeyVaultForLinux") + .withPublisher("Microsoft.Azure.KeyVault") + .withType("KeyVaultForLinux") + .withVersion("1.0") + .withPublicSetting("secretsManagementSettings", extensionSecretSettings) + .attach() + .create(); VirtualMachineExtension extension = vm.listExtensions().get("KeyVaultForLinux"); Assertions.assertNotNull(extension); Assertions.assertNotNull(extension.publicSettingsAsJsonString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java index c6cead94f558f..1eac89826db21 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java @@ -25,8 +25,8 @@ public void canListVirtualMachineImages() throws Exception { Assertions.assertTrue(TestUtilities.getSize(images) > 0); */ - PagedIterable publishers = - computeManager.virtualMachineImages().publishers().listByRegion(Region.US_EAST); + PagedIterable publishers + = computeManager.virtualMachineImages().publishers().listByRegion(Region.US_EAST); VirtualMachinePublisher canonicalPublisher = null; for (VirtualMachinePublisher publisher : publishers) { @@ -59,32 +59,18 @@ public void canListVirtualMachineImages() throws Exception { Assertions.assertNotNull(diskImage.lun()); } - VirtualMachineImage vmImage = - computeManager - .virtualMachineImages() - .getImage( - Region.US_EAST, - firstVMImage.publisherName(), - firstVMImage.offer(), - firstVMImage.sku(), - firstVMImage.version()); + VirtualMachineImage vmImage = computeManager.virtualMachineImages() + .getImage(Region.US_EAST, firstVMImage.publisherName(), firstVMImage.offer(), firstVMImage.sku(), + firstVMImage.version()); Assertions.assertNotNull(vmImage); - vmImage = - computeManager - .virtualMachineImages() - .getImage( - "eastus", - firstVMImage.publisherName(), - firstVMImage.offer(), - firstVMImage.sku(), - firstVMImage.version()); + vmImage = computeManager.virtualMachineImages() + .getImage("eastus", firstVMImage.publisherName(), firstVMImage.offer(), firstVMImage.sku(), + firstVMImage.version()); Assertions.assertNotNull(vmImage); - vmImage = - computeManager - .virtualMachineImages() - .getImage("eastus", firstVMImage.publisherName(), firstVMImage.offer(), firstVMImage.sku(), "latest"); + vmImage = computeManager.virtualMachineImages() + .getImage("eastus", firstVMImage.publisherName(), firstVMImage.offer(), firstVMImage.sku(), "latest"); Assertions.assertNotNull(vmImage); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java index 690d432a096dd..1b8cf9ce51813 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java @@ -54,21 +54,19 @@ public void canCreateVirtualMachineFromPIRImageWithManagedOsDisk() { final String uname = "juser"; final String password = password(); - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); // Ensure default to managed disk // Assertions.assertTrue(virtualMachine.isManagedDiskEnabled()); @@ -109,55 +107,47 @@ public void canCreateUpdateVirtualMachineWithEmptyManagedDataDisks() { ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Creatable creatableEmptyDisk1 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk2 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk3 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName3) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - // Start: Add 5 empty managed disks - .withNewDataDisk(100) // CreateOption: EMPTY - .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) // CreateOption: EMPTY - .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH - // End : Add 5 empty managed disks - .withSize(VirtualMachineSizeTypes.fromString("Standard_D4a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + Creatable creatableEmptyDisk1 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk2 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk3 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName3) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + // Start: Add 5 empty managed disks + .withNewDataDisk(100) // CreateOption: EMPTY + .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) // CreateOption: EMPTY + .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH + // End : Add 5 empty managed disks + .withSize(VirtualMachineSizeTypes.fromString("Standard_D4a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Assertions.assertTrue(virtualMachine.isManagedDiskEnabled()); // There should not be any un-managed data disks @@ -269,55 +259,47 @@ public void canCreateVirtualMachineFromCustomImageWithManagedDisks() { ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Creatable creatableEmptyDisk1 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk2 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk3 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName3) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - VirtualMachine virtualMachine1 = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - // Start: Add bunch of empty managed disks - .withNewDataDisk(100) // CreateOption: EMPTY - .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) // CreateOption: EMPTY - .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH - // End : Add bunch of empty managed disks - .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + Creatable creatableEmptyDisk1 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk2 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk3 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName3) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + VirtualMachine virtualMachine1 = computeManager.virtualMachines() + .define(vmName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + // Start: Add bunch of empty managed disks + .withNewDataDisk(100) // CreateOption: EMPTY + .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) // CreateOption: EMPTY + .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH + // End : Add bunch of empty managed disks + .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); LOGGER.log(LogLevel.VERBOSE, () -> "Waiting for some time before de-provision"); sleep(60 * 1000); // Wait for some time to ensure vm is publicly accessible deprovisionAgentInLinuxVM(virtualMachine1); @@ -326,14 +308,12 @@ public void canCreateVirtualMachineFromCustomImageWithManagedDisks() { virtualMachine1.generalize(); final String customImageName = generateRandomResourceName("img-", 10); - VirtualMachineCustomImage customImage = - computeManager - .virtualMachineCustomImages() - .define(customImageName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .fromVirtualMachine(virtualMachine1) - .create(); + VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages() + .define(customImageName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .fromVirtualMachine(virtualMachine1) + .create(); Assertions.assertNotNull(customImage); Assertions.assertNotNull(customImage.sourceVirtualMachineId()); Assertions @@ -353,22 +333,20 @@ public void canCreateVirtualMachineFromCustomImageWithManagedDisks() { // image data disk images. // final String vmName2 = "myvm2"; - VirtualMachine virtualMachine2 = - computeManager - .virtualMachines() - .define(vmName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(customImage.id()) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - // No explicit data disks, let CRP create it from the image's data disk images - .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine2 = computeManager.virtualMachines() + .define(vmName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(customImage.id()) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + // No explicit data disks, let CRP create it from the image's data disk images + .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Map dataDisks = virtualMachine2.dataDisks(); Assertions.assertNotNull(dataDisks); @@ -387,40 +365,33 @@ public void canCreateVirtualMachineFromCustomImageWithManagedDisks() { // final String vmName3 = "myvm3"; - VirtualMachine.DefinitionStages.WithManagedCreate creatableVirtualMachine3 = - computeManager - .virtualMachines() - .define(vmName3) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(customImage.id()) - .withRootUsername(uname) - .withSsh(sshPublicKey()); + VirtualMachine.DefinitionStages.WithManagedCreate creatableVirtualMachine3 = computeManager.virtualMachines() + .define(vmName3) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(customImage.id()) + .withRootUsername(uname) + .withSsh(sshPublicKey()); for (ImageDataDisk dataDiskImage : customImage.dataDiskImages().values()) { // Explicitly override the properties of the data disks created from disk image // // CreateOption: FROM_IMAGE VirtualMachineDataDisk dataDisk = dataDisks.get(dataDiskImage.lun()); - creatableVirtualMachine3 - .withNewDataDiskFromImage( - dataDiskImage.lun(), - dataDisk.size() + 10, // increase size by 10 GB - CachingTypes.READ_ONLY); + creatableVirtualMachine3.withNewDataDiskFromImage(dataDiskImage.lun(), dataDisk.size() + 10, // increase size by 10 GB + CachingTypes.READ_ONLY); } - VirtualMachine virtualMachine3 = - creatableVirtualMachine3 - .withNewDataDisk(200) // CreateOption: EMPTY - .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine3 = creatableVirtualMachine3.withNewDataDisk(200) // CreateOption: EMPTY + .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); dataDisks = virtualMachine3.dataDisks(); Assertions.assertNotNull(dataDisks); - Assertions - .assertEquals(dataDisks.size(), customImage.dataDiskImages().size() + 1 /* count one extra empty disk */); + Assertions.assertEquals(dataDisks.size(), + customImage.dataDiskImages().size() + 1 /* count one extra empty disk */); for (ImageDataDisk imageDataDisk : customImage.dataDiskImages().values()) { Assertions.assertTrue(dataDisks.containsKey(imageDataDisk.lun())); VirtualMachineDataDisk dataDisk = dataDisks.get(imageDataDisk.lun()); @@ -444,60 +415,51 @@ public void canUpdateVirtualMachineByAddingAndRemovingManagedDisks() { ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Creatable creatableEmptyDisk1 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk2 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - Creatable creatableEmptyDisk3 = - computeManager - .disks() - .define(explicitlyCreatedEmptyDiskName3) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(150); - - VirtualMachine virtualMachine1 = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - // Start: Add bunch of empty managed disks - .withNewDataDisk(100) // CreateOption: EMPTY - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) // CreateOption: EMPTY - .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH - .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH - // End : Add bunch of empty managed disks - .withDataDiskDefaultCachingType(CachingTypes.READ_ONLY) - .withDataDiskDefaultStorageAccountType(StorageAccountTypes.STANDARD_LRS) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D4a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); - - virtualMachine1 - .update() + Creatable creatableEmptyDisk1 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk2 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + Creatable creatableEmptyDisk3 = computeManager.disks() + .define(explicitlyCreatedEmptyDiskName3) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(150); + + VirtualMachine virtualMachine1 = computeManager.virtualMachines() + .define(vmName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + // Start: Add bunch of empty managed disks + .withNewDataDisk(100) // CreateOption: EMPTY + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) // CreateOption: EMPTY + .withNewDataDisk(creatableEmptyDisk1) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE) // CreateOption: ATTACH + .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE) // CreateOption: ATTACH + // End : Add bunch of empty managed disks + .withDataDiskDefaultCachingType(CachingTypes.READ_ONLY) + .withDataDiskDefaultStorageAccountType(StorageAccountTypes.STANDARD_LRS) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D4a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); + + virtualMachine1.update() .withoutDataDisk(1) .withNewDataDisk(100, 6, CachingTypes.READ_WRITE) // CreateOption: EMPTY .apply(); @@ -518,23 +480,21 @@ public void canCreateVirtualMachineByAttachingManagedOsDisk() { // Creates a native virtual machine // - VirtualMachine nativeVm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(storageAccountName) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine nativeVm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() /* UN-MANAGED OS and DATA DISKS */ + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(storageAccountName) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Assertions.assertFalse(nativeVm.isManagedDiskEnabled()); String osVhdUri = nativeVm.osUnmanagedDiskVhdUri(); @@ -543,31 +503,27 @@ public void canCreateVirtualMachineByAttachingManagedOsDisk() { computeManager.virtualMachines().deleteById(nativeVm.id()); final String diskName = generateRandomResourceName("dsk-", 15); - Disk osDisk = - computeManager - .disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromVhd(osVhdUri) - .withStorageAccountName(storageAccountName) - .create(); + Disk osDisk = computeManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromVhd(osVhdUri) + .withStorageAccountName(storageAccountName) + .create(); // Creates a managed virtual machine // - VirtualMachine managedVm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSDisk(osDisk, OperatingSystemTypes.LINUX) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine managedVm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSDisk(osDisk, OperatingSystemTypes.LINUX) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Assertions.assertTrue(managedVm.isManagedDiskEnabled()); Assertions.assertTrue(managedVm.osDiskId().equalsIgnoreCase(osDisk.id().toLowerCase())); @@ -580,25 +536,23 @@ public void canCreateVirtualMachineWithManagedDiskInManagedAvailabilitySet() { final String password = password(); final String vmName = "myvm6"; - VirtualMachine managedVm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(linuxImage) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) - .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) - .withNewAvailabilitySet(availSetName) // Default to managed availability set - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine managedVm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(linuxImage) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_ONLY) + .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) + .withNewAvailabilitySet(availSetName) // Default to managed availability set + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); Assertions.assertNotNull(managedVm.availabilitySetId()); AvailabilitySet availabilitySet = computeManager.availabilitySets().getById(managedVm.availabilitySetId()); @@ -640,9 +594,7 @@ public void canCreateVirtualMachineWithHibernationEnabledUsingOsDisk() { vmWithHibernation.deallocate(); computeManager.virtualMachines().deleteById(vmWithHibernation.id()); - osDisk.update() - .withoutHibernationSupport() - .apply(); + osDisk.update().withoutHibernationSupport().apply(); Assertions.assertFalse(osDisk.isHibernationSupported()); } @@ -665,8 +617,7 @@ private String prepareLinuxDiskWithOSImage() { String osDiskId = vm.osDiskId(); vm.deallocate(); - computeManager.virtualMachines() - .deleteById(vm.id()); + computeManager.virtualMachines().deleteById(vm.id()); return osDiskId; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedServiceIdentityOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedServiceIdentityOperationsTests.java index dd57894cdee5f..e137bff0c6577 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedServiceIdentityOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedServiceIdentityOperationsTests.java @@ -43,22 +43,20 @@ public void canSetMSIOnNewOrExistingVMWithoutRoleAssignment() throws Exception { // and "test timing out after latest test proxy update" // Create a virtual machine with just MSI enabled without role and scope. // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); @@ -68,23 +66,22 @@ public void canSetMSIOnNewOrExistingVMWithoutRoleAssignment() throws Exception { // Ensure NO role assigned for resource group // - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); - PagedIterable rgRoleAssignments1 = - authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); + PagedIterable rgRoleAssignments1 + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(rgRoleAssignments1); boolean found = false; for (RoleAssignment roleAssignment : rgRoleAssignments1) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertFalse(found, "Resource group should not have a role assignment with virtual machine MSI principal"); + Assertions.assertFalse(found, + "Resource group should not have a role assignment with virtual machine MSI principal"); virtualMachine = virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); @@ -101,36 +98,33 @@ public void canSetMSIOnNewOrExistingVMWithoutRoleAssignment() throws Exception { found = false; for (RoleAssignment roleAssignment : rgRoleAssignments1) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertFalse(found, "Resource group should not have a role assignment with virtual machine MSI principal"); + Assertions.assertFalse(found, + "Resource group should not have a role assignment with virtual machine MSI principal"); } @Test public void canSetMSIOnNewVMWithRoleAssignedToCurrentResourceGroup() throws Exception { - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); @@ -149,14 +143,14 @@ public void canSetMSIOnNewVMWithRoleAssignedToCurrentResourceGroup() throws Exce // Ensure role assigned // - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); - PagedIterable rgRoleAssignments = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); + PagedIterable rgRoleAssignments + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); boolean found = false; for (RoleAssignment rgRoleAssignment : rgRoleAssignments) { if (rgRoleAssignment.principalId() != null - && rgRoleAssignment - .principalId() + && rgRoleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; @@ -170,35 +164,31 @@ public void canSetMSIOnNewVMWithRoleAssignedToCurrentResourceGroup() throws Exce public void canSetMSIOnNewVMWithMultipleRoleAssignments() throws Exception { String storageAccountName = generateRandomResourceName("javacsrg", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageAccountName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .create(); - - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().getByName(storageAccount.resourceGroupName()); - - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessTo(resourceGroup.id(), BuiltInRole.CONTRIBUTOR) - .withSystemAssignedIdentityBasedAccessTo(storageAccount.id(), BuiltInRole.CONTRIBUTOR) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .create(); + + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().getByName(storageAccount.resourceGroupName()); + + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessTo(resourceGroup.id(), BuiltInRole.CONTRIBUTOR) + .withSystemAssignedIdentityBasedAccessTo(storageAccount.id(), BuiltInRole.CONTRIBUTOR) + .create(); // Validate service created service principal // @@ -214,13 +204,13 @@ public void canSetMSIOnNewVMWithMultipleRoleAssignments() throws Exception { // Ensure role assigned for resource group // - PagedIterable rgRoleAssignments = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + PagedIterable rgRoleAssignments + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(rgRoleAssignments); boolean found = false; for (RoleAssignment roleAssignment : rgRoleAssignments) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; @@ -230,21 +220,20 @@ public void canSetMSIOnNewVMWithMultipleRoleAssignments() throws Exception { // Ensure role assigned for storage account // - PagedIterable stgRoleAssignments = - authorizationManager.roleAssignments().listByScope(storageAccount.id()); + PagedIterable stgRoleAssignments + = authorizationManager.roleAssignments().listByScope(storageAccount.id()); Assertions.assertNotNull(stgRoleAssignments); found = false; for (RoleAssignment roleAssignment : stgRoleAssignments) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertTrue(found, "Storage account should have a role assignment with virtual machine MSI principal"); + Assertions.assertTrue(found, + "Storage account should have a role assignment with virtual machine MSI principal"); } @Test @@ -252,22 +241,20 @@ public void canSetMSIOnNewVMWithMultipleRoleAssignments() throws Exception { public void canSetMSIOnExistingVMWithRoleAssignments() throws Exception { // LiveOnly because test needs to be refactored for storing/evaluating PrincipalId // and "test timing out after latest test proxy update" - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); @@ -280,38 +267,36 @@ public void canSetMSIOnExistingVMWithRoleAssignments() throws Exception { // Ensure NO role assigned for resource group // - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); - PagedIterable rgRoleAssignments1 = - authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); + PagedIterable rgRoleAssignments1 + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(rgRoleAssignments1); boolean found = false; for (RoleAssignment roleAssignment : rgRoleAssignments1) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertFalse(found, "Resource group should not have a role assignment with virtual machine MSI principal"); + Assertions.assertFalse(found, + "Resource group should not have a role assignment with virtual machine MSI principal"); - virtualMachine - .update() + virtualMachine.update() .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .apply(); // Ensure role assigned for resource group // - PagedIterable roleAssignments2 = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + PagedIterable roleAssignments2 + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(roleAssignments2); for (RoleAssignment roleAssignment : roleAssignments2) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java index 4a1ea22927fe1..2f2da688c8dce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java @@ -120,8 +120,7 @@ public void canCreateAndUpdateVirtualMachineWithUserData() { String userDataForUpdate = "Njc5MDI3MUItQ0RGRC00RjdELUI5NTEtMTA4QjA2RTNGNDRE"; // Create - VirtualMachine vm = computeManager - .virtualMachines() + VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -135,63 +134,57 @@ public void canCreateAndUpdateVirtualMachineWithUserData() { .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .withUserData(userDataForCreate) .create(); - Response response = computeManager.serviceClient().getVirtualMachines() + Response response = computeManager.serviceClient() + .getVirtualMachines() .getByResourceGroupWithResponse(rgName, vmName, InstanceViewTypes.USER_DATA, Context.NONE); Assertions.assertEquals(userDataForCreate, response.getValue().userData()); // Update vm.update().withUserData(userDataForUpdate).apply(); - response = computeManager.serviceClient().getVirtualMachines() + response = computeManager.serviceClient() + .getVirtualMachines() .getByResourceGroupWithResponse(rgName, vmName, InstanceViewTypes.USER_DATA, Context.NONE); Assertions.assertEquals(userDataForUpdate, response.getValue().userData()); } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { - NetworkSecurityGroup nsg = - this - .networkManager - .networkSecurityGroups() - .define("nsg") - .withRegion(region) - .withNewResourceGroup(rgName) - .defineRule("rule1") - .allowInbound() - .fromAnyAddress() - .fromPort(80) - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() - .create(); + NetworkSecurityGroup nsg = this.networkManager.networkSecurityGroups() + .define("nsg") + .withRegion(region) + .withNewResourceGroup(rgName) + .defineRule("rule1") + .allowInbound() + .fromAnyAddress() + .fromPort(80) + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() + .create(); - Creatable networkDefinition = - this - .networkManager - .networks() - .define("network1") - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .defineSubnet("subnet1") - .withAddressPrefix("10.0.0.0/29") - .withExistingNetworkSecurityGroup(nsg) - .attach(); + Creatable networkDefinition = this.networkManager.networks() + .define("network1") + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .defineSubnet("subnet1") + .withAddressPrefix("10.0.0.0/29") + .withExistingNetworkSecurityGroup(nsg) + .attach(); // Create - VirtualMachine vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .create(); + VirtualMachine vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); @@ -217,8 +210,7 @@ public void canCreateVirtualMachineWithNetworking() throws Exception { @Test public void canRefreshAfterDeallocation() { // Create - VirtualMachine vm = computeManager - .virtualMachines() + VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -258,8 +250,7 @@ public void canRefreshAfterDeallocation() { @Test public void canCreateVirtualMachine() throws Exception { // Create - computeManager - .virtualMachines() + computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -306,35 +297,36 @@ public void canCreateVirtualMachine() throws Exception { @Test public void cannotCreateVirtualMachineSyncPoll() throws Exception { - final String mySqlInstallScript = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/4397e808d07df60ff3cdfd1ae40999f0130eb1b3/mysql-standalone-server-ubuntu/scripts/install_mysql_server_5.6.sh"; + final String mySqlInstallScript + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/4397e808d07df60ff3cdfd1ae40999f0130eb1b3/mysql-standalone-server-ubuntu/scripts/install_mysql_server_5.6.sh"; final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x("; Assertions.assertThrows(IllegalStateException.class, () -> { - Accepted acceptedVirtualMachine = - this.computeManager.virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - // virtual machine extensions is not compatible with "beginCreate" method - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .beginCreate(); + Accepted acceptedVirtualMachine = this.computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + // virtual machine extensions is not compatible with "beginCreate" method + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript)) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .beginCreate(); }); // verify dependent resources is not created in the case of above failed "beginCreate" method - boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); + boolean dependentResourceCreated + = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName); Assertions.assertFalse(dependentResourceCreated); // skip cleanup @@ -345,8 +337,7 @@ public void cannotCreateVirtualMachineSyncPoll() throws Exception { public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; - Accepted acceptedVirtualMachine = computeManager - .virtualMachines() + Accepted acceptedVirtualMachine = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -374,9 +365,8 @@ public void canCreateVirtualMachineSyncPoll() throws Exception { PollResponse pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); - delayInMills = pollResponse.getRetryAfter() == null - ? defaultDelayInMillis - : pollResponse.getRetryAfter().toMillis(); + delayInMills + = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); @@ -415,8 +405,7 @@ public void canCreateVirtualMachineSyncPoll() throws Exception { @Test public void canCreateUpdatePriorityAndPrice() throws Exception { // Create - computeManager - .virtualMachines() + computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -490,47 +479,40 @@ public void canCreateUpdatePriorityAndPrice() throws Exception { @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { - AvailabilitySet setCreated = - computeManager - .availabilitySets() - .define(availabilitySetName) - .withRegion(regionProxPlacementGroup) - .withNewResourceGroup(rgName) - .withNewProximityPlacementGroup(proxGroupName, proxGroupType) - .create(); + AvailabilitySet setCreated = computeManager.availabilitySets() + .define(availabilitySetName) + .withRegion(regionProxPlacementGroup) + .withNewResourceGroup(rgName) + .withNewProximityPlacementGroup(proxGroupName, proxGroupType) + .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); - AvailabilitySet setCreated2 = - computeManager - .availabilitySets() - .define(availabilitySetName2) - .withRegion(regionProxPlacementGroup2) - .withNewResourceGroup(rgName2) - .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) - .create(); + AvailabilitySet setCreated2 = computeManager.availabilitySets() + .define(availabilitySetName2) + .withRegion(regionProxPlacementGroup2) + .withNewResourceGroup(rgName2) + .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) + .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); // Create - computeManager - .virtualMachines() + computeManager.virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) @@ -575,9 +557,8 @@ public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Except Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions @@ -585,16 +566,12 @@ public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Except try { // Update Vm to remove it from proximity placement group - VirtualMachine updatedVm = - foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); + VirtualMachine updatedVm + = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { - Assertions - .assertTrue( - clEx - .getMessage() - .contains( - "Updating proximity placement group of VM javavm is not allowed while the VM is running." - + " Please stop/deallocate the VM and retry the operation.")); + Assertions.assertTrue(clEx.getMessage() + .contains("Updating proximity placement group of VM javavm is not allowed while the VM is running." + + " Please stop/deallocate the VM and retry the operation.")); } // Delete VM @@ -604,28 +581,24 @@ public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Except @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { - AvailabilitySet setCreated = - computeManager - .availabilitySets() - .define(availabilitySetName) - .withRegion(regionProxPlacementGroup) - .withNewResourceGroup(rgName) - .withNewProximityPlacementGroup(proxGroupName, proxGroupType) - .create(); + AvailabilitySet setCreated = computeManager.availabilitySets() + .define(availabilitySetName) + .withRegion(regionProxPlacementGroup) + .withNewResourceGroup(rgName) + .withNewProximityPlacementGroup(proxGroupName, proxGroupType) + .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); // Create - computeManager - .virtualMachines() + computeManager.virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) @@ -670,9 +643,8 @@ public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGr Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions @@ -685,9 +657,8 @@ public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGr Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); - Assertions - .assertTrue( - setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); + Assertions.assertTrue( + setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); // TODO: this does not work... can not remove cvm from the placement group // Assertions.assertNull(foundVM.proximityPlacementGroup().virtualMachineIds()); @@ -704,14 +675,14 @@ public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Excep String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; - CreatablesInfo creatablesInfo = - prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); + CreatablesInfo creatablesInfo + = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List networkCreatableKeys = creatablesInfo.networkCreatableKeys; List publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; - CreatedResources createdVirtualMachines = - computeManager.virtualMachines().create(virtualMachineCreatables); + CreatedResources createdVirtualMachines + = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set virtualMachineNames = new HashSet<>(); @@ -738,8 +709,8 @@ public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Excep publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { - PublicIpAddress createdPublicIpAddress = - (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); + PublicIpAddress createdPublicIpAddress + = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } @@ -767,36 +738,31 @@ public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } - final CreatablesInfo creatablesInfo = - prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); + final CreatablesInfo creatablesInfo + = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; - computeManager - .virtualMachines() - .createAsync(virtualMachineCreatables) - .map( - createdResource -> { - if (createdResource instanceof Resource) { - Resource resource = (Resource) createdResource; - LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); - if (resource instanceof VirtualMachine) { - VirtualMachine virtualMachine = (VirtualMachine) resource; - Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); - Assertions.assertNotNull(virtualMachine.id()); - } else if (resource instanceof Network) { - Network network = (Network) resource; - Assertions.assertTrue(networkNames.contains(network.name())); - Assertions.assertNotNull(network.id()); - } else if (resource instanceof PublicIpAddress) { - PublicIpAddress publicIPAddress = (PublicIpAddress) resource; - Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); - Assertions.assertNotNull(publicIPAddress.id()); - } - } - resourceCount.incrementAndGet(); - return createdResource; - }) - .blockLast(); + computeManager.virtualMachines().createAsync(virtualMachineCreatables).map(createdResource -> { + if (createdResource instanceof Resource) { + Resource resource = (Resource) createdResource; + LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); + if (resource instanceof VirtualMachine) { + VirtualMachine virtualMachine = (VirtualMachine) resource; + Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); + Assertions.assertNotNull(virtualMachine.id()); + } else if (resource instanceof Network) { + Network network = (Network) resource; + Assertions.assertTrue(networkNames.contains(network.name())); + Assertions.assertNotNull(network.id()); + } else if (resource instanceof PublicIpAddress) { + PublicIpAddress publicIPAddress = (PublicIpAddress) resource; + Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); + Assertions.assertNotNull(publicIPAddress.id()); + } + } + resourceCount.incrementAndGet(); + return createdResource; + }).blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); @@ -817,44 +783,40 @@ public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); // Create a premium storage account for virtual machine data disk // - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.PREMIUM_LRS) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.PREMIUM_LRS) + .create(); // Creates a virtual machine with an unmanaged data disk that gets stored in the above // premium storage account // - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk1") - .withNewVhd(100) - .withLun(2) - .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") - .attach() - .defineUnmanagedDataDisk("disk2") - .withNewVhd(100) - .withLun(3) - .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") - .attach() - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk1") + .withNewVhd(100) + .withLun(2) + .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") + .attach() + .defineUnmanagedDataDisk("disk2") + .withNewVhd(100) + .withLun(3) + .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") + .attach() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .create(); // Validate the unmanaged data disks // @@ -875,22 +837,20 @@ public void canSetStorageAccountForUnmanagedDisk() { // Creates another virtual machine by attaching existing unmanaged data disk detached from the // above virtual machine. // - virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("Foo12") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) - .create(); + virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("Foo12") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) + .create(); // Gets the vm // virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); @@ -908,8 +868,7 @@ public void canSetStorageAccountForUnmanagedDisk() { Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); // Update the VM by attaching another existing data disk // - virtualMachine - .update() + virtualMachine.update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); // Gets the vm @@ -925,20 +884,18 @@ public void canSetStorageAccountForUnmanagedDisk() { @Test public void canUpdateTagsOnVM() { // Create - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("firstuser") - .withSsh(sshPublicKey()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("firstuser") + .withSsh(sshPublicKey()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); // checking to see if withTag correctly update virtualMachine.update().withTag("test", "testValue").apply(); @@ -954,26 +911,24 @@ public void canUpdateTagsOnVM() { @Test public void canRunScriptOnVM() { // Create - VirtualMachine virtualMachine = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("firstuser") - .withSsh(sshPublicKey()) - .create(); + VirtualMachine virtualMachine = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("firstuser") + .withSsh(sshPublicKey()) + .create(); List installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); - RunCommandResult runResult = - virtualMachine.runShellScript(installGit, new ArrayList()); + RunCommandResult runResult + = virtualMachine.runShellScript(installGit, new ArrayList()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); @@ -1067,9 +1022,7 @@ public void canCreateVirtualMachineWithDeleteOption() throws Exception { final String publicIpDnsLabel = generateRandomResourceName("pip", 20); - Network network = this - .networkManager - .networks() + Network network = this.networkManager.networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) @@ -1078,8 +1031,7 @@ public void canCreateVirtualMachineWithDeleteOption() throws Exception { .create(); // 1. VM with NIC and Disk - VirtualMachine vm1 = computeManager - .virtualMachines() + VirtualMachine vm1 = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1113,27 +1065,28 @@ public void canCreateVirtualMachineWithDeleteOption() throws Exception { // verify that nic, os/data disk is deleted // only Network and PublicIpAddress remains in the resource group, others is deleted together with the virtual machine resource - Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); + Assertions.assertEquals(2, + computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); // delete PublicIpAddress - PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get(); + PublicIpAddress publicIpAddress = computeManager.networkManager() + .publicIpAddresses() + .listByResourceGroup(rgName) + .stream() + .findFirst() + .get(); computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id()); - // 2. VM with secondary NIC String secondaryNicName = generateRandomResourceName("nic", 10); - Creatable secondaryNetworkInterfaceCreatable = - this - .networkManager - .networkInterfaces() - .define(secondaryNicName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("default") - .withPrimaryPrivateIPAddressDynamic(); + Creatable secondaryNetworkInterfaceCreatable = this.networkManager.networkInterfaces() + .define(secondaryNicName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("default") + .withPrimaryPrivateIPAddressDynamic(); - VirtualMachine vm2 = computeManager - .virtualMachines() + VirtualMachine vm2 = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1154,23 +1107,19 @@ public void canCreateVirtualMachineWithDeleteOption() throws Exception { ResourceManagerUtils.sleep(Duration.ofSeconds(10)); // verify nic and disk is deleted - Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); - + Assertions.assertEquals(1, + computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count()); // 3. VM without DeleteOptions - secondaryNetworkInterfaceCreatable = - this - .networkManager - .networkInterfaces() - .define(secondaryNicName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("default") - .withPrimaryPrivateIPAddressDynamic(); + secondaryNetworkInterfaceCreatable = this.networkManager.networkInterfaces() + .define(secondaryNicName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("default") + .withPrimaryPrivateIPAddressDynamic(); - VirtualMachine vm3 = computeManager - .virtualMachines() + VirtualMachine vm3 = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1201,16 +1150,15 @@ public void canCreateVirtualMachineWithDeleteOption() throws Exception { // verify nic and disk is not deleted Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count()); - Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); + Assertions.assertEquals(2, + computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count()); } @Test public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Region region = Region.US_WEST3; - Network network = this - .networkManager - .networks() + Network network = this.networkManager.networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) @@ -1219,8 +1167,7 @@ public void canUpdateVirtualMachineWithDeleteOption() throws Exception { .create(); // 1. VM with DeleteOptions=DELETE, to be updated - VirtualMachine vm1 = computeManager - .virtualMachines() + VirtualMachine vm1 = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1239,9 +1186,7 @@ public void canUpdateVirtualMachineWithDeleteOption() throws Exception { .create(); // update with new Disk without DeleteOptions - vm1.update() - .withNewDataDisk(10) - .apply(); + vm1.update().withNewDataDisk(10).apply(); computeManager.virtualMachines().deleteById(vm1.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); @@ -1251,10 +1196,8 @@ public void canUpdateVirtualMachineWithDeleteOption() throws Exception { Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get(); computeManager.disks().deleteById(disk.id()); - // 2. VM with DeleteOptions=null for Disk, to be updated - VirtualMachine vm2 = computeManager - .virtualMachines() + VirtualMachine vm2 = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1271,10 +1214,7 @@ public void canUpdateVirtualMachineWithDeleteOption() throws Exception { .create(); // update with new Disk with DeleteOptions=DELETE - vm2.update() - .withNewDataDisk(10) - .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) - .apply(); + vm2.update().withNewDataDisk(10).withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE).apply(); computeManager.virtualMachines().deleteById(vm2.id()); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); @@ -1295,9 +1235,9 @@ public void canHibernateVirtualMachine() { .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() -// .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) -// .withRootUsername("Foo12") -// .withSsh(sshPublicKey()) + // .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + // .withRootUsername("Foo12") + // .withSsh(sshPublicKey()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) @@ -1310,25 +1250,27 @@ public void canHibernateVirtualMachine() { // deallocate with hibernate vm.deallocate(true); - InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream() + InstanceViewStatus hibernationStatus = vm.instanceView() + .statuses() + .stream() .filter(status -> "HibernationState/Hibernated".equals(status.code())) - .findFirst().orElse(null); + .findFirst() + .orElse(null); Assertions.assertNotNull(hibernationStatus); vm.start(); // update to disable hibernation vm.deallocate(); - vm.update() - .disableHibernation() - .apply(); + vm.update().disableHibernation().apply(); Assertions.assertFalse(vm.isHibernationEnabled()); } @Test public void canEnableUltraSsdVirtualMachine() { - Disk dataDisk = computeManager.disks().define("data_disk") + Disk dataDisk = computeManager.disks() + .define("data_disk") .withRegion(region) .withNewResourceGroup(rgName) .withData() @@ -1362,13 +1304,9 @@ public void canEnableUltraSsdVirtualMachine() { int lun = vm.dataDisks().get(0).lun(); - vm.update() - .withoutDataDisk(lun) - .apply(); + vm.update().withoutDataDisk(lun).apply(); - vm.update() - .disableUltraSsd() - .apply(); + vm.update().disableUltraSsd().apply(); Assertions.assertFalse(vm.isUltraSsdEnabled()); } @@ -1438,11 +1376,7 @@ public void canCreateVirtualMachineWithEphemeralOSDisk() { String osDiskId = vm.osDiskId(); - vm.update() - .withoutDataDisk(1) - .withNewDataDisk(1, 2, CachingTypes.NONE) - .withNewDataDisk(1) - .apply(); + vm.update().withoutDataDisk(1).withNewDataDisk(1, 2, CachingTypes.NONE).withNewDataDisk(1).apply(); Assertions.assertEquals(vm.dataDisks().size(), 2); vm.powerOff(); @@ -1458,20 +1392,17 @@ public void canCreateVirtualMachineWithEphemeralOSDisk() { public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { // can add regular vm to vmss final String vmssName = generateRandomResourceName("vmss", 10); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region.name()) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region.name()) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(rgName); - LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); - VirtualMachineScaleSet flexibleVMSS = this.computeManager - .virtualMachineScaleSets() + LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + VirtualMachineScaleSet flexibleVMSS = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1489,8 +1420,7 @@ public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { String regularVMName = generateRandomResourceName("vm", 10); final String pipDnsLabel = generateRandomResourceName("pip", 10); - VirtualMachine regularVM = this.computeManager - .virtualMachines() + VirtualMachine regularVM = this.computeManager.virtualMachines() .define(regularVMName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1506,24 +1436,21 @@ public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.id(), regularVM.virtualMachineScaleSetId()); Assertions.assertEquals(2, flexibleVMSS.capacity()); -// // Flexible vmss vm instance ids are all null, which means VMs in flexible vmss can only be operated by individual `VirtualMachine` APIs. -// Assertions.assertTrue(flexibleVMSS.virtualMachines().list().stream().allMatch(vm -> vm.instanceId() == null)); + // // Flexible vmss vm instance ids are all null, which means VMs in flexible vmss can only be operated by individual `VirtualMachine` APIs. + // Assertions.assertTrue(flexibleVMSS.virtualMachines().list().stream().allMatch(vm -> vm.instanceId() == null)); // as 2023-03-01, instanceId is not null for FlexibleOrchestrationMode regularVM.deallocate(); Assertions.assertEquals(regularVM.powerState(), PowerState.DEALLOCATED); - this.computeManager - .virtualMachines().deleteById(regularVM.id()); + this.computeManager.virtualMachines().deleteById(regularVM.id()); flexibleVMSS.refresh(); Assertions.assertEquals(flexibleVMSS.capacity(), 1); // can't add vm with unmanaged disk to vmss final String storageAccountName = generateRandomResourceName("stg", 17); - Assertions.assertThrows( - ApiErrorException.class, - () -> computeManager - .virtualMachines() + Assertions.assertThrows(ApiErrorException.class, + () -> computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1538,24 +1465,20 @@ public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { .withNewStorageAccount(storageAccountName) .withOSDiskCaching(CachingTypes.READ_WRITE) .withExistingVirtualMachineScaleSet(flexibleVMSS) - .create() - ); + .create()); // can't add vm to `UNIFORM` vmss final String vmssName2 = generateRandomResourceName("vmss", 10); - Network network2 = - this - .networkManager - .networks() - .define("vmssvnet2") - .withRegion(region.name()) - .withExistingResourceGroup(rgName) - .withAddressSpace("192.168.0.0/28") - .withSubnet("subnet2", "192.168.0.0/28") - .create(); - LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); - VirtualMachineScaleSet uniformVMSS = this.computeManager - .virtualMachineScaleSets() + Network network2 = this.networkManager.networks() + .define("vmssvnet2") + .withRegion(region.name()) + .withExistingResourceGroup(rgName) + .withAddressSpace("192.168.0.0/28") + .withSubnet("subnet2", "192.168.0.0/28") + .create(); + LoadBalancer publicLoadBalancer2 = createHttpLoadBalancers(region, resourceGroup, "2", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + VirtualMachineScaleSet uniformVMSS = this.computeManager.virtualMachineScaleSets() .define(vmssName2) .withRegion(region) .withNewResourceGroup(rgName) @@ -1571,10 +1494,8 @@ public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(v -> v.instanceId() != null)); String regularVMName2 = generateRandomResourceName("vm", 10); - Assertions.assertThrows( - ApiErrorException.class, - () -> this.computeManager - .virtualMachines() + Assertions.assertThrows(ApiErrorException.class, + () -> this.computeManager.virtualMachines() .define(regularVMName2) .withRegion(region) .withNewResourceGroup(rgName) @@ -1586,16 +1507,14 @@ public void canCreateVirtualMachineWithExistingScaleSet() throws Exception { .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_B1S) .withExistingVirtualMachineScaleSet(uniformVMSS) - .create() - ); + .create()); } @Test @DoNotRecord(skipInPlayback = true) public void canSwapOSDiskWithManagedDisk() { String storageAccountName = generateRandomResourceName("sa", 15); - StorageAccount storageAccount = this.storageManager - .storageAccounts() + StorageAccount storageAccount = this.storageManager.storageAccounts() .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1603,8 +1522,7 @@ public void canSwapOSDiskWithManagedDisk() { // create vm with os disk encrypted with platform managed key String vm1Name = generateRandomResourceName("vm", 15); - VirtualMachine vm1 = this.computeManager - .virtualMachines() + VirtualMachine vm1 = this.computeManager.virtualMachines() .define(vm1Name) .withRegion(region) .withNewResourceGroup(rgName) @@ -1623,8 +1541,7 @@ public void canSwapOSDiskWithManagedDisk() { // create vm with os disk encrypted with customer managed key (cmk) String vaultName = generateRandomResourceName("vault", 15); - Vault vault = this.keyVaultManager - .vaults() + Vault vault = this.keyVaultManager.vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1635,11 +1552,7 @@ public void canSwapOSDiskWithManagedDisk() { .create(); String keyName = generateRandomResourceName("key", 15); - Key key = vault.keys() - .define(keyName) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key key = vault.keys().define(keyName).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); String desName = generateRandomResourceName("des", 15); DiskEncryptionSet des = this.computeManager.diskEncryptionSets() @@ -1681,19 +1594,16 @@ public void canSwapOSDiskWithManagedDisk() { // swap vm1's os disk(encrypted with pmk) with vm2's os disk(encrypted with cmk) vm1.deallocate(); - vm1.update() - .withOSDisk(vm2OSDiskId) - .apply(); + vm1.update().withOSDisk(vm2OSDiskId).apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm2OSDiskId); - Assertions.assertTrue(des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); + Assertions.assertTrue( + des.id().equalsIgnoreCase(vm1.storageProfile().osDisk().managedDisk().diskEncryptionSet().id())); // swap back vm1's os disk(encrypted with pmk) vm1.deallocate(); - vm1.update() - .withOSDisk(vm1OSDisk) - .apply(); + vm1.update().withOSDisk(vm1OSDisk).apply(); vm1.start(); vm1.refresh(); Assertions.assertEquals(vm1.osDiskId(), vm1OSDisk.id()); @@ -1749,9 +1659,7 @@ public void canUpdateDeleteOptions() { String nicName = generateRandomResourceName("nic", 15); String nicName2 = generateRandomResourceName("nic", 15); - Network network = this - .networkManager - .networks() + Network network = this.networkManager.networks() .define(networkName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1774,9 +1682,7 @@ public void canUpdateDeleteOptions() { .withSsh(sshPublicKey()) .withNewDataDisk(10, 1, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withSize(VirtualMachineSizeTypes.STANDARD_D8S_V3) - .withNewSecondaryNetworkInterface(this - .networkManager - .networkInterfaces() + .withNewSecondaryNetworkInterface(this.networkManager.networkInterfaces() .define(nicName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1789,7 +1695,8 @@ public void canUpdateDeleteOptions() { Assertions.assertEquals(DeleteOptions.DELETE, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); - Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); + Assertions.assertTrue( + vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); // update delete options all to DETACH, except for secondary nic vm.update() @@ -1801,21 +1708,21 @@ public void canUpdateDeleteOptions() { Assertions.assertEquals(DeleteOptions.DETACH, vm.osDiskDeleteOptions()); Assertions.assertEquals(DeleteOptions.DETACH, vm.primaryNetworkInterfaceDeleteOptions()); // secondary nic delete options remains unchanged - Assertions.assertTrue(vm.networkInterfaceIds().stream() - .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())).allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); - Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); - - NetworkInterface secondaryNic2 = - this - .networkManager - .networkInterfaces() - .define(nicName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet2") - .withPrimaryPrivateIPAddressDynamic() - .create(); + Assertions.assertTrue(vm.networkInterfaceIds() + .stream() + .filter(nicId -> !nicId.equals(vm.primaryNetworkInterfaceId())) + .allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); + Assertions.assertTrue( + vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); + + NetworkInterface secondaryNic2 = this.networkManager.networkInterfaces() + .define(nicName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet2") + .withPrimaryPrivateIPAddressDynamic() + .create(); vm.powerOff(); vm.deallocate(); @@ -1829,15 +1736,21 @@ public void canUpdateDeleteOptions() { // update all back to DELETE, including the newly added data disk and the secondary nic vm.update() .withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE) - .withDataDisksDeleteOptions(DeleteOptions.DELETE, new ArrayList<>(vm.dataDisks().keySet()).toArray(new Integer[0])) - .withNetworkInterfacesDeleteOptions( - DeleteOptions.DELETE, - vm.networkInterfaceIds().stream().filter(nic -> !nic.equals(vm.primaryNetworkInterfaceId())).toArray(String[]::new)) + .withDataDisksDeleteOptions(DeleteOptions.DELETE, + new ArrayList<>(vm.dataDisks().keySet()).toArray(new Integer[0])) + .withNetworkInterfacesDeleteOptions(DeleteOptions.DELETE, + vm.networkInterfaceIds() + .stream() + .filter(nic -> !nic.equals(vm.primaryNetworkInterfaceId())) + .toArray(String[]::new)) .apply(); Assertions.assertEquals(DeleteOptions.DELETE, vm.primaryNetworkInterfaceDeleteOptions()); - Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); - Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); + Assertions.assertTrue(vm.networkInterfaceIds() + .stream() + .allMatch(nicId -> DeleteOptions.DELETE.equals(vm.networkInterfaceDeleteOptions(nicId)))); + Assertions.assertTrue( + vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DELETE.equals(disk.deleteOptions()))); // update all to DETACH vm.update() @@ -1845,8 +1758,11 @@ public void canUpdateDeleteOptions() { .withNetworkInterfacesDeleteOptions(DeleteOptions.DETACH) .apply(); - Assertions.assertTrue(vm.networkInterfaceIds().stream().allMatch(nicId -> DeleteOptions.DETACH.equals(vm.networkInterfaceDeleteOptions(nicId)))); - Assertions.assertTrue(vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); + Assertions.assertTrue(vm.networkInterfaceIds() + .stream() + .allMatch(nicId -> DeleteOptions.DETACH.equals(vm.networkInterfaceDeleteOptions(nicId)))); + Assertions.assertTrue( + vm.dataDisks().values().stream().allMatch(disk -> DeleteOptions.DETACH.equals(disk.deleteOptions()))); } @Test @@ -1862,7 +1778,8 @@ public void testListVmByVmssId() { .withFlexibleOrchestrationMode() .create(); - Assertions.assertEquals(0, computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()).stream().count()); + Assertions.assertEquals(0, + computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()).stream().count()); VirtualMachine vm = computeManager.virtualMachines() .define(vmName) @@ -1893,8 +1810,15 @@ public void testListVmByVmssId() { Assertions.assertNull(vm2.virtualMachineScaleSetId()); - Assertions.assertEquals(1, computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()).stream().count()); - Assertions.assertTrue(vm.id().equalsIgnoreCase(computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()).stream().iterator().next().id())); + Assertions.assertEquals(1, + computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()).stream().count()); + Assertions.assertTrue(vm.id() + .equalsIgnoreCase(computeManager.virtualMachines() + .listByVirtualMachineScaleSetId(vmss.id()) + .stream() + .iterator() + .next() + .id())); Assertions.assertEquals(2, computeManager.virtualMachines().listByResourceGroup(rgName).stream().count()); } @@ -1920,13 +1844,16 @@ public void testListByVmssIdNextLink() throws Exception { .withSsh(sshPublicKey()) .create(); - Network network = networkManager.networks().define(vnetName) + Network network = networkManager.networks() + .define(vnetName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("subnet1", "10.0.0.0/24") .create(); - LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, this.resourceManager.resourceGroups().getByName(rgName), "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + LoadBalancer publicLoadBalancer + = createHttpLoadBalancers(region, this.resourceManager.resourceGroups().getByName(rgName), "1", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); VirtualMachineScaleSet vmss = computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) @@ -1942,7 +1869,8 @@ public void testListByVmssIdNextLink() throws Exception { .withCapacity(vmssCapacity) .create(); - PagedIterable vmPaged = computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()); + PagedIterable vmPaged + = computeManager.virtualMachines().listByVirtualMachineScaleSetId(vmss.id()); Iterable> vmIterable = vmPaged.iterableByPage(); int pageCount = 0; for (PagedResponse response : vmIterable) { @@ -1956,8 +1884,7 @@ public void testListByVmssIdNextLink() throws Exception { @Test public void canCreateVMWithEncryptionAtHost() { - VirtualMachine vm = computeManager - .virtualMachines() + VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1981,8 +1908,7 @@ public void canCreateVMWithEncryptionAtHost() { @Test public void canUpdateVMWithEncryptionAtHost() { - VirtualMachine vm = computeManager - .virtualMachines() + VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -2008,8 +1934,7 @@ public void canUpdateVMWithEncryptionAtHost() { @Test public void canUpdateVMWithoutEncryptionAtHost() { - VirtualMachine vm = computeManager - .virtualMachines() + VirtualMachine vm = computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -2036,54 +1961,46 @@ public void canUpdateVMWithoutEncryptionAtHost() { // *********************************** helper methods *********************************** - private CreatablesInfo prepareCreatableVirtualMachines( - Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { + private CreatablesInfo prepareCreatableVirtualMachines(Region region, String vmNamePrefix, String networkNamePrefix, + String publicIpNamePrefix, int vmCount) { - Creatable resourceGroupCreatable = - resourceManager.resourceGroups().define(rgName).withRegion(region); + Creatable resourceGroupCreatable + = resourceManager.resourceGroups().define(rgName).withRegion(region); - Creatable storageAccountCreatable = - storageManager - .storageAccounts() - .define(generateRandomResourceName("stg", 20)) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable); + Creatable storageAccountCreatable = storageManager.storageAccounts() + .define(generateRandomResourceName("stg", 20)) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable); List networkCreatableKeys = new ArrayList<>(); List publicIpCreatableKeys = new ArrayList<>(); List> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { - Creatable networkCreatable = - networkManager - .networks() - .define(String.format("%s-%d", networkNamePrefix, i)) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withAddressSpace("10.0.0.0/28"); + Creatable networkCreatable = networkManager.networks() + .define(String.format("%s-%d", networkNamePrefix, i)) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); - Creatable publicIPAddressCreatable = - networkManager - .publicIpAddresses() - .define(String.format("%s-%d", publicIpNamePrefix, i)) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable); + Creatable publicIPAddressCreatable = networkManager.publicIpAddresses() + .define(String.format("%s-%d", publicIpNamePrefix, i)) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); - Creatable virtualMachineCreatable = - computeManager - .virtualMachines() - .define(String.format("%s-%d", vmNamePrefix, i)) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tirekicker") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withNewStorageAccount(storageAccountCreatable); + Creatable virtualMachineCreatable = computeManager.virtualMachines() + .define(String.format("%s-%d", vmNamePrefix, i)) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tirekicker") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachinePopularImageTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachinePopularImageTests.java index ad33bc225beab..3bed378561669 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachinePopularImageTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachinePopularImageTests.java @@ -32,9 +32,10 @@ public void canCreateAllPopularImageVM() { rgName = generateRandomResourceName("rg", 10); List> vmMonos = new ArrayList<>(); for (KnownWindowsVirtualMachineImage image : Arrays.stream(KnownWindowsVirtualMachineImage.values()) - .filter(image -> image != KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS_GEN2 - && image != KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS - && image != KnownWindowsVirtualMachineImage.WINDOWS_DESKTOP_10_20H1_PRO) + .filter( + image -> image != KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS_GEN2 + && image != KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER_WITH_CONTAINERS + && image != KnownWindowsVirtualMachineImage.WINDOWS_DESKTOP_10_20H1_PRO) .collect(Collectors.toList())) { Mono mono = computeManager.virtualMachines() .define(generateRandomResourceName("vm", 10)) diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java index 0f72c477a6045..9064f65f0ebcf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java @@ -62,13 +62,12 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { final String resourceGroupName = rgName; // Create one resource group for everything, to ensure no reliance on resource groups - ResourceGroup resourceGroup = - resourceManager.resourceGroups().define(resourceGroupName).withRegion(region).create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(resourceGroupName).withRegion(region).create(); // Needed for tracking related resources final Map>> vmNonNicResourceDefinitions = new HashMap<>(); - final Map> nicDefinitions = - new HashMap<>(); // Tracking NICs separately because they have to be deleted first + final Map> nicDefinitions = new HashMap<>(); // Tracking NICs separately because they have to be deleted first final Map> vmDefinitions = new HashMap<>(); final Map createdResourceIds = new HashMap<>(); final List errors = new ArrayList<>(); @@ -79,56 +78,45 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { // Define a network for each VM String networkName = generateRandomResourceName("net", 14); - Creatable networkDefinition = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0." + i + ".0/29"); + Creatable networkDefinition = networkManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0." + i + ".0/29"); relatedDefinitions.add(networkDefinition); // Define a PIP for each VM String pipName = generateRandomResourceName("pip", 14); - PublicIpAddress.DefinitionStages.WithCreate pipDefinition = - this - .networkManager - .publicIpAddresses() - .define(pipName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + PublicIpAddress.DefinitionStages.WithCreate pipDefinition = this.networkManager.publicIpAddresses() + .define(pipName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); relatedDefinitions.add(pipDefinition); // Define a NIC for each VM String nicName = generateRandomResourceName("nic", 14); - Creatable nicDefinition = - networkManager - .networkInterfaces() - .define(nicName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipDefinition); + Creatable nicDefinition = networkManager.networkInterfaces() + .define(nicName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipDefinition); // Define a storage account for each VM String storageAccountName = generateRandomResourceName("st", 14); - Creatable storageAccountDefinition = - storageManager - .storageAccounts() - .define(storageAccountName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable storageAccountDefinition = storageManager.storageAccounts() + .define(storageAccountName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); relatedDefinitions.add(storageAccountDefinition); // Define an availability set for each VM String availabilitySetName = generateRandomResourceName("as", 14); - Creatable availabilitySetDefinition = - computeManager - .availabilitySets() - .define(availabilitySetName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable availabilitySetDefinition = computeManager.availabilitySets() + .define(availabilitySetName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); relatedDefinitions.add(availabilitySetDefinition); String vmName = generateRandomResourceName("vm", 14); @@ -141,19 +129,17 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { } else { userName = "tester"; } - Creatable vmDefinition = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetworkInterface(nicDefinition) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey()) - .withNewStorageAccount(storageAccountDefinition) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availabilitySetDefinition); + Creatable vmDefinition = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetworkInterface(nicDefinition) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey()) + .withNewStorageAccount(storageAccountDefinition) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availabilitySetDefinition); // Keep track of all the related resource definitions based on the VM definition vmNonNicResourceDefinitions.put(vmDefinition.key(), relatedDefinitions); @@ -162,38 +148,31 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { } // Start the parallel creation of everything - computeManager - .virtualMachines() - .createAsync(new ArrayList<>(vmDefinitions.values())) - .map( - createdResource -> { - if (createdResource instanceof Resource) { - Resource resource = (Resource) createdResource; - LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); - if (resource instanceof VirtualMachine) { - VirtualMachine virtualMachine = (VirtualMachine) resource; - - // Record that this VM was created successfully - vmDefinitions.remove(virtualMachine.key()); - - // Remove the associated resources from cleanup list - vmNonNicResourceDefinitions.remove(virtualMachine.key()); - - // Remove the associated NIC from cleanup list - nicDefinitions.remove(virtualMachine.key()); - } else { - // Add this related resource to potential cleanup list - createdResourceIds.put(resource.key(), resource.id()); - } - } - return createdResource; - }) - .onErrorResume( - e -> { - errors.add(e); - return Mono.empty(); - }) - .singleOrEmpty(); + computeManager.virtualMachines().createAsync(new ArrayList<>(vmDefinitions.values())).map(createdResource -> { + if (createdResource instanceof Resource) { + Resource resource = (Resource) createdResource; + LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); + if (resource instanceof VirtualMachine) { + VirtualMachine virtualMachine = (VirtualMachine) resource; + + // Record that this VM was created successfully + vmDefinitions.remove(virtualMachine.key()); + + // Remove the associated resources from cleanup list + vmNonNicResourceDefinitions.remove(virtualMachine.key()); + + // Remove the associated NIC from cleanup list + nicDefinitions.remove(virtualMachine.key()); + } else { + // Add this related resource to potential cleanup list + createdResourceIds.put(resource.key(), resource.id()); + } + } + return createdResource; + }).onErrorResume(e -> { + errors.add(e); + return Mono.empty(); + }).singleOrEmpty(); // Delete remaining successfully created NICs of failed VM creations Collection nicIdsToDelete = new ArrayList<>(); @@ -237,25 +216,25 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { // Verifications final int successfulVMCount = desiredVMCount - vmNonNicResourceDefinitions.size(); - final int actualVMCount = - TestUtilities.getSize(computeManager.virtualMachines().listByResourceGroup(resourceGroupName)); + final int actualVMCount + = TestUtilities.getSize(computeManager.virtualMachines().listByResourceGroup(resourceGroupName)); LOGGER.log(LogLevel.VERBOSE, () -> "Number of actual successful VMs: " + actualVMCount); Assertions.assertEquals(successfulVMCount, actualVMCount); - final int actualNicCount = - TestUtilities.getSize(networkManager.networkInterfaces().listByResourceGroup(resourceGroupName)); + final int actualNicCount + = TestUtilities.getSize(networkManager.networkInterfaces().listByResourceGroup(resourceGroupName)); Assertions.assertEquals(successfulVMCount, actualNicCount); - final int actualNetworkCount = - TestUtilities.getSize(networkManager.networks().listByResourceGroup(resourceGroupName)); + final int actualNetworkCount + = TestUtilities.getSize(networkManager.networks().listByResourceGroup(resourceGroupName)); Assertions.assertEquals(successfulVMCount, actualNetworkCount); - final int actualPipCount = - TestUtilities.getSize(networkManager.publicIpAddresses().listByResourceGroup(resourceGroupName)); + final int actualPipCount + = TestUtilities.getSize(networkManager.publicIpAddresses().listByResourceGroup(resourceGroupName)); Assertions.assertEquals(successfulVMCount, actualPipCount); - final int actualAvailabilitySetCount = - TestUtilities.getSize(computeManager.availabilitySets().listByResourceGroup(resourceGroupName)); + final int actualAvailabilitySetCount + = TestUtilities.getSize(computeManager.availabilitySets().listByResourceGroup(resourceGroupName)); Assertions.assertEquals(successfulVMCount, actualAvailabilitySetCount); - final int actualStorageAccountCount = - TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(resourceGroupName)); + final int actualStorageAccountCount + = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(resourceGroupName)); Assertions.assertEquals(successfulVMCount, actualStorageAccountCount); // Verify that at least one VM failed. diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetBootDiagnosticsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetBootDiagnosticsTests.java index 5036df2af3718..78a080f911580 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetBootDiagnosticsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetBootDiagnosticsTests.java @@ -43,19 +43,16 @@ public void canEnableBootDiagnosticsWithImplicitStorageOnManagedVMSSCreation() t ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -63,23 +60,20 @@ public void canEnableBootDiagnosticsWithImplicitStorageOnManagedVMSSCreation() t } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnostics() - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -93,19 +87,16 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMSSCreation() ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -113,26 +104,23 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMSSCreation() } Assertions.assertTrue(backends.size() == 2); - Creatable creatableStorageAccount = - storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnostics(creatableStorageAccount) - .create(); + Creatable creatableStorageAccount + = storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnostics(creatableStorageAccount) + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -147,19 +135,16 @@ public void canEnableBootDiagnosticsWithExplicitStorageOnManagedVMSSCreation() t ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -167,31 +152,26 @@ public void canEnableBootDiagnosticsWithExplicitStorageOnManagedVMSSCreation() t } Assertions.assertTrue(backends.size() == 2); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .create(); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnostics(storageAccount) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .create(); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnostics(storageAccount) + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -205,19 +185,16 @@ public void canDisableVMSSBootDiagnostics() throws Exception { ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -225,23 +202,20 @@ public void canDisableVMSSBootDiagnostics() throws Exception { } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnostics() - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -260,19 +234,16 @@ public void bootDiagnosticsShouldUsesVMSSOSUnManagedDiskImplicitStorage() throws ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -280,24 +251,21 @@ public void bootDiagnosticsShouldUsesVMSSOSUnManagedDiskImplicitStorage() throws } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withBootDiagnostics() - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withBootDiagnostics() + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -313,8 +281,7 @@ public void bootDiagnosticsShouldUsesVMSSOSUnManagedDiskImplicitStorage() throws // Boot diagnostics should share storage used for os/disk containers boolean found = false; for (String containerStorageUri : containers) { - if (containerStorageUri - .toLowerCase() + if (containerStorageUri.toLowerCase() .startsWith(virtualMachineScaleSet.bootDiagnosticsStorageUri().toLowerCase())) { found = true; break; @@ -330,19 +297,16 @@ public void bootDiagnosticsShouldUseVMSSUnManagedDisksExplicitStorage() throws E ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -350,34 +314,28 @@ public void bootDiagnosticsShouldUseVMSSUnManagedDisksExplicitStorage() throws E } Assertions.assertTrue(backends.size() == 2); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(region) - .withNewResourceGroup(rgName) - .create(); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withBootDiagnostics() - .withExistingStorageAccount( - storageAccount) // This storage account must be shared by disk and boot diagnostics - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withNewResourceGroup(rgName) + .create(); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withBootDiagnostics() + .withExistingStorageAccount(storageAccount) // This storage account must be shared by disk and boot diagnostics + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -400,19 +358,16 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMSSCreation( ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -420,29 +375,25 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMSSCreation( } Assertions.assertTrue(backends.size() == 2); - Creatable creatableStorageAccount = - storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withBootDiagnostics( - creatableStorageAccount) // This storage account should be used for BDiagnostics not OS disk storage - // account - .create(); + Creatable creatableStorageAccount + = storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withBootDiagnostics(creatableStorageAccount) // This storage account should be used for BDiagnostics not OS disk storage + // account + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); @@ -459,8 +410,7 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMSSCreation( Assertions.assertFalse(containers.isEmpty()); boolean notFound = true; for (String containerStorageUri : containers) { - if (containerStorageUri - .toLowerCase() + if (containerStorageUri.toLowerCase() .startsWith(virtualMachineScaleSet.bootDiagnosticsStorageUri().toLowerCase())) { notFound = false; break; @@ -469,36 +419,29 @@ public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMSSCreation( Assertions.assertTrue(notFound); } - @Test public void canEnableBootDiagnosticsOnManagedStorageAccount() { - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withBootDiagnosticsOnManagedStorageAccount() - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withBootDiagnosticsOnManagedStorageAccount() + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetEMSILMSIOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetEMSILMSIOperationsTests.java index 6a9e942841067..e6dd9ab0e71f3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetEMSILMSIOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetEMSILMSIOperationsTests.java @@ -52,81 +52,66 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { // Create a virtual network to which we will assign "EMSI" with reader access // - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); // Create an "User Assigned (External) MSI" residing in the above RG and assign reader access to the virtual // network // - Identity createdIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAccessTo(network, BuiltInRole.READER) - .create(); + Identity createdIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAccessTo(network, BuiltInRole.READER) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create a virtual network for VMSS // - Network vmssNetwork = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network vmssNetwork = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); // Create a Load balancer for VMSS // LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); - Assertions - .assertNull( - virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); // No Local MSI enabled - Assertions - .assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); // No Local MSI enabled + Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); // No Local MSI enabled + Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); // No Local MSI enabled // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine scale set // @@ -140,9 +125,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); - Assertions - .assertTrue( - identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); + Assertions.assertTrue( + identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { @@ -157,8 +141,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { RoleAssignment assignment; if (!isPlaybackMode()) { // principalId redacted - PagedIterable roleAssignmentsForNetwork = - this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); + PagedIterable roleAssignmentsForNetwork + = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { @@ -166,23 +150,19 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); + Assertions.assertTrue(found, + "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); - assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) - .block(); + assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, + createdIdentity.principalId()).block(); - Assertions - .assertNotNull( - assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the virtual network for identity"); // Ensure expected role assignment exists for explicitly created EMSI // - PagedIterable roleAssignmentsForResourceGroup = - this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); + PagedIterable roleAssignmentsForResourceGroup + = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { @@ -192,27 +172,20 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the resource group for identity" - + implicitlyCreatedIdentity.name()); + Assertions.assertTrue(found, "Expected role assignment not found for the resource group for identity" + + implicitlyCreatedIdentity.name()); - assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) - .block(); + assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(resourceGroup.id(), BuiltInRole.CONTRIBUTOR, + implicitlyCreatedIdentity.principalId()).block(); - Assertions - .assertNotNull( - assignment, "Expected role assignment with ROLE not found for the resource group for identity"); + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the resource group for identity"); } emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Iterator itr = emsiIds.iterator(); // Remove both (all) identities - virtualMachineScaleSet - .update() + virtualMachineScaleSet.update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); @@ -238,8 +211,7 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { Identity identity2 = msiManager.identities().getById(itr.next()); // // Update VM by enabling System-MSI and add two identities - virtualMachineScaleSet - .update() + virtualMachineScaleSet.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) @@ -248,11 +220,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachineScaleSet - .managedServiceIdentityType() - .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue(virtualMachineScaleSet.managedServiceIdentityType() + .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); // Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); @@ -261,11 +230,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachineScaleSet - .managedServiceIdentityType() - .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue(virtualMachineScaleSet.managedServiceIdentityType() + .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); // Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); @@ -277,11 +243,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachineScaleSet - .managedServiceIdentityType() - .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); + Assertions.assertTrue(virtualMachineScaleSet.managedServiceIdentityType() + .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); // Remove identities one by one (second one) @@ -289,9 +252,8 @@ public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { // Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); + Assertions.assertTrue( + virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); // virtualMachineScaleSet.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); @@ -310,61 +272,51 @@ public void canCreateVirtualMachineScaleSetWithLMSIAndEMSI() throws Exception { // Create a virtual network to which we will assign "EMSI" with reader access // - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create a virtual network for VMSS // - Network vmssNetwork = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network vmssNetwork = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); // Create a Load balancer for VMSS // LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); @@ -386,45 +338,33 @@ public void canCreateVirtualMachineScaleSetWithLMSIAndEMSI() throws Exception { // if (!isPlaybackMode()) { // principalId redacted - PagedIterable roleAssignmentsForNetwork = - this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); + PagedIterable roleAssignmentsForNetwork + = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() + && roleAssignment.principalId() .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertTrue( - found, - "Expected role assignment not found for the virtual network for local identity" - + virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); - - RoleAssignment assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - network.id(), - BuiltInRole.CONTRIBUTOR, - virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()) - .block(); + Assertions.assertTrue(found, "Expected role assignment not found for the virtual network for local identity" + + virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); - Assertions - .assertNotNull( - assignment, - "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); + RoleAssignment assignment + = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.CONTRIBUTOR, + virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()).block(); + + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); // Ensure expected role assignment exists for EMSI // - PagedIterable roleAssignmentsForResourceGroup = - this - .msiManager - .authorizationManager() - .roleAssignments() - .listByScope( - resourceManager.resourceGroups().getByName(virtualMachineScaleSet.resourceGroupName()).id()); + PagedIterable roleAssignmentsForResourceGroup = this.msiManager.authorizationManager() + .roleAssignments() + .listByScope( + resourceManager.resourceGroups().getByName(virtualMachineScaleSet.resourceGroupName()).id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null @@ -433,19 +373,14 @@ public void canCreateVirtualMachineScaleSetWithLMSIAndEMSI() throws Exception { break; } } - Assertions - .assertTrue( - found, "Expected role assignment not found for the resource group for identity" + identity.name()); + Assertions.assertTrue(found, + "Expected role assignment not found for the resource group for identity" + identity.name()); - assignment = - lookupRoleAssignmentUsingScopeAndRoleAsync( - resourceGroup.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) - .block(); + assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(resourceGroup.id(), BuiltInRole.CONTRIBUTOR, + identity.principalId()).block(); - Assertions - .assertNotNull( - assignment, - "Expected role assignment with ROLE not found for the resource group for system assigned identity"); + Assertions.assertNotNull(assignment, + "Expected role assignment with ROLE not found for the resource group for system assigned identity"); } } @@ -456,59 +391,52 @@ public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { // Create a virtual network for VMSS // - Network vmssNetwork = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network vmssNetwork = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); // Create a Load balancer for VMSS // LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the // resource group // it resides // - Creatable creatableIdentity = - msiManager - .identities() - .define(identityName1) - .withRegion(region) - .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = msiManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Update virtual machine so that it depends on the EMSI // - virtualMachineScaleSet = - virtualMachineScaleSet.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); + virtualMachineScaleSet + = virtualMachineScaleSet.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine // Set emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); - Optional emsiIdOptional = emsiIds.stream().filter(emsiId -> emsiId.endsWith("/" + identityName1)).findAny(); + Optional emsiIdOptional + = emsiIds.stream().filter(emsiId -> emsiId.endsWith("/" + identityName1)).findAny(); Assertions.assertTrue(emsiIdOptional.isPresent()); Identity identity = msiManager.identities().getById(emsiIdOptional.get()); @@ -516,9 +444,7 @@ public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); // Update VMSS without modify MSI - virtualMachineScaleSet.update() - .withNewDataDisk(10) - .apply(); + virtualMachineScaleSet.update().withNewDataDisk(10).apply(); emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); emsiIdOptional = emsiIds.stream().filter(emsiId -> emsiId.endsWith("/" + identityName1)).findAny(); @@ -526,23 +452,19 @@ public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { // Creates an EMSI // - Identity createdIdentity = - msiManager - .identities() - .define(identityName2) - .withRegion(region) - .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .create(); + Identity createdIdentity = msiManager.identities() + .define(identityName2) + .withRegion(region) + .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .create(); // Update the virtual machine by removing the an EMSI and adding existing EMSI // - virtualMachineScaleSet = - virtualMachineScaleSet - .update() - .withoutUserAssignedManagedServiceIdentity(identity.id()) - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .apply(); + virtualMachineScaleSet = virtualMachineScaleSet.update() + .withoutUserAssignedManagedServiceIdentity(identity.id()) + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .apply(); // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine // @@ -566,24 +488,17 @@ public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); } - private Mono lookupRoleAssignmentUsingScopeAndRoleAsync( - final String scope, BuiltInRole role, final String principalId) { - return this - .msiManager - .authorizationManager() + private Mono lookupRoleAssignmentUsingScopeAndRoleAsync(final String scope, BuiltInRole role, + final String principalId) { + return this.msiManager.authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) - .flatMap( - roleDefinition -> - msiManager - .authorizationManager() - .roleAssignments() - .listByScopeAsync(scope) - .filter( - roleAssignment -> - roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) - && roleAssignment.principalId().equalsIgnoreCase(principalId)) - .singleOrEmpty()) + .flatMap(roleDefinition -> msiManager.authorizationManager() + .roleAssignments() + .listByScopeAsync(scope) + .filter(roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) + && roleAssignment.principalId().equalsIgnoreCase(principalId)) + .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetManagedDiskOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetManagedDiskOperationsTests.java index b1f96be41b33e..9baad1c14ef03 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetManagedDiskOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetManagedDiskOperationsTests.java @@ -51,37 +51,31 @@ public void canCreateUpdateVirtualMachineScaleSetFromPIRWithManagedDisk() throws ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define(generateRandomResourceName("vmssvnet", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define(generateRandomResourceName("vmssvnet", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1"); - VirtualMachineScaleSet vmScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - .withNewDataDisk(100, 2, CachingTypes.READ_ONLY) - .withOSDiskStorageAccountType(StorageAccountTypes.PREMIUM_LRS) // Override the default STANDARD_LRS - .create(); + VirtualMachineScaleSet vmScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_DS1_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + .withNewDataDisk(100, 2, CachingTypes.READ_ONLY) + .withOSDiskStorageAccountType(StorageAccountTypes.PREMIUM_LRS) // Override the default STANDARD_LRS + .create(); Assertions.assertTrue(vmScaleSet.managedOSDiskStorageAccountType().equals(StorageAccountTypes.PREMIUM_LRS)); VirtualMachineScaleSetVMs virtualMachineScaleSetVMs = vmScaleSet.virtualMachines(); @@ -112,16 +106,13 @@ public void canCreateUpdateVirtualMachineScaleSetFromPIRWithManagedDisk() throws // test attach/detach data disk to single instance final String diskName = generateRandomResourceName("disk", 10); - Disk disk0 = - this - .computeManager - .disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(32) - .create(); + Disk disk0 = this.computeManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(32) + .create(); Iterator vmIterator = virtualMachines.iterator(); VirtualMachineScaleSetVM vm0 = vmIterator.next(); @@ -155,8 +146,7 @@ public void canCreateUpdateVirtualMachineScaleSetFromPIRWithManagedDisk() throws // cannot attach disk with same lun expectedException = null; try { - vm0 - .update() + vm0.update() .withExistingDataDisk(disk0, newDiskLun, CachingTypes.NONE) .withExistingDataDisk(disk0, newDiskLun, CachingTypes.NONE); } catch (IllegalStateException e) { @@ -194,30 +184,27 @@ public void canCreateVirtualMachineScaleSetFromCustomImageWithManagedDisk() thro ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - VirtualMachine vm = - this - .computeManager - .virtualMachines() - .define(generateRandomResourceName("vm", 10)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(100) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine vm = this.computeManager.virtualMachines() + .define(generateRandomResourceName("vm", 10)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(100) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); Assertions.assertNotNull(vm); @@ -229,45 +216,36 @@ public void canCreateVirtualMachineScaleSetFromCustomImageWithManagedDisk() thro vm.deallocate(); vm.generalize(); - VirtualMachineCustomImage virtualMachineCustomImage = - this - .computeManager - .virtualMachineCustomImages() - .define(customImageName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .fromVirtualMachine(vm) - .create(); + VirtualMachineCustomImage virtualMachineCustomImage = this.computeManager.virtualMachineCustomImages() + .define(customImageName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .fromVirtualMachine(vm) + .create(); Assertions.assertNotNull(virtualMachineCustomImage); - Network network = - this - .networkManager - .networks() - .define(generateRandomResourceName("vmssvnet", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define(generateRandomResourceName("vmssvnet", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1"); - VirtualMachineScaleSet vmScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D1_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withoutPrimaryInternalLoadBalancer() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey()) - .create(); + VirtualMachineScaleSet vmScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D1_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withoutPrimaryInternalLoadBalancer() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey()) + .create(); VirtualMachineScaleSetVMs virtualMachineScaleSetVMs = vmScaleSet.virtualMachines(); PagedIterable virtualMachines = virtualMachineScaleSetVMs.list(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetOperationsTests.java index c0462db2e1130..aad771a62242a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetOperationsTests.java @@ -100,47 +100,38 @@ public void canCreateVMSSWithPlan() { ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); final String uname = "jvuser"; - Network network = - this - .networkManager - .networks() - .define(generateRandomResourceName("vmssvnet", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - PurchasePlan plan = new PurchasePlan() - .withName("openvpnas") - .withPublisher("openvpn") - .withProduct("openvpnas"); - - ImageReference imageReference = new ImageReference() - .withPublisher("openvpn") + Network network = this.networkManager.networks() + .define(generateRandomResourceName("vmssvnet", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + PurchasePlan plan = new PurchasePlan().withName("openvpnas").withPublisher("openvpn").withProduct("openvpnas"); + + ImageReference imageReference = new ImageReference().withPublisher("openvpn") .withOffer("openvpnas") .withSku("openvpnas") .withVersion("latest"); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withoutPrimaryInternalLoadBalancer() - .withSpecificLinuxImageVersion(imageReference) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withNewDataDisk(1) - .withPlan(plan) - .create(); - - VirtualMachineScaleSet currentVirtualMachineScaleSet = this.computeManager.virtualMachineScaleSets().getByResourceGroup(rgName, vmssName); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withoutPrimaryInternalLoadBalancer() + .withSpecificLinuxImageVersion(imageReference) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withNewDataDisk(1) + .withPlan(plan) + .create(); + + VirtualMachineScaleSet currentVirtualMachineScaleSet + = this.computeManager.virtualMachineScaleSets().getByResourceGroup(rgName, vmssName); // assertion for purchase plan Assertions.assertEquals("openvpnas", currentVirtualMachineScaleSet.plan().name()); Assertions.assertEquals("openvpn", currentVirtualMachineScaleSet.plan().publisher()); @@ -156,58 +147,49 @@ public void canUpdateVirtualMachineScaleSetWithExtensionProtectedSettings() thro ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - StorageAccount storageAccount = - this - .storageManager - .storageAccounts() - .define(generateRandomResourceName("stg", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + StorageAccount storageAccount = this.storageManager.storageAccounts() + .define(generateRandomResourceName("stg", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); List keys = storageAccount.getKeys(); Assertions.assertNotNull(keys); Assertions.assertTrue(keys.size() > 0); String storageAccountKey = keys.get(0).value(); - Network network = - this - .networkManager - .networks() - .define(generateRandomResourceName("vmssvnet", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .withExistingStorageAccount(storageAccount) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("commandToExecute", "ls") - .withProtectedSetting("storageAccountName", storageAccount.name()) - .withProtectedSetting("storageAccountKey", storageAccountKey) - .attach() - .create(); + Network network = this.networkManager.networks() + .define(generateRandomResourceName("vmssvnet", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .withExistingStorageAccount(storageAccount) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("commandToExecute", "ls") + .withProtectedSetting("storageAccountName", storageAccount.name()) + .withProtectedSetting("storageAccountKey", storageAccountKey) + .attach() + .create(); // Validate extensions after create // Map extensions = virtualMachineScaleSet.extensions(); @@ -219,8 +201,8 @@ public void canUpdateVirtualMachineScaleSetWithExtensionProtectedSettings() thro Assertions.assertEquals(1, extension.publicSettings().size()); Assertions.assertNotNull(extension.publicSettingsAsJsonString()); // Retrieve scale set - VirtualMachineScaleSet scaleSet = - this.computeManager.virtualMachineScaleSets().getById(virtualMachineScaleSet.id()); + VirtualMachineScaleSet scaleSet + = this.computeManager.virtualMachineScaleSets().getById(virtualMachineScaleSet.id()); // Validate extensions after get // extensions = scaleSet.extensions(); @@ -255,44 +237,38 @@ public void canCreateVirtualMachineScaleSetWithCustomScriptExtension() throws Ex ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define(generateRandomResourceName("vmssvnet", 15)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define(generateRandomResourceName("vmssvnet", 15)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1"); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(uname) - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("commandToExecute", "ls") - .attach() - .withUpgradeMode(UpgradeMode.MANUAL) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(uname) + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("commandToExecute", "ls") + .attach() + .withUpgradeMode(UpgradeMode.MANUAL) + .create(); checkVMInstances(virtualMachineScaleSet); @@ -301,13 +277,13 @@ public void canCreateVirtualMachineScaleSetWithCustomScriptExtension() throws Ex String fqdn = publicIPAddress.fqdn(); Assertions.assertNotNull(fqdn); -// // Assert public load balancing connection -// if (!isPlaybackMode()) { -// HttpClient client = HttpClient.createDefault(); -// HttpRequest request = new HttpRequest(HttpMethod.GET, "http://" + fqdn); -// HttpResponse response = client.send(request).block(); -// Assertions.assertEquals(response.getStatusCode(), 200); -// } + // // Assert public load balancing connection + // if (!isPlaybackMode()) { + // HttpClient client = HttpClient.createDefault(); + // HttpRequest request = new HttpRequest(HttpMethod.GET, "http://" + fqdn); + // HttpResponse response = client.send(request).block(); + // Assertions.assertEquals(response.getStatusCode(), 200); + // } // Check SSH to VM instances via Nat rule // @@ -328,8 +304,8 @@ public void canCreateVirtualMachineScaleSetWithCustomScriptExtension() throws Ex } Assertions.assertNotNull(sshFrontendPort); -// this.sleep(1000 * 60); // Wait some time for VM to be available -// this.ensureCanDoSsh(fqdn, sshFrontendPort, uname, password); + // this.sleep(1000 * 60); // Wait some time for VM to be available + // this.ensureCanDoSsh(fqdn, sshFrontendPort, uname, password); } } @@ -342,47 +318,38 @@ public void canCreateVirtualMachineScaleSetWithOptionalNetworkSettings() throws ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - ApplicationSecurityGroup asg = - this - .networkManager - .applicationSecurityGroups() - .define(asgName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + ApplicationSecurityGroup asg = this.networkManager.applicationSecurityGroups() + .define(asgName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); // Create VMSS with instance public ip - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withVirtualMachinePublicIp(vmssVmDnsLabel) - .withExistingApplicationSecurityGroup(asg) - .create(); - - VirtualMachineScaleSetPublicIpAddressConfiguration currentIpConfig = - virtualMachineScaleSet.virtualMachinePublicIpConfig(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withVirtualMachinePublicIp(vmssVmDnsLabel) + .withExistingApplicationSecurityGroup(asg) + .create(); + + VirtualMachineScaleSetPublicIpAddressConfiguration currentIpConfig + = virtualMachineScaleSet.virtualMachinePublicIpConfig(); Assertions.assertNotNull(currentIpConfig); Assertions.assertNotNull(currentIpConfig.dnsSettings()); @@ -407,24 +374,21 @@ public void canCreateVirtualMachineScaleSetWithOptionalNetworkSettings() throws Assertions.assertNotNull(asgIds); Assertions.assertEquals(1, asgIds.size()); - NetworkSecurityGroup nsg = - networkManager - .networkSecurityGroups() - .define(nsgName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .defineRule("rule1") - .allowOutbound() - .fromAnyAddress() - .fromPort(80) - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() - .create(); + NetworkSecurityGroup nsg = networkManager.networkSecurityGroups() + .define(nsgName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .defineRule("rule1") + .allowOutbound() + .fromAnyAddress() + .fromPort(80) + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() + .create(); virtualMachineScaleSet.deallocate(); - virtualMachineScaleSet - .update() + virtualMachineScaleSet.update() .withIpForwarding() .withAcceleratedNetworking() .withExistingNetworkSecurityGroup(nsg) @@ -440,8 +404,7 @@ public void canCreateVirtualMachineScaleSetWithOptionalNetworkSettings() throws Assertions.assertTrue(virtualMachineScaleSet.isAcceleratedNetworkingEnabled()); Assertions.assertNotNull(virtualMachineScaleSet.networkSecurityGroupId()); - virtualMachineScaleSet - .update() + virtualMachineScaleSet.update() .withoutIpForwarding() .withoutAcceleratedNetworking() .withoutNetworkSecurityGroup() @@ -460,19 +423,16 @@ public void canCreateVirtualMachineScaleSetWithSecret() throws Exception { ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -480,52 +440,42 @@ public void canCreateVirtualMachineScaleSetWithSecret() throws Exception { } Assertions.assertTrue(backends.size() == 2); - Vault vault = - this - .keyVaultManager - .vaults() - .define(vaultName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowSecretAllPermissions() - .attach() - .withDeploymentEnabled() - .create(); - final InputStream embeddedJsonConfig = - this.getClass().getResourceAsStream("/myTest.txt"); + Vault vault = this.keyVaultManager.vaults() + .define(vaultName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .defineAccessPolicy() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowSecretAllPermissions() + .attach() + .withDeploymentEnabled() + .create(); + final InputStream embeddedJsonConfig = this.getClass().getResourceAsStream("/myTest.txt"); String secretValue = IOUtils.toString(embeddedJsonConfig, StandardCharsets.UTF_8); Secret secret = vault.secrets().define(secretName).withValue(secretValue).create(); List certs = new ArrayList<>(); certs.add(new VaultCertificate().withCertificateUrl(secret.id())); List group = new ArrayList<>(); - group - .add( - new VaultSecretGroup() - .withSourceVault(new SubResource().withId(vault.id())) - .withVaultCertificates(certs)); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withSecrets(group) - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .withNewStorageAccount(generateRandomResourceName("stg3", 15)) - .withUpgradeMode(UpgradeMode.MANUAL) - .create(); + group.add( + new VaultSecretGroup().withSourceVault(new SubResource().withId(vault.id())).withVaultCertificates(certs)); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withSecrets(group) + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .withNewStorageAccount(generateRandomResourceName("stg3", 15)) + .withUpgradeMode(UpgradeMode.MANUAL) + .create(); for (VirtualMachineScaleSetVM vm : virtualMachineScaleSet.virtualMachines().list()) { Assertions.assertTrue(vm.osProfile().secrets().size() > 0); @@ -543,44 +493,38 @@ public void canCreateVirtualMachineScaleSet() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { backends.add(backend); } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withUnmanagedDisks() - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withUnmanagedDisks() + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .create(); // Validate Network specific properties (LB, VNet, NIC, IPConfig etc..) // @@ -627,10 +571,8 @@ public void canCreateVirtualMachineScaleSet() throws Exception { for (Map.Entry ruleEntry : lbRules.entrySet()) { LoadBalancingRule rule = ruleEntry.getValue(); Assertions.assertNotNull(rule); - Assertions - .assertTrue( - (rule.frontendPort() == 80 && rule.backendPort() == 80) - || (rule.frontendPort() == 443 && rule.backendPort() == 443)); + Assertions.assertTrue((rule.frontendPort() == 80 && rule.backendPort() == 80) + || (rule.frontendPort() == 443 && rule.backendPort() == 443)); } } List lbNatRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); @@ -638,10 +580,8 @@ public void canCreateVirtualMachineScaleSet() throws Exception { // nat rules in ip-config as well Assertions.assertEquals(lbNatRules.size(), 2); for (LoadBalancerInboundNatRule lbNatRule : lbNatRules) { - Assertions - .assertTrue( - (lbNatRule.frontendPort() >= 5000 && lbNatRule.frontendPort() <= 5099) - || (lbNatRule.frontendPort() >= 6000 && lbNatRule.frontendPort() <= 6099)); + Assertions.assertTrue((lbNatRule.frontendPort() >= 5000 && lbNatRule.frontendPort() <= 5099) + || (lbNatRule.frontendPort() >= 6000 && lbNatRule.frontendPort() <= 6099)); Assertions.assertTrue(lbNatRule.backendPort() == 22 || lbNatRule.backendPort() == 23); } } @@ -659,16 +599,15 @@ public void canCreateVirtualMachineScaleSet() throws Exception { primaryNetwork = virtualMachineScaleSet.getPrimaryNetwork(); String inboundNatPoolToRemove = null; - for (String inboundNatPoolName - : virtualMachineScaleSet.listPrimaryInternetFacingLoadBalancerInboundNatPools().keySet()) { + for (String inboundNatPoolName : virtualMachineScaleSet.listPrimaryInternetFacingLoadBalancerInboundNatPools() + .keySet()) { inboundNatPoolToRemove = inboundNatPoolName; break; } LoadBalancer internalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, primaryNetwork, "1"); - virtualMachineScaleSet - .update() + virtualMachineScaleSet.update() .withExistingPrimaryInternalLoadBalancer(internalLoadBalancer) .withoutPrimaryInternetFacingLoadBalancerNatPools(inboundNatPoolToRemove) // Remove one NatPool .apply(); @@ -711,12 +650,10 @@ public void canCreateVirtualMachineScaleSet() throws Exception { for (Map.Entry ruleEntry : lbRules.entrySet()) { LoadBalancingRule rule = ruleEntry.getValue(); Assertions.assertNotNull(rule); - Assertions - .assertTrue( - (rule.frontendPort() == 80 && rule.backendPort() == 80) - || (rule.frontendPort() == 443 && rule.backendPort() == 443) - || (rule.frontendPort() == 1000 && rule.backendPort() == 1000) - || (rule.frontendPort() == 1001 && rule.backendPort() == 1001)); + Assertions.assertTrue((rule.frontendPort() == 80 && rule.backendPort() == 80) + || (rule.frontendPort() == 443 && rule.backendPort() == 443) + || (rule.frontendPort() == 1000 && rule.backendPort() == 1000) + || (rule.frontendPort() == 1001 && rule.backendPort() == 1001)); } } List lbNatRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); @@ -728,19 +665,15 @@ public void canCreateVirtualMachineScaleSet() throws Exception { // Assertions.assertEquals(lbNatRules.size(), 3); for (LoadBalancerInboundNatRule lbNatRule : lbNatRules) { // As mentioned above some chnages are not propgating to all VM instances 6000+ should be there - Assertions - .assertTrue( - (lbNatRule.frontendPort() >= 6000 && lbNatRule.frontendPort() <= 6099) - || (lbNatRule.frontendPort() >= 5000 && lbNatRule.frontendPort() <= 5099) - || (lbNatRule.frontendPort() >= 8000 && lbNatRule.frontendPort() <= 8099) - || (lbNatRule.frontendPort() >= 9000 && lbNatRule.frontendPort() <= 9099)); + Assertions.assertTrue((lbNatRule.frontendPort() >= 6000 && lbNatRule.frontendPort() <= 6099) + || (lbNatRule.frontendPort() >= 5000 && lbNatRule.frontendPort() <= 5099) + || (lbNatRule.frontendPort() >= 8000 && lbNatRule.frontendPort() <= 8099) + || (lbNatRule.frontendPort() >= 9000 && lbNatRule.frontendPort() <= 9099)); // Same as above - Assertions - .assertTrue( - lbNatRule.backendPort() == 23 - || lbNatRule.backendPort() == 22 - || lbNatRule.backendPort() == 44 - || lbNatRule.backendPort() == 45); + Assertions.assertTrue(lbNatRule.backendPort() == 23 + || lbNatRule.backendPort() == 22 + || lbNatRule.backendPort() == 44 + || lbNatRule.backendPort() == 45); } } } @@ -761,25 +694,21 @@ public void canCreateTwoRegionalVMScaleSetsWithDifferentPoolOfZoneResilientLoadB Region region2 = Region.US_EAST2; - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().define(rgName).withRegion(region2).create(); + ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region2).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region2) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region2) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); // Creates a STANDARD LB with one public frontend ip configuration with two backend pools // Each address pool of STANDARD LB can hold different VMSS resource. // - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region2, resourceGroup, "1", LoadBalancerSkuType.STANDARD); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region2, resourceGroup, "1", LoadBalancerSkuType.STANDARD); // With default LB SKU BASIC, an attempt to associate two different VMSS to different // backend pool will cause below error (more accurately, while trying to put second VMSS) @@ -810,44 +739,38 @@ public void canCreateTwoRegionalVMScaleSetsWithDifferentPoolOfZoneResilientLoadB final String vmssName1 = generateRandomResourceName("vmss1", 10); // HTTP goes to this virtual machine scale set // - VirtualMachineScaleSet virtualMachineScaleSet1 = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName1) - .withRegion(region2) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0)) // This VMSS in the first backend pool - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(0)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet1 = this.computeManager.virtualMachineScaleSets() + .define(vmssName1) + .withRegion(region2) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0)) // This VMSS in the first backend pool + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(0)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .create(); final String vmssName2 = generateRandomResourceName("vmss2", 10); // HTTPS goes to this virtual machine scale set // - VirtualMachineScaleSet virtualMachineScaleSet2 = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName2) - .withRegion(region2) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(1)) // This VMSS in the second backend pool - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet2 = this.computeManager.virtualMachineScaleSets() + .define(vmssName2) + .withRegion(region2) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(1)) // This VMSS in the second backend pool + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .create(); // Validate Network specific properties (LB, VNet, NIC, IPConfig etc..) // @@ -873,27 +796,23 @@ public void canCreateZoneRedundantVirtualMachineScaleSetWithZoneResilientLoadBal Region region2 = Region.US_EAST2; - ResourceGroup resourceGroup = - this.resourceManager.resourceGroups().define(rgName).withRegion(region2).create(); + ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region2).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region2) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region2) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); // Zone redundant VMSS requires STANDARD LB // // Creates a STANDARD LB with one public frontend ip configuration with two backend pools // Each address pool of STANDARD LB can hold different VMSS resource. // - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region2, resourceGroup, "1", LoadBalancerSkuType.STANDARD); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region2, resourceGroup, "1", LoadBalancerSkuType.STANDARD); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -905,24 +824,21 @@ public void canCreateZoneRedundantVirtualMachineScaleSetWithZoneResilientLoadBal // HTTP & HTTPS traffic on port 80, 443 of Internet-facing LB goes to corresponding port in virtual machine // scale set // - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region2) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) // Zone redundant - zone 1 + zone 2 - .withAvailabilityZone(AvailabilityZoneId.ZONE_2) - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region2) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) // Zone redundant - zone 1 + zone 2 + .withAvailabilityZone(AvailabilityZoneId.ZONE_2) + .create(); // Check zones // @@ -948,44 +864,39 @@ public void canCreateZoneRedundantVirtualMachineScaleSetWithZoneResilientLoadBal public void canEnableMSIOnVirtualMachineScaleSetWithoutRoleAssignment() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); Region localRegion = Region.US_WEST2; - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(localRegion).create(); - - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(localRegion) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(localRegion, resourceGroup, "1", LoadBalancerSkuType.BASIC); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(localRegion).create(); + + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(localRegion) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(localRegion, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { backends.add(backend); } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(localRegion) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withSystemAssignedManagedServiceIdentity() - .create(); + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(localRegion) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withSystemAssignedManagedServiceIdentity() + .create(); // Validate service created service principal // @@ -1002,21 +913,20 @@ public void canEnableMSIOnVirtualMachineScaleSetWithoutRoleAssignment() throws E // if (!isPlaybackMode()) { // principalId redacted - PagedIterable rgRoleAssignments = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + PagedIterable rgRoleAssignments + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(rgRoleAssignments); boolean found = false; for (RoleAssignment roleAssignment : rgRoleAssignments) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() - .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { + && roleAssignment.principalId() + .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertFalse( - found, "Resource group should not have a role assignment with virtual machine scale set MSI principal"); + Assertions.assertFalse(found, + "Resource group should not have a role assignment with virtual machine scale set MSI principal"); } } @@ -1025,58 +935,48 @@ public void canEnableMSIOnVirtualMachineScaleSetWithMultipleRoleAssignment() thr final String vmssName = generateRandomResourceName("vmss", 10); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { backends.add(backend); } Assertions.assertTrue(backends.size() == 2); - StorageAccount storageAccount = - this - .storageManager - .storageAccounts() - .define(generateRandomResourceName("jvcsrg", 10)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); - - VirtualMachineScaleSet virtualMachineScaleSet = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .withSystemAssignedIdentityBasedAccessTo(storageAccount.id(), BuiltInRole.CONTRIBUTOR) - .create(); + StorageAccount storageAccount = this.storageManager.storageAccounts() + .define(generateRandomResourceName("jvcsrg", 10)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); + + VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withSystemAssignedIdentityBasedAccessTo(storageAccount.id(), BuiltInRole.CONTRIBUTOR) + .create(); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); - Assertions - .assertTrue( - virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); + Assertions.assertTrue( + virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); // Validate service created service principal // @@ -1091,40 +991,37 @@ public void canEnableMSIOnVirtualMachineScaleSetWithMultipleRoleAssignment() thr // Ensure role assigned for resource group // - PagedIterable rgRoleAssignments = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); + PagedIterable rgRoleAssignments + = authorizationManager.roleAssignments().listByScope(resourceGroup.id()); Assertions.assertNotNull(rgRoleAssignments); boolean found = false; for (RoleAssignment roleAssignment : rgRoleAssignments) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() - .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { + && roleAssignment.principalId() + .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertTrue( - found, "Resource group should have a role assignment with virtual machine scale set MSI principal"); + Assertions.assertTrue(found, + "Resource group should have a role assignment with virtual machine scale set MSI principal"); // Ensure role assigned for storage account // - PagedIterable stgRoleAssignments = - authorizationManager.roleAssignments().listByScope(storageAccount.id()); + PagedIterable stgRoleAssignments + = authorizationManager.roleAssignments().listByScope(storageAccount.id()); Assertions.assertNotNull(stgRoleAssignments); found = false; for (RoleAssignment roleAssignment : stgRoleAssignments) { if (roleAssignment.principalId() != null - && roleAssignment - .principalId() - .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { + && roleAssignment.principalId() + .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } - Assertions - .assertTrue( - found, "Storage account should have a role assignment with virtual machine scale set MSI principal"); + Assertions.assertTrue(found, + "Storage account should have a role assignment with virtual machine scale set MSI principal"); } @Test @@ -1133,19 +1030,16 @@ public void canGetSingleVMSSInstance() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -1153,9 +1047,7 @@ public void canGetSingleVMSSInstance() throws Exception { } Assertions.assertTrue(backends.size() == 2); - this - .computeManager - .virtualMachineScaleSets() + this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -1172,14 +1064,14 @@ public void canGetSingleVMSSInstance() throws Exception { .withUpgradeMode(UpgradeMode.MANUAL) .create(); - VirtualMachineScaleSet virtualMachineScaleSet = - this.computeManager.virtualMachineScaleSets().getByResourceGroup(rgName, vmssName); + VirtualMachineScaleSet virtualMachineScaleSet + = this.computeManager.virtualMachineScaleSets().getByResourceGroup(rgName, vmssName); VirtualMachineScaleSetVMs virtualMachineScaleSetVMs = virtualMachineScaleSet.virtualMachines(); VirtualMachineScaleSetVM firstVm = virtualMachineScaleSetVMs.list().iterator().next(); VirtualMachineScaleSetVM fetchedVm = virtualMachineScaleSetVMs.getInstance(firstVm.instanceId()); this.checkVmsEqual(firstVm, fetchedVm); - VirtualMachineScaleSetVM fetchedAsyncVm = - virtualMachineScaleSetVMs.getInstanceAsync(firstVm.instanceId()).block(); + VirtualMachineScaleSetVM fetchedAsyncVm + = virtualMachineScaleSetVMs.getInstanceAsync(firstVm.instanceId()).block(); this.checkVmsEqual(firstVm, fetchedAsyncVm); } @@ -1188,19 +1080,16 @@ public void canCreateLowPriorityVMSSInstance() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); - LoadBalancer publicLoadBalancer = - createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD); + LoadBalancer publicLoadBalancer + = createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD); List backends = new ArrayList<>(); for (String backend : publicLoadBalancer.backends().keySet()) { @@ -1208,27 +1097,24 @@ public void canCreateLowPriorityVMSSInstance() throws Exception { } Assertions.assertTrue(backends.size() == 2); - VirtualMachineScaleSet vmss = - this - .computeManager - .virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("jvuser") - .withSsh(sshPublicKey()) - .withNewStorageAccount(generateRandomResourceName("stg", 15)) - .withNewStorageAccount(generateRandomResourceName("stg3", 15)) - .withUpgradeMode(UpgradeMode.MANUAL) - .withLowPriorityVirtualMachine(VirtualMachineEvictionPolicyTypes.DEALLOCATE) - .withMaxPrice(-1.0) - .create(); + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("jvuser") + .withSsh(sshPublicKey()) + .withNewStorageAccount(generateRandomResourceName("stg", 15)) + .withNewStorageAccount(generateRandomResourceName("stg3", 15)) + .withUpgradeMode(UpgradeMode.MANUAL) + .withLowPriorityVirtualMachine(VirtualMachineEvictionPolicyTypes.DEALLOCATE) + .withMaxPrice(-1.0) + .create(); Assertions.assertEquals(vmss.virtualMachinePriority(), VirtualMachinePriorityTypes.LOW); Assertions.assertEquals(vmss.virtualMachineEvictionPolicy(), VirtualMachineEvictionPolicyTypes.DEALLOCATE); @@ -1245,8 +1131,7 @@ public void canListInstancesIncludingInstanceView() { final String vmssName = generateRandomResourceName("vmss", 10); - Network network = this.networkManager - .networks() + Network network = this.networkManager.networks() .define("vmssvnet") .withRegion(region) .withNewResourceGroup(rgName) @@ -1254,8 +1139,7 @@ public void canListInstancesIncludingInstanceView() { .withSubnet("subnet1", "10.0.0.0/28") .create(); - this.computeManager - .virtualMachineScaleSets() + this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1272,10 +1156,14 @@ public void canListInstancesIncludingInstanceView() { // list with VirtualMachineScaleSetVMExpandType.INSTANCE_VIEW VirtualMachineScaleSet vmss = computeManager.virtualMachineScaleSets().getByResourceGroup(rgName, vmssName); - List vmInstances = vmss.virtualMachines().list(null, VirtualMachineScaleSetVMExpandType.INSTANCE_VIEW).stream().collect(Collectors.toList()); + List vmInstances = vmss.virtualMachines() + .list(null, VirtualMachineScaleSetVMExpandType.INSTANCE_VIEW) + .stream() + .collect(Collectors.toList()); Assertions.assertEquals(3, vmInstances.size()); Assertions.assertTrue(vmInstances.stream().allMatch(vm -> vm.timeCreated() != null)); - List powerStates = vmInstances.stream().map(VirtualMachineScaleSetVM::powerState).collect(Collectors.toList()); + List powerStates + = vmInstances.stream().map(VirtualMachineScaleSetVM::powerState).collect(Collectors.toList()); Assertions.assertEquals(Arrays.asList(PowerState.RUNNING, PowerState.RUNNING, PowerState.RUNNING), powerStates); // update status of VM and check again @@ -1283,7 +1171,8 @@ public void canListInstancesIncludingInstanceView() { computeManager.serviceClient().getVirtualMachineScaleSetVMs().deallocate(rgName, vmssName, firstInstanceId); vmInstances.get(0).refresh(); powerStates = vmInstances.stream().map(VirtualMachineScaleSetVM::powerState).collect(Collectors.toList()); - Assertions.assertEquals(Arrays.asList(PowerState.DEALLOCATED, PowerState.RUNNING, PowerState.RUNNING), powerStates); + Assertions.assertEquals(Arrays.asList(PowerState.DEALLOCATED, PowerState.RUNNING, PowerState.RUNNING), + powerStates); // check single VM VirtualMachineScaleSetVM vmInstance0 = vmss.virtualMachines().getInstance(firstInstanceId); @@ -1296,13 +1185,9 @@ public void canListInstancesIncludingInstanceView() { public void canPerformSimulateEvictionOnSpotVMSSInstance() { final String vmssName = generateRandomResourceName("vmss", 10); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups() - .define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); - Network network = this.networkManager - .networks() + Network network = this.networkManager.networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) @@ -1367,7 +1252,8 @@ private void checkVmsEqual(VirtualMachineScaleSetVM original, VirtualMachineScal Assertions.assertEquals(original.extensions().size(), fetched.extensions().size()); Assertions.assertEquals(original.instanceId(), fetched.instanceId()); Assertions.assertEquals(original.isLatestScaleSetUpdateApplied(), fetched.isLatestScaleSetUpdateApplied()); - Assertions.assertEquals(original.isLinuxPasswordAuthenticationEnabled(), fetched.isLinuxPasswordAuthenticationEnabled()); + Assertions.assertEquals(original.isLinuxPasswordAuthenticationEnabled(), + fetched.isLinuxPasswordAuthenticationEnabled()); Assertions.assertEquals(original.isManagedDiskEnabled(), fetched.isManagedDiskEnabled()); Assertions.assertEquals(original.isOSBasedOnCustomImage(), fetched.isOSBasedOnCustomImage()); Assertions.assertEquals(original.isOSBasedOnPlatformImage(), fetched.isOSBasedOnPlatformImage()); @@ -1428,19 +1314,20 @@ private void checkVMInstances(VirtualMachineScaleSet vmScaleSet) { // Check Instance NICs // for (VirtualMachineScaleSetVM vm : virtualMachines) { - PagedIterable nics = - vmScaleSet.listNetworkInterfacesByInstanceId(vm.instanceId()); + PagedIterable nics + = vmScaleSet.listNetworkInterfacesByInstanceId(vm.instanceId()); Assertions.assertNotNull(nics); Assertions.assertEquals(TestUtilities.getSize(nics), 1); VirtualMachineScaleSetNetworkInterface nic = nics.iterator().next(); Assertions.assertNotNull(nic.virtualMachineId()); Assertions.assertTrue(nic.virtualMachineId().toLowerCase().equalsIgnoreCase(vm.id())); Assertions.assertNotNull(vm.listNetworkInterfaces()); - VirtualMachineScaleSetNetworkInterface nicA = - vmScaleSet.getNetworkInterfaceByInstanceId(vm.instanceId(), nic.name()); + VirtualMachineScaleSetNetworkInterface nicA + = vmScaleSet.getNetworkInterfaceByInstanceId(vm.instanceId(), nic.name()); Assertions.assertNotNull(nicA); VirtualMachineScaleSetNetworkInterface nicB = vm.getNetworkInterface(nic.name()); - String nicIdB = vm.getNetworkInterfaceAsync(nic.name()).map(n -> nic.primaryIPConfiguration().networkId()).block(); + String nicIdB + = vm.getNetworkInterfaceAsync(nic.name()).map(n -> nic.primaryIPConfiguration().networkId()).block(); Assertions.assertNotNull(nicB); Assertions.assertNotNull(nicIdB); } @@ -1474,24 +1361,18 @@ public void canDeleteVMSSInstance() throws Exception { String euapRegion = "eastus2euap"; final String vmssName = generateRandomResourceName("vmss", 10); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName) + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(euapRegion).create(); + + Network network = this.networkManager.networks() + .define("vmssvnet") .withRegion(euapRegion) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") .create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(euapRegion) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - VirtualMachineScaleSet vmss = this - .computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(euapRegion) .withExistingResourceGroup(resourceGroup) @@ -1508,7 +1389,9 @@ public void canDeleteVMSSInstance() throws Exception { Assertions.assertEquals(4, vmss.virtualMachines().list().stream().count()); // force delete first 2 instances - List firstTwoIds = vmss.virtualMachines().list().stream() + List firstTwoIds = vmss.virtualMachines() + .list() + .stream() .limit(2) .map(VirtualMachineScaleSetVM::instanceId) .collect(Collectors.toList()); @@ -1517,12 +1400,16 @@ public void canDeleteVMSSInstance() throws Exception { Assertions.assertEquals(2, vmss.virtualMachines().list().stream().count()); // delete next 1 instance - vmss.virtualMachines().deleteInstances(Collections.singleton(vmss.virtualMachines().list().stream().findFirst().get().instanceId()), false); + vmss.virtualMachines() + .deleteInstances( + Collections.singleton(vmss.virtualMachines().list().stream().findFirst().get().instanceId()), false); Assertions.assertEquals(1, vmss.virtualMachines().list().stream().count()); // force delete next 1 instance - computeManager.virtualMachineScaleSets().deleteInstances(rgName, vmssName, Collections.singleton(vmss.virtualMachines().list().stream().findFirst().get().instanceId()), false); + computeManager.virtualMachineScaleSets() + .deleteInstances(rgName, vmssName, + Collections.singleton(vmss.virtualMachines().list().stream().findFirst().get().instanceId()), false); } @Test @@ -1533,26 +1420,21 @@ public void canCreateFlexibleVMSS() throws Exception { .withPlatformFaultDomainCount(1) .withLocation(region.name()); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName) + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(region.name()).create(); + + Network network = this.networkManager.networks() + .define("vmssvnet") .withRegion(region.name()) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") .create(); - - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(region.name()) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); final String vmssName = generateRandomResourceName("vmss", 10); - LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, resourceGroup, "1", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); - VirtualMachineScaleSet vmss = this - .computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region.name()) .withExistingResourceGroup(resourceGroup) @@ -1580,12 +1462,10 @@ public void canUpdateVMSSInCreateOrUpdateMode() throws Exception { String euapRegion = "eastus2euap"; final String vmssName = generateRandomResourceName("vmss", 10); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName) - .withRegion(euapRegion) - .create(); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(euapRegion).create(); - VirtualMachineScaleSet vmss = this.computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(euapRegion) .withExistingResourceGroup(resourceGroup) @@ -1619,29 +1499,24 @@ public void canUpdateVMSSInCreateOrUpdateMode() throws Exception { Assertions.assertFalse(vmss.isManagedDiskEnabled()); // update tag on vmss flex with no profile - vmss.update() - .withTag("tag1", "value1") - .apply(); + vmss.update().withTag("tag1", "value1").apply(); Assertions.assertNotNull(vmss.tags()); Assertions.assertEquals(vmss.tags().get("tag1"), "value1"); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(euapRegion) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - LoadBalancer publicLoadBalancer = createHttpLoadBalancers(Region.fromName(euapRegion), resourceGroup, "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + Network network = this.networkManager.networks() + .define("vmssvnet") + .withRegion(euapRegion) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); + LoadBalancer publicLoadBalancer = createHttpLoadBalancers(Region.fromName(euapRegion), resourceGroup, "1", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); final String vmssVmDnsLabel = generateRandomResourceName("pip", 10); // update vmss, attach profile - vmss = this.computeManager - .virtualMachineScaleSets() + vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(euapRegion) .withExistingResourceGroup(resourceGroup) @@ -1662,13 +1537,9 @@ public void canUpdateVMSSInCreateOrUpdateMode() throws Exception { Assertions.assertNotNull(vmss.getPrimaryNetwork()); // update tag on vmss flex with profile - vmss = this.computeManager - .virtualMachineScaleSets() - .getById(vmss.id()); + vmss = this.computeManager.virtualMachineScaleSets().getById(vmss.id()); Assertions.assertNotNull(vmss); - vmss.update() - .withTag("tag1", "value2") - .apply(); + vmss.update().withTag("tag1", "value2").apply(); Assertions.assertNotNull(vmss.innerModel().virtualMachineProfile()); Assertions.assertNotNull(vmss.tags()); Assertions.assertEquals(vmss.tags().get("tag1"), "value2"); @@ -1691,24 +1562,18 @@ public void canGetOrchestrationType() { String euapRegion = "eastus2euap"; final String vmssName = generateRandomResourceName("vmss", 10); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName) + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(euapRegion).create(); + + Network network = this.networkManager.networks() + .define("vmssvnet") .withRegion(euapRegion) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") .create(); - Network network = - this - .networkManager - .networks() - .define("vmssvnet") - .withRegion(euapRegion) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); - - VirtualMachineScaleSet vmss = this - .computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(euapRegion) .withExistingResourceGroup(resourceGroup) @@ -1726,9 +1591,7 @@ public void canGetOrchestrationType() { // create vmss with flexible orchestration type final String vmssName2 = generateRandomResourceName("vmss", 10); - VirtualMachineScaleSet vmss2 = this - .computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss2 = this.computeManager.virtualMachineScaleSets() .define(vmssName2) .withRegion(euapRegion) .withExistingResourceGroup(rgName) @@ -1744,19 +1607,18 @@ public void npeProtectionTest() throws Exception { String euapRegion = "eastus2euap"; final String vmssName = generateRandomResourceName("vmss", 10); - ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName) - .withRegion(euapRegion) - .create(); + ResourceGroup resourceGroup + = this.resourceManager.resourceGroups().define(rgName).withRegion(euapRegion).create(); - VirtualMachineScaleSet vmss = this.computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(euapRegion) .withExistingResourceGroup(resourceGroup) .withFlexibleOrchestrationMode() .create(); - String excludeMethodsString = "start,startAsync,reimage,reimageAsync,deallocate,deallocateAsync,powerOff,powerOffAsync,restart,restartAsync"; + String excludeMethodsString + = "start,startAsync,reimage,reimageAsync,deallocate,deallocateAsync,powerOff,powerOffAsync,restart,restartAsync"; Set excludeMethods = new HashSet<>(Arrays.asList(excludeMethodsString.split(","))); Set invoked = new HashSet<>(); // invoke all the methods with 0 parameters except those from the exclusion set @@ -1774,8 +1636,7 @@ public void npeProtectionTest() throws Exception { public void canBatchOperateVMSSInstance() { final String vmssName = generateRandomResourceName("vmss", 10); - Network network = this.networkManager - .networks() + Network network = this.networkManager.networks() .define("vmssvnet") .withRegion(region) .withNewResourceGroup(rgName) @@ -1783,8 +1644,7 @@ public void canBatchOperateVMSSInstance() { .withSubnet("subnet1", "10.0.0.0/28") .create(); - VirtualMachineScaleSet vmss = this.computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet vmss = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1809,7 +1669,7 @@ public void canBatchOperateVMSSInstance() { VirtualMachineScaleSetVMs vmInstances = vmss.virtualMachines(); VirtualMachineScaleSetVM vmInstance2 = vmss.virtualMachines().getInstance(instances.get(2).instanceId()); -// vmInstances.reimageInstances(instanceIds); + // vmInstances.reimageInstances(instanceIds); vmInstances.redeployInstances(instanceIds); @@ -1839,8 +1699,7 @@ public void canCreateVMSSWithEphemeralOSDisk() throws Exception { // uniform vmss with ephemeral os disk final String vmssName = generateRandomResourceName("vmss", 10); - Network network = this.networkManager - .networks() + Network network = this.networkManager.networks() .define("vmssvnet") .withRegion(region) .withNewResourceGroup(rgName) @@ -1848,8 +1707,7 @@ public void canCreateVMSSWithEphemeralOSDisk() throws Exception { .withSubnet("subnet1", "10.0.0.0/28") .create(); - VirtualMachineScaleSet uniformVMSS = this.computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet uniformVMSS = this.computeManager.virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -1871,41 +1729,43 @@ public void canCreateVMSSWithEphemeralOSDisk() throws Exception { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); // update VMs to latest model, create baseline - uniformVMSS.virtualMachines().updateInstances( - uniformVMSS.virtualMachines() + uniformVMSS.virtualMachines() + .updateInstances(uniformVMSS.virtualMachines() .list() .stream() .map(VirtualMachineScaleSetVM::instanceId) .toArray(String[]::new)); - Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(VirtualMachineScaleSetVM::isLatestScaleSetUpdateApplied)); + Assertions.assertTrue(uniformVMSS.virtualMachines() + .list() + .stream() + .allMatch(VirtualMachineScaleSetVM::isLatestScaleSetUpdateApplied)); // scale up vmss - uniformVMSS.update() - .withCapacity(2) - .apply(); + uniformVMSS.update().withCapacity(2).apply(); ResourceManagerUtils.sleep(Duration.ofMinutes(1)); // verify that scaling up won't result in outdated VMs - Assertions.assertTrue(uniformVMSS.virtualMachines().list().stream().allMatch(VirtualMachineScaleSetVM::isLatestScaleSetUpdateApplied)); + Assertions.assertTrue(uniformVMSS.virtualMachines() + .list() + .stream() + .allMatch(VirtualMachineScaleSetVM::isLatestScaleSetUpdateApplied)); // flex vmss with ephemeral os disk - Network network2 = - this - .networkManager - .networks() - .define("vmssvnet2") - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("10.1.0.0/16") - .withSubnet("subnet1", "10.1.0.0/16") - .create(); - LoadBalancer publicLoadBalancer = createHttpLoadBalancers(region, this.resourceManager.resourceGroups().getByName(rgName), "1", LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); + Network network2 = this.networkManager.networks() + .define("vmssvnet2") + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("10.1.0.0/16") + .withSubnet("subnet1", "10.1.0.0/16") + .create(); + LoadBalancer publicLoadBalancer + = createHttpLoadBalancers(region, this.resourceManager.resourceGroups().getByName(rgName), "1", + LoadBalancerSkuType.STANDARD, PublicIPSkuType.STANDARD, true); final String vmssName1 = generateRandomResourceName("vmss", 10); - VirtualMachineScaleSet flexVMSS = this.computeManager - .virtualMachineScaleSets() + VirtualMachineScaleSet flexVMSS = this.computeManager.virtualMachineScaleSets() .define(vmssName1) .withRegion(region) .withNewResourceGroup(rgName) @@ -1921,15 +1781,13 @@ public void canCreateVMSSWithEphemeralOSDisk() throws Exception { .withPlacement(DiffDiskPlacement.CACHE_DISK) .create(); Assertions.assertTrue(flexVMSS.isEphemeralOSDisk()); - VirtualMachine instance1 = this.computeManager - .virtualMachines() + VirtualMachine instance1 = this.computeManager.virtualMachines() .getById(flexVMSS.virtualMachines().list().stream().iterator().next().id()); Assertions.assertTrue(instance1.isOSDiskEphemeral()); // can add vm with non-ephemeral os disk to flex vmss with ephemeral os disk vm profile final String vmName = generateRandomResourceName("vm", 10); - VirtualMachine vm = this.computeManager - .virtualMachines() + VirtualMachine vm = this.computeManager.virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) @@ -1954,8 +1812,7 @@ public void canCreateVMSSWithEphemeralOSDisk() throws Exception { public void canCreateVMSSWithProximityPlacementGroup() throws Exception { final String vmssName = generateRandomResourceName("vmss", 10); - Network network = this.networkManager - .networks() + Network network = this.networkManager.networks() .define("vmssvnet") .withRegion(region) .withNewResourceGroup(rgName) @@ -1981,6 +1838,7 @@ public void canCreateVMSSWithProximityPlacementGroup() throws Exception { .create(); Assertions.assertNotNull(vmss.proximityPlacementGroup()); - Assertions.assertEquals(ProximityPlacementGroupType.STANDARD, vmss.proximityPlacementGroup().proximityPlacementGroupType()); + Assertions.assertEquals(ProximityPlacementGroupType.STANDARD, + vmss.proximityPlacementGroup().proximityPlacementGroupType()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/SerializationTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/SerializationTests.java index b5f40d99a096f..e59ef95e2e6cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/SerializationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/SerializationTests.java @@ -41,7 +41,8 @@ public void testIdentity() throws IOException { @Test public void testExtension() throws IOException { // invalid JSON object or JSON string will result in empty settings - VirtualMachineExtensionInner extensionInner = new VirtualMachineExtensionInner().withSettings("invalidJSON").withProtectedSettings("invalidJSON"); + VirtualMachineExtensionInner extensionInner + = new VirtualMachineExtensionInner().withSettings("invalidJSON").withProtectedSettings("invalidJSON"); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl("myExt", null, extensionInner, null); Assertions.assertEquals(0, extension.publicSettings().size()); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java index ff57088d54a4b..2a30ac5a9e491 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java @@ -53,7 +53,9 @@ public void listByVmssByIdWithNextLinkEncoded() { ComputeManager computeManager = mockComputeManager(); - PagedIterable virtualMachines = computeManager.virtualMachines().listByVirtualMachineScaleSetId("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/javacsmrg97796/providers/Microsoft.Compute/virtualMachineScaleSets/vmss035803b7"); + PagedIterable virtualMachines = computeManager.virtualMachines() + .listByVirtualMachineScaleSetId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/javacsmrg97796/providers/Microsoft.Compute/virtualMachineScaleSets/vmss035803b7"); // 1 element per page, 2 pages in total Assertions.assertEquals(2, virtualMachines.stream().count()); Assertions.assertTrue(stateHolder.firstPageRequested); @@ -61,12 +63,11 @@ public void listByVmssByIdWithNextLinkEncoded() { } private ComputeManager mockComputeManager() { - HttpClient httpClient - = mockHttpClient(); - AzureProfile mockProfile = new AzureProfile(UUID.randomUUID().toString(), UUID.randomUUID().toString(), AzureEnvironment.AZURE); - ComputeManager computeManager = ComputeManager.authenticate(new HttpPipelineBuilder() - .httpClient(httpClient).build(), - mockProfile); + HttpClient httpClient = mockHttpClient(); + AzureProfile mockProfile + = new AzureProfile(UUID.randomUUID().toString(), UUID.randomUUID().toString(), AzureEnvironment.AZURE); + ComputeManager computeManager + = ComputeManager.authenticate(new HttpPipelineBuilder().httpClient(httpClient).build(), mockProfile); stateHolder.nextLinkUrl = String.format("%s%s?filter=%s", HOST, NEXT_LINK_PATH, QUERY); return computeManager; } @@ -76,7 +77,8 @@ private HttpClient mockHttpClient() { Map vm; VirtualMachineInner vmInner = mockVmInner(); try { - vm = SERIALIZER.deserialize(SERIALIZER.serialize(vmInner, SerializerEncoding.JSON), Map.class, SerializerEncoding.JSON); + vm = SERIALIZER.deserialize(SERIALIZER.serialize(vmInner, SerializerEncoding.JSON), Map.class, + SerializerEncoding.JSON); } catch (IOException e) { throw new IllegalStateException(e); } @@ -108,37 +110,22 @@ private static Mono failedResponse(HttpRequest request, String err } private static VirtualMachineInner mockVmInner() { - return new VirtualMachineInner() - .withLocation("westus") + return new VirtualMachineInner().withLocation("westus") .withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2)) - .withStorageProfile( - new StorageProfile() - .withImageReference( - new ImageReference() - .withSharedGalleryImageId( - "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName")) - .withOsDisk( - new OSDisk() - .withName("myVMosdisk") - .withCaching(CachingTypes.READ_WRITE) - .withCreateOption(DiskCreateOptionTypes.FROM_IMAGE) - .withManagedDisk( - new ManagedDiskParameters() - .withStorageAccountType(StorageAccountTypes.STANDARD_LRS)))) - .withOsProfile( - new OSProfile() - .withComputerName("myVM") - .withAdminUsername("{your-username}") - .withAdminPassword("fakeTokenPlaceholder")) - .withNetworkProfile( - new NetworkProfile() - .withNetworkInterfaces( - Arrays - .asList( - new NetworkInterfaceReference() - .withId( - "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}") - .withPrimary(true)))); + .withStorageProfile(new StorageProfile().withImageReference(new ImageReference().withSharedGalleryImageId( + "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName")) + .withOsDisk(new OSDisk().withName("myVMosdisk") + .withCaching(CachingTypes.READ_WRITE) + .withCreateOption(DiskCreateOptionTypes.FROM_IMAGE) + .withManagedDisk( + new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS)))) + .withOsProfile(new OSProfile().withComputerName("myVM") + .withAdminUsername("{your-username}") + .withAdminPassword("fakeTokenPlaceholder")) + .withNetworkProfile(new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference() + .withId( + "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}") + .withPrimary(true)))); } private Mono successResponse(HttpRequest request, Map responseBody) { diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineUpdateTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineUpdateTests.java index 89c7bf944db36..d9318d3d446af 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineUpdateTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineUpdateTests.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.compute.implementation; - import com.azure.core.http.HttpPipeline; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; @@ -41,7 +40,8 @@ protected void cleanUpResources() { public void testVirtualMachineUpdate() { final String vmname = "javavm1"; - final String mySqlInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/00df5c3ae1e25c526e265e78a00211d068b94f93/sdk/resourcemanager/azure-resourcemanager-compute/src/test/assets/install_mysql_server_5.7.sh"; + final String mySqlInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/00df5c3ae1e25c526e265e78a00211d068b94f93/sdk/resourcemanager/azure-resourcemanager-compute/src/test/assets/install_mysql_server_5.7.sh"; final String installCommand = "bash install_mysql_server_5.7.sh " + password(); List fileUris = new ArrayList<>(); fileUris.add(mySqlInstallScript); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml index d2d9d78294e95..660c3bfdf5c76 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml @@ -48,6 +48,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManager.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManager.java index 194dab0de83a9..1d7d1adc194f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManager.java @@ -21,8 +21,7 @@ import java.util.Objects; /** Entry point to Azure container instance management. */ -public final class ContainerInstanceManager - extends Manager { +public final class ContainerInstanceManager extends Manager { // The service managers private ContainerGroupsImpl containerGroups; @@ -86,11 +85,8 @@ public ContainerInstanceManager authenticate(TokenCredential credential, AzurePr } private ContainerInstanceManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new ContainerInstanceManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new ContainerInstanceManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupImpl.java index b6931dc0fbfe8..7ba4d8154858b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupImpl.java @@ -61,9 +61,8 @@ import java.util.Set; /** Implementation for ContainerGroup and its create interfaces. */ -public class ContainerGroupImpl - extends GroupableParentResourceImpl< - ContainerGroup, ContainerGroupInner, ContainerGroupImpl, ContainerInstanceManager> +public class ContainerGroupImpl extends + GroupableParentResourceImpl implements ContainerGroup, ContainerGroup.Definition, ContainerGroup.Update { private final ClientLogger logger = new ClientLogger(ContainerGroupImpl.class); @@ -88,14 +87,10 @@ protected ContainerGroupImpl(String name, ContainerGroupInner innerObject, Conta private Mono beforeCreation() { Mono mono = Mono.empty(); if (creatableVirtualNetwork != null) { - mono = - mono - .then(creatableVirtualNetwork.createAsync()) - .flatMap( - network -> { - creatableVirtualNetwork = null; - return Mono.empty(); - }); + mono = mono.then(creatableVirtualNetwork.createAsync()).flatMap(network -> { + creatableVirtualNetwork = null; + return Mono.empty(); + }); } return mono; } @@ -110,83 +105,63 @@ protected Mono createInner() { Resource resource = new Resource(); resource.withLocation(self.regionName()); resource.withTags(self.tags()); - return beforeCreation() - .then( - manager() - .serviceClient() - .getContainerGroups() - .updateAsync(self.resourceGroupName(), self.name(), resource)); + return beforeCreation().then(manager().serviceClient() + .getContainerGroups() + .updateAsync(self.resourceGroupName(), self.name(), resource)); } else if (newFileShares == null || creatableStorageAccountKey == null) { - return beforeCreation() - .then(manager().serviceClient().getContainerGroups() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); + return beforeCreation().then(manager().serviceClient() + .getContainerGroups() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } else { final StorageAccount storageAccount = this.taskResult(this.creatableStorageAccountKey); - return beforeCreation() - .thenMany(createFileShareAsync(storageAccount)) - .map( - volumeParameters -> - this - .defineVolume(volumeParameters.volumeName) - .withExistingReadWriteAzureFileShare(volumeParameters.fileShareName) - .withStorageAccountName(storageAccount.name()) - .withStorageAccountKey(volumeParameters.storageAccountKey) - .attach()) - .then( - this - .manager() - .serviceClient() - .getContainerGroups() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); + return beforeCreation().thenMany(createFileShareAsync(storageAccount)) + .map(volumeParameters -> this.defineVolume(volumeParameters.volumeName) + .withExistingReadWriteAzureFileShare(volumeParameters.fileShareName) + .withStorageAccountName(storageAccount.name()) + .withStorageAccountKey(volumeParameters.storageAccountKey) + .attach()) + .then(this.manager() + .serviceClient() + .getContainerGroups() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } } @Override public Accepted beginCreate() { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> - this - .manager() - .serviceClient() - .getContainerGroups() - .createOrUpdateWithResponseAsync(resourceGroupName(), name(), innerModel()) - .block(), - inner -> - new ContainerGroupImpl( - inner.name(), - inner, - this.manager()), - ContainerGroupInner.class, - () -> { - Flux dependencyTasksAsync = - taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); - dependencyTasksAsync.blockLast(); - - // same as createInner - beforeCreation().block(); - // msi - this.containerGroupMsiHandler.processCreatedExternalIdentities(); - this.containerGroupMsiHandler.handleExternalIdentities(); - // storage account - if (!(newFileShares == null || creatableStorageAccountKey == null)) { - final StorageAccount storageAccount = this.taskResult(this.creatableStorageAccountKey); - List volumeParametersList = createFileShareAsync(storageAccount).collectList().block(); - if (!CoreUtils.isNullOrEmpty(volumeParametersList)) { - for (VolumeParameters volumeParameters : volumeParametersList) { - this.defineVolume(volumeParameters.volumeName) - .withExistingReadWriteAzureFileShare(volumeParameters.fileShareName) - .withStorageAccountName(storageAccount.name()) - .withStorageAccountKey(volumeParameters.storageAccountKey) - .attach(); - } + return AcceptedImpl.newAccepted(logger, + this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), + () -> this.manager() + .serviceClient() + .getContainerGroups() + .createOrUpdateWithResponseAsync(resourceGroupName(), name(), innerModel()) + .block(), + inner -> new ContainerGroupImpl(inner.name(), inner, this.manager()), ContainerGroupInner.class, () -> { + Flux dependencyTasksAsync + = taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); + dependencyTasksAsync.blockLast(); + + // same as createInner + beforeCreation().block(); + // msi + this.containerGroupMsiHandler.processCreatedExternalIdentities(); + this.containerGroupMsiHandler.handleExternalIdentities(); + // storage account + if (!(newFileShares == null || creatableStorageAccountKey == null)) { + final StorageAccount storageAccount = this.taskResult(this.creatableStorageAccountKey); + List volumeParametersList + = createFileShareAsync(storageAccount).collectList().block(); + if (!CoreUtils.isNullOrEmpty(volumeParametersList)) { + for (VolumeParameters volumeParameters : volumeParametersList) { + this.defineVolume(volumeParameters.volumeName) + .withExistingReadWriteAzureFileShare(volumeParameters.fileShareName) + .withStorageAccountName(storageAccount.name()) + .withStorageAccountKey(volumeParameters.storageAccountKey) + .attach(); } } - }, - Context.NONE); + } + }, Context.NONE); } private static final class VolumeParameters { @@ -202,36 +177,25 @@ private static final class VolumeParameters { } private Flux createFileShareAsync(final StorageAccount storageAccount) { - return storageAccount - .getKeysAsync() + return storageAccount.getKeysAsync() .map(storageAccountKeys -> storageAccountKeys.get(0).value()) - .flatMapMany( - key -> { - ShareServiceAsyncClient shareServiceAsyncClient = - new ShareServiceClientBuilder() - .connectionString( - ResourceManagerUtils.getStorageConnectionString( - storageAccount.name(), key, manager().environment())) - .httpClient(manager().httpPipeline().getHttpClient()) - .buildAsyncClient(); - - Objects.requireNonNull(newFileShares); - return Flux - .fromIterable(newFileShares.entrySet()) - .flatMap( - fileShareEntry -> - createSingleFileShareAsync( - shareServiceAsyncClient, fileShareEntry.getKey(), fileShareEntry.getValue(), key)); - }); - } - - private Mono createSingleFileShareAsync( - final ShareServiceAsyncClient client, - final String volumeName, - final String fileShareName, - final String storageAccountKey) { - return client - .createShare(fileShareName) + .flatMapMany(key -> { + ShareServiceAsyncClient shareServiceAsyncClient = new ShareServiceClientBuilder() + .connectionString(ResourceManagerUtils.getStorageConnectionString(storageAccount.name(), key, + manager().environment())) + .httpClient(manager().httpPipeline().getHttpClient()) + .buildAsyncClient(); + + Objects.requireNonNull(newFileShares); + return Flux.fromIterable(newFileShares.entrySet()) + .flatMap(fileShareEntry -> createSingleFileShareAsync(shareServiceAsyncClient, + fileShareEntry.getKey(), fileShareEntry.getValue(), key)); + }); + } + + private Mono createSingleFileShareAsync(final ShareServiceAsyncClient client, + final String volumeName, final String fileShareName, final String storageAccountKey) { + return client.createShare(fileShareName) .then(Mono.just(new VolumeParameters(volumeName, fileShareName, storageAccountKey))); } @@ -306,20 +270,16 @@ protected void initializeChildrenFromInner() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - containerGroup -> { - ContainerGroupImpl impl = (ContainerGroupImpl) containerGroup; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(containerGroup -> { + ContainerGroupImpl impl = (ContainerGroupImpl) containerGroup; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getContainerGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -393,8 +353,7 @@ public ContainerGroupImpl withPrivateImageRegistry(String server, String usernam if (this.innerModel().imageRegistryCredentials() == null) { this.innerModel().withImageRegistryCredentials(new ArrayList()); } - this - .innerModel() + this.innerModel() .imageRegistryCredentials() .add(new ImageRegistryCredential().withServer(server).withUsername(username).withPassword(password)); @@ -404,12 +363,10 @@ public ContainerGroupImpl withPrivateImageRegistry(String server, String usernam @Override public ContainerGroupImpl withNewAzureFileShareVolume(String volumeName, String shareName) { if (this.newFileShares == null || this.creatableStorageAccountKey == null) { - StorageAccount.DefinitionStages.WithGroup definitionWithGroup = - manager() - .storageManager() - .storageAccounts() - .define(manager().resourceManager().internalContext().randomResourceName("fs", 24)) - .withRegion(this.regionName()); + StorageAccount.DefinitionStages.WithGroup definitionWithGroup = manager().storageManager() + .storageAccounts() + .define(manager().resourceManager().internalContext().randomResourceName("fs", 24)) + .withRegion(this.regionName()); Creatable creatable; if (this.creatableGroup != null) { creatable = definitionWithGroup.withNewResourceGroup(this.creatableGroup); @@ -453,8 +410,7 @@ public ContainerImpl defineContainerInstance(String name) { @Override public ContainerGroupImpl withContainerInstance(String imageName) { - return this - .defineContainerInstance(this.name()) + return this.defineContainerInstance(this.name()) .withImage(imageName) .withoutPorts() .withCpuCoreCount(1) @@ -464,8 +420,7 @@ public ContainerGroupImpl withContainerInstance(String imageName) { @Override public ContainerGroupImpl withContainerInstance(String imageName, int port) { - return this - .defineContainerInstance(this.name()) + return this.defineContainerInstance(this.name()) .withImage(imageName) .withExternalTcpPort(port) .withCpuCoreCount(1) @@ -506,8 +461,8 @@ public ContainerGroupImpl withExistingSubnet(String subnetId) { } @Override - public ContainerGroupImpl withNewNetworkProfileOnExistingVirtualNetwork( - String virtualNetworkId, String subnetName) { + public ContainerGroupImpl withNewNetworkProfileOnExistingVirtualNetwork(String virtualNetworkId, + String subnetName) { String subnetId = String.format("%s/subnets/%s", virtualNetworkId, subnetName); return this.withExistingSubnet(subnetId); } @@ -517,24 +472,20 @@ public ContainerGroupImpl withNewVirtualNetwork(String addressSpace) { String virtualNetworkName = manager().resourceManager().internalContext().randomResourceName("net", 20); String subnetName = "subnet0"; - creatableVirtualNetwork = - manager() - .networkManager() - .networks() - .define(virtualNetworkName) - .withRegion(region()) - .withExistingResourceGroup(resourceGroupName()) - .withAddressSpace(addressSpace) - .defineSubnet(subnetName) - .withAddressPrefix(addressSpace) - .withDelegation("Microsoft.ContainerInstance/containerGroups") - .attach(); - - String virtualNetworkId = - String - .format( - "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s", - manager().subscriptionId(), resourceGroupName(), virtualNetworkName); + creatableVirtualNetwork = manager().networkManager() + .networks() + .define(virtualNetworkName) + .withRegion(region()) + .withExistingResourceGroup(resourceGroupName()) + .withAddressSpace(addressSpace) + .defineSubnet(subnetName) + .withAddressPrefix(addressSpace) + .withDelegation("Microsoft.ContainerInstance/containerGroups") + .attach(); + + String virtualNetworkId + = String.format("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s", + manager().subscriptionId(), resourceGroupName(), virtualNetworkName); return withNewNetworkProfileOnExistingVirtualNetwork(virtualNetworkId, subnetName); } @@ -545,41 +496,32 @@ public ContainerGroupImpl withDnsServerNames(List dnsServerNames) { } @Override - public ContainerGroupImpl withDnsConfiguration( - List dnsServerNames, String dnsSearchDomains, String dnsOptions) { - this - .innerModel() - .withDnsConfig( - new DnsConfiguration() - .withNameServers(dnsServerNames) - .withSearchDomains(dnsSearchDomains) - .withOptions(dnsOptions)); + public ContainerGroupImpl withDnsConfiguration(List dnsServerNames, String dnsSearchDomains, + String dnsOptions) { + this.innerModel() + .withDnsConfig(new DnsConfiguration().withNameServers(dnsServerNames) + .withSearchDomains(dnsSearchDomains) + .withOptions(dnsOptions)); return this; } @Override public ContainerGroupImpl withLogAnalytics(String workspaceId, String workspaceKey) { - this - .innerModel() - .withDiagnostics( - new ContainerGroupDiagnostics() - .withLogAnalytics(new LogAnalytics().withWorkspaceId(workspaceId).withWorkspaceKey(workspaceKey))); + this.innerModel() + .withDiagnostics(new ContainerGroupDiagnostics() + .withLogAnalytics(new LogAnalytics().withWorkspaceId(workspaceId).withWorkspaceKey(workspaceKey))); return this; } @Override - public ContainerGroupImpl withLogAnalytics( - String workspaceId, String workspaceKey, LogAnalyticsLogType logType, Map metadata) { - this - .innerModel() + public ContainerGroupImpl withLogAnalytics(String workspaceId, String workspaceKey, LogAnalyticsLogType logType, + Map metadata) { + this.innerModel() .withDiagnostics( - new ContainerGroupDiagnostics() - .withLogAnalytics( - new LogAnalytics() - .withWorkspaceId(workspaceId) - .withWorkspaceKey(workspaceKey) - .withLogType(logType) - .withMetadata(metadata))); + new ContainerGroupDiagnostics().withLogAnalytics(new LogAnalytics().withWorkspaceId(workspaceId) + .withWorkspaceKey(workspaceKey) + .withLogType(logType) + .withMetadata(metadata))); return this; } @@ -591,10 +533,9 @@ public Map containers() { @Override public Set externalPorts() { return Collections - .unmodifiableSet( - this.innerModel().ipAddress() != null && this.innerModel().ipAddress().ports() != null - ? new HashSet(this.innerModel().ipAddress().ports()) - : new HashSet()); + .unmodifiableSet(this.innerModel().ipAddress() != null && this.innerModel().ipAddress().ports() != null + ? new HashSet(this.innerModel().ipAddress().ports()) + : new HashSet()); } @Override @@ -688,11 +629,10 @@ public String provisioningState() { @Override public Set events() { - return Collections - .unmodifiableSet( - this.innerModel().instanceView() != null && this.innerModel().instanceView().events() != null - ? new HashSet(this.innerModel().instanceView().events()) - : new HashSet()); + return Collections.unmodifiableSet( + this.innerModel().instanceView() != null && this.innerModel().instanceView().events() != null + ? new HashSet(this.innerModel().instanceView().events()) + : new HashSet()); } @Override @@ -776,24 +716,21 @@ public String getLogContent(String containerName) { @Override public String getLogContent(String containerName, int tailLineCount) { - return this - .manager() + return this.manager() .containerGroups() .getLogContent(this.resourceGroupName(), this.name(), containerName, tailLineCount); } @Override public Mono getLogContentAsync(String containerName) { - return this - .manager() + return this.manager() .containerGroups() .getLogContentAsync(this.resourceGroupName(), this.name(), containerName); } @Override public Mono getLogContentAsync(String containerName, int tailLineCount) { - return this - .manager() + return this.manager() .containerGroups() .getLogContentAsync(this.resourceGroupName(), this.name(), containerName, tailLineCount); } @@ -805,16 +742,11 @@ public ContainerExecResponse executeCommand(String containerName, String command @Override public Mono executeCommandAsync(String containerName, String command, int row, int column) { - return this - .manager() + return this.manager() .serviceClient() .getContainers() - .executeCommandAsync( - this.resourceGroupName(), - this.name(), - containerName, - new ContainerExecRequest() - .withCommand(command) + .executeCommandAsync(this.resourceGroupName(), this.name(), containerName, + new ContainerExecRequest().withCommand(command) .withTerminalSize(new ContainerExecRequestTerminalSize().withRows(row).withCols(column))) .map(ContainerExecResponseImpl::new); } @@ -826,8 +758,9 @@ public ContainerAttachResult attachOutputStream(String containerName) { @Override public Mono attachOutputStreamAsync(String containerName) { - return this.manager().containerGroups().attachOutputStreamAsync( - this.resourceGroupName(), this.name(), containerName); + return this.manager() + .containerGroups() + .attachOutputStreamAsync(this.resourceGroupName(), this.name(), containerName); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupsImpl.java index 0817419d33914..b21e06133f450 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerGroupsImpl.java @@ -22,9 +22,8 @@ import reactor.core.publisher.Mono; /** Implementation for ContainerGroups. */ -public class ContainerGroupsImpl - extends TopLevelModifiableResourcesImpl< - ContainerGroup, ContainerGroupImpl, ContainerGroupInner, ContainerGroupsClient, ContainerInstanceManager> +public class ContainerGroupsImpl extends + TopLevelModifiableResourcesImpl implements ContainerGroups { public ContainerGroupsImpl(final ContainerInstanceManager manager) { @@ -56,31 +55,30 @@ public ContainerGroup.DefinitionStages.Blank define(String name) { @Override public String getLogContent(String resourceGroupName, String containerGroupName, String containerName) { - LogsInner logsInner = this.manager().serviceClient().getContainers() + LogsInner logsInner = this.manager() + .serviceClient() + .getContainers() .listLogs(resourceGroupName, containerGroupName, containerName); return logsInner != null ? logsInner.content() : null; } @Override - public String getLogContent( - String resourceGroupName, String containerGroupName, String containerName, int tailLineCount) { - LogsInner logsInner = - this - .manager() - .serviceClient() - .getContainers() - .listLogsWithResponse(resourceGroupName, containerGroupName, containerName, tailLineCount, null, - Context.NONE) - .getValue(); + public String getLogContent(String resourceGroupName, String containerGroupName, String containerName, + int tailLineCount) { + LogsInner logsInner = this.manager() + .serviceClient() + .getContainers() + .listLogsWithResponse(resourceGroupName, containerGroupName, containerName, tailLineCount, null, + Context.NONE) + .getValue(); return logsInner != null ? logsInner.content() : null; } @Override public Mono getLogContentAsync(String resourceGroupName, String containerGroupName, String containerName) { - return this - .manager() + return this.manager() .serviceClient() .getContainers() .listLogsAsync(resourceGroupName, containerGroupName, containerName) @@ -88,14 +86,12 @@ public Mono getLogContentAsync(String resourceGroupName, String containe } @Override - public Mono getLogContentAsync( - String resourceGroupName, String containerGroupName, String containerName, int tailLineCount) { - return this - .manager() + public Mono getLogContentAsync(String resourceGroupName, String containerGroupName, String containerName, + int tailLineCount) { + return this.manager() .serviceClient() .getContainers() - .listLogsWithResponseAsync( - resourceGroupName, containerGroupName, containerName, tailLineCount, null) + .listLogsWithResponseAsync(resourceGroupName, containerGroupName, containerName, tailLineCount, null) .map(Response::getValue) .map(LogsInner::content); } @@ -141,13 +137,17 @@ public Mono startAsync(String resourceGroupName, String containerGroupName } @Override - public ContainerAttachResult attachOutputStream(String resourceGroupName, String containerGroupName, String containerName) { + public ContainerAttachResult attachOutputStream(String resourceGroupName, String containerGroupName, + String containerName) { return this.attachOutputStreamAsync(resourceGroupName, containerGroupName, containerName).block(); } @Override - public Mono attachOutputStreamAsync(String resourceGroupName, String containerGroupName, String containerName) { - return this.manager().serviceClient().getContainers() + public Mono attachOutputStreamAsync(String resourceGroupName, String containerGroupName, + String containerName) { + return this.manager() + .serviceClient() + .getContainers() .attachAsync(resourceGroupName, containerGroupName, containerName) .map(ContainerAttachResultImpl::new); } @@ -160,8 +160,8 @@ public PagedFlux listAsync() { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerImpl.java index 87704f7ce001b..8900b17563dfa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/ContainerImpl.java @@ -25,19 +25,16 @@ import java.util.Map; /** Implementation for container group's container instance definition stages interface. */ -class ContainerImpl - implements ContainerGroup.DefinitionStages.ContainerInstanceDefinitionStages.ContainerInstanceDefinition< - ContainerGroup.DefinitionStages.WithNextContainerInstance> { +class ContainerImpl implements + ContainerGroup.DefinitionStages.ContainerInstanceDefinitionStages.ContainerInstanceDefinition { private Container innerContainer; private ContainerGroupImpl parent; ContainerImpl(ContainerGroupImpl parent, String containerName) { this.parent = parent; - this.innerContainer = - new Container() - .withName(containerName) - .withResources( - new ResourceRequirements().withRequests(new ResourceRequests().withCpu(1).withMemoryInGB(1.5))); + this.innerContainer = new Container().withName(containerName) + .withResources( + new ResourceRequirements().withRequests(new ResourceRequests().withCpu(1).withMemoryInGB(1.5))); } @Override @@ -227,8 +224,7 @@ public ContainerImpl withEnvironmentVariableWithSecuredValue(String envName, Str innerContainer.withEnvironmentVariables(new ArrayList()); } - innerContainer - .environmentVariables() + innerContainer.environmentVariables() .add(new EnvironmentVariable().withName(envName).withSecureValue(securedValue)); return this; @@ -239,8 +235,7 @@ public ContainerImpl withVolumeMountSetting(String volumeName, String mountPath) if (innerContainer.volumeMounts() == null) { innerContainer.withVolumeMounts(new ArrayList()); } - innerContainer - .volumeMounts() + innerContainer.volumeMounts() .add(new VolumeMount().withName(volumeName).withMountPath(mountPath).withReadOnly(false)); return this; @@ -260,8 +255,7 @@ public ContainerImpl withReadOnlyVolumeMountSetting(String volumeName, String mo if (innerContainer.volumeMounts() == null) { innerContainer.withVolumeMounts(new ArrayList()); } - innerContainer - .volumeMounts() + innerContainer.volumeMounts() .add(new VolumeMount().withName(volumeName).withMountPath(mountPath).withReadOnly(true)); return this; @@ -278,44 +272,29 @@ public ContainerImpl withReadOnlyVolumeMountSetting(Map volumeMo @Override public ContainerImpl withLivenessProbeExecutionCommand(List command, int probePeriodSeconds) { - return this.withLivenessProbe( - new ContainerProbe() - .withExec( - new ContainerExec() - .withCommand(command)) - .withPeriodSeconds(probePeriodSeconds)); + return this.withLivenessProbe(new ContainerProbe().withExec(new ContainerExec().withCommand(command)) + .withPeriodSeconds(probePeriodSeconds)); } @Override - public ContainerImpl withLivenessProbeExecutionCommand(List command, int probePeriodSeconds, int failureThreshold) { - return this.withLivenessProbe( - new ContainerProbe() - .withExec( - new ContainerExec() - .withCommand(command)) - .withPeriodSeconds(probePeriodSeconds) - .withFailureThreshold(failureThreshold)); + public ContainerImpl withLivenessProbeExecutionCommand(List command, int probePeriodSeconds, + int failureThreshold) { + return this.withLivenessProbe(new ContainerProbe().withExec(new ContainerExec().withCommand(command)) + .withPeriodSeconds(probePeriodSeconds) + .withFailureThreshold(failureThreshold)); } @Override public ContainerImpl withLivenessProbeHttpGet(String path, int port, int probePeriodSeconds) { - return this.withLivenessProbe( - new ContainerProbe() - .withHttpGet( - new ContainerHttpGet() - .withPath(path) - .withPort(port)) + return this + .withLivenessProbe(new ContainerProbe().withHttpGet(new ContainerHttpGet().withPath(path).withPort(port)) .withPeriodSeconds(probePeriodSeconds)); } @Override public ContainerImpl withLivenessProbeHttpGet(String path, int port, int probePeriodSeconds, int failureThreshold) { - return this.withLivenessProbe( - new ContainerProbe() - .withHttpGet( - new ContainerHttpGet() - .withPath(path) - .withPort(port)) + return this + .withLivenessProbe(new ContainerProbe().withHttpGet(new ContainerHttpGet().withPath(path).withPort(port)) .withPeriodSeconds(probePeriodSeconds) .withFailureThreshold(failureThreshold)); } @@ -330,44 +309,30 @@ public ContainerImpl withLivenessProbe(ContainerProbe livenessProbe) { @Override public ContainerImpl withReadinessProbeExecutionCommand(List command, int probePeriodSeconds) { - return this.withReadinessProbe( - new ContainerProbe() - .withExec( - new ContainerExec() - .withCommand(command)) - .withPeriodSeconds(probePeriodSeconds)); + return this.withReadinessProbe(new ContainerProbe().withExec(new ContainerExec().withCommand(command)) + .withPeriodSeconds(probePeriodSeconds)); } @Override - public ContainerImpl withReadinessProbeExecutionCommand(List command, int probePeriodSeconds, int failureThreshold) { - return this.withReadinessProbe( - new ContainerProbe() - .withExec( - new ContainerExec() - .withCommand(command)) - .withPeriodSeconds(probePeriodSeconds) - .withFailureThreshold(failureThreshold)); + public ContainerImpl withReadinessProbeExecutionCommand(List command, int probePeriodSeconds, + int failureThreshold) { + return this.withReadinessProbe(new ContainerProbe().withExec(new ContainerExec().withCommand(command)) + .withPeriodSeconds(probePeriodSeconds) + .withFailureThreshold(failureThreshold)); } @Override public ContainerImpl withReadinessProbeHttpGet(String path, int port, int probePeriodSeconds) { - return this.withReadinessProbe( - new ContainerProbe() - .withHttpGet( - new ContainerHttpGet() - .withPath(path) - .withPort(port)) + return this + .withReadinessProbe(new ContainerProbe().withHttpGet(new ContainerHttpGet().withPath(path).withPort(port)) .withPeriodSeconds(probePeriodSeconds)); } @Override - public ContainerImpl withReadinessProbeHttpGet(String path, int port, int probePeriodSeconds, int failureThreshold) { - return this.withReadinessProbe( - new ContainerProbe() - .withHttpGet( - new ContainerHttpGet() - .withPath(path) - .withPort(port)) + public ContainerImpl withReadinessProbeHttpGet(String path, int port, int probePeriodSeconds, + int failureThreshold) { + return this + .withReadinessProbe(new ContainerProbe().withHttpGet(new ContainerHttpGet().withPath(path).withPort(port)) .withPeriodSeconds(probePeriodSeconds) .withFailureThreshold(failureThreshold)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/VolumeImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/VolumeImpl.java index 4580c63601a16..4fa0d917e1a95 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/VolumeImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/implementation/VolumeImpl.java @@ -11,9 +11,8 @@ import java.util.Map; /** Implementation for container group's volume definition stages interface. */ -class VolumeImpl - implements ContainerGroup.DefinitionStages.VolumeDefinitionStages.VolumeDefinition< - ContainerGroup.DefinitionStages.WithVolume> { +class VolumeImpl implements + ContainerGroup.DefinitionStages.VolumeDefinitionStages.VolumeDefinition { private Volume innerVolume; private ContainerGroupImpl parent; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroup.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroup.java index 13be5b4b4257f..2301a0a812cd4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroup.java @@ -26,10 +26,8 @@ /** An immutable client-side representation of an Azure Container Group. */ @Fluent -public interface ContainerGroup - extends GroupableResource, - Refreshable, - Updatable { +public interface ContainerGroup extends GroupableResource, + Refreshable, Updatable { /*********************************************************** * Getters @@ -239,19 +237,12 @@ public interface ContainerGroup Mono attachOutputStreamAsync(Container container); /** Starts the exec command for a specific container instance within the current group asynchronously. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithOsType, - DefinitionStages.WithPublicOrPrivateImageRegistry, - DefinitionStages.WithPrivateImageRegistryOrVolume, - DefinitionStages.WithVolume, - DefinitionStages.WithFirstContainerInstance, - DefinitionStages.WithSystemAssignedManagedServiceIdentity, - DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, - DefinitionStages.WithNextContainerInstance, - DefinitionStages.DnsConfigFork, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithOsType, + DefinitionStages.WithPublicOrPrivateImageRegistry, DefinitionStages.WithPrivateImageRegistryOrVolume, + DefinitionStages.WithVolume, DefinitionStages.WithFirstContainerInstance, + DefinitionStages.WithSystemAssignedManagedServiceIdentity, + DefinitionStages.WithSystemAssignedIdentityBasedAccessOrCreate, DefinitionStages.WithNextContainerInstance, + DefinitionStages.DnsConfigFork, DefinitionStages.WithCreate { } /** Grouping of the container group definition stages. */ @@ -511,15 +502,9 @@ interface WithVolumeAttach extends Attachable.InDefinition { /** Grouping of the container group's volume definition stages. */ interface VolumeDefinition - extends VolumeDefinitionBlank, - WithAzureFileShare, - WithStorageAccountName, - WithStorageAccountKey, - WithSecretsMap, - WithGitUrl, - WithGitDirectoryName, - WithGitRevision, - WithVolumeAttach { + extends VolumeDefinitionBlank, WithAzureFileShare, WithStorageAccountName, + WithStorageAccountKey, WithSecretsMap, WithGitUrl, + WithGitDirectoryName, WithGitRevision, WithVolumeAttach { } } @@ -837,8 +822,8 @@ interface WithEnvironmentVariables { * container gets initialized * @return the next stage of the definition */ - WithContainerInstanceAttach withEnvironmentVariableWithSecuredValue( - Map environmentVariables); + WithContainerInstanceAttach + withEnvironmentVariableWithSecuredValue(Map environmentVariables); /** * Specifies the environment variable that has a secured value. @@ -847,8 +832,8 @@ WithContainerInstanceAttach withEnvironmentVariableWithSecuredValue( * @param securedValue the environment variable secured value * @return the next stage of the definition */ - WithContainerInstanceAttach withEnvironmentVariableWithSecuredValue( - String envName, String securedValue); + WithContainerInstanceAttach withEnvironmentVariableWithSecuredValue(String envName, + String securedValue); } /** @@ -903,8 +888,8 @@ interface WithVolumeMountSetting { * @throws IllegalArgumentException thrown if volumeName was not defined in the respective container * group definition stage. */ - WithContainerInstanceAttach withReadOnlyVolumeMountSetting( - String volumeName, String mountPath); + WithContainerInstanceAttach withReadOnlyVolumeMountSetting(String volumeName, + String mountPath); /** * Specifies the container group's volume to be mounted by the container instance at a specified mount @@ -920,8 +905,8 @@ WithContainerInstanceAttach withReadOnlyVolumeMountSetting( * @throws IllegalArgumentException thrown if volumeName was not defined in the respective container * group definition stage. */ - WithContainerInstanceAttach withReadOnlyVolumeMountSetting( - Map volumeMountSetting); + WithContainerInstanceAttach + withReadOnlyVolumeMountSetting(Map volumeMountSetting); } /** @@ -943,7 +928,8 @@ interface WithLivenessProbe { * @see liveness command * @see liveness probes and restart policies */ - WithContainerInstanceAttach withLivenessProbeExecutionCommand(List command, int probePeriodSeconds); + WithContainerInstanceAttach withLivenessProbeExecutionCommand(List command, + int probePeriodSeconds); /** * Specifies the container's liveness probe to execute a given command at a given interval. @@ -957,7 +943,8 @@ interface WithLivenessProbe { * @see liveness command * @see liveness probes and restart policies */ - WithContainerInstanceAttach withLivenessProbeExecutionCommand(List command, int probePeriodSeconds, int failureThreshold); + WithContainerInstanceAttach withLivenessProbeExecutionCommand(List command, + int probePeriodSeconds, int failureThreshold); /** * Specifies the container's liveness probe to perform an Http Get at a given interval. @@ -970,7 +957,8 @@ interface WithLivenessProbe { * @return the next stage of the definition * @see liveness probes and restart policies */ - WithContainerInstanceAttach withLivenessProbeHttpGet(String path, int port, int probePeriodSeconds); + WithContainerInstanceAttach withLivenessProbeHttpGet(String path, int port, + int probePeriodSeconds); /** * Specifies the container's liveness probe to perform an Http Get at a given interval. @@ -984,7 +972,8 @@ interface WithLivenessProbe { * @return the next stage of the definition * @see liveness probes and restart policies */ - WithContainerInstanceAttach withLivenessProbeHttpGet(String path, int port, int probePeriodSeconds, int failureThreshold); + WithContainerInstanceAttach withLivenessProbeHttpGet(String path, int port, + int probePeriodSeconds, int failureThreshold); /** * Specifies the container's liveness probe. @@ -1014,7 +1003,8 @@ interface WithReadinessProbe { * @return the next stage of the definition * @see readiness command */ - WithContainerInstanceAttach withReadinessProbeExecutionCommand(List command, int probePeriodSeconds); + WithContainerInstanceAttach withReadinessProbeExecutionCommand(List command, + int probePeriodSeconds); /** * Specifies the container's readiness probe to execute a given command at a given interval. @@ -1027,7 +1017,8 @@ interface WithReadinessProbe { * @return the next stage of the definition * @see readiness command */ - WithContainerInstanceAttach withReadinessProbeExecutionCommand(List command, int probePeriodSeconds, int failureThreshold); + WithContainerInstanceAttach withReadinessProbeExecutionCommand(List command, + int probePeriodSeconds, int failureThreshold); /** * Specifies the container's readiness probe to perform an Http Get at a given interval. @@ -1039,7 +1030,8 @@ interface WithReadinessProbe { * @param probePeriodSeconds the interval at which the Http Get performs * @return the next stage of the definition */ - WithContainerInstanceAttach withReadinessProbeHttpGet(String path, int port, int probePeriodSeconds); + WithContainerInstanceAttach withReadinessProbeHttpGet(String path, int port, + int probePeriodSeconds); /** * Specifies the container's readiness probe to perform an Http Get at a given interval. @@ -1052,7 +1044,8 @@ interface WithReadinessProbe { * @param failureThreshold the consecutive probe failure count before the container becomes inaccessible * @return the next stage of the definition */ - WithContainerInstanceAttach withReadinessProbeHttpGet(String path, int port, int probePeriodSeconds, int failureThreshold); + WithContainerInstanceAttach withReadinessProbeHttpGet(String path, int port, + int probePeriodSeconds, int failureThreshold); /** * Specifies the container's readiness probe. @@ -1072,24 +1065,15 @@ interface WithReadinessProbe { * @param the stage of the parent definition to return to after attaching this definition */ interface WithContainerInstanceAttach - extends WithCpuCoreCount, - WithGpuResource, - WithMemorySize, - WithStartingCommandLine, - WithEnvironmentVariables, - WithVolumeMountSetting, - WithLivenessProbe, - WithReadinessProbe, - Attachable.InDefinition { + extends WithCpuCoreCount, WithGpuResource, WithMemorySize, + WithStartingCommandLine, WithEnvironmentVariables, WithVolumeMountSetting, + WithLivenessProbe, WithReadinessProbe, Attachable.InDefinition { } /** Grouping of the container group's volume definition stages. */ interface ContainerInstanceDefinition - extends ContainerInstanceDefinitionBlank, - WithImage, - WithOrWithoutPorts, - WithPortsOrContainerInstanceAttach, - WithContainerInstanceAttach { + extends ContainerInstanceDefinitionBlank, WithImage, WithOrWithoutPorts, + WithPortsOrContainerInstanceAttach, WithContainerInstanceAttach { } } @@ -1119,8 +1103,8 @@ interface WithSystemAssignedIdentityBasedAccessOrCreate extends WithCreate { * @param role access role to be assigned to the identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + BuiltInRole role); /** * Specifies a system assigned managed service identity with access to the current resource group and with @@ -1129,8 +1113,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param role access role to be assigned to the identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - BuiltInRole role); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /** * Specifies a system assigned managed service identity with access to a specific resource with a specified @@ -1140,8 +1124,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId id of the access role to be assigned to the identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo( - String resourceId, String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessTo(String resourceId, + String roleDefinitionId); /** * Specifies a system assigned managed service identity with access to the current resource group and with @@ -1150,8 +1134,8 @@ WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAcc * @param roleDefinitionId id of the access role to be assigned to the identity * @return the next stage of the definition */ - WithSystemAssignedIdentityBasedAccessOrCreate withSystemAssignedIdentityBasedAccessToCurrentResourceGroup( - String roleDefinitionId); + WithSystemAssignedIdentityBasedAccessOrCreate + withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(String roleDefinitionId); } /** @@ -1294,23 +1278,17 @@ interface WithLogAnalytics { * @param metadata the metadata for log analytics * @return the next stage of the definition */ - WithCreate withLogAnalytics( - String workspaceId, String workspaceKey, LogAnalyticsLogType logType, Map metadata); + WithCreate withLogAnalytics(String workspaceId, String workspaceKey, LogAnalyticsLogType logType, + Map metadata); } /** * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends WithRestartPolicy, - WithSystemAssignedManagedServiceIdentity, - WithUserAssignedManagedServiceIdentity, - WithDnsPrefix, - WithNetworkProfile, - WithLogAnalytics, - Creatable, - Resource.DefinitionWithTags { + interface WithCreate extends WithRestartPolicy, WithSystemAssignedManagedServiceIdentity, + WithUserAssignedManagedServiceIdentity, WithDnsPrefix, WithNetworkProfile, WithLogAnalytics, + Creatable, Resource.DefinitionWithTags { /** * Begins creating the deployment resource. diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroups.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroups.java index 03f6faff54f63..fc7fcb04a1f6c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/main/java/com/azure/resourcemanager/containerinstance/models/ContainerGroups.java @@ -22,16 +22,10 @@ /** Entry point to the container instance management API. */ @Fluent public interface ContainerGroups - extends SupportsCreating, - HasManager, - SupportsBatchCreation, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsDeletingById, - SupportsBatchDeletion, - SupportsListingByResourceGroup, - SupportsListing { + extends SupportsCreating, HasManager, + SupportsBatchCreation, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsDeletingById, SupportsBatchDeletion, + SupportsListingByResourceGroup, SupportsListing { /** * Get the log content for the specified container instance within a container group. @@ -77,8 +71,8 @@ public interface ContainerGroups * @throws IllegalArgumentException thrown if parameters fail the validation * @return a representation of the future computation of this call */ - Mono getLogContentAsync( - String resourceGroupName, String containerGroupName, String containerName, int tailLineCount); + Mono getLogContentAsync(String resourceGroupName, String containerGroupName, String containerName, + int tailLineCount); /** * Lists all operations for Azure Container Instance service. @@ -161,6 +155,6 @@ Mono getLogContentAsync( * @param containerName the name of the container instance * @return the information for the output stream */ - Mono attachOutputStreamAsync( - String resourceGroupName, String containerGroupName, String containerName); + Mono attachOutputStreamAsync(String resourceGroupName, String containerGroupName, + String containerName); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerGroupTest.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerGroupTest.java index fe12cae4f617b..7769b8f6f15c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerGroupTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerGroupTest.java @@ -29,18 +29,16 @@ public void testContainerGroupWithVirtualNetwork() { String containerGroupName = generateRandomResourceName("container", 20); Region region = Region.US_WEST3; - ContainerGroup containerGroup = - containerInstanceManager - .containerGroups() - .define(containerGroupName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withoutVolume() - .withContainerInstance("nginx", 80) - .withNewVirtualNetwork("10.0.0.0/24") - .create(); + ContainerGroup containerGroup = containerInstanceManager.containerGroups() + .define(containerGroupName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withoutVolume() + .withContainerInstance("nginx", 80) + .withNewVirtualNetwork("10.0.0.0/24") + .create(); Assertions.assertEquals(1, containerGroup.subnetIds().size()); @@ -49,17 +47,20 @@ public void testContainerGroupWithVirtualNetwork() { final String subnetName = "default"; final String containerGroupName1 = generateRandomResourceName("container", 20); - Network vnet = containerInstanceManager.networkManager().networks().define("vnet1") + Network vnet = containerInstanceManager.networkManager() + .networks() + .define("vnet1") .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.1.0.0/24") .defineSubnet(subnetName) - .withAddressPrefix("10.1.0.0/24") - .withDelegation("Microsoft.ContainerInstance/containerGroups") - .attach() + .withAddressPrefix("10.1.0.0/24") + .withDelegation("Microsoft.ContainerInstance/containerGroups") + .attach() .create(); - ContainerGroup containerGroup1 = containerInstanceManager.containerGroups().define(containerGroupName1) + ContainerGroup containerGroup1 = containerInstanceManager.containerGroups() + .define(containerGroupName1) .withRegion(region) .withExistingResourceGroup(rgName) .withLinux() @@ -71,7 +72,8 @@ public void testContainerGroupWithVirtualNetwork() { Assertions.assertEquals(1, containerGroup1.subnetIds().size()); Assertions.assertEquals(subnetName, containerGroup1.subnetIds().iterator().next().name()); - Assertions.assertEquals(vnet.subnets().get(subnetName).id(), containerGroup1.subnetIds().iterator().next().id()); + Assertions.assertEquals(vnet.subnets().get(subnetName).id(), + containerGroup1.subnetIds().iterator().next().id()); } @Test @@ -81,18 +83,16 @@ public void testContainerOperation() { String dnsPrefix = generateRandomResourceName("aci-dns", 20); Region region = Region.US_EAST; - ContainerGroup containerGroup = - containerInstanceManager - .containerGroups() - .define(containerGroupName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withoutVolume() - .withContainerInstance("mcr.microsoft.com/azuredocs/aci-helloworld", 80) - .withDnsPrefix(dnsPrefix) - .create(); + ContainerGroup containerGroup = containerInstanceManager.containerGroups() + .define(containerGroupName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withoutVolume() + .withContainerInstance("mcr.microsoft.com/azuredocs/aci-helloworld", 80) + .withDnsPrefix(dnsPrefix) + .create(); Assertions.assertTrue(containerGroup.fqdn().startsWith(dnsPrefix)); Container container = containerGroup.containers().values().iterator().next(); @@ -115,46 +115,38 @@ public void testCreateWithLivenessAndReadiness() { int failureThreshold = 3; int probePeriodSeconds = 10; - ContainerGroup containerGroup = - containerInstanceManager - .containerGroups() - .define(containerGroupName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withoutVolume() - .defineContainerInstance(containerName1) - .withImage("mcr.microsoft.com/azuredocs/aci-helloworld") - .withExternalTcpPort(80) - // simulate the situation where, container starts healthy for a given period of time, and then becomes unhealthy - .withStartingCommandLine("/bin/sh", "-c", "touch /tmp/healthy; sleep " + healthySeconds + "; rm -rf /tmp/healthy; sleep 600;") - .withLivenessProbeExecutionCommand(Arrays.asList("cat", "/tmp/healthy"), probePeriodSeconds, failureThreshold) - .withReadinessProbeHttpGet("/mypath", 80, 30, 3) - .attach() - .defineContainerInstance(containerName2) - .withImage("mcr.microsoft.com/azuredocs/aci-helloworld") - .withExternalTcpPort(8080) - .withLivenessProbe( - new ContainerProbe() - .withExec( - new ContainerExec() - .withCommand(Arrays.asList("/bin/bash", "myCustomScript2.sh"))) - .withPeriodSeconds(30) - .withFailureThreshold(2)) - .withReadinessProbe( - new ContainerProbe() - .withHttpGet( - new ContainerHttpGet() - .withPath("/") - .withPort(8080) - .withScheme(Scheme.HTTP)) - .withPeriodSeconds(30) - .withInitialDelaySeconds(0)) - .attach() - .withDnsPrefix(dnsPrefix) - .withRestartPolicy(ContainerGroupRestartPolicy.ALWAYS) - .create(); + ContainerGroup containerGroup = containerInstanceManager.containerGroups() + .define(containerGroupName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withoutVolume() + .defineContainerInstance(containerName1) + .withImage("mcr.microsoft.com/azuredocs/aci-helloworld") + .withExternalTcpPort(80) + // simulate the situation where, container starts healthy for a given period of time, and then becomes unhealthy + .withStartingCommandLine("/bin/sh", "-c", + "touch /tmp/healthy; sleep " + healthySeconds + "; rm -rf /tmp/healthy; sleep 600;") + .withLivenessProbeExecutionCommand(Arrays.asList("cat", "/tmp/healthy"), probePeriodSeconds, + failureThreshold) + .withReadinessProbeHttpGet("/mypath", 80, 30, 3) + .attach() + .defineContainerInstance(containerName2) + .withImage("mcr.microsoft.com/azuredocs/aci-helloworld") + .withExternalTcpPort(8080) + .withLivenessProbe(new ContainerProbe() + .withExec(new ContainerExec().withCommand(Arrays.asList("/bin/bash", "myCustomScript2.sh"))) + .withPeriodSeconds(30) + .withFailureThreshold(2)) + .withReadinessProbe(new ContainerProbe() + .withHttpGet(new ContainerHttpGet().withPath("/").withPort(8080).withScheme(Scheme.HTTP)) + .withPeriodSeconds(30) + .withInitialDelaySeconds(0)) + .attach() + .withDnsPrefix(dnsPrefix) + .withRestartPolicy(ContainerGroupRestartPolicy.ALWAYS) + .create(); Assertions.assertEquals(0, containerGroup.containers().get(containerName1).instanceView().restartCount()); Assertions.assertNull(containerGroup.containers().get(containerName1).instanceView().previousState()); @@ -175,11 +167,15 @@ public void testCreateWithLivenessAndReadiness() { ContainerState previousState = container.instanceView().previousState(); Assertions.assertNotNull(previousState); - Duration durationBeforeRestart = Duration.ofSeconds(previousState.finishTime().toEpochSecond() - previousState.startTime().toEpochSecond()); + Duration durationBeforeRestart = Duration + .ofSeconds(previousState.finishTime().toEpochSecond() - previousState.startTime().toEpochSecond()); // duration before restart should be in between healthy duration plus last probe and healthy duration plus latest probe - Assertions.assertTrue(durationBeforeRestart.compareTo(Duration.ofSeconds(healthySeconds + probePeriodSeconds * (failureThreshold - 1))) > 0); - Assertions.assertTrue(durationBeforeRestart.compareTo(Duration.ofSeconds(healthySeconds + probePeriodSeconds * failureThreshold)) <= 0); + Assertions.assertTrue(durationBeforeRestart + .compareTo(Duration.ofSeconds(healthySeconds + probePeriodSeconds * (failureThreshold - 1))) > 0); + Assertions.assertTrue( + durationBeforeRestart.compareTo(Duration.ofSeconds(healthySeconds + probePeriodSeconds * failureThreshold)) + <= 0); } @Test @@ -189,18 +185,16 @@ public void testBeginCreate() { Region region = Region.US_WEST3; // create resource group and virtual network, but no storage account, before create container group - Accepted acceptedContainerGroup = - containerInstanceManager - .containerGroups() - .define(containerGroupName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withoutVolume() - .withContainerInstance("nginx", 80) - .withNewVirtualNetwork("10.0.0.0/24") - .beginCreate(); + Accepted acceptedContainerGroup = containerInstanceManager.containerGroups() + .define(containerGroupName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withoutVolume() + .withContainerInstance("nginx", 80) + .withNewVirtualNetwork("10.0.0.0/24") + .beginCreate(); ContainerGroup createdContainerGroup = acceptedContainerGroup.getActivationResponse().getValue(); Assertions.assertNotEquals(succeededState, createdContainerGroup.provisioningState()); @@ -217,19 +211,17 @@ public void testBeginCreateWithFileShareVolume() { Region region = Region.US_WEST3; // create storage account (and virtual network), before create container group - Accepted acceptedContainerGroup = - containerInstanceManager - .containerGroups() - .define(containerGroupName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - // definition step only allow creating one file share volume - .withNewAzureFileShareVolume("vol1", "share1") - .withContainerInstance("nginx", 80) - .withNewVirtualNetwork("10.0.0.0/24") - .beginCreate(); + Accepted acceptedContainerGroup = containerInstanceManager.containerGroups() + .define(containerGroupName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + // definition step only allow creating one file share volume + .withNewAzureFileShareVolume("vol1", "share1") + .withContainerInstance("nginx", 80) + .withNewVirtualNetwork("10.0.0.0/24") + .beginCreate(); ContainerGroup containerGroup = acceptedContainerGroup.getSyncPoller().getFinalResult(); Assertions.assertEquals(1, containerGroup.volumes().size()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManagementTest.java index fcdf2a663f8fa..684736c281229 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/test/java/com/azure/resourcemanager/containerinstance/ContainerInstanceManagementTest.java @@ -24,21 +24,10 @@ public class ContainerInstanceManagementTest extends ResourceManagerTestProxyTes protected String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml index 46e21523bcca4..3457c2be7b063 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml @@ -42,6 +42,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/ContainerRegistryManager.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/ContainerRegistryManager.java index 43a0a62b50775..534e38329ffd9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/ContainerRegistryManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/ContainerRegistryManager.java @@ -22,8 +22,7 @@ import java.util.Objects; /** Entry point to Azure container registry management. */ -public final class ContainerRegistryManager - extends Manager { +public final class ContainerRegistryManager extends Manager { // The service managers private RegistriesImpl registries; private RegistryTasksImpl tasks; @@ -91,11 +90,8 @@ public ContainerRegistryManager authenticate(TokenCredential credential, AzurePr * @param profile the profile to use */ private ContainerRegistryManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new ContainerRegistryManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new ContainerRegistryManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesImpl.java index d4f8a645a3d19..bfbf3b9211fd9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesImpl.java @@ -45,17 +45,15 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this - .inner() - .listAsync(), + return PagedConverter.mapPage(this.inner().listAsync(), inner -> new RegistryImpl(inner.name(), inner, this.manager())); } @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } @@ -95,8 +93,7 @@ protected RegistryImpl wrapModel(RegistryInner containerServiceInner) { return null; } - return new RegistryImpl( - containerServiceInner.name(), containerServiceInner, this.manager()); + return new RegistryImpl(containerServiceInner.name(), containerServiceInner, this.manager()); } @Override @@ -106,30 +103,24 @@ public RegistryCredentials getCredentials(String resourceGroupName, String regis @Override public Mono getCredentialsAsync(String resourceGroupName, String registryName) { - return this - .inner() + return this.inner() .listCredentialsAsync(resourceGroupName, registryName) .map(registryListCredentialsResultInner -> new RegistryCredentialsImpl(registryListCredentialsResultInner)); } @Override - public RegistryCredentials regenerateCredential( - String resourceGroupName, String registryName, AccessKeyType accessKeyType) { - return new RegistryCredentialsImpl( - this - .inner() - .regenerateCredential( - resourceGroupName, registryName, - new RegenerateCredentialParameters().withName(PasswordName.fromString(accessKeyType.toString())))); + public RegistryCredentials regenerateCredential(String resourceGroupName, String registryName, + AccessKeyType accessKeyType) { + return new RegistryCredentialsImpl(this.inner() + .regenerateCredential(resourceGroupName, registryName, + new RegenerateCredentialParameters().withName(PasswordName.fromString(accessKeyType.toString())))); } @Override - public Mono regenerateCredentialAsync( - String resourceGroupName, String registryName, AccessKeyType accessKeyType) { - return this - .inner() - .regenerateCredentialAsync( - resourceGroupName, registryName, + public Mono regenerateCredentialAsync(String resourceGroupName, String registryName, + AccessKeyType accessKeyType) { + return this.inner() + .regenerateCredentialAsync(resourceGroupName, registryName, new RegenerateCredentialParameters().withName(PasswordName.fromString(accessKeyType.toString()))) .map(RegistryCredentialsImpl::new); } @@ -138,35 +129,27 @@ public Mono regenerateCredentialAsync( public Collection listQuotaUsages(String resourceGroupName, String registryName) { RegistryUsageListResultInner resultInner = this.inner().listUsages(resourceGroupName, registryName); - return Collections - .unmodifiableList( - resultInner != null && resultInner.value() != null - ? resultInner.value() - : new ArrayList<>()); + return Collections.unmodifiableList( + resultInner != null && resultInner.value() != null ? resultInner.value() : new ArrayList<>()); } @Override public PagedFlux listQuotaUsagesAsync(String resourceGroupName, String registryName) { - return PagedConverter - .convertListToPagedFlux( - this - .inner() - .listUsagesWithResponseAsync(resourceGroupName, registryName) - .map(r -> new SimpleResponse<>( - r.getRequest(), r.getStatusCode(), r.getHeaders(), - r.getValue().value() == null ? Collections.emptyList() : r.getValue().value()))); + return PagedConverter.convertListToPagedFlux(this.inner() + .listUsagesWithResponseAsync(resourceGroupName, registryName) + .map(r -> new SimpleResponse<>(r.getRequest(), r.getStatusCode(), r.getHeaders(), + r.getValue().value() == null ? Collections.emptyList() : r.getValue().value()))); } @Override public CheckNameAvailabilityResult checkNameAvailability(String name) { - return new CheckNameAvailabilityResultImpl(this.inner() - .checkNameAvailability(new RegistryNameCheckRequest().withName(name))); + return new CheckNameAvailabilityResultImpl( + this.inner().checkNameAvailability(new RegistryNameCheckRequest().withName(name))); } @Override public Mono checkNameAvailabilityAsync(String name) { - return this - .inner() + return this.inner() .checkNameAvailabilityAsync(new RegistryNameCheckRequest().withName(name)) .map(registryNameStatusInner -> new CheckNameAvailabilityResultImpl(registryNameStatusInner)); } @@ -178,8 +161,7 @@ public SourceUploadDefinition getBuildSourceUploadUrl(String rgName, String acrN @Override public Mono getBuildSourceUploadUrlAsync(String rgName, String acrName) { - return this - .manager() + return this.manager() .serviceClient() .getRegistries() .getBuildSourceUploadUrlAsync(rgName, acrName) diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesWebhooksClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesWebhooksClientImpl.java index 6116377287c0d..441f6fc54c07e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesWebhooksClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistriesWebhooksClientImpl.java @@ -30,35 +30,27 @@ public Webhook get(final String resourceGroupName, final String registryName, fi public Mono getAsync(final String resourceGroupName, final String registryName, final String webhookName) { final WebhooksClient webhooksInner = this.containerRegistryManager.serviceClient().getWebhooks(); - return webhooksInner - .getAsync(resourceGroupName, registryName, webhookName) - .map( - webhookInner -> { - if (this.containerRegistry != null) { - return new WebhookImpl( - webhookName, this.containerRegistry, webhookInner, this.containerRegistryManager); - } else { - return new WebhookImpl( - resourceGroupName, registryName, webhookName, webhookInner, this.containerRegistryManager); - } - }) - .flatMap(WebhookImpl::setCallbackConfigAsync); + return webhooksInner.getAsync(resourceGroupName, registryName, webhookName).map(webhookInner -> { + if (this.containerRegistry != null) { + return new WebhookImpl(webhookName, this.containerRegistry, webhookInner, + this.containerRegistryManager); + } else { + return new WebhookImpl(resourceGroupName, registryName, webhookName, webhookInner, + this.containerRegistryManager); + } + }).flatMap(WebhookImpl::setCallbackConfigAsync); } @Override public void delete(final String resourceGroupName, final String registryName, final String webhookName) { - this - .containerRegistryManager - .serviceClient() + this.containerRegistryManager.serviceClient() .getWebhooks() .delete(resourceGroupName, registryName, webhookName); } @Override public Mono deleteAsync(final String resourceGroupName, final String registryName, final String webhookName) { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .deleteAsync(resourceGroupName, registryName, webhookName); } @@ -73,23 +65,13 @@ public PagedFlux listAsync(final String resourceGroupName, final String final WebhooksClient webhooksInner = this.containerRegistryManager.serviceClient().getWebhooks(); return PagedConverter - .flatMapPage( - PagedConverter - .mapPage( - webhooksInner.listAsync(resourceGroupName, registryName), - inner -> { - if (this.containerRegistry != null) { - return new WebhookImpl( - inner.name(), this.containerRegistry, inner, this.containerRegistryManager); - } else { - return new WebhookImpl( - resourceGroupName, - registryName, - inner.name(), - inner, - this.containerRegistryManager); - } - }), - WebhookImpl::setCallbackConfigAsync); + .flatMapPage(PagedConverter.mapPage(webhooksInner.listAsync(resourceGroupName, registryName), inner -> { + if (this.containerRegistry != null) { + return new WebhookImpl(inner.name(), this.containerRegistry, inner, this.containerRegistryManager); + } else { + return new WebhookImpl(resourceGroupName, registryName, inner.name(), inner, + this.containerRegistryManager); + } + }), WebhookImpl::setCallbackConfigAsync); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryCredentialsImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryCredentialsImpl.java index e8e75d7230a0b..a24906ac7edf9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryCredentialsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryCredentialsImpl.java @@ -26,9 +26,11 @@ protected RegistryCredentialsImpl(RegistryListCredentialsResultInner innerObject case PASSWORD: this.accessKeys.put(AccessKeyType.PRIMARY, registryPassword.value()); break; + case PASSWORD2: this.accessKeys.put(AccessKeyType.SECONDARY, registryPassword.value()); break; + default: break; } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskRunRequestImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskRunRequestImpl.java index fad8ee6e0a0cb..79f356c6aa8ab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskRunRequestImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskRunRequestImpl.java @@ -13,10 +13,8 @@ import java.util.List; import java.util.Map; -class RegistryDockerTaskRunRequestImpl - implements RegistryDockerTaskRunRequest, - RegistryDockerTaskRunRequest.Definition, - HasInnerModel { +class RegistryDockerTaskRunRequestImpl implements RegistryDockerTaskRunRequest, RegistryDockerTaskRunRequest.Definition, + HasInnerModel { private DockerBuildRequest inner; private RegistryTaskRunImpl registryTaskRunImpl; @@ -84,8 +82,8 @@ public RegistryDockerTaskRunRequestImpl withCacheEnabled(boolean enabled) { } @Override - public RegistryDockerTaskRunRequestImpl withOverridingArguments( - Map overridingArguments) { + public RegistryDockerTaskRunRequestImpl + withOverridingArguments(Map overridingArguments) { if (overridingArguments.size() == 0) { return this; } @@ -102,8 +100,8 @@ public RegistryDockerTaskRunRequestImpl withOverridingArguments( } @Override - public DefinitionStages.DockerTaskRunRequestStepAttachable withOverridingArgument( - String name, OverridingArgument overridingArgument) { + public DefinitionStages.DockerTaskRunRequestStepAttachable withOverridingArgument(String name, + OverridingArgument overridingArgument) { if (this.inner.arguments() == null) { this.inner.withArguments(new ArrayList()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskStepImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskStepImpl.java index 11320f4eb890e..d6a0cdd4513bd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskStepImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryDockerTaskStepImpl.java @@ -16,11 +16,8 @@ import java.util.List; import java.util.Map; -class RegistryDockerTaskStepImpl extends RegistryTaskStepImpl - implements RegistryDockerTaskStep, - RegistryDockerTaskStep.Definition, - RegistryDockerTaskStep.Update, - HasInnerModel { +class RegistryDockerTaskStepImpl extends RegistryTaskStepImpl implements RegistryDockerTaskStep, + RegistryDockerTaskStep.Definition, RegistryDockerTaskStep.Update, HasInnerModel { private DockerTaskStep inner; private DockerBuildStepUpdateParameters dockerTaskStepUpdateParameters; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskRunRequestImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskRunRequestImpl.java index 2e7ab196b9eb2..7f072e4ee8690 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskRunRequestImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskRunRequestImpl.java @@ -13,10 +13,8 @@ import java.util.List; import java.util.Map; -class RegistryEncodedTaskRunRequestImpl - implements RegistryEncodedTaskRunRequest, - RegistryEncodedTaskRunRequest.Definition, - HasInnerModel { +class RegistryEncodedTaskRunRequestImpl implements RegistryEncodedTaskRunRequest, + RegistryEncodedTaskRunRequest.Definition, HasInnerModel { private EncodedTaskRunRequest inner; private RegistryTaskRunImpl registryTaskRunImpl; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskStepImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskStepImpl.java index 01b63aad41953..e51b8cd6a108f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskStepImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryEncodedTaskStepImpl.java @@ -16,11 +16,8 @@ import java.util.List; import java.util.Map; -class RegistryEncodedTaskStepImpl extends RegistryTaskStepImpl - implements RegistryEncodedTaskStep, - RegistryEncodedTaskStep.Definition, - RegistryEncodedTaskStep.Update, - HasInnerModel { +class RegistryEncodedTaskStepImpl extends RegistryTaskStepImpl implements RegistryEncodedTaskStep, + RegistryEncodedTaskStep.Definition, RegistryEncodedTaskStep.Update, HasInnerModel { private EncodedTaskStep inner; private EncodedTaskStepUpdateParameters encodedTaskStepUpdateParameters; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryFileTaskStepImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryFileTaskStepImpl.java index 01a4c6e9487ec..3b781d20f83f4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryFileTaskStepImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryFileTaskStepImpl.java @@ -16,11 +16,8 @@ import java.util.List; import java.util.Map; -class RegistryFileTaskStepImpl extends RegistryTaskStepImpl - implements RegistryFileTaskStep, - RegistryFileTaskStep.Definition, - RegistryFileTaskStep.Update, - HasInnerModel { +class RegistryFileTaskStepImpl extends RegistryTaskStepImpl implements RegistryFileTaskStep, + RegistryFileTaskStep.Definition, RegistryFileTaskStep.Update, HasInnerModel { private FileTaskStep inner; private FileTaskStepUpdateParameters fileTaskStepUpdateParameters; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryImpl.java index fdc832dc0b63b..b6d4bb69378ee 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryImpl.java @@ -53,8 +53,7 @@ public class RegistryImpl extends GroupableResourceImpl getInnerAsync() { - return this.manager().serviceClient().getRegistries() + return this.manager() + .serviceClient() + .getRegistries() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @@ -76,15 +77,13 @@ public RegistryImpl update() { public Mono createResourceAsync() { final RegistryImpl self = this; if (isInCreateMode()) { - return manager() - .serviceClient() + return manager().serviceClient() .getRegistries() .createAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(innerToFluentMap(this)); } else { updateParameters.withTags(innerModel().tags()); - return manager() - .serviceClient() + return manager().serviceClient() .getRegistries() .updateAsync(self.resourceGroupName(), self.name(), self.updateParameters) .map(innerToFluentMap(this)); @@ -176,16 +175,14 @@ public Mono getCredentialsAsync() { @Override public RegistryCredentials regenerateCredential(AccessKeyType accessKeyType) { - return this - .manager() + return this.manager() .containerRegistries() .regenerateCredential(this.resourceGroupName(), this.name(), accessKeyType); } @Override public Mono regenerateCredentialAsync(AccessKeyType accessKeyType) { - return this - .manager() + return this.manager() .containerRegistries() .regenerateCredentialAsync(this.resourceGroupName(), this.name(), accessKeyType); } @@ -227,19 +224,21 @@ public boolean isDedicatedDataEndpointsEnabled() { @Override public boolean isZoneRedundancyEnabled() { - return !Objects.isNull(this.innerModel().zoneRedundancy()) && ZoneRedundancy.ENABLED.equals(this.innerModel().zoneRedundancy()); + return !Objects.isNull(this.innerModel().zoneRedundancy()) + && ZoneRedundancy.ENABLED.equals(this.innerModel().zoneRedundancy()); } @Override public List dedicatedDataEndpointsHostNames() { return this.innerModel().dataEndpointHostNames() == null - ? Collections.emptyList() : Collections.unmodifiableList(this.innerModel().dataEndpointHostNames()); + ? Collections.emptyList() + : Collections.unmodifiableList(this.innerModel().dataEndpointHostNames()); } @Override public RegistryTaskRun.DefinitionStages.BlankFromRegistry scheduleRun() { - return new RegistryTaskRunImpl(this.manager(), new RunInner()) - .withExistingRegistry(this.resourceGroupName(), this.name()); + return new RegistryTaskRunImpl(this.manager(), new RunInner()).withExistingRegistry(this.resourceGroupName(), + this.name()); } @Override @@ -249,8 +248,7 @@ public SourceUploadDefinition getBuildSourceUploadUrl() { @Override public Mono getBuildSourceUploadUrlAsync() { - return this - .manager() + return this.manager() .serviceClient() .getRegistries() .getBuildSourceUploadUrlAsync(this.resourceGroupName(), this.name()) @@ -318,9 +316,15 @@ public RegistryImpl withAccessFromAllNetworks() { @Override public RegistryImpl withAccessFromIpAddressRange(String ipAddressCidr) { ensureNetworkRuleSet(); - if (this.innerModel().networkRuleSet().ipRules() - .stream().noneMatch(ipRule -> Objects.equals(ipRule.ipAddressOrRange(), ipAddressCidr))) { - this.innerModel().networkRuleSet().ipRules().add(new IpRule().withAction(Action.ALLOW).withIpAddressOrRange(ipAddressCidr)); + if (this.innerModel() + .networkRuleSet() + .ipRules() + .stream() + .noneMatch(ipRule -> Objects.equals(ipRule.ipAddressOrRange(), ipAddressCidr))) { + this.innerModel() + .networkRuleSet() + .ipRules() + .add(new IpRule().withAction(Action.ALLOW).withIpAddressOrRange(ipAddressCidr)); } if (!isInCreateMode()) { updateParameters.networkRuleSet().withIpRules(this.innerModel().networkRuleSet().ipRules()); @@ -334,7 +338,10 @@ public RegistryImpl withoutAccessFromIpAddressRange(String ipAddressCidr) { return this; } ensureNetworkRuleSet(); - this.innerModel().networkRuleSet().ipRules().removeIf(ipRule -> Objects.equals(ipRule.ipAddressOrRange(), ipAddressCidr)); + this.innerModel() + .networkRuleSet() + .ipRules() + .removeIf(ipRule -> Objects.equals(ipRule.ipAddressOrRange(), ipAddressCidr)); if (!isInCreateMode()) { updateParameters.networkRuleSet().withIpRules(this.innerModel().networkRuleSet().ipRules()); } @@ -398,7 +405,9 @@ public PagedIterable listPrivateEndpointConnections() @Override public PagedFlux listPrivateEndpointConnectionsAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() + return PagedConverter.mapPage(this.manager() + .serviceClient() + .getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @@ -409,12 +418,12 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .createOrUpdateAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState() - .withStatus( - ConnectionStatus.APPROVED))) + new PrivateLinkServiceConnectionState().withStatus(ConnectionStatus.APPROVED))) .then(); } @@ -425,12 +434,12 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .createOrUpdateAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState() - .withStatus( - ConnectionStatus.REJECTED))) + new PrivateLinkServiceConnectionState().withStatus(ConnectionStatus.REJECTED))) .then(); } @@ -454,7 +463,9 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - return this.manager().serviceClient().getRegistries() + return this.manager() + .serviceClient() + .getRegistries() .listPrivateLinkResourcesAsync(this.resourceGroupName(), this.name()) .mapPage(PrivateLinkResourceImpl::new); } @@ -494,27 +505,25 @@ private static final class PrivateEndpointConnectionImpl implements PrivateEndpo private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; - private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState - privateLinkServiceConnectionState; + private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; - this.privateEndpoint = innerModel.privateEndpoint() == null - ? null - : new PrivateEndpoint(innerModel.privateEndpoint().id()); + this.privateEndpoint + = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( - innerModel.privateLinkServiceConnectionState().status() == null - ? null - : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus - .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), - innerModel.privateLinkServiceConnectionState().description(), - innerModel.privateLinkServiceConnectionState().actionsRequired() == null - ? ActionsRequired.NONE.toString() - : innerModel.privateLinkServiceConnectionState().actionsRequired().toString()); + innerModel.privateLinkServiceConnectionState().status() == null + ? null + : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus + .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), + innerModel.privateLinkServiceConnectionState().description(), + innerModel.privateLinkServiceConnectionState().actionsRequired() == null + ? ActionsRequired.NONE.toString() + : innerModel.privateLinkServiceConnectionState().actionsRequired().toString()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistrySourceTriggerImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistrySourceTriggerImpl.java index 71caf0563656d..efbdbc69eb9fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistrySourceTriggerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistrySourceTriggerImpl.java @@ -18,12 +18,8 @@ import java.util.ArrayList; import java.util.List; -class RegistrySourceTriggerImpl - implements RegistrySourceTrigger, - RegistrySourceTrigger.Definition, - RegistrySourceTrigger.Update, - RegistrySourceTrigger.UpdateDefinition, - HasInnerModel { +class RegistrySourceTriggerImpl implements RegistrySourceTrigger, RegistrySourceTrigger.Definition, + RegistrySourceTrigger.Update, RegistrySourceTrigger.UpdateDefinition, HasInnerModel { private SourceTrigger inner; private RegistryTaskImpl registryTaskImpl; private SourceTriggerUpdateParameters sourceTriggerUpdateParameters; @@ -46,8 +42,8 @@ class RegistrySourceTriggerImpl this.inner.withSourceRepository(new SourceProperties()); boolean foundSourceTrigger = false; - for (SourceTriggerUpdateParameters stup - : registryTaskImpl.taskUpdateParameters.trigger().sourceTriggers()) { + for (SourceTriggerUpdateParameters stup : registryTaskImpl.taskUpdateParameters.trigger() + .sourceTriggers()) { if (stup.name().equals(sourceTriggerName)) { this.sourceTriggerUpdateParameters = stup; foundSourceTrigger = true; @@ -102,9 +98,7 @@ public RegistrySourceTriggerImpl withAzureDevOpsAsSourceControl() { if (isInCreateMode()) { this.inner.sourceRepository().withSourceControlType(SourceControlType.VISUAL_STUDIO_TEAM_SERVICE); } else { - this - .sourceTriggerUpdateParameters - .sourceRepository() + this.sourceTriggerUpdateParameters.sourceRepository() .withSourceControlType(SourceControlType.VISUAL_STUDIO_TEAM_SERVICE); } return this; @@ -115,9 +109,7 @@ public RegistrySourceTriggerImpl withSourceControl(SourceControlType sourceContr if (isInCreateMode()) { this.inner.sourceRepository().withSourceControlType(SourceControlType.fromString(sourceControl.toString())); } else { - this - .sourceTriggerUpdateParameters - .sourceRepository() + this.sourceTriggerUpdateParameters.sourceRepository() .withSourceControlType(SourceControlType.fromString(sourceControl.toString())); } return this; @@ -149,39 +141,31 @@ public RegistrySourceTriggerImpl withRepositoryAuthentication(TokenType tokenTyp AuthInfo authInfo = new AuthInfo().withTokenType(tokenType).withToken(token); this.inner.sourceRepository().withSourceControlAuthProperties(authInfo); } else { - AuthInfoUpdateParameters authInfoUpdateParameters = - new AuthInfoUpdateParameters().withTokenType(tokenType).withToken(token); - this - .sourceTriggerUpdateParameters - .sourceRepository() + AuthInfoUpdateParameters authInfoUpdateParameters + = new AuthInfoUpdateParameters().withTokenType(tokenType).withToken(token); + this.sourceTriggerUpdateParameters.sourceRepository() .withSourceControlAuthProperties(authInfoUpdateParameters); } return this; } @Override - public RegistrySourceTriggerImpl withRepositoryAuthentication( - TokenType tokenType, String token, String refreshToken, String scope, int expiresIn) { + public RegistrySourceTriggerImpl withRepositoryAuthentication(TokenType tokenType, String token, + String refreshToken, String scope, int expiresIn) { if (isInCreateMode()) { - AuthInfo authInfo = - new AuthInfo() - .withTokenType(tokenType) - .withToken(token) - .withRefreshToken(refreshToken) - .withScope(scope) - .withExpiresIn(expiresIn); + AuthInfo authInfo = new AuthInfo().withTokenType(tokenType) + .withToken(token) + .withRefreshToken(refreshToken) + .withScope(scope) + .withExpiresIn(expiresIn); this.inner.sourceRepository().withSourceControlAuthProperties(authInfo); } else { - AuthInfoUpdateParameters authInfoUpdateParameters = - new AuthInfoUpdateParameters() - .withTokenType(tokenType) - .withToken(token) - .withRefreshToken(refreshToken) - .withScope(scope) - .withExpiresIn(expiresIn); - this - .sourceTriggerUpdateParameters - .sourceRepository() + AuthInfoUpdateParameters authInfoUpdateParameters = new AuthInfoUpdateParameters().withTokenType(tokenType) + .withToken(token) + .withRefreshToken(refreshToken) + .withScope(scope) + .withExpiresIn(expiresIn); + this.sourceTriggerUpdateParameters.sourceRepository() .withSourceControlAuthProperties(authInfoUpdateParameters); } return this; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskImpl.java index 50293bb628d3d..9085bbb22681b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskImpl.java @@ -171,8 +171,8 @@ public TriggerProperties trigger() { public Map sourceTriggers() { Map sourceTriggerMap = new HashMap(); for (SourceTrigger sourceTrigger : this.inner.trigger().sourceTriggers()) { - sourceTriggerMap - .put(sourceTrigger.name(), new RegistrySourceTriggerImpl(sourceTrigger.name(), this, false)); + sourceTriggerMap.put(sourceTrigger.name(), + new RegistrySourceTriggerImpl(sourceTrigger.name(), this, false)); } return sourceTriggerMap; } @@ -189,8 +189,8 @@ public Map sourceTriggers() { this.taskName = inner.name(); this.inner = inner; this.resourceGroupName = ResourceUtils.groupFromResourceId(this.inner.id()); - this.registryName = - ResourceUtils.nameFromResourceId(ResourceUtils.parentResourceIdFromResourceId(this.inner.id())); + this.registryName + = ResourceUtils.nameFromResourceId(ResourceUtils.parentResourceIdFromResourceId(this.inner.id())); this.taskUpdateParameters = new TaskUpdateParameters(); setTaskUpdateParameterTriggers(); } @@ -355,33 +355,27 @@ public RegistrySourceTriggerImpl defineSourceTrigger(String sourceTriggerName) { } @Override - public DefinitionStages.TaskCreatable withBaseImageTrigger( - String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType) { + public DefinitionStages.TaskCreatable withBaseImageTrigger(String baseImageTriggerName, + BaseImageTriggerType baseImageTriggerType) { if (this.inner.trigger() == null) { this.inner.withTrigger(new TriggerProperties()); } - this - .inner - .trigger() + this.inner.trigger() .withBaseImageTrigger( new BaseImageTrigger().withBaseImageTriggerType(baseImageTriggerType).withName(baseImageTriggerName)); return this; } @Override - public DefinitionStages.TaskCreatable withBaseImageTrigger( - String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus) { + public DefinitionStages.TaskCreatable withBaseImageTrigger(String baseImageTriggerName, + BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus) { if (this.inner.trigger() == null) { this.inner.withTrigger(new TriggerProperties()); } - this - .inner - .trigger() - .withBaseImageTrigger( - new BaseImageTrigger() - .withBaseImageTriggerType(baseImageTriggerType) - .withName(baseImageTriggerName) - .withStatus(triggerStatus)); + this.inner.trigger() + .withBaseImageTrigger(new BaseImageTrigger().withBaseImageTriggerType(baseImageTriggerType) + .withName(baseImageTriggerName) + .withStatus(triggerStatus)); return this; } @@ -429,17 +423,14 @@ public RegistryTask create(Context context) { @Override public Mono createAsync(Context context) { final RegistryTaskImpl self = this; - return this - .tasksInner - .createAsync(this.resourceGroupName, this.registryName, this.taskName, this.inner) + return this.tasksInner.createAsync(this.resourceGroupName, this.registryName, this.taskName, this.inner) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .flatMap( - taskInner -> { - self.inner = taskInner; - self.taskUpdateParameters = new TaskUpdateParameters(); - self.setTaskUpdateParameterTriggers(); - return Mono.just(self); - }); + .flatMap(taskInner -> { + self.inner = taskInner; + self.taskUpdateParameters = new TaskUpdateParameters(); + self.setTaskUpdateParameterTriggers(); + return Mono.just(self); + }); } @Override @@ -450,25 +441,20 @@ public RegistryTask refresh() { @Override public Mono refreshAsync() { final RegistryTaskImpl self = this; - return this - .tasksInner - .getAsync(this.resourceGroupName, this.registryName, this.taskName) - .map( - taskInner -> { - self.inner = taskInner; - self.taskUpdateParameters = new TaskUpdateParameters(); - self.setTaskUpdateParameterTriggers(); - return self; - }); + return this.tasksInner.getAsync(this.resourceGroupName, this.registryName, this.taskName).map(taskInner -> { + self.inner = taskInner; + self.taskUpdateParameters = new TaskUpdateParameters(); + self.setTaskUpdateParameterTriggers(); + return self; + }); } @Override public RegistryFileTaskStep.Update updateFileTaskStep() { if (!(this.inner.step() instanceof FileTaskStep)) { - throw logger.logExceptionAsError(new UnsupportedOperationException( - "Calling updateFileTaskStep on a RegistryTask that is of type " - + this.inner.step().getClass().getName() - + ".")); + throw logger.logExceptionAsError( + new UnsupportedOperationException("Calling updateFileTaskStep on a RegistryTask that is of type " + + this.inner.step().getClass().getName() + ".")); } return new RegistryFileTaskStepImpl(this); } @@ -476,10 +462,9 @@ public RegistryFileTaskStep.Update updateFileTaskStep() { @Override public RegistryEncodedTaskStep.Update updateEncodedTaskStep() { if (!(this.inner.step() instanceof EncodedTaskStep)) { - throw logger.logExceptionAsError(new UnsupportedOperationException( - "Calling updateEncodedTaskStep on a RegistryTask that is of type " - + this.inner.step().getClass().getName() - + ".")); + throw logger.logExceptionAsError( + new UnsupportedOperationException("Calling updateEncodedTaskStep on a RegistryTask that is of type " + + this.inner.step().getClass().getName() + ".")); } return new RegistryEncodedTaskStepImpl(this); } @@ -487,10 +472,9 @@ public RegistryEncodedTaskStep.Update updateEncodedTaskStep() { @Override public RegistryDockerTaskStep.Update updateDockerTaskStep() { if (!(this.inner.step() instanceof DockerTaskStep)) { - throw logger.logExceptionAsError(new UnsupportedOperationException( - "Calling updateDockerTaskStep on a RegistryTask that is of type " - + this.inner.step().getClass().getName() - + ".")); + throw logger.logExceptionAsError( + new UnsupportedOperationException("Calling updateDockerTaskStep on a RegistryTask that is of type " + + this.inner.step().getClass().getName() + ".")); } return new RegistryDockerTaskStepImpl(this); } @@ -502,27 +486,19 @@ public RegistrySourceTrigger.Update updateSourceTrigger(String sourceTriggerName @Override public Update updateBaseImageTrigger(String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType) { - this - .taskUpdateParameters - .trigger() - .withBaseImageTrigger( - new BaseImageTriggerUpdateParameters() - .withBaseImageTriggerType(baseImageTriggerType) - .withName(baseImageTriggerName)); + this.taskUpdateParameters.trigger() + .withBaseImageTrigger(new BaseImageTriggerUpdateParameters().withBaseImageTriggerType(baseImageTriggerType) + .withName(baseImageTriggerName)); return this; } @Override - public Update updateBaseImageTrigger( - String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus) { - this - .taskUpdateParameters - .trigger() - .withBaseImageTrigger( - new BaseImageTriggerUpdateParameters() - .withBaseImageTriggerType(baseImageTriggerType) - .withName(baseImageTriggerName) - .withStatus(triggerStatus)); + public Update updateBaseImageTrigger(String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, + TriggerStatus triggerStatus) { + this.taskUpdateParameters.trigger() + .withBaseImageTrigger(new BaseImageTriggerUpdateParameters().withBaseImageTriggerType(baseImageTriggerType) + .withName(baseImageTriggerName) + .withStatus(triggerStatus)); return this; } @@ -549,19 +525,17 @@ public RegistryTask apply(Context context) { @Override public Mono applyAsync(Context context) { final RegistryTaskImpl self = this; - return this - .tasksInner + return this.tasksInner .updateAsync(this.resourceGroupName, this.registryName, this.taskName, this.taskUpdateParameters) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map( - taskInner -> { - self.inner = taskInner; - self.taskUpdateParameters = new TaskUpdateParameters(); - self.registryTaskStep = null; - self.taskUpdateParameters = new TaskUpdateParameters(); - self.setTaskUpdateParameterTriggers(); - return self; - }); + .map(taskInner -> { + self.inner = taskInner; + self.taskUpdateParameters = new TaskUpdateParameters(); + self.registryTaskStep = null; + self.taskUpdateParameters = new TaskUpdateParameters(); + self.setTaskUpdateParameterTriggers(); + return self; + }); } private boolean isInCreateMode() { @@ -602,8 +576,8 @@ void withSourceTriggerCreateParameters(SourceTrigger sourceTrigger) { } void withSourceTriggerUpdateParameters(SourceTriggerUpdateParameters sourceTriggerUpdateParameters) { - List sourceTriggerUpdateParametersList = - this.taskUpdateParameters.trigger().sourceTriggers(); + List sourceTriggerUpdateParametersList + = this.taskUpdateParameters.trigger().sourceTriggers(); sourceTriggerUpdateParametersList.add(sourceTriggerUpdateParameters); this.taskUpdateParameters.trigger().withSourceTriggers(sourceTriggerUpdateParametersList); } @@ -617,8 +591,8 @@ void setTaskUpdateParameterTriggers() { return; } if (this.inner.trigger().sourceTriggers() != null) { - List sourceTriggerUpdateParameters = - new ArrayList(); + List sourceTriggerUpdateParameters + = new ArrayList(); for (SourceTrigger sourceTrigger : this.inner.trigger().sourceTriggers()) { sourceTriggerUpdateParameters.add(sourceTriggerToSourceTriggerUpdateParameters(sourceTrigger)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunImpl.java index 1cd8f6f9bfba0..74f6dd2c24409 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunImpl.java @@ -301,41 +301,33 @@ public RegistryTaskRun execute() { public Mono executeAsync() { final RegistryTaskRunImpl self = this; if (this.fileTaskRunRequest != null) { - return this - .registriesInner + return this.registriesInner .scheduleRunAsync(this.resourceGroupName(), this.registryName(), this.fileTaskRunRequest) - .map( - runInner -> { - self.inner = runInner; - return self; - }); + .map(runInner -> { + self.inner = runInner; + return self; + }); } else if (this.encodedTaskRunRequest != null) { - return this - .registriesInner + return this.registriesInner .scheduleRunAsync(this.resourceGroupName(), this.registryName(), this.encodedTaskRunRequest) - .map( - runInner -> { - self.inner = runInner; - return self; - }); + .map(runInner -> { + self.inner = runInner; + return self; + }); } else if (this.dockerTaskRunRequest != null) { - return this - .registriesInner + return this.registriesInner .scheduleRunAsync(this.resourceGroupName(), this.registryName(), this.dockerTaskRunRequest) - .map( - runInner -> { - self.inner = runInner; - return self; - }); + .map(runInner -> { + self.inner = runInner; + return self; + }); } else if (this.taskRunRequest != null) { - return this - .registriesInner + return this.registriesInner .scheduleRunAsync(this.resourceGroupName(), this.registryName(), this.taskRunRequest) - .map( - runInner -> { - self.inner = runInner; - return self; - }); + .map(runInner -> { + self.inner = runInner; + return self; + }); } throw logger.logExceptionAsError(new RuntimeException("Unsupported file task run request")); } @@ -373,14 +365,12 @@ public RegistryTaskRun refresh() { @Override public Mono refreshAsync() { final RegistryTaskRunImpl self = this; - return registryManager - .serviceClient() + return registryManager.serviceClient() .getRuns() .getAsync(this.resourceGroupName(), this.registryName(), this.inner.runId()) - .map( - runInner -> { - self.inner = runInner; - return self; - }); + .map(runInner -> { + self.inner = runInner; + return self; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunsImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunsImpl.java index 9859834b6c661..ce17ba64d1dce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTaskRunsImpl.java @@ -37,9 +37,7 @@ public PagedIterable listByRegistry(String rgName, String acrNa @Override public Mono getLogSasUrlAsync(String rgName, String acrName, String runId) { - return this - .registryManager - .serviceClient() + return this.registryManager.serviceClient() .getRuns() .getLogSasUrlAsync(rgName, acrName, runId) .map(runGetLogResultInner -> runGetLogResultInner.logLink()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTasksImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTasksImpl.java index 2b5127f21f6df..573db6b801cd6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTasksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/RegistryTasksImpl.java @@ -28,11 +28,8 @@ public RegistryTask.DefinitionStages.Blank define(String name) { @Override public PagedFlux listByRegistryAsync(String resourceGroupName, String registryName) { - return PagedConverter.mapPage(this - .registryManager - .serviceClient() - .getTasks() - .listAsync(resourceGroupName, registryName), + return PagedConverter.mapPage( + this.registryManager.serviceClient().getTasks().listAsync(resourceGroupName, registryName), inner -> wrapModel(inner)); } @@ -42,19 +39,15 @@ public PagedIterable listByRegistry(String resourceGroupName, Stri } @Override - public Mono getByRegistryAsync( - String resourceGroupName, String registryName, String taskName, boolean includeSecrets) { + public Mono getByRegistryAsync(String resourceGroupName, String registryName, String taskName, + boolean includeSecrets) { if (includeSecrets) { - return this - .registryManager - .serviceClient() + return this.registryManager.serviceClient() .getTasks() .getDetailsAsync(resourceGroupName, registryName, taskName) .map(taskInner -> new RegistryTaskImpl(registryManager, taskInner)); } else { - return this - .registryManager - .serviceClient() + return this.registryManager.serviceClient() .getTasks() .getAsync(resourceGroupName, registryName, taskName) .map(taskInner -> new RegistryTaskImpl(registryManager, taskInner)); @@ -62,8 +55,8 @@ public Mono getByRegistryAsync( } @Override - public RegistryTask getByRegistry( - String resourceGroupName, String registryName, String taskName, boolean includeSecrets) { + public RegistryTask getByRegistry(String resourceGroupName, String registryName, String taskName, + boolean includeSecrets) { return this.getByRegistryAsync(resourceGroupName, registryName, taskName, includeSecrets).block(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookImpl.java index 086f8be508b3d..3d1a19312f9c3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookImpl.java @@ -32,11 +32,8 @@ /** Implementation for Webhook. */ public class WebhookImpl extends ExternalChildResourceImpl - implements Webhook, - Webhook.WebhookDefinition, - Webhook.UpdateDefinition, - Webhook.UpdateResource, - Webhook.Update { + implements Webhook, Webhook.WebhookDefinition, + Webhook.UpdateDefinition, Webhook.UpdateResource, Webhook.Update { private WebhookCreateParameters webhookCreateParametersInner; private WebhookUpdateParameters webhookUpdateParametersInner; @@ -58,8 +55,8 @@ public class WebhookImpl extends ExternalChildResourceImpl nameLowerCase.equals(r.name().toLowerCase(Locale.ROOT))) .findFirst() .orElse(null); @@ -196,9 +190,7 @@ public Mono disableAsync() { @Override public String ping() { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .ping(this.resourceGroupName, this.registryName, name()) .id(); @@ -206,9 +198,7 @@ public String ping() { @Override public Mono pingAsync() { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .pingAsync(this.resourceGroupName, this.registryName, name()) .map(eventInfoInner -> eventInfoInner.id()); @@ -223,11 +213,10 @@ public PagedIterable listEvents() { public PagedFlux listEventsAsync() { final WebhookImpl self = this; - return PagedConverter.mapPage(this - .containerRegistryManager - .serviceClient() - .getWebhooks() - .listEventsAsync(self.resourceGroupName, self.registryName, self.name()), + return PagedConverter.mapPage( + this.containerRegistryManager.serviceClient() + .getWebhooks() + .listEventsAsync(self.resourceGroupName, self.registryName, self.name()), inner -> new WebhookEventInfoImpl(inner)); } @@ -235,17 +224,14 @@ public PagedFlux listEventsAsync() { public Mono createResourceAsync() { final WebhookImpl self = this; if (webhookCreateParametersInner != null) { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .createAsync(self.resourceGroupName, this.registryName, this.name(), this.webhookCreateParametersInner) - .map( - inner -> { - self.webhookCreateParametersInner = null; - self.setInner(inner); - return self; - }) + .map(inner -> { + self.webhookCreateParametersInner = null; + self.setInner(inner); + return self; + }) .flatMap(webhook -> self.setCallbackConfigAsync()); } else { return Mono.just(this); @@ -254,43 +240,36 @@ public Mono createResourceAsync() { WebhookImpl setCallbackConfig(CallbackConfigInner callbackConfigInner) { this.serviceUri = callbackConfigInner.serviceUri(); - this.customHeaders = - callbackConfigInner.customHeaders() != null - ? callbackConfigInner.customHeaders() - : new HashMap(); + this.customHeaders = callbackConfigInner.customHeaders() != null + ? callbackConfigInner.customHeaders() + : new HashMap(); return this; } Mono setCallbackConfigAsync() { final WebhookImpl self = this; - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .getCallbackConfigAsync(self.resourceGroupName, self.registryName, self.name()) - .map( - callbackConfigInner -> { - setCallbackConfig(callbackConfigInner); - return self; - }); + .map(callbackConfigInner -> { + setCallbackConfig(callbackConfigInner); + return self; + }); } @Override public Mono updateResourceAsync() { final WebhookImpl self = this; if (webhookUpdateParametersInner != null) { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .updateAsync(self.resourceGroupName, self.registryName, self.name(), self.webhookUpdateParametersInner) - .map( - inner -> { - self.setInner(inner); - self.webhookUpdateParametersInner = null; - return self; - }) + .map(inner -> { + self.setInner(inner); + self.webhookUpdateParametersInner = null; + return self; + }) .flatMap(webhook -> self.setCallbackConfigAsync()); } else { return Mono.just(this); @@ -299,9 +278,7 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .containerRegistryManager - .serviceClient() + return this.containerRegistryManager.serviceClient() .getWebhooks() .deleteAsync(this.resourceGroupName, this.registryName, this.name()); } @@ -310,14 +287,10 @@ public Mono deleteResourceAsync() { protected Mono getInnerAsync() { final WebhookImpl self = this; final WebhooksClient webhooksInner = this.containerRegistryManager.serviceClient().getWebhooks(); - return webhooksInner - .getAsync(this.resourceGroupName, this.registryName, this.name()) - .flatMap( - webhookInner -> { - self.setInner(webhookInner); - return webhooksInner.getCallbackConfigAsync(self.resourceGroupName, self.registryName, self.name()); - }) - .map(callbackConfigInner -> setCallbackConfig(callbackConfigInner).innerModel()); + return webhooksInner.getAsync(this.resourceGroupName, this.registryName, this.name()).flatMap(webhookInner -> { + self.setInner(webhookInner); + return webhooksInner.getCallbackConfigAsync(self.resourceGroupName, self.registryName, self.name()); + }).map(callbackConfigInner -> setCallbackConfig(callbackConfigInner).innerModel()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookOperationsImpl.java index 4f2b9e89141e9..6db25ac0bd7c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhookOperationsImpl.java @@ -32,8 +32,8 @@ public Mono getAsync(final String webhookName) { if (this.containerRegistry == null) { return null; } - return webhooksClient - .getAsync(this.containerRegistry.resourceGroupName(), this.containerRegistry.name(), webhookName); + return webhooksClient.getAsync(this.containerRegistry.resourceGroupName(), this.containerRegistry.name(), + webhookName); } @Override @@ -41,9 +41,8 @@ public void delete(final String webhookName) { if (this.containerRegistry == null) { return; } - this - .webhooksClient - .delete(this.containerRegistry.resourceGroupName(), this.containerRegistry.name(), webhookName); + this.webhooksClient.delete(this.containerRegistry.resourceGroupName(), this.containerRegistry.name(), + webhookName); } @Override @@ -51,9 +50,8 @@ public Mono deleteAsync(final String webhookName) { if (this.containerRegistry == null) { return null; } - return this - .webhooksClient - .deleteAsync(this.containerRegistry.resourceGroupName(), this.containerRegistry.name(), webhookName); + return this.webhooksClient.deleteAsync(this.containerRegistry.resourceGroupName(), + this.containerRegistry.name(), webhookName); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhooksImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhooksImpl.java index 8332b8a51c226..f643181c0c3ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhooksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/WebhooksImpl.java @@ -34,8 +34,7 @@ WebhookImpl updateWebhook(String name) { } void withoutWebhook(String name) { - prepareInlineRemove( - new WebhookImpl(name, this.getParent(), new WebhookInner(), this.getParent().manager()) - .setCreateMode(false)); + prepareInlineRemove(new WebhookImpl(name, this.getParent(), new WebhookInner(), this.getParent().manager()) + .setCreateMode(false)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/CheckNameAvailabilityResult.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/CheckNameAvailabilityResult.java index 4e3d7ea80ed99..622cb40ef1378 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/CheckNameAvailabilityResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/CheckNameAvailabilityResult.java @@ -11,6 +11,7 @@ public interface CheckNameAvailabilityResult extends HasInnerModel { /** @return true if the specified name is valid and available for use, otherwise false */ boolean isAvailable(); + /** @return the reason why the user-provided name for the container registry could not be used */ String unavailabilityReason(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registries.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registries.java index 666d2ab5505d5..f2f69b374412a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registries.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registries.java @@ -21,16 +21,10 @@ /** Entry point to the registry management API. */ @Fluent() -public interface Registries - extends SupportsCreating, - HasManager, - SupportsBatchCreation, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsListing { +public interface Registries extends SupportsCreating, + HasManager, SupportsBatchCreation, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsListing { /** * Gets the login credentials for the specified container registry. @@ -59,8 +53,8 @@ public interface Registries * @param accessKeyType the admin user access key name to regenerate the value for * @return the container registry's login credentials */ - RegistryCredentials regenerateCredential( - String resourceGroupName, String registryName, AccessKeyType accessKeyType); + RegistryCredentials regenerateCredential(String resourceGroupName, String registryName, + AccessKeyType accessKeyType); /** * Regenerates the value for one of the admin user access key for the specified container registry. @@ -71,8 +65,8 @@ RegistryCredentials regenerateCredential( * @return a representation of the future computation of this call, returning the container registry's login * credentials */ - Mono regenerateCredentialAsync( - String resourceGroupName, String registryName, AccessKeyType accessKeyType); + Mono regenerateCredentialAsync(String resourceGroupName, String registryName, + AccessKeyType accessKeyType); /** * Lists the quota usages for the specified container registry. diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registry.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registry.java index 48ff1e10cbd13..a8a406263f296 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registry.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Registry.java @@ -23,13 +23,9 @@ /** An immutable client-side representation of an Azure registry. */ @Fluent -public interface Registry - extends GroupableResource, - Refreshable, - Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, - SupportsUpdatingPrivateEndpointConnection { +public interface Registry extends GroupableResource, Refreshable, + Updatable, SupportsListingPrivateLinkResource, SupportsListingPrivateEndpointConnection, + SupportsUpdatingPrivateEndpointConnection { /** @return the SKU of the container registry. */ Sku sku(); @@ -120,11 +116,8 @@ public interface Registry RegistryTaskRun.DefinitionStages.BlankFromRegistry scheduleRun(); /** Container interface for all the definitions related to a registry. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSku, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSku, + DefinitionStages.WithCreate { } /** Grouping of registry definition stages. */ @@ -261,26 +254,15 @@ interface WithZoneRedundancy { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - WithAdminUserEnabled, - WithWebhook, - WithPublicNetworkAccess, - WithDedicatedDataEndpoints, - WithZoneRedundancy, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, WithAdminUserEnabled, WithWebhook, WithPublicNetworkAccess, + WithDedicatedDataEndpoints, WithZoneRedundancy, Resource.DefinitionWithTags { } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Resource.UpdateWithTags, - Appliable, - UpdateStages.WithAdminUserEnabled, - UpdateStages.WithSku, - UpdateStages.WithWebhook, - UpdateStages.WithDedicatedDataEndpoints, - UpdateStages.WithPublicNetworkAccess { + interface Update extends Resource.UpdateWithTags, Appliable, UpdateStages.WithAdminUserEnabled, + UpdateStages.WithSku, UpdateStages.WithWebhook, UpdateStages.WithDedicatedDataEndpoints, + UpdateStages.WithPublicNetworkAccess { } /** Grouping of container service update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskRunRequest.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskRunRequest.java index b69754ee2ea71..ae05a16645c76 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskRunRequest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskRunRequest.java @@ -27,10 +27,8 @@ public interface RegistryDockerTaskRunRequest { boolean isArchiveEnabled(); /** Container interface for all the definitions related to a registry Docker task run request. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.DockerFilePath, - DefinitionStages.DockerTaskRunRequestStepAttachable { + interface Definition extends DefinitionStages.Blank, DefinitionStages.DockerFilePath, + DefinitionStages.DockerTaskRunRequestStepAttachable { } /** Grouping of registry Docker task run request definition stages. */ @@ -93,8 +91,8 @@ interface DockerTaskRunRequestStepAttachable * OverridingArgument specifying the content of the overriding argument. * @return the next stage of the container Docker task run request definition. */ - DockerTaskRunRequestStepAttachable withOverridingArguments( - Map overridingArguments); + DockerTaskRunRequestStepAttachable + withOverridingArguments(Map overridingArguments); /** * The function that specifies the overriding argument and what it will override. @@ -103,8 +101,8 @@ DockerTaskRunRequestStepAttachable withOverridingArguments( * @param overridingArgument the content of the overriding argument. * @return the next stage of the container Docker task run request definition. */ - DockerTaskRunRequestStepAttachable withOverridingArgument( - String name, OverridingArgument overridingArgument); + DockerTaskRunRequestStepAttachable withOverridingArgument(String name, + OverridingArgument overridingArgument); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskStep.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskStep.java index 0a9c49db938d4..2580244c649de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskStep.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryDockerTaskStep.java @@ -29,19 +29,15 @@ public interface RegistryDockerTaskStep extends HasInnerModel, R /** Container interface for all the definitions related to a RegistryDockerTaskStep. */ interface Definition - extends RegistryDockerTaskStep.DefinitionStages.Blank, - RegistryDockerTaskStep.DefinitionStages.DockerFilePath, - RegistryDockerTaskStep.DefinitionStages.DockerTaskStepAttachable { + extends RegistryDockerTaskStep.DefinitionStages.Blank, RegistryDockerTaskStep.DefinitionStages.DockerFilePath, + RegistryDockerTaskStep.DefinitionStages.DockerTaskStepAttachable { } /** Container interface for all the updates related to a RegistryDockerTaskStep. */ interface Update - extends RegistryDockerTaskStep.UpdateStages.DockerFilePath, - RegistryDockerTaskStep.UpdateStages.ImageNames, - RegistryDockerTaskStep.UpdateStages.Push, - RegistryDockerTaskStep.UpdateStages.Cache, - RegistryDockerTaskStep.UpdateStages.OverridingArgumentUpdate, - Settable { + extends RegistryDockerTaskStep.UpdateStages.DockerFilePath, RegistryDockerTaskStep.UpdateStages.ImageNames, + RegistryDockerTaskStep.UpdateStages.Push, RegistryDockerTaskStep.UpdateStages.Cache, + RegistryDockerTaskStep.UpdateStages.OverridingArgumentUpdate, Settable { } /** Grouping of registry Docker task definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskRunRequest.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskRunRequest.java index d5370849679b5..a69d5b2b2d97d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskRunRequest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskRunRequest.java @@ -25,10 +25,8 @@ public interface RegistryEncodedTaskRunRequest { boolean isArchiveEnabled(); /** Container interface for all the definitions related to a registry Encoded task run request. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.EncodedTaskContent, - DefinitionStages.EncodedTaskRunRequestStepAttachable { + interface Definition extends DefinitionStages.Blank, DefinitionStages.EncodedTaskContent, + DefinitionStages.EncodedTaskRunRequestStepAttachable { } /** Grouping of registry encoded task run request definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskStep.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskStep.java index b7ce4381d8980..e05529c9b0370 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskStep.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryEncodedTaskStep.java @@ -22,18 +22,15 @@ public interface RegistryEncodedTaskStep extends RegistryTaskStep { List values(); /** Container interface for all the definitions related to a RegistryEncodedTaskStep. */ - interface Definition - extends RegistryEncodedTaskStep.DefinitionStages.Blank, - RegistryEncodedTaskStep.DefinitionStages.EncodedTaskContent, - RegistryEncodedTaskStep.DefinitionStages.EncodedTaskStepAttachable { + interface Definition extends RegistryEncodedTaskStep.DefinitionStages.Blank, + RegistryEncodedTaskStep.DefinitionStages.EncodedTaskContent, + RegistryEncodedTaskStep.DefinitionStages.EncodedTaskStepAttachable { } /** Container interface for all the updates related to a RegistryEncodedTaskStep. */ interface Update - extends RegistryEncodedTaskStep.UpdateStages.EncodedTaskContent, - RegistryEncodedTaskStep.UpdateStages.ValuePath, - RegistryEncodedTaskStep.UpdateStages.OverridingValues, - Settable { + extends RegistryEncodedTaskStep.UpdateStages.EncodedTaskContent, RegistryEncodedTaskStep.UpdateStages.ValuePath, + RegistryEncodedTaskStep.UpdateStages.OverridingValues, Settable { } /** Grouping of registry encoded task definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskRunRequest.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskRunRequest.java index d2df53cb675cf..aa9ee869cc987 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskRunRequest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskRunRequest.java @@ -25,10 +25,8 @@ public interface RegistryFileTaskRunRequest { boolean isArchiveEnabled(); /** Container interface for all the definitions related to a registry file task run request. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.FileTaskPath, - DefinitionStages.FileTaskRunRequestStepAttachable { + interface Definition extends DefinitionStages.Blank, DefinitionStages.FileTaskPath, + DefinitionStages.FileTaskRunRequestStepAttachable { } /** Grouping of registry file task run request definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskStep.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskStep.java index 8384796b4747f..c17c9529c153b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskStep.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryFileTaskStep.java @@ -23,17 +23,14 @@ public interface RegistryFileTaskStep extends RegistryTaskStep { /** Container interface for all the definitions related to a RegistryFileTaskStep. */ interface Definition - extends RegistryFileTaskStep.DefinitionStages.Blank, - RegistryFileTaskStep.DefinitionStages.FileTaskPath, - RegistryFileTaskStep.DefinitionStages.FileTaskStepAttachable { + extends RegistryFileTaskStep.DefinitionStages.Blank, RegistryFileTaskStep.DefinitionStages.FileTaskPath, + RegistryFileTaskStep.DefinitionStages.FileTaskStepAttachable { } /** Container interface for all the updates related to a RegistryFileTaskStep. */ interface Update - extends RegistryFileTaskStep.UpdateStages.FileTaskPath, - RegistryFileTaskStep.UpdateStages.ValuePath, - RegistryFileTaskStep.UpdateStages.OverridingValues, - Settable { + extends RegistryFileTaskStep.UpdateStages.FileTaskPath, RegistryFileTaskStep.UpdateStages.ValuePath, + RegistryFileTaskStep.UpdateStages.OverridingValues, Settable { } /** Grouping of registry file task definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistrySourceTrigger.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistrySourceTrigger.java index 79e08056147da..a9f958d716110 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistrySourceTrigger.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistrySourceTrigger.java @@ -29,33 +29,27 @@ public interface RegistrySourceTrigger extends HasInnerModel { /** Container interface for all of the definitions related to a container registry source trigger. */ interface Definition - extends RegistrySourceTrigger.DefinitionStages.Blank, - RegistrySourceTrigger.DefinitionStages.RepositoryUrl, - RegistrySourceTrigger.DefinitionStages.TriggerEventsDefinition, - RegistrySourceTrigger.DefinitionStages.RepositoryBranchAndAuth, - RegistrySourceTrigger.DefinitionStages.TriggerStatusDefinition, - RegistrySourceTrigger.DefinitionStages.SourceTriggerAttachable { + extends RegistrySourceTrigger.DefinitionStages.Blank, RegistrySourceTrigger.DefinitionStages.RepositoryUrl, + RegistrySourceTrigger.DefinitionStages.TriggerEventsDefinition, + RegistrySourceTrigger.DefinitionStages.RepositoryBranchAndAuth, + RegistrySourceTrigger.DefinitionStages.TriggerStatusDefinition, + RegistrySourceTrigger.DefinitionStages.SourceTriggerAttachable { } /** Container interface for all of the updates related to a container registry source trigger. */ - interface Update - extends RegistrySourceTrigger.UpdateStages.SourceControlType, - RegistrySourceTrigger.UpdateStages.RepositoryUrl, - RegistrySourceTrigger.UpdateStages.TriggerEventsDefinition, - RegistrySourceTrigger.UpdateStages.RepositoryBranchAndAuth, - RegistrySourceTrigger.UpdateStages.TriggerStatusDefinition, - Settable { + interface Update extends RegistrySourceTrigger.UpdateStages.SourceControlType, + RegistrySourceTrigger.UpdateStages.RepositoryUrl, RegistrySourceTrigger.UpdateStages.TriggerEventsDefinition, + RegistrySourceTrigger.UpdateStages.RepositoryBranchAndAuth, + RegistrySourceTrigger.UpdateStages.TriggerStatusDefinition, Settable { } /** Container interface for defining a new trigger during a task update. */ - interface UpdateDefinition - extends RegistrySourceTrigger.UpdateDefinitionStages.Blank, - RegistrySourceTrigger.UpdateDefinitionStages.RepositoryUrl, - RegistrySourceTrigger.UpdateDefinitionStages.TriggerEventsDefinition, - RegistrySourceTrigger.UpdateDefinitionStages.RepositoryBranchAndAuth, - RegistrySourceTrigger.UpdateDefinitionStages.TriggerStatusDefinition, - RegistrySourceTrigger.UpdateDefinitionStages.SourceTriggerAttachable, - Settable { + interface UpdateDefinition extends RegistrySourceTrigger.UpdateDefinitionStages.Blank, + RegistrySourceTrigger.UpdateDefinitionStages.RepositoryUrl, + RegistrySourceTrigger.UpdateDefinitionStages.TriggerEventsDefinition, + RegistrySourceTrigger.UpdateDefinitionStages.RepositoryBranchAndAuth, + RegistrySourceTrigger.UpdateDefinitionStages.TriggerStatusDefinition, + RegistrySourceTrigger.UpdateDefinitionStages.SourceTriggerAttachable, Settable { } /** Grouping of source trigger definition stages. */ @@ -162,8 +156,8 @@ interface RepositoryBranchAndAuth { * @param expiresIn time in seconds that the token remains valid. * @return the next stage of the container registry source trigger definition. */ - SourceTriggerAttachable withRepositoryAuthentication( - TokenType tokenType, String token, String refreshToken, String scope, int expiresIn); + SourceTriggerAttachable withRepositoryAuthentication(TokenType tokenType, String token, String refreshToken, + String scope, int expiresIn); } /** @@ -197,11 +191,8 @@ interface TriggerStatusDefinition { * The stage of the definition which contains all the minimum required inputs for the resource to be attached, * but also allows for any other optional settings to be specified. */ - interface SourceTriggerAttachable - extends RepositoryBranchAndAuth, - TriggerEventsDefinition, - TriggerStatusDefinition, - Attachable.InDefinition { + interface SourceTriggerAttachable extends RepositoryBranchAndAuth, TriggerEventsDefinition, + TriggerStatusDefinition, Attachable.InDefinition { } } @@ -229,8 +220,8 @@ interface SourceControlType { * @param sourceControl the source control the user wishes to use. * @return the next stage of the container registry source trigger definition. */ - Update withSourceControl( - com.azure.resourcemanager.containerregistry.models.SourceControlType sourceControl); + Update + withSourceControl(com.azure.resourcemanager.containerregistry.models.SourceControlType sourceControl); } /** @@ -309,8 +300,8 @@ interface RepositoryBranchAndAuth { * @param expiresIn time in seconds that the token remains valid. * @return the next stage of the container registry source trigger definition. */ - Update withRepositoryAuthentication( - TokenType tokenType, String token, String refreshToken, String scope, int expiresIn); + Update withRepositoryAuthentication(TokenType tokenType, String token, String refreshToken, String scope, + int expiresIn); } /** The stage of the container registry source trigger update allowing to specify the status of the trigger. */ @@ -443,8 +434,8 @@ interface RepositoryBranchAndAuth { * @param expiresIn time in seconds that the token remains valid. * @return the next stage of the container registry source trigger definition. */ - SourceTriggerAttachable withRepositoryAuthentication( - TokenType tokenType, String token, String refreshToken, String scope, int expiresIn); + SourceTriggerAttachable withRepositoryAuthentication(TokenType tokenType, String token, String refreshToken, + String scope, int expiresIn); } /** @@ -478,11 +469,8 @@ interface TriggerStatusDefinition { * The stage of the definition which contains all the minimum required inputs for the resource to be attached, * but also allows for any other optional settings to be specified. */ - interface SourceTriggerAttachable - extends RepositoryBranchAndAuth, - TriggerEventsDefinition, - TriggerStatusDefinition, - Attachable.InUpdate { + interface SourceTriggerAttachable extends RepositoryBranchAndAuth, TriggerEventsDefinition, + TriggerStatusDefinition, Attachable.InUpdate { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTask.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTask.java index 7108526843624..be9eeeeefe4f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTask.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTask.java @@ -54,24 +54,14 @@ public interface RegistryTask Map sourceTriggers(); /** Container interface for all the definitions related to a registry task. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.Location, - DefinitionStages.Platform, - DefinitionStages.TaskStepType, - DefinitionStages.SourceTriggerDefinition, - DefinitionStages.TriggerTypes, - DefinitionStages.TaskCreatable { + interface Definition extends DefinitionStages.Blank, DefinitionStages.Location, DefinitionStages.Platform, + DefinitionStages.TaskStepType, DefinitionStages.SourceTriggerDefinition, DefinitionStages.TriggerTypes, + DefinitionStages.TaskCreatable { } /** Container interface for all the updates related to a registry task. */ - interface Update - extends UpdateStages.Platform, - UpdateStages.TriggerTypes, - UpdateStages.AgentConfiguration, - UpdateStages.Timeout, - UpdateStages.TaskStepType, - Appliable { + interface Update extends UpdateStages.Platform, UpdateStages.TriggerTypes, UpdateStages.AgentConfiguration, + UpdateStages.Timeout, UpdateStages.TaskStepType, Appliable { } /** Grouping of registry task definition stages. */ @@ -236,8 +226,8 @@ interface TriggerTypes { * user inputs. * @return the next stage of the container registry task definition. */ - TaskCreatable withBaseImageTrigger( - String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus); + TaskCreatable withBaseImageTrigger(String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, + TriggerStatus triggerStatus); } /** @@ -406,8 +396,8 @@ interface TriggerTypes { * user inputs. * @return the next stage of the container registry task update. */ - Update updateBaseImageTrigger( - String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus); + Update updateBaseImageTrigger(String baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, + TriggerStatus triggerStatus); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTaskRun.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTaskRun.java index 35e4749f9bed0..d9043c247641b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTaskRun.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/RegistryTaskRun.java @@ -53,15 +53,10 @@ public interface RegistryTaskRun extends HasInnerModel, Refreshable getByRegistryAsync( - String resourceGroupName, String registryName, String taskName, boolean includeSecrets); + Mono getByRegistryAsync(String resourceGroupName, String registryName, String taskName, + boolean includeSecrets); /** * Gets a task in a registry. diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Webhook.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Webhook.java index 0004d2d0b9df4..ad43686ca070b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Webhook.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/Webhook.java @@ -20,12 +20,8 @@ /** An object that represents a webhook for a container registry. */ @Fluent -public interface Webhook - extends ExternalChildResource, - Resource, - HasInnerModel, - Refreshable, - Updatable { +public interface Webhook extends ExternalChildResource, Resource, HasInnerModel, + Refreshable, Updatable { /** @return the status of the webhook */ boolean isEnabled(); @@ -196,12 +192,8 @@ interface WithDefaultStatus { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends WithCustomHeaders, - WithRepositoriesScope, - WithDefaultStatus, - DefinitionWithTags>, - Attachable.InDefinition { + interface WithAttach extends WithCustomHeaders, WithRepositoriesScope, + WithDefaultStatus, DefinitionWithTags>, Attachable.InDefinition { } } @@ -211,10 +203,8 @@ interface WithAttach * @param the stage of the parent definition to return to after attaching this definition */ interface WebhookDefinition - extends DefinitionStages.Blank, - DefinitionStages.WithTriggerWhen, - DefinitionStages.WithServiceUri, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithTriggerWhen, + DefinitionStages.WithServiceUri, DefinitionStages.WithAttach { } /** Grouping of webhook update definition stages. */ @@ -353,12 +343,8 @@ interface WithTags { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends WithCustomHeaders, - WithRepositoriesScope, - WithDefaultStatus, - WithTags, - Attachable.InUpdate { + interface WithAttach extends WithCustomHeaders, WithRepositoriesScope, + WithDefaultStatus, WithTags, Attachable.InUpdate { } } @@ -368,21 +354,14 @@ interface WithAttach * @param the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithTriggerWhen, - UpdateDefinitionStages.WithServiceUri, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithTriggerWhen, + UpdateDefinitionStages.WithServiceUri, UpdateDefinitionStages.WithAttach { } /** The entirety of a webhook update. */ - interface Update - extends UpdateStages.WithTriggerWhen, - UpdateStages.WithServiceUri, - UpdateStages.WithCustomHeaders, - UpdateStages.WithRepositoriesScope, - UpdateStages.WithDefaultStatus, - Resource.UpdateWithTags, - Appliable { + interface Update extends UpdateStages.WithTriggerWhen, UpdateStages.WithServiceUri, UpdateStages.WithCustomHeaders, + UpdateStages.WithRepositoriesScope, UpdateStages.WithDefaultStatus, Resource.UpdateWithTags, + Appliable { } /** Grouping of webhook update stages. */ @@ -622,13 +601,8 @@ interface WithOrWithoutTags { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends WithTriggerWhen, - WithServiceUri, - WithCustomHeaders, - WithRepositoriesScope, - WithDefaultStatus, - WithOrWithoutTags, - Settable { + extends WithTriggerWhen, WithServiceUri, WithCustomHeaders, + WithRepositoriesScope, WithDefaultStatus, WithOrWithoutTags, Settable { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryOperationsTests.java index b2a4332176610..448c41b4f14ab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryOperationsTests.java @@ -18,16 +18,14 @@ protected void cleanUpResources() { @Test public void canCreateContainerRegisterWithZoneRedundancy() { final String acrName = generateRandomResourceName("acr", 10); - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withZoneRedundancy() - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withZoneRedundancy() + .create(); Assertions.assertTrue(registry.isZoneRedundancyEnabled()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTaskTests.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTaskTests.java index baa78329edea3..369773bb13163 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTaskTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTaskTests.java @@ -42,43 +42,39 @@ public void fileTaskTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String taskFilePath = "Path to your task file that is relative to the githubRepoUrl"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineFileTaskStep() - .withTaskPath(taskFilePath) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineFileTaskStep() + .withTaskPath(taskFilePath) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); RegistryFileTaskStep registryFileTaskStep = (RegistryFileTaskStep) registryTask.registryTaskStep(); @@ -119,44 +115,40 @@ public void fileTaskUpdateTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String taskFilePath = "Path to your task file that is relative to the githubRepoUrl"; String taskFileUpdatePath = "Path to your update task file that is relative to the githubRepoUrl"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineFileTaskStep() - .withTaskPath(taskFilePath) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineFileTaskStep() + .withTaskPath(taskFilePath) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); registryTask.update().updateFileTaskStep().withTaskPath(taskFileUpdatePath).parent().apply(); @@ -209,44 +201,40 @@ public void encodedTaskTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String encodedTaskContent = "Base64 encoded task content"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineEncodedTaskStep() - .withBase64EncodedTaskContent(encodedTaskContent) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineEncodedTaskStep() + .withBase64EncodedTaskContent(encodedTaskContent) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); RegistryEncodedTaskStep registryEncodedTaskStep = (RegistryEncodedTaskStep) registryTask.registryTaskStep(); @@ -287,48 +275,43 @@ public void encodedTaskUpdateTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String encodedTaskContent = "Base64 encoded task content"; String encodedTaskContentUpdate = "Base64 encoded task content that we want to update to"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineEncodedTaskStep() - .withBase64EncodedTaskContent(encodedTaskContent) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); - - registryTask - .update() + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineEncodedTaskStep() + .withBase64EncodedTaskContent(encodedTaskContent) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); + + registryTask.update() .updateEncodedTaskStep() .withBase64EncodedTaskContent(encodedTaskContentUpdate) .parent() @@ -383,47 +366,43 @@ public void dockerTaskTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String dockerFilePath = "Replace with your docker file path relative to githubContext, eg: Dockerfile"; String imageName = "Replace with the name of your image."; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); RegistryDockerTaskStep registryDockerTaskStep = (RegistryDockerTaskStep) registryTask.registryTaskStep(); @@ -473,53 +452,48 @@ public void dsockerTaskUpdateTest() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String dockerFilePath = "Replace with your docker file path relative to githubContext, eg: Dockerfile"; - String dockerFilePathUpdate = - "Replace this with your docker file path that you updated your registryTask to, if you did update your" + String dockerFilePathUpdate + = "Replace this with your docker file path that you updated your registryTask to, if you did update your" + " docker file path"; String imageName = "Replace with the name of your image."; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); - - registryTask - .update() + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); + + registryTask.update() .updateDockerTaskStep() .withDockerFilePath(dockerFilePathUpdate) .withCacheEnabled(false) @@ -582,28 +556,24 @@ public void fileTaskRunRequestFromRegistry() { String sourceLocation = "https://github.com/Azure/acr.git"; String taskFilePath = "samples/java/task/acb.yaml"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registry - .scheduleRun() - .withWindows() - .withFileTaskRunRequest() - .defineFileTaskStep() - .withTaskPath(taskFilePath) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registry.scheduleRun() + .withWindows() + .withFileTaskRunRequest() + .defineFileTaskStep() + .withTaskPath(taskFilePath) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); Assertions.assertEquals(registry.resourceGroupName(), registryTaskRun.resourceGroupName()); @@ -611,8 +581,8 @@ public void fileTaskRunRequestFromRegistry() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.WINDOWS, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertNotNull(registryTaskRunFromList.status()); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -629,30 +599,26 @@ public void fileTaskRunRequestFromRuns() { String sourceLocation = "https://github.com/Azure/acr.git"; String taskFilePath = "samples/java/task/acb.yaml"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registryManager - .registryTaskRuns() - .scheduleRun() - .withExistingRegistry(rgName, acrName) - .withLinux() - .withFileTaskRunRequest() - .defineFileTaskStep() - .withTaskPath(taskFilePath) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registryManager.registryTaskRuns() + .scheduleRun() + .withExistingRegistry(rgName, acrName) + .withLinux() + .withFileTaskRunRequest() + .defineFileTaskStep() + .withTaskPath(taskFilePath) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); Assertions.assertEquals(registry.resourceGroupName(), registryTaskRun.resourceGroupName()); @@ -660,8 +626,8 @@ public void fileTaskRunRequestFromRuns() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -676,28 +642,24 @@ public void encodedTaskRunRequestFromRegistry() throws Exception { String sourceLocation = "https://github.com/Azure/acr.git"; String encodedTaskContent = Base64.getEncoder().encodeToString(readTaskYaml()); - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registry - .scheduleRun() - .withLinux() - .withEncodedTaskRunRequest() - .defineEncodedTaskStep() - .withBase64EncodedTaskContent(encodedTaskContent) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registry.scheduleRun() + .withLinux() + .withEncodedTaskRunRequest() + .defineEncodedTaskStep() + .withBase64EncodedTaskContent(encodedTaskContent) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); @@ -706,8 +668,8 @@ public void encodedTaskRunRequestFromRegistry() throws Exception { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -722,30 +684,26 @@ public void encodedTaskRunRequestFromRuns() throws Exception { String sourceLocation = "https://github.com/Azure/acr.git#master:samples/java/task"; String encodedTaskContent = Base64.getEncoder().encodeToString(readTaskYaml()); - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registryManager - .registryTaskRuns() - .scheduleRun() - .withExistingRegistry(rgName, acrName) - .withLinux() - .withEncodedTaskRunRequest() - .defineEncodedTaskStep() - .withBase64EncodedTaskContent(encodedTaskContent) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registryManager.registryTaskRuns() + .scheduleRun() + .withExistingRegistry(rgName, acrName) + .withLinux() + .withEncodedTaskRunRequest() + .defineEncodedTaskStep() + .withBase64EncodedTaskContent(encodedTaskContent) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); @@ -754,8 +712,8 @@ public void encodedTaskRunRequestFromRuns() throws Exception { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -771,31 +729,27 @@ public void dockerTaskRunRequestFromRegistry() { String imageName = "test"; String sourceLocation = "https://github.com/Azure/acr.git#master:samples/java/task"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registry - .scheduleRun() - .withLinux() - .withDockerTaskRunRequest() - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registry.scheduleRun() + .withLinux() + .withDockerTaskRunRequest() + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); Assertions.assertEquals(registry.resourceGroupName(), registryTaskRun.resourceGroupName()); @@ -803,8 +757,8 @@ public void dockerTaskRunRequestFromRegistry() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -820,33 +774,29 @@ public void dockerTaskRunRequestFromRuns() { String imageName = "test"; String sourceLocation = "https://github.com/Azure/acr.git#master:samples/java/task"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registryManager - .registryTaskRuns() - .scheduleRun() - .withExistingRegistry(rgName, acrName) - .withLinux() - .withDockerTaskRunRequest() - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registryManager.registryTaskRuns() + .scheduleRun() + .withExistingRegistry(rgName, acrName) + .withLinux() + .withDockerTaskRunRequest() + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); registryTaskRun.refresh(); Assertions.assertEquals(registry.resourceGroupName(), registryTaskRun.resourceGroupName()); @@ -855,8 +805,8 @@ public void dockerTaskRunRequestFromRuns() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -874,47 +824,43 @@ public void taskRunRequestFromRegistry() { String dockerFilePath = "Replace with your docker file path relative to githubContext, eg: Dockerfile"; String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; - - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); - - RegistryTaskRun registryTaskRun = - registry.scheduleRun().withTaskRunRequest(taskName).withArchiveEnabled(true).execute(); + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); + + RegistryTaskRun registryTaskRun + = registry.scheduleRun().withTaskRunRequest(taskName).withArchiveEnabled(true).execute(); boolean stillQueued = true; while (stillQueued) { @@ -923,8 +869,7 @@ public void taskRunRequestFromRegistry() { stillQueued = false; } if (registryTaskRun.status() == RunStatus.FAILED) { - System - .out + System.out .println(registryManager.registryTaskRuns().getLogSasUrl(rgName, acrName, registryTaskRun.runId())); stillQueued = false; } @@ -937,8 +882,8 @@ public void taskRunRequestFromRegistry() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -956,54 +901,48 @@ public void taskRunRequestFromRuns() { String taskName = generateRandomResourceName("ft", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String dockerFilePath = "Replace with your docker file path relative to githubContext, eg: Dockerfile"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); - - RegistryTaskRun registryTaskRun = - registryManager - .registryTaskRuns() - .scheduleRun() - .withExistingRegistry(rgName, acrName) - .withTaskRunRequest(taskName) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); + + RegistryTaskRun registryTaskRun = registryManager.registryTaskRuns() + .scheduleRun() + .withExistingRegistry(rgName, acrName) + .withTaskRunRequest(taskName) + .withArchiveEnabled(true) + .execute(); boolean stillQueued = true; while (stillQueued) { @@ -1012,8 +951,7 @@ public void taskRunRequestFromRuns() { stillQueued = false; } if (registryTaskRun.status() == RunStatus.FAILED) { - System - .out + System.out .println(registryManager.registryTaskRuns().getLogSasUrl(rgName, acrName, registryTaskRun.runId())); stillQueued = false; } @@ -1025,8 +963,8 @@ public void taskRunRequestFromRuns() { Assertions.assertTrue(registryTaskRun.isArchiveEnabled()); Assertions.assertEquals(OS.LINUX, registryTaskRun.platform().os()); - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); RegistryTaskRun registryTaskRunFromList = registryTaskRuns.stream().findFirst().get(); Assertions.assertTrue(registryTaskRunFromList.status() != null); Assertions.assertEquals("QuickRun", registryTaskRunFromList.runType().toString()); @@ -1040,16 +978,14 @@ public void taskRunRequestFromRuns() { public void getBuildSourceUploadUrlFromRegistryAndRegistries() { final String acrName = generateRandomResourceName("acr", 10); - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); // Calling getBuildSourceUploadUrl from Registry SourceUploadDefinition buildSourceUploadUrlRegistry = registry.getBuildSourceUploadUrl(); @@ -1057,8 +993,8 @@ public void getBuildSourceUploadUrlFromRegistryAndRegistries() { Assertions.assertNotNull(buildSourceUploadUrlRegistry.uploadUrl()); // Calling getBuildSourceUploadUrl from Registries - SourceUploadDefinition buildSourceUploadUrlRegistries = - registryManager.containerRegistries().getBuildSourceUploadUrl(rgName, acrName); + SourceUploadDefinition buildSourceUploadUrlRegistries + = registryManager.containerRegistries().getBuildSourceUploadUrl(rgName, acrName); Assertions.assertNotNull(buildSourceUploadUrlRegistries.relativePath()); Assertions.assertNotNull(buildSourceUploadUrlRegistries.uploadUrl()); } @@ -1072,47 +1008,43 @@ public void cancelAndDeleteRunsAndTasks() { String imageName = "Replace with the name of your image."; String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; - - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); - - RegistryTaskRun registryTaskRun = - registry.scheduleRun().withTaskRunRequest(taskName).withArchiveEnabled(true).execute(); + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); + + RegistryTaskRun registryTaskRun + = registry.scheduleRun().withTaskRunRequest(taskName).withArchiveEnabled(true).execute(); boolean stillQueued = true; while (stillQueued) { @@ -1121,8 +1053,7 @@ public void cancelAndDeleteRunsAndTasks() { stillQueued = false; } if (registryTaskRun.status() == RunStatus.FAILED) { - System - .out + System.out .println(registryManager.registryTaskRuns().getLogSasUrl(rgName, acrName, registryTaskRun.runId())); Assertions.fail("Registry registryTask run failed"); } @@ -1141,16 +1072,15 @@ public void cancelAndDeleteRunsAndTasks() { notCanceled = false; } if (registryTaskRun.status() == RunStatus.FAILED) { - System - .out + System.out .println(registryManager.registryTaskRuns().getLogSasUrl(rgName, acrName, registryTaskRun.runId())); Assertions.fail("Registry registryTask run failed"); } ResourceManagerUtils.sleep(Duration.ofSeconds(10)); } - PagedIterable registryTaskRuns = - registryManager.registryTaskRuns().listByRegistry(rgName, acrName); + PagedIterable registryTaskRuns + = registryManager.registryTaskRuns().listByRegistry(rgName, acrName); for (RegistryTaskRun rtr : registryTaskRuns) { Assertions.assertTrue(rtr.status() == RunStatus.CANCELED); @@ -1175,33 +1105,29 @@ public void getLogSasUrl() { String imageName = "test"; String sourceLocation = "https://github.com/Azure/acr.git#master:samples/java/task"; - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); - - RegistryTaskRun registryTaskRun = - registryManager - .registryTaskRuns() - .scheduleRun() - .withExistingRegistry(rgName, acrName) - .withLinux() - .withDockerTaskRunRequest() - .defineDockerTaskStep() - .withDockerFilePath(dockerFilePath) - .withImageNames(Arrays.asList(imageName)) - .withCacheEnabled(true) - .withPushEnabled(true) - .attach() - .withSourceLocation(sourceLocation) - .withArchiveEnabled(true) - .execute(); + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + RegistryTaskRun registryTaskRun = registryManager.registryTaskRuns() + .scheduleRun() + .withExistingRegistry(rgName, acrName) + .withLinux() + .withDockerTaskRunRequest() + .defineDockerTaskStep() + .withDockerFilePath(dockerFilePath) + .withImageNames(Arrays.asList(imageName)) + .withCacheEnabled(true) + .withPushEnabled(true) + .attach() + .withSourceLocation(sourceLocation) + .withArchiveEnabled(true) + .execute(); String sasUrl = registryManager.registryTaskRuns().getLogSasUrl(rgName, acrName, registryTaskRun.runId()); Assertions.assertNotNull(sasUrl); @@ -1214,60 +1140,53 @@ public void updateTriggers() { final String acrName = generateRandomResourceName("acr", 10); String githubRepoUrl = "Replace with your github repository url, eg: https://github.com/Azure/acr.git"; String githubBranch = "Replace with your github repositoty branch, eg: master"; - String githubPAT = - "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; + String githubPAT + = "Replace with your github personal access token which should have the scopes: admin:repo_hook and repo"; String taskFilePath = "Path to your task file that is relative to the githubRepoUrl"; - String githubRepoUrlUpdate = - "Replace with your github repository url to update to, eg: https://github.com/Azure/acr.git"; - - Registry registry = - registryManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + String githubRepoUrlUpdate + = "Replace with your github repository url to update to, eg: https://github.com/Azure/acr.git"; + + Registry registry = registryManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); String taskName = generateRandomResourceName("ft", 10); - RegistryTask registryTask = - registryManager - .containerRegistryTasks() - .define(taskName) - .withExistingRegistry(rgName, acrName) - .withLocation(Region.US_WEST_CENTRAL.name()) - .withLinux(Architecture.AMD64) - .defineFileTaskStep() - .withTaskPath(taskFilePath) - .attach() - .defineSourceTrigger("SampleSourceTrigger") - .withGithubAsSourceControl() - .withSourceControlRepositoryUrl(githubRepoUrl) - .withCommitTriggerEvent() - .withPullTriggerEvent() - .withRepositoryBranch(githubBranch) - .withRepositoryAuthentication(TokenType.PAT, githubPAT) - .withTriggerStatusEnabled() - .attach() - .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) - .withCpuCount(2) - .create(); + RegistryTask registryTask = registryManager.containerRegistryTasks() + .define(taskName) + .withExistingRegistry(rgName, acrName) + .withLocation(Region.US_WEST_CENTRAL.name()) + .withLinux(Architecture.AMD64) + .defineFileTaskStep() + .withTaskPath(taskFilePath) + .attach() + .defineSourceTrigger("SampleSourceTrigger") + .withGithubAsSourceControl() + .withSourceControlRepositoryUrl(githubRepoUrl) + .withCommitTriggerEvent() + .withPullTriggerEvent() + .withRepositoryBranch(githubBranch) + .withRepositoryAuthentication(TokenType.PAT, githubPAT) + .withTriggerStatusEnabled() + .attach() + .withBaseImageTrigger("SampleBaseImageTrigger", BaseImageTriggerType.RUNTIME) + .withCpuCount(2) + .create(); // Assert there is the correct number of source triggers Assertions.assertTrue(registryTask.trigger().sourceTriggers().size() == 1); // Assert source control is correct - Assertions - .assertEquals( - SourceControlType.GITHUB.toString(), - registryTask.trigger().sourceTriggers().get(0).sourceRepository().sourceControlType().toString()); + Assertions.assertEquals(SourceControlType.GITHUB.toString(), + registryTask.trigger().sourceTriggers().get(0).sourceRepository().sourceControlType().toString()); // Assert source control repository url is correct - Assertions - .assertEquals( - githubRepoUrl, registryTask.trigger().sourceTriggers().get(0).sourceRepository().repositoryUrl()); + Assertions.assertEquals(githubRepoUrl, + registryTask.trigger().sourceTriggers().get(0).sourceRepository().repositoryUrl()); // Ignore because of server-side error regarding pull request // Assert source control source trigger event list is of correct size @@ -1279,39 +1198,29 @@ public void updateTriggers() { Assertions.assertTrue(registryTask.trigger().sourceTriggers().get(0).sourceTriggerEvents().size() == 1); // Assert source trigger event list contains commit - Assertions - .assertTrue( - registryTask - .trigger() - .sourceTriggers() - .get(0) - .sourceTriggerEvents() - .contains(SourceTriggerEvent.COMMIT)); + Assertions.assertTrue( + registryTask.trigger().sourceTriggers().get(0).sourceTriggerEvents().contains(SourceTriggerEvent.COMMIT)); // // //Assert source trigger event list contains pull request // // Assertions.assertTrue(registryTask.trigger().sourceTriggers().get(0).sourceTriggerEvents().contains(SourceTriggerEvent.PULLREQUEST)); // Assert source control repository branch is correct - Assertions - .assertEquals(githubBranch, registryTask.trigger().sourceTriggers().get(0).sourceRepository().branch()); + Assertions.assertEquals(githubBranch, + registryTask.trigger().sourceTriggers().get(0).sourceRepository().branch()); // Assert trigger status is correct - Assertions - .assertEquals( - TriggerStatus.ENABLED.toString(), registryTask.trigger().sourceTriggers().get(0).status().toString()); + Assertions.assertEquals(TriggerStatus.ENABLED.toString(), + registryTask.trigger().sourceTriggers().get(0).status().toString()); // Assert name of the base image trigger is correct Assertions.assertEquals("SampleBaseImageTrigger", registryTask.trigger().baseImageTrigger().name()); // Assert that the base image trigger type is correct - Assertions - .assertEquals( - BaseImageTriggerType.RUNTIME.toString(), - registryTask.trigger().baseImageTrigger().baseImageTriggerType().toString()); + Assertions.assertEquals(BaseImageTriggerType.RUNTIME.toString(), + registryTask.trigger().baseImageTrigger().baseImageTriggerType().toString()); - registryTask - .update() + registryTask.update() .updateSourceTrigger("SampleSourceTrigger") .withGithubAsSourceControl() .withSourceControlRepositoryUrl(githubRepoUrlUpdate) @@ -1326,42 +1235,30 @@ public void updateTriggers() { Assertions.assertEquals("SampleSourceTrigger", registryTask.trigger().sourceTriggers().get(0).name()); // Assert source control is correct - Assertions - .assertEquals( - SourceControlType.GITHUB.toString(), - registryTask.trigger().sourceTriggers().get(0).sourceRepository().sourceControlType().toString()); + Assertions.assertEquals(SourceControlType.GITHUB.toString(), + registryTask.trigger().sourceTriggers().get(0).sourceRepository().sourceControlType().toString()); // Assert source control repository url is correct - Assertions - .assertEquals( - githubRepoUrlUpdate, registryTask.trigger().sourceTriggers().get(0).sourceRepository().repositoryUrl()); + Assertions.assertEquals(githubRepoUrlUpdate, + registryTask.trigger().sourceTriggers().get(0).sourceRepository().repositoryUrl()); // Assert source trigger has correct number of trigger events Assertions.assertTrue(registryTask.trigger().sourceTriggers().size() == 1); // Assert source trigger event list contains commit - Assertions - .assertTrue( - registryTask - .trigger() - .sourceTriggers() - .get(0) - .sourceTriggerEvents() - .contains(SourceTriggerEvent.COMMIT)); + Assertions.assertTrue( + registryTask.trigger().sourceTriggers().get(0).sourceTriggerEvents().contains(SourceTriggerEvent.COMMIT)); // Assert trigger status is correct - Assertions - .assertEquals( - TriggerStatus.DISABLED.toString(), registryTask.trigger().sourceTriggers().get(0).status().toString()); + Assertions.assertEquals(TriggerStatus.DISABLED.toString(), + registryTask.trigger().sourceTriggers().get(0).status().toString()); // Assert name of the base image trigger is correct Assertions.assertEquals("SampleBaseImageTriggerUpdate", registryTask.trigger().baseImageTrigger().name()); // Assert that the base image trigger type is correct - Assertions - .assertEquals( - BaseImageTriggerType.ALL.toString(), - registryTask.trigger().baseImageTrigger().baseImageTriggerType().toString()); + Assertions.assertEquals(BaseImageTriggerType.ALL.toString(), + registryTask.trigger().baseImageTrigger().baseImageTriggerType().toString()); } @Test @@ -1380,9 +1277,7 @@ public void testRegistryPublicNetworkAccess() { Assertions.assertEquals(SkuTier.PREMIUM, registry.sku().tier()); Assertions.assertEquals(PublicNetworkAccess.DISABLED, registry.publicNetworkAccess()); - registry.update() - .enablePublicNetworkAccess() - .apply(); + registry.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, registry.publicNetworkAccess()); } @@ -1406,9 +1301,7 @@ public void testRegistryNetworkRules() { Assertions.assertFalse(registryWithDefaultNetworkRules.isDedicatedDataEndpointsEnabled()); Assertions.assertEquals(0, registryWithDefaultNetworkRules.dedicatedDataEndpointsHostNames().size()); - registryWithDefaultNetworkRules.update() - .disablePublicNetworkAccess() - .apply(); + registryWithDefaultNetworkRules.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, registryWithDefaultNetworkRules.publicNetworkAccess()); Assertions.assertTrue(registryWithDefaultNetworkRules.canAccessFromTrustedServices()); @@ -1447,36 +1340,26 @@ public void testRegistryNetworkRules() { Assertions.assertEquals(2, networkRuleSet.ipRules().size()); // revoke access from a certain IP - registry.update() - .withoutAccessFromIpAddress(ipAddress) - .apply(); + registry.update().withoutAccessFromIpAddress(ipAddress).apply(); networkRuleSet = registry.networkRuleSet(); Assertions.assertEquals(1, networkRuleSet.ipRules().size()); // disable dedicated endpoint - registry.update() - .disableDedicatedDataEndpoints() - .apply(); + registry.update().disableDedicatedDataEndpoints().apply(); Assertions.assertFalse(registry.isDedicatedDataEndpointsEnabled()); Assertions.assertEquals(0, registry.dedicatedDataEndpointsHostNames().size()); // deny access from trusted services - registry.update() - .withoutAccessFromTrustedServices() - .apply(); + registry.update().withoutAccessFromTrustedServices().apply(); Assertions.assertFalse(registry.canAccessFromTrustedServices()); // restore access to public network - registry.update() - .withAccessFromAllNetworks() - .apply(); + registry.update().withAccessFromAllNetworks().apply(); networkRuleSet = registry.networkRuleSet(); Assertions.assertEquals(DefaultAction.ALLOW, networkRuleSet.defaultAction()); // disable public network access - registry.update() - .disablePublicNetworkAccess() - .apply(); + registry.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, registry.publicNetworkAccess()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTest.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTest.java index 90affdefbfef8..b345b685bd700 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/test/java/com/azure/resourcemanager/containerregistry/RegistryTest.java @@ -26,28 +26,15 @@ public abstract class RegistryTest extends ResourceManagerTestProxyTestBase { protected String rgName; public RegistryTest() { - addSanitizers( - new TestProxySanitizer("$..uploadUrl", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$..logLink", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) - ); + addSanitizers(new TestProxySanitizer("$..uploadUrl", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..logLink", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)); } @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml index ffc8ab55129ab..a685e95c7b93c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml @@ -43,6 +43,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/ContainerServiceManager.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/ContainerServiceManager.java index 4f4e31083b7ec..31a17f32c6124 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/ContainerServiceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/ContainerServiceManager.java @@ -18,8 +18,7 @@ import java.util.Objects; /** Entry point to Azure Container Service management. */ -public final class ContainerServiceManager - extends Manager { +public final class ContainerServiceManager extends Manager { // The service managers private KubernetesClustersImpl kubernetesClusters; @@ -80,9 +79,7 @@ public ContainerServiceManager authenticate(TokenCredential credential, AzurePro } private ContainerServiceManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, + super(httpPipeline, profile, new ContainerServiceManagementClientBuilder() .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .pipeline(httpPipeline) diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java index 9e090b1d1882b..ffa128cec6de1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java @@ -29,8 +29,7 @@ /** The implementation for KubernetesClusterAgentPool and its create and update interfaces. */ public class KubernetesClusterAgentPoolImpl extends ChildResourceImpl - implements KubernetesClusterAgentPool, - KubernetesClusterAgentPool.Definition, + implements KubernetesClusterAgentPool, KubernetesClusterAgentPool.Definition, KubernetesClusterAgentPool.Update { private String subnetName; @@ -168,9 +167,7 @@ public KubeletDiskType kubeletDiskType() { @Override public Map tags() { - return innerModel().tags() == null - ? Collections.emptyMap() - : Collections.unmodifiableMap(innerModel().tags()); + return innerModel().tags() == null ? Collections.emptyMap() : Collections.unmodifiableMap(innerModel().tags()); } @Override @@ -178,49 +175,49 @@ public boolean isFipsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableFips()); } -// @Override -// public void start() { -// startAsync().block(); -// } -// -// @Override -// public Mono startAsync() { -// AgentPoolInner innerModel = this.getAgentPoolInner(); -// PowerState powerState = innerModel.powerState(); -// if (powerState == null) { -// powerState = new PowerState(); -// innerModel.withPowerState(powerState); -// } -// powerState.withCode(Code.RUNNING); -// return parent().manager().serviceClient().getAgentPools() -// .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), this.name(), innerModel) -// .map(inner -> { -// this.innerModel().withPowerState(inner.powerState()); -// return inner; -// }).then(); -// } -// -// @Override -// public void stop() { -// stopAsync().block(); -// } -// -// @Override -// public Mono stopAsync() { -// AgentPoolInner innerModel = this.getAgentPoolInner(); -// PowerState powerState = innerModel.powerState(); -// if (powerState == null) { -// powerState = new PowerState(); -// innerModel.withPowerState(powerState); -// } -// powerState.withCode(Code.STOPPED); -// return parent().manager().serviceClient().getAgentPools() -// .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), this.name(), innerModel) -// .map(inner -> { -// this.innerModel().withPowerState(inner.powerState()); -// return inner; -// }).then(); -// } + // @Override + // public void start() { + // startAsync().block(); + // } + // + // @Override + // public Mono startAsync() { + // AgentPoolInner innerModel = this.getAgentPoolInner(); + // PowerState powerState = innerModel.powerState(); + // if (powerState == null) { + // powerState = new PowerState(); + // innerModel.withPowerState(powerState); + // } + // powerState.withCode(Code.RUNNING); + // return parent().manager().serviceClient().getAgentPools() + // .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), this.name(), innerModel) + // .map(inner -> { + // this.innerModel().withPowerState(inner.powerState()); + // return inner; + // }).then(); + // } + // + // @Override + // public void stop() { + // stopAsync().block(); + // } + // + // @Override + // public Mono stopAsync() { + // AgentPoolInner innerModel = this.getAgentPoolInner(); + // PowerState powerState = innerModel.powerState(); + // if (powerState == null) { + // powerState = new PowerState(); + // innerModel.withPowerState(powerState); + // } + // powerState.withCode(Code.STOPPED); + // return parent().manager().serviceClient().getAgentPools() + // .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), this.name(), innerModel) + // .map(inner -> { + // this.innerModel().withPowerState(inner.powerState()); + // return inner; + // }).then(); + // } @Override public KubernetesClusterAgentPoolImpl withVirtualMachineSize(ContainerServiceVMSizeTypes vmSize) { @@ -297,7 +294,7 @@ AgentPoolInner getAgentPoolInner() { agentPoolInner.withTypePropertiesType(innerModel().type()); agentPoolInner.withMode(innerModel().mode()); agentPoolInner.withOrchestratorVersion(innerModel().orchestratorVersion()); -// agentPoolInner.withNodeImageVersion(innerModel().nodeImageVersion()); // nodeImageVersion is readOnly now + // agentPoolInner.withNodeImageVersion(innerModel().nodeImageVersion()); // nodeImageVersion is readOnly now agentPoolInner.withUpgradeSettings(innerModel().upgradeSettings()); agentPoolInner.withPowerState(innerModel().powerState()); agentPoolInner.withAvailabilityZones(innerModel().availabilityZones()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImpl.java index e1a65a2f47883..529ba97817bea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImpl.java @@ -65,9 +65,8 @@ import java.util.stream.Collectors; /** The implementation for KubernetesCluster and its create and update interfaces. */ -public class KubernetesClusterImpl - extends GroupableResourceImpl< - KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> +public class KubernetesClusterImpl extends + GroupableResourceImpl implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); @@ -76,8 +75,8 @@ public class KubernetesClusterImpl private final Map> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; - private static final SerializerAdapter SERIALIZER_ADAPTER = - SerializerFactory.createDefaultManagementSerializerAdapter(); + private static final SerializerAdapter SERIALIZER_ADAPTER + = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); @@ -112,8 +111,8 @@ public String version() { @Override public List adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { - this.adminKubeConfigs = - this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); + this.adminKubeConfigs + = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @@ -121,8 +120,8 @@ public List adminKubeConfigs() { @Override public List userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { - this.userKubeConfigs = - this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); + this.userKubeConfigs + = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @@ -132,18 +131,11 @@ public List userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } - return Collections.unmodifiableList( - this.formatUserKubeConfigsMap.computeIfAbsent( - format, - key -> KubernetesClusterImpl.this - .manager() - .kubernetesClusters() - .listUserKubeConfigContent( - KubernetesClusterImpl.this.resourceGroupName(), - KubernetesClusterImpl.this.name(), - format - )) - ); + return Collections.unmodifiableList(this.formatUserKubeConfigsMap.computeIfAbsent(format, + key -> KubernetesClusterImpl.this.manager() + .kubernetesClusters() + .listUserKubeConfigContent(KubernetesClusterImpl.this.resourceGroupName(), + KubernetesClusterImpl.this.name(), format))); } @Override @@ -260,8 +252,7 @@ public ManagedClusterSku sku() { public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { - UserAssignedIdentity identity = - this.innerModel().identityProfile().get("kubeletidentity"); + UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } @@ -327,23 +318,19 @@ public Mono stopAsync() { @Override public Accepted beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { - return AcceptedImpl.newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), - () -> this.manager().serviceClient().getAgentPools() + () -> this.manager() + .serviceClient() + .getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), - AgentPoolDataImpl::new, - AgentPoolInner.class, - null, - Context.NONE); + AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) @@ -364,15 +351,17 @@ boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { - final List parameterSnapshotAgentPools = - parameterSnapshotOnUpdate.agentPoolProfiles(); + final List parameterSnapshotAgentPools + = parameterSnapshotOnUpdate.agentPoolProfiles(); final List parameterAgentPools = parameter.agentPoolProfiles(); // intersection of agent pool names - Set intersectAgentPoolNames = parameter.agentPoolProfiles().stream() + Set intersectAgentPoolNames = parameter.agentPoolProfiles() + .stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); - intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() + intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles() + .stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); @@ -392,8 +381,8 @@ boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { parameter.withAgentPoolProfiles(agentPools); try { - String jsonStrSnapshot = - SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); + String jsonStrSnapshot + = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { @@ -411,8 +400,8 @@ ManagedClusterInner deepCopyInner() { try { // deep copy via json String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); - updateParameter = - SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); + updateParameter + = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { // ignored, null to signify not available updateParameter = null; @@ -430,8 +419,7 @@ public Mono createResourceAsync() { final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { - return this - .manager() + return this.manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) @@ -453,21 +441,26 @@ private void clearKubeConfig() { @Override public KubernetesClusterImpl withFreeSku() { - this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); + this.innerModel() + .withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withStandardSku() { - this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); + this.innerModel() + .withSku( + new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { - this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); + this.innerModel() + .withSku( + new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @@ -496,21 +489,23 @@ public KubernetesClusterImpl withRootUsername(String rootUserName) { @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { - this - .innerModel() + this.innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList())); - this.innerModel().linuxProfile().ssh().publicKeys().add( - new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); + this.innerModel() + .linuxProfile() + .ssh() + .publicKeys() + .add(new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { - this.innerModel().withServicePrincipalProfile( - new ManagedClusterServicePrincipalProfile().withClientId(clientId)); + this.innerModel() + .withServicePrincipalProfile(new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @@ -534,8 +529,7 @@ public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { - ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() - .withName(name) + ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile().withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @@ -547,28 +541,29 @@ public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } - throw logger.logExceptionAsError(new IllegalArgumentException(String.format( - "Cannot get agent pool named %s", name))); + throw logger + .logExceptionAsError(new IllegalArgumentException(String.format("Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { - innerModel().withAgentPoolProfiles( - innerModel().agentPoolProfiles().stream() - .filter(p -> !name.equals(p.name())) - .collect(Collectors.toList())); + innerModel().withAgentPoolProfiles(innerModel().agentPoolProfiles() + .stream() + .filter(p -> !name.equals(p.name())) + .collect(Collectors.toList())); - this.addDependency(context -> - manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) - .then(context.voidMono())); + this.addDependency(context -> manager().serviceClient() + .getAgentPools() + .deleteAsync(resourceGroupName(), name(), name) + .then(context.voidMono())); } return this; } @Override - public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< - KubernetesCluster.DefinitionStages.WithCreate> + public + KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @@ -599,10 +594,10 @@ public KubernetesClusterImpl withRBACDisabled() { public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { - this.addDependency(context -> - manager().serviceClient().getAgentPools().createOrUpdateAsync( - resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) - .then(context.voidMono())); + this.addDependency(context -> manager().serviceClient() + .getAgentPools() + .createOrUpdateAsync(resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) + .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; @@ -630,11 +625,12 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - Mono>> retList = this.manager().serviceClient().getPrivateLinkResources() + Mono>> retList = this.manager() + .serviceClient() + .getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(PrivateLinkResourceImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue().value().stream().map(PrivateLinkResourceImpl::new).collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -646,12 +642,16 @@ public PagedIterable listPrivateEndpointConnections() @Override public PagedFlux listPrivateEndpointConnectionsAsync() { - Mono>> retList = this.manager().serviceClient() + Mono>> retList = this.manager() + .serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(PrivateEndpointConnectionImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue() + .value() + .stream() + .map(PrivateEndpointConnectionImpl::new) + .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -750,25 +750,22 @@ private static final class PrivateEndpointConnectionImpl implements PrivateEndpo private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; - private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState - privateLinkServiceConnectionState; + private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; - this.privateEndpoint = innerModel.privateEndpoint() == null - ? null - : new PrivateEndpoint(innerModel.privateEndpoint().id()); + this.privateEndpoint + = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( - innerModel.privateLinkServiceConnectionState().status() == null - ? null - : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus - .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), - innerModel.privateLinkServiceConnectionState().description(), - ""); + innerModel.privateLinkServiceConnectionState().status() == null + ? null + : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus + .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), + innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterNetworkProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterNetworkProfileImpl.java index afa05b93781c9..701230b818e23 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterNetworkProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterNetworkProfileImpl.java @@ -12,9 +12,8 @@ import com.azure.resourcemanager.containerservice.models.NetworkPolicy; /** The implementation for KubernetesClusterAgentPool and its create and update interfaces. */ -public class KubernetesClusterNetworkProfileImpl - implements KubernetesCluster.DefinitionStages.NetworkProfileDefinition< - KubernetesCluster.DefinitionStages.WithCreate> { +public class KubernetesClusterNetworkProfileImpl implements + KubernetesCluster.DefinitionStages.NetworkProfileDefinition { KubernetesClusterImpl parentKubernetesCluster; diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClustersImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClustersImpl.java index 85ba4450a39ad..59fccfec5c350 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClustersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClustersImpl.java @@ -28,9 +28,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for KubernetesClusters. */ -public class KubernetesClustersImpl - extends GroupableResourcesImpl< - KubernetesCluster, KubernetesClusterImpl, ManagedClusterInner, ManagedClustersClient, ContainerServiceManager> +public class KubernetesClustersImpl extends + GroupableResourcesImpl implements KubernetesClusters { public KubernetesClustersImpl(final ContainerServiceManager containerServiceManager) { @@ -44,7 +43,8 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.inner().listAsync(), inner -> new KubernetesClusterImpl(inner.name(), inner, manager())); + return PagedConverter.mapPage(this.inner().listAsync(), + inner -> new KubernetesClusterImpl(inner.name(), inner, manager())); } @Override @@ -55,8 +55,8 @@ public PagedIterable listByResourceGroup(String resourceGroup @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } @@ -97,8 +97,8 @@ public KubernetesClusterImpl define(String name) { @Override public Set listKubernetesVersions(Region region) { TreeSet kubernetesVersions = new TreeSet<>(); - OrchestratorVersionProfileListResultInner inner = - this.manager().serviceClient().getContainerServices().listOrchestrators(region.name()); + OrchestratorVersionProfileListResultInner inner + = this.manager().serviceClient().getContainerServices().listOrchestrators(region.name()); if (inner != null && inner.orchestrators() != null && inner.orchestrators().size() > 0) { for (OrchestratorVersionProfile orchestrator : inner.orchestrators()) { @@ -113,46 +113,42 @@ public Set listKubernetesVersions(Region region) { @Override public Mono> listKubernetesVersionsAsync(Region region) { - return this - .manager() + return this.manager() .serviceClient() .getContainerServices() .listOrchestratorsAsync(region.name()) - .map( - inner -> { - Set kubernetesVersions = new TreeSet<>(); - if (inner != null && inner.orchestrators() != null && inner.orchestrators().size() > 0) { - for (OrchestratorVersionProfile orchestrator : inner.orchestrators()) { - if (orchestrator.orchestratorType().equals("Kubernetes")) { - kubernetesVersions.add(orchestrator.orchestratorVersion()); - } + .map(inner -> { + Set kubernetesVersions = new TreeSet<>(); + if (inner != null && inner.orchestrators() != null && inner.orchestrators().size() > 0) { + for (OrchestratorVersionProfile orchestrator : inner.orchestrators()) { + if (orchestrator.orchestratorType().equals("Kubernetes")) { + kubernetesVersions.add(orchestrator.orchestratorVersion()); } } - return Collections.unmodifiableSet(kubernetesVersions); - }); + } + return Collections.unmodifiableSet(kubernetesVersions); + }); } @Override public PagedIterable listOrchestrators(Region region, - ContainerServiceResourceTypes resourceTypes) { + ContainerServiceResourceTypes resourceTypes) { return new PagedIterable<>(this.listOrchestratorsAsync(region, resourceTypes)); } @Override public PagedFlux listOrchestratorsAsync(Region region, - ContainerServiceResourceTypes resourceTypes) { - return new PagedFlux<>(() -> this.manager().serviceClient().getContainerServices() + ContainerServiceResourceTypes resourceTypes) { + return new PagedFlux<>(() -> this.manager() + .serviceClient() + .getContainerServices() .listOrchestratorsWithResponseAsync(region.name(), resourceTypes.toString()) - .map(response -> new PagedResponseBase( - response.getRequest(), - response.getStatusCode(), - response.getHeaders(), + .map(response -> new PagedResponseBase(response.getRequest(), + response.getStatusCode(), response.getHeaders(), (response.getValue() == null || response.getValue().orchestrators() == null) ? Collections.emptyList() : response.getValue().orchestrators(), - null, - null - ))); + null, null))); } @Override @@ -161,10 +157,9 @@ public List listAdminKubeConfigContent(String resourceGroupNam } @Override - public Mono> listAdminKubeConfigContentAsync( - String resourceGroupName, String kubernetesClusterName) { - return this - .manager() + public Mono> listAdminKubeConfigContentAsync(String resourceGroupName, + String kubernetesClusterName) { + return this.manager() .serviceClient() .getManagedClusters() .listClusterAdminCredentialsAsync(resourceGroupName, kubernetesClusterName) @@ -177,15 +172,15 @@ public List listUserKubeConfigContent(String resourceGroupName } @Override - public List listUserKubeConfigContent(String resourceGroupName, String kubernetesClusterName, Format format) { + public List listUserKubeConfigContent(String resourceGroupName, String kubernetesClusterName, + Format format) { return listUserKubeConfigContentAsync(resourceGroupName, kubernetesClusterName, format).block(); } @Override - public Mono> listUserKubeConfigContentAsync( - String resourceGroupName, String kubernetesClusterName) { - return this - .manager() + public Mono> listUserKubeConfigContentAsync(String resourceGroupName, + String kubernetesClusterName) { + return this.manager() .serviceClient() .getManagedClusters() .listClusterUserCredentialsAsync(resourceGroupName, kubernetesClusterName) @@ -193,10 +188,9 @@ public Mono> listUserKubeConfigContentAsync( } @Override - public Mono> listUserKubeConfigContentAsync( - String resourceGroupName, String kubernetesClusterName, Format format) { - return this - .manager() + public Mono> listUserKubeConfigContentAsync(String resourceGroupName, + String kubernetesClusterName, Format format) { + return this.manager() .serviceClient() .getManagedClusters() .listClusterUserCredentialsWithResponseAsync(resourceGroupName, kubernetesClusterName, null, format) @@ -210,8 +204,7 @@ public void start(String resourceGroupName, String kubernetesClusterName) { @Override public Mono startAsync(String resourceGroupName, String kubernetesClusterName) { - return this.manager().serviceClient().getManagedClusters() - .startAsync(resourceGroupName, kubernetesClusterName); + return this.manager().serviceClient().getManagedClusters().startAsync(resourceGroupName, kubernetesClusterName); } @Override @@ -221,7 +214,6 @@ public void stop(String resourceGroupName, String kubernetesClusterName) { @Override public Mono stopAsync(String resourceGroupName, String kubernetesClusterName) { - return this.manager().serviceClient().getManagedClusters() - .stopAsync(resourceGroupName, kubernetesClusterName); + return this.manager().serviceClient().getManagedClusters().stopAsync(resourceGroupName, kubernetesClusterName); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesCluster.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesCluster.java index 8989186c9aa8d..ceabbcfb0d262 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesCluster.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesCluster.java @@ -24,11 +24,8 @@ /** A client-side representation for a managed Kubernetes cluster. */ @Fluent public interface KubernetesCluster - extends GroupableResource, - Refreshable, - Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection { + extends GroupableResource, Refreshable, + Updatable, SupportsListingPrivateLinkResource, SupportsListingPrivateEndpointConnection { /** @return the provisioning state of the Kubernetes cluster */ String provisioningState(); @@ -169,21 +166,12 @@ public interface KubernetesCluster // Fluent interfaces /** Interface for all the definitions related to a Kubernetes cluster. */ - interface Definition - extends KubernetesCluster.DefinitionStages.Blank, - KubernetesCluster.DefinitionStages.WithGroup, - KubernetesCluster.DefinitionStages.WithVersion, - DefinitionStages.WithLinuxRootUsername, - DefinitionStages.WithLinuxSshKey, - DefinitionStages.WithServicePrincipalClientId, - DefinitionStages.WithServicePrincipalProfile, - DefinitionStages.WithDnsPrefix, - DefinitionStages.WithAgentPool, - DefinitionStages.WithNetworkProfile, - DefinitionStages.WithAddOnProfiles, - DefinitionStages.WithManagedClusterSku, - DefinitionStages.WithPublicNetworkAccess, - KubernetesCluster.DefinitionStages.WithCreate { + interface Definition extends KubernetesCluster.DefinitionStages.Blank, KubernetesCluster.DefinitionStages.WithGroup, + KubernetesCluster.DefinitionStages.WithVersion, DefinitionStages.WithLinuxRootUsername, + DefinitionStages.WithLinuxSshKey, DefinitionStages.WithServicePrincipalClientId, + DefinitionStages.WithServicePrincipalProfile, DefinitionStages.WithDnsPrefix, DefinitionStages.WithAgentPool, + DefinitionStages.WithNetworkProfile, DefinitionStages.WithAddOnProfiles, DefinitionStages.WithManagedClusterSku, + DefinitionStages.WithPublicNetworkAccess, KubernetesCluster.DefinitionStages.WithCreate { } /** Grouping of Kubernetes cluster definition stages. */ @@ -492,7 +480,6 @@ interface WithNetworkDataPlan { WithAttach withNetworkDataPlan(NetworkDataplane networkDataPlan); } - /** * The final stage of a network profile definition. At this stage, any remaining optional settings can be * specified, or the container service agent pool can be attached to the parent container service @@ -501,17 +488,15 @@ interface WithNetworkDataPlan { * @param the stage of the container service definition to return to after attaching this * definition */ - interface WithAttach - extends NetworkProfileDefinitionStages.WithNetworkPolicy, - NetworkProfileDefinitionStages.WithPodCidr, - NetworkProfileDefinitionStages.WithServiceCidr, - NetworkProfileDefinitionStages.WithDnsServiceIP, - NetworkProfileDefinitionStages.WithDockerBridgeCidr, - NetworkProfileDefinitionStages.WithLoadBalancerProfile, - NetworkProfileDefinitionStages.WithNetworkMode, - NetworkProfileDefinitionStages.WithNetworkDataPlan, - NetworkProfileDefinitionStages.WithNetworkPluginMode, - Attachable.InDefinition { + interface WithAttach extends NetworkProfileDefinitionStages.WithNetworkPolicy, + NetworkProfileDefinitionStages.WithPodCidr, + NetworkProfileDefinitionStages.WithServiceCidr, + NetworkProfileDefinitionStages.WithDnsServiceIP, + NetworkProfileDefinitionStages.WithDockerBridgeCidr, + NetworkProfileDefinitionStages.WithLoadBalancerProfile, + NetworkProfileDefinitionStages.WithNetworkMode, + NetworkProfileDefinitionStages.WithNetworkDataPlan, + NetworkProfileDefinitionStages.WithNetworkPluginMode, Attachable.InDefinition { } } @@ -521,17 +506,16 @@ interface WithAttach * * @param the stage of the container service definition to return to after attaching this definition */ - interface NetworkProfileDefinition - extends NetworkProfileDefinitionStages.Blank, - NetworkProfileDefinitionStages.WithNetworkPolicy, - NetworkProfileDefinitionStages.WithPodCidr, - NetworkProfileDefinitionStages.WithServiceCidr, - NetworkProfileDefinitionStages.WithDnsServiceIP, - NetworkProfileDefinitionStages.WithDockerBridgeCidr, - NetworkProfileDefinitionStages.WithNetworkMode, - NetworkProfileDefinitionStages.WithNetworkDataPlan, - NetworkProfileDefinitionStages.WithNetworkPluginMode, - NetworkProfileDefinitionStages.WithAttach { + interface NetworkProfileDefinition extends NetworkProfileDefinitionStages.Blank, + NetworkProfileDefinitionStages.WithNetworkPolicy, + NetworkProfileDefinitionStages.WithPodCidr, + NetworkProfileDefinitionStages.WithServiceCidr, + NetworkProfileDefinitionStages.WithDnsServiceIP, + NetworkProfileDefinitionStages.WithDockerBridgeCidr, + NetworkProfileDefinitionStages.WithNetworkMode, + NetworkProfileDefinitionStages.WithNetworkDataPlan, + NetworkProfileDefinitionStages.WithNetworkPluginMode, + NetworkProfileDefinitionStages.WithAttach { } /** The stage of the Kubernetes cluster definition allowing to specify the DNS prefix label. */ @@ -670,40 +654,19 @@ interface WithPublicNetworkAccess { * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - WithAgentPool, - WithNetworkProfile, - WithDnsPrefix, - WithAddOnProfiles, - WithAccessProfiles, - WithAutoScalerProfile, - WithManagedServiceIdentity, - WithRBAC, - WithAAD, - WithLocalAccounts, - WithDiskEncryption, - WithAgentPoolResourceGroup, - WithManagedClusterSku, - WithPublicNetworkAccess, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, WithAgentPool, WithNetworkProfile, WithDnsPrefix, + WithAddOnProfiles, WithAccessProfiles, WithAutoScalerProfile, WithManagedServiceIdentity, WithRBAC, WithAAD, + WithLocalAccounts, WithDiskEncryption, WithAgentPoolResourceGroup, WithManagedClusterSku, + WithPublicNetworkAccess, Resource.DefinitionWithTags { } } /** The template for an update operation, containing all the settings that can be modified. */ interface Update - extends UpdateStages.WithAgentPool, - UpdateStages.WithAddOnProfiles, - UpdateStages.WithNetworkProfile, - UpdateStages.WithRBAC, - UpdateStages.WithAutoScalerProfile, - UpdateStages.WithAAD, - UpdateStages.WithLocalAccounts, - UpdateStages.WithVersion, - UpdateStages.WithManagedClusterSku, - UpdateStages.WithPublicNetworkAccess, - Resource.UpdateWithTags, - Appliable { + extends UpdateStages.WithAgentPool, UpdateStages.WithAddOnProfiles, UpdateStages.WithNetworkProfile, + UpdateStages.WithRBAC, UpdateStages.WithAutoScalerProfile, UpdateStages.WithAAD, UpdateStages.WithLocalAccounts, + UpdateStages.WithVersion, UpdateStages.WithManagedClusterSku, UpdateStages.WithPublicNetworkAccess, + Resource.UpdateWithTags, Appliable { } /** Grouping of the Kubernetes cluster update stages. */ @@ -880,7 +843,6 @@ interface WithVersion { Update withVersion(String kubernetesVersion); } - /** The stage of kubernetes cluster update allowing to configure network access settings. */ interface WithPublicNetworkAccess { /** @@ -889,6 +851,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the kubernetes cluster. * diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusterAgentPool.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusterAgentPool.java index d7e84dca77365..8507831fb4deb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusterAgentPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusterAgentPool.java @@ -96,29 +96,29 @@ public interface KubernetesClusterAgentPool */ Map tags(); -// /** -// * Starts the agent pool. -// */ -// void start(); -// -// /** -// * Starts the agent pool. -// * -// * @return A {@link Mono} that completes when a successful response is received. -// */ -// Mono startAsync(); -// -// /** -// * Stops the agent pool. -// */ -// void stop(); -// -// /** -// * Stops the agent pool. -// * -// * @return A {@link Mono} that completes when a successful response is received. -// */ -// Mono stopAsync(); + // /** + // * Starts the agent pool. + // */ + // void start(); + // + // /** + // * Starts the agent pool. + // * + // * @return A {@link Mono} that completes when a successful response is received. + // */ + // Mono startAsync(); + // + // /** + // * Stops the agent pool. + // */ + // void stop(); + // + // /** + // * Stops the agent pool. + // * + // * @return A {@link Mono} that completes when a successful response is received. + // */ + // Mono stopAsync(); // Fluent interfaces @@ -127,15 +127,10 @@ public interface KubernetesClusterAgentPool * * @param the stage of the container service definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithOSType, - DefinitionStages.WithOSDiskSize, - DefinitionStages.WithAgentPoolType, - DefinitionStages.WithAgentPoolVirtualMachineCount, - DefinitionStages.WithMaxPodsCount, - DefinitionStages.WithVirtualNetwork, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithOSType, + DefinitionStages.WithOSDiskSize, DefinitionStages.WithAgentPoolType, + DefinitionStages.WithAgentPoolVirtualMachineCount, DefinitionStages.WithMaxPodsCount, + DefinitionStages.WithVirtualNetwork, DefinitionStages.WithAttach { } /** Grouping of container service agent pool definition stages as a part of parent container service definition. */ @@ -458,34 +453,18 @@ interface WithFips { * * @param the stage of the container service definition to return to after attaching this definition */ - interface WithAttach - extends WithOSType, - WithOSDiskSize, - WithAgentPoolType, - WithAgentPoolVirtualMachineCount, - WithMaxPodsCount, - WithVirtualNetwork, - WithAgentPoolMode, - WithAutoScaling, - WithAvailabilityZones, - WithNodeLabelsTaints, - WithVMPriority, - WithBillingProfile, - WithDiskType, - WithFips, - WithTags, - Attachable.InDefinition { + interface WithAttach extends WithOSType, WithOSDiskSize, WithAgentPoolType, + WithAgentPoolVirtualMachineCount, WithMaxPodsCount, WithVirtualNetwork, + WithAgentPoolMode, WithAutoScaling, WithAvailabilityZones, + WithNodeLabelsTaints, WithVMPriority, WithBillingProfile, WithDiskType, + WithFips, WithTags, Attachable.InDefinition { } } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Settable, - UpdateStages.WithAgentPoolVirtualMachineCount, - UpdateStages.WithAutoScaling, - UpdateStages.WithAgentPoolMode, - UpdateStages.WithDiskType, - UpdateStages.WithTags { + interface Update extends Settable, UpdateStages.WithAgentPoolVirtualMachineCount, + UpdateStages.WithAutoScaling, UpdateStages.WithAgentPoolMode, + UpdateStages.WithDiskType, UpdateStages.WithTags { } /** Grouping of agent pool update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusters.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusters.java index 6fdb3ad7a8092..2dd6fea5b5055 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusters.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/KubernetesClusters.java @@ -24,15 +24,10 @@ /** Entry point to managed Kubernetes service management API. */ @Fluent public interface KubernetesClusters - extends HasManager, - SupportsCreating, - SupportsBatchCreation, - SupportsListing, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup { + extends HasManager, SupportsCreating, + SupportsBatchCreation, SupportsListing, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup { /** * Returns the list of available Kubernetes versions available for the given Azure region. @@ -63,7 +58,7 @@ public interface KubernetesClusters * @return a list of orchestrators which can be used when creating a service in this region */ PagedIterable listOrchestrators(Region region, - ContainerServiceResourceTypes resourceTypes); + ContainerServiceResourceTypes resourceTypes); /** * Returns the list of available orchestrators for the given Azure region. @@ -73,7 +68,7 @@ PagedIterable listOrchestrators(Region region, * @return a list of orchestrators which can be used when creating a service in this region */ PagedFlux listOrchestratorsAsync(Region region, - ContainerServiceResourceTypes resourceTypes); + ContainerServiceResourceTypes resourceTypes); /** * Returns the admin Kube.config content which can be used with a Kubernetes client. @@ -91,8 +86,8 @@ PagedFlux listOrchestratorsAsync(Region region, * @param kubernetesClusterName the managed cluster name * @return a future representation of the Kube.config content which can be used with a Kubernetes client */ - Mono> listAdminKubeConfigContentAsync( - String resourceGroupName, String kubernetesClusterName); + Mono> listAdminKubeConfigContentAsync(String resourceGroupName, + String kubernetesClusterName); /** * Returns the user Kube.config content which can be used with a Kubernetes client. @@ -111,7 +106,8 @@ Mono> listAdminKubeConfigContentAsync( * @param format Only apply to AAD clusters, specifies the format of returned kubeconfig. Format 'azure' will return azure auth-provider kubeconfig; format 'exec' will return exec format kubeconfig, which requires kubelogin binary in the path. * @return the Kube.config content which can be used with a Kubernetes client */ - List listUserKubeConfigContent(String resourceGroupName, String kubernetesClusterName, Format format); + List listUserKubeConfigContent(String resourceGroupName, String kubernetesClusterName, + Format format); /** * Returns asynchronously the user Kube.config content which can be used with a Kubernetes client. @@ -130,7 +126,8 @@ Mono> listAdminKubeConfigContentAsync( * @param format Only apply to AAD clusters, specifies the format of returned kubeconfig. Format 'azure' will return azure auth-provider kubeconfig; format 'exec' will return exec format kubeconfig, which requires kubelogin binary in the path. * @return a future representation of the Kube.config content which can be used with a Kubernetes client */ - Mono> listUserKubeConfigContentAsync(String resourceGroupName, String kubernetesClusterName, Format format); + Mono> listUserKubeConfigContentAsync(String resourceGroupName, String kubernetesClusterName, + Format format); /** * Starts a stopped Kubernetes cluster. diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/ContainerServiceManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/ContainerServiceManagementTest.java index d10b23d0fda06..339e3cead74cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/ContainerServiceManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/ContainerServiceManagementTest.java @@ -26,21 +26,10 @@ public class ContainerServiceManagementTest extends ResourceManagerTestProxyTest protected String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java index 192195a3f25cc..fde1994b9e9dd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java @@ -57,8 +57,7 @@ public class KubernetesClustersTests extends ContainerServiceManagementTest { @Test public void canCRUDKubernetesCluster() { // enable preview feature of ACR Teleport for AKS - Context context = new Context( - AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, + Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders().set("EnableACRTeleport", "true")); String aksName = generateRandomResourceName("aks", 15); @@ -75,35 +74,33 @@ public void canCRUDKubernetesCluster() { */ // create - KubernetesCluster kubernetesCluster = - containerServiceManager - .kubernetesClusters() - .define(aksName) - .withRegion(Region.US_WEST2) - .withExistingResourceGroup(rgName) - .withDefaultVersion() - .withRootUsername("testaks") - .withSshKey(SSH_KEY) - .withSystemAssignedManagedServiceIdentity() - .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) - .withAgentPoolVirtualMachineCount(1) - .withOSDiskSizeInGB(30) - .withOSDiskType(OSDiskType.EPHEMERAL) - .withKubeletDiskType(KubeletDiskType.TEMPORARY) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withTag("pool.name", agentPoolName) - .attach() - .defineAgentPool(agentPoolName1) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(1) - .withTag("pool.name", agentPoolName1) - .attach() - .withDnsPrefix("mp1" + dnsPrefix) - .withTag("tag1", "value1") - .withAgentPoolResourceGroup(agentPoolResourceGroupName) - .create(context); + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) + .withRegion(Region.US_WEST2) + .withExistingResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername("testaks") + .withSshKey(SSH_KEY) + .withSystemAssignedManagedServiceIdentity() + .defineAgentPool(agentPoolName) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) + .withAgentPoolVirtualMachineCount(1) + .withOSDiskSizeInGB(30) + .withOSDiskType(OSDiskType.EPHEMERAL) + .withKubeletDiskType(KubeletDiskType.TEMPORARY) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withTag("pool.name", agentPoolName) + .attach() + .defineAgentPool(agentPoolName1) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(1) + .withTag("pool.name", agentPoolName1) + .attach() + .withDnsPrefix("mp1" + dnsPrefix) + .withTag("tag1", "value1") + .withAgentPoolResourceGroup(agentPoolResourceGroupName) + .create(context); Assertions.assertNotNull(kubernetesCluster.id()); Assertions.assertEquals(Region.US_WEST2, kubernetesCluster.region()); @@ -111,7 +108,8 @@ public void canCRUDKubernetesCluster() { Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); Assertions.assertEquals(agentPoolResourceGroupName, kubernetesCluster.agentPoolResourceGroup()); - Assertions.assertEquals(agentPoolResourceGroupName, resourceManager.resourceGroups().getByName(agentPoolResourceGroupName).name()); + Assertions.assertEquals(agentPoolResourceGroupName, + resourceManager.resourceGroups().getByName(agentPoolResourceGroupName).name()); KubernetesClusterAgentPool agentPool = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertNotNull(agentPool); @@ -151,32 +149,30 @@ public void canCRUDKubernetesCluster() { nodeTaints.add("key=value:NoSchedule"); // update - kubernetesCluster = - kubernetesCluster - .update() - .updateAgentPool(agentPoolName1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withAgentPoolVirtualMachineCount(2) - .withKubeletDiskType(KubeletDiskType.OS) - .withoutTag("pool.name") - .withTags(Collections.singletonMap("state", "updated")) - .parent() - .defineAgentPool(agentPoolName2) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) - .withAgentPoolVirtualMachineCount(1) - .withOSDiskSizeInGB(30) - .withAgentPoolMode(AgentPoolMode.USER) - .withOSDiskType(OSDiskType.MANAGED) - .withKubeletDiskType(KubeletDiskType.TEMPORARY) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withNodeLabels(Collections.unmodifiableMap(nodeLables)) - .withNodeTaints(Collections.unmodifiableList(nodeTaints)) - .withTags(Collections.singletonMap("state", "created")) - .attach() - .withTag("tag2", "value2") - .withTag("tag3", "value3") - .withoutTag("tag1") - .apply(context); + kubernetesCluster = kubernetesCluster.update() + .updateAgentPool(agentPoolName1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withAgentPoolVirtualMachineCount(2) + .withKubeletDiskType(KubeletDiskType.OS) + .withoutTag("pool.name") + .withTags(Collections.singletonMap("state", "updated")) + .parent() + .defineAgentPool(agentPoolName2) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) + .withAgentPoolVirtualMachineCount(1) + .withOSDiskSizeInGB(30) + .withAgentPoolMode(AgentPoolMode.USER) + .withOSDiskType(OSDiskType.MANAGED) + .withKubeletDiskType(KubeletDiskType.TEMPORARY) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withNodeLabels(Collections.unmodifiableMap(nodeLables)) + .withNodeTaints(Collections.unmodifiableList(nodeTaints)) + .withTags(Collections.singletonMap("state", "created")) + .attach() + .withTag("tag2", "value2") + .withTag("tag3", "value3") + .withoutTag("tag1") + .apply(context); Assertions.assertEquals(3, kubernetesCluster.agentPools().size()); @@ -201,13 +197,13 @@ public void canCRUDKubernetesCluster() { Assertions.assertFalse(kubernetesCluster.tags().containsKey("tag1")); // preview feature -// // stop agent pool -// agentPool.stop(); -// Assertions.assertEquals(Code.STOPPED, agentPool.powerState().code()); -// -// // start agent pool -// agentPool.start(); -// Assertions.assertEquals(Code.RUNNING, agentPool.powerState().code()); + // // stop agent pool + // agentPool.stop(); + // Assertions.assertEquals(Code.STOPPED, agentPool.powerState().code()); + // + // // start agent pool + // agentPool.start(); + // Assertions.assertEquals(Code.RUNNING, agentPool.powerState().code()); } @Test @@ -227,34 +223,35 @@ public void canAutoScaleKubernetesCluster() { nodeTaints.add("key=value:NoSchedule"); // create cluster - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() // zone redundancy .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(3) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withAvailabilityZones(1, 2, 3) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(3) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withAvailabilityZones(1, 2, 3) + .attach() // auto-scaling // labels and taints .defineAgentPool(agentPoolName1) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAutoScaling(1, 3) - .withNodeLabels(Collections.unmodifiableMap(nodeLables)) - .withNodeTaints(Collections.unmodifiableList(nodeTaints)) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAutoScaling(1, 3) + .withNodeLabels(Collections.unmodifiableMap(nodeLables)) + .withNodeTaints(Collections.unmodifiableList(nodeTaints)) + .attach() // number of nodes = 0 .defineAgentPool(agentPoolName2) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(0) - .withMaxPodsCount(10) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(0) + .withMaxPodsCount(10) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .withAutoScalerProfile(new ManagedClusterPropertiesAutoScalerProfile().withScanInterval("30s")) .create(); @@ -284,11 +281,7 @@ public void canAutoScaleKubernetesCluster() { Assertions.assertEquals(10, agentPoolProfile2.maximumPodsPerNode()); // disable auto-scaling - kubernetesCluster.update() - .updateAgentPool(agentPoolName1) - .withoutAutoScaling() - .parent() - .apply(); + kubernetesCluster.update().updateAgentPool(agentPoolName1).withoutAutoScaling().parent().apply(); Assertions.assertFalse(agentPoolProfile1.isAutoScalingEnabled()); @@ -297,9 +290,9 @@ public void canAutoScaleKubernetesCluster() { .withoutAgentPool(agentPoolName1) .withoutAgentPool(agentPoolName2) .defineAgentPool(agentPoolName3) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(0) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(0) + .attach() .apply(); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); @@ -317,7 +310,8 @@ public void canCreateClusterWithSpotVM() { String agentPoolName2 = generateRandomResourceName("ap2", 10); // create cluster - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() @@ -325,17 +319,17 @@ public void canCreateClusterWithSpotVM() { .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() // spot vm .defineAgentPool(agentPoolName1) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(1) - .withSpotPriorityVirtualMachine() - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(1) + .withSpotPriorityVirtualMachine() + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -344,7 +338,8 @@ public void canCreateClusterWithSpotVM() { () -> new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); - Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR); + Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null + || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR); KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile1.virtualMachinePriority()); @@ -353,11 +348,11 @@ public void canCreateClusterWithSpotVM() { kubernetesCluster.update() .defineAgentPool(agentPoolName2) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(1) - .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE) - .withVirtualMachineMaximumPrice(100.0) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(1) + .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE) + .withVirtualMachineMaximumPrice(100.0) + .attach() .apply(); KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2); @@ -373,7 +368,8 @@ public void canListKubeConfigWithFormat() { String agentPoolName = generateRandomResourceName("ap0", 10); // create cluster - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() @@ -381,11 +377,11 @@ public void canListKubeConfigWithFormat() { .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -416,8 +412,7 @@ public void testKubernetesClusterAzureRbac() { final String agentPoolName = generateRandomResourceName("ap0", 10); // Azure AD integration with Azure RBAC - KubernetesCluster kubernetesCluster = containerServiceManager - .kubernetesClusters() + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST3) .withExistingResourceGroup(rgName) @@ -426,11 +421,11 @@ public void testKubernetesClusterAzureRbac() { .enableAzureRbac() .disableLocalAccounts() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withOSDiskSizeInGB(30) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withOSDiskSizeInGB(30) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -444,7 +439,8 @@ public void testKubernetesClusterAzureRbac() { public void canListOrchestrators() { List profiles = containerServiceManager.kubernetesClusters() .listOrchestrators(Region.US_WEST3, ContainerServiceResourceTypes.MANAGED_CLUSTERS) - .stream().collect(Collectors.toList()); + .stream() + .collect(Collectors.toList()); Assertions.assertFalse(profiles.isEmpty()); Assertions.assertEquals("Kubernetes", profiles.iterator().next().orchestratorType()); } @@ -457,7 +453,8 @@ public void testBeginCreateAgentPool() { String agentPoolName1 = generateRandomResourceName("ap1", 10); // create cluster - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() @@ -465,17 +462,16 @@ public void testBeginCreateAgentPool() { .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Accepted acceptedAgentPool = kubernetesCluster.beginCreateAgentPool(agentPoolName1, - new AgentPoolData() - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + new AgentPoolData().withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1)); @@ -504,7 +500,8 @@ public void testFipsEnabled() { String agentPoolName2 = generateRandomResourceName("ap2", 10); // create cluster - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() @@ -512,18 +509,18 @@ public void testFipsEnabled() { .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .defineAgentPool(agentPoolName1) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.USER) - .withFipsEnabled() // enable FIPS - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.USER) + .withFipsEnabled() // enable FIPS + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -531,8 +528,7 @@ public void testFipsEnabled() { Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName1).isFipsEnabled()); // create a new agent pool with FIPS enabled - AgentPoolData request = new AgentPoolData() - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + AgentPoolData request = new AgentPoolData().withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) @@ -621,22 +617,26 @@ public void testUpdateManagedClusterSkuAndKubernetesSupportPlan() { kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); - Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); + Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, + kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withStandardSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.STANDARD, kubernetesCluster.sku().tier()); - Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); + Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, + kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); - Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); + Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, + kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withFreeSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.FREE, kubernetesCluster.sku().tier()); - Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); + Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, + kubernetesCluster.innerModel().supportPlan()); } @Test @@ -646,23 +646,23 @@ public void canCreateKubernetesClusterWithDisablePublicNetworkAccess() { String agentPoolName = generateRandomResourceName("ap0", 10); // create - KubernetesCluster kubernetesCluster = - containerServiceManager.kubernetesClusters().define(aksName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withDefaultVersion() - .withRootUsername("testaks") - .withSshKey(SSH_KEY) - .withSystemAssignedManagedServiceIdentity() - .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() - .withDnsPrefix("mp1" + dnsPrefix) - .disablePublicNetworkAccess() - .create(); + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername("testaks") + .withSshKey(SSH_KEY) + .withSystemAssignedManagedServiceIdentity() + .defineAgentPool(agentPoolName) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() + .withDnsPrefix("mp1" + dnsPrefix) + .disablePublicNetworkAccess() + .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); } @@ -674,22 +674,22 @@ public void canUpdatePublicNetworkAccess() { String agentPoolName = generateRandomResourceName("ap0", 10); // create - KubernetesCluster kubernetesCluster = - containerServiceManager.kubernetesClusters().define(aksName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withDefaultVersion() - .withRootUsername("testaks") - .withSshKey(SSH_KEY) - .withSystemAssignedManagedServiceIdentity() - .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() - .withDnsPrefix("mp1" + dnsPrefix) - .create(); + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername("testaks") + .withSshKey(SSH_KEY) + .withSystemAssignedManagedServiceIdentity() + .defineAgentPool(agentPoolName) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() + .withDnsPrefix("mp1" + dnsPrefix) + .create(); kubernetesCluster.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); @@ -705,29 +705,29 @@ public void canCreateAndUpdateWithNetworkProperties() { String agentPoolName = generateRandomResourceName("ap0", 10); // create - KubernetesCluster kubernetesCluster = - containerServiceManager.kubernetesClusters().define(aksName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withDefaultVersion() - .withRootUsername("testaks") - .withSshKey(SSH_KEY) - .withSystemAssignedManagedServiceIdentity() - .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() - .defineNetworkProfile() - .withNetworkPlugin(NetworkPlugin.AZURE) - .withNetworkPluginMode(NetworkPluginMode.OVERLAY) - .withNetworkPolicy(NetworkPolicy.AZURE) - .withNetworkMode(NetworkMode.TRANSPARENT) - .withNetworkDataPlan(NetworkDataplane.AZURE) - .attach() - .withDnsPrefix("mp1" + dnsPrefix) - .create(); + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername("testaks") + .withSshKey(SSH_KEY) + .withSystemAssignedManagedServiceIdentity() + .defineAgentPool(agentPoolName) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() + .defineNetworkProfile() + .withNetworkPlugin(NetworkPlugin.AZURE) + .withNetworkPluginMode(NetworkPluginMode.OVERLAY) + .withNetworkPolicy(NetworkPolicy.AZURE) + .withNetworkMode(NetworkMode.TRANSPARENT) + .withNetworkDataPlan(NetworkDataplane.AZURE) + .attach() + .withDnsPrefix("mp1" + dnsPrefix) + .create(); kubernetesCluster.refresh(); Assertions.assertEquals(NetworkPlugin.AZURE, kubernetesCluster.networkProfile().networkPlugin()); @@ -736,11 +736,11 @@ public void canCreateAndUpdateWithNetworkProperties() { Assertions.assertEquals(NetworkMode.TRANSPARENT, kubernetesCluster.networkProfile().networkMode()); Assertions.assertEquals(NetworkDataplane.AZURE, kubernetesCluster.networkProfile().networkDataplane()); - kubernetesCluster.update().withNetworkProfile( - kubernetesCluster.networkProfile() + kubernetesCluster.update() + .withNetworkProfile(kubernetesCluster.networkProfile() .withNetworkPolicy(NetworkPolicy.CILIUM) - .withNetworkDataplane(NetworkDataplane.CILIUM) - ).apply(); + .withNetworkDataplane(NetworkDataplane.CILIUM)) + .apply(); kubernetesCluster.refresh(); Assertions.assertEquals(NetworkPolicy.CILIUM, kubernetesCluster.networkProfile().networkPolicy()); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImplTests.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImplTests.java index 8a9d502957ea1..80772dbb364d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImplTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImplTests.java @@ -25,10 +25,7 @@ public class KubernetesClusterAgentPoolImplTests { void testGetAgentPoolInner() throws Exception { // test case for the manual conversion of ManagedClusterAgentPoolProfile to AgentPoolInner - Set excludeMethods = new HashSet<>(Arrays.asList( - "name", - "type", - "vnetSubnetId" // skip because this had to be a well-formed resource ID + Set excludeMethods = new HashSet<>(Arrays.asList("name", "type", "vnetSubnetId" // skip because this had to be a well-formed resource ID )); Map mockValues = new HashMap<>(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImplTests.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImplTests.java index ecbc95312595b..e13545608b8ab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImplTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterImplTests.java @@ -19,17 +19,8 @@ void testNpeForKubernetesCluster() throws Exception { // npe test for KubernetesClusterImpl if inner model's properties are null // exclude those which do rest calls - Set excludeMethods = new HashSet<>(Arrays.asList( - "beginCreateAgentPool", - "stopAsync", - "stop", - "start", - "startAsync", - "adminKubeConfigs", - "adminKubeConfigContent", - "userKubeConfigs", - "userKubeConfigContent" - )); + Set excludeMethods = new HashSet<>(Arrays.asList("beginCreateAgentPool", "stopAsync", "stop", "start", + "startAsync", "adminKubeConfigs", "adminKubeConfigContent", "userKubeConfigs", "userKubeConfigContent")); ManagedClusterInner inner = new ManagedClusterInner(); KubernetesCluster cluster = new KubernetesClusterImpl("testCluster", inner, null); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterUpdateTests.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterUpdateTests.java index fc0bbf28c8080..f5de63bb9c459 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterUpdateTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterUpdateTests.java @@ -39,7 +39,8 @@ private static class ValidationPipeline implements HttpPipelinePolicy { private int countOfPut = 0; @Override - public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + public Mono process(HttpPipelineCallContext httpPipelineCallContext, + HttpPipelineNextPolicy httpPipelineNextPolicy) { HttpRequest request = httpPipelineCallContext.getHttpRequest(); if (request.getHttpMethod() == HttpMethod.PUT && request.getHeaders().get(HEADER_NAME) != null) { ++countOfPut; @@ -56,12 +57,8 @@ public HttpPipelinePosition getPipelinePosition() { private final ValidationPipeline validationPipeline = new ValidationPipeline(); @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { policies.add(validationPipeline); return super.buildHttpPipeline(credential, profile, httpLogOptions, policies, httpClient); @@ -74,18 +71,19 @@ public void testKubernetesClusterUpdate() { String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); - KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() + .define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withAutoScaling(1, 3) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withAutoScaling(1, 3) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName).isAutoScalingEnabled()); @@ -93,43 +91,31 @@ public void testKubernetesClusterUpdate() { KubernetesCluster.Update clusterUpdate = kubernetesCluster.update(); Assertions.assertFalse(isClusterModifiedDuringUpdate(kubernetesCluster)); - clusterUpdate = clusterUpdate - .defineAgentPool(agentPoolName1) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) - .withAgentPoolVirtualMachineCount(1) - .attach(); + clusterUpdate = clusterUpdate.defineAgentPool(agentPoolName1) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) + .withAgentPoolVirtualMachineCount(1) + .attach(); Assertions.assertFalse(isClusterModifiedDuringUpdate(kubernetesCluster)); Assertions.assertEquals(2, kubernetesCluster.innerModel().agentPoolProfiles().size()); - clusterUpdate = clusterUpdate - .updateAgentPool(agentPoolName) - .withoutAutoScaling() - .parent(); + clusterUpdate = clusterUpdate.updateAgentPool(agentPoolName).withoutAutoScaling().parent(); Assertions.assertTrue(isClusterModifiedDuringUpdate(kubernetesCluster)); - clusterUpdate = clusterUpdate - .updateAgentPool(agentPoolName) - .withAutoScaling(1, 3) - .parent(); + clusterUpdate = clusterUpdate.updateAgentPool(agentPoolName).withAutoScaling(1, 3).parent(); Assertions.assertFalse(isClusterModifiedDuringUpdate(kubernetesCluster)); Assertions.assertEquals(2, kubernetesCluster.innerModel().agentPoolProfiles().size()); // this should not send PUT to ManagedClustersClient - kubernetesCluster = clusterUpdate.apply( - new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, - new HttpHeaders().set(ValidationPipeline.HEADER_NAME, "createOrUpdate"))); + kubernetesCluster = clusterUpdate.apply(new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, + new HttpHeaders().set(ValidationPipeline.HEADER_NAME, "createOrUpdate"))); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); Assertions.assertEquals(1, validationPipeline.countOfPut); - clusterUpdate = clusterUpdate - .withoutAgentPool(agentPoolName1); + clusterUpdate = clusterUpdate.withoutAgentPool(agentPoolName1); Assertions.assertFalse(isClusterModifiedDuringUpdate(kubernetesCluster)); Assertions.assertEquals(1, kubernetesCluster.innerModel().agentPoolProfiles().size()); - clusterUpdate = clusterUpdate - .updateAgentPool(agentPoolName) - .withoutAutoScaling() - .parent(); + clusterUpdate = clusterUpdate.updateAgentPool(agentPoolName).withoutAutoScaling().parent(); Assertions.assertTrue(isClusterModifiedDuringUpdate(kubernetesCluster)); kubernetesCluster = clusterUpdate.apply(); diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml index 80b62cc655eba..974987ce5c102 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml @@ -44,6 +44,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/CosmosManager.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/CosmosManager.java index 10b8a4282c56f..0e55dca0b05c6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/CosmosManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/CosmosManager.java @@ -20,6 +20,7 @@ /** Entry point to Azure compute resource management. */ public final class CosmosManager extends Manager { private CosmosDBAccountsImpl databaseAccounts; + /** * Get a Configurable instance that can be used to create ComputeManager with optional configuration. * @@ -76,11 +77,8 @@ public CosmosManager authenticate(TokenCredential credential, AzureProfile profi } private CosmosManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new CosmosDBManagementClientBuilder() - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + super(httpPipeline, profile, + new CosmosDBManagementClientBuilder().endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .pipeline(httpPipeline) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountImpl.java index e27c33399d000..699a70d1dec4f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountImpl.java @@ -62,8 +62,8 @@ class CosmosDBAccountImpl CosmosDBAccountImpl(String name, DatabaseAccountGetResultsInner innerObject, CosmosManager manager) { super(fixDBName(name), innerObject, manager); this.failoverPolicies = new ArrayList<>(); - this.privateEndpointConnections = - new PrivateEndpointConnectionsImpl(this.manager().serviceClient().getPrivateEndpointConnections(), this); + this.privateEndpointConnections + = new PrivateEndpointConnectionsImpl(this.manager().serviceClient().getPrivateEndpointConnections(), this); } @Override @@ -130,13 +130,11 @@ public DatabaseAccountListKeysResult listKeys() { @Override public Mono listKeysAsync() { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) - .map( - DatabaseAccountListKeysResultImpl::new); + .map(DatabaseAccountListKeysResultImpl::new); } @Override @@ -146,13 +144,11 @@ public DatabaseAccountListReadOnlyKeysResult listReadOnlyKeys() { @Override public Mono listReadOnlyKeysAsync() { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .listReadOnlyKeysAsync(this.resourceGroupName(), this.name()) - .map( - DatabaseAccountListReadOnlyKeysResultImpl::new); + .map(DatabaseAccountListReadOnlyKeysResultImpl::new); } @Override @@ -162,13 +158,11 @@ public DatabaseAccountListConnectionStringsResult listConnectionStrings() { @Override public Mono listConnectionStringsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .listConnectionStringsAsync(this.resourceGroupName(), this.name()) - .map( - DatabaseAccountListConnectionStringsResultImpl::new); + .map(DatabaseAccountListConnectionStringsResultImpl::new); } @Override @@ -178,12 +172,10 @@ public List listSqlDatabases() { @Override public PagedFlux listSqlDatabasesAsync() { - return PagedConverter.mapPage(this - .manager() + return PagedConverter.mapPage(this.manager() .serviceClient() .getSqlResources() - .listSqlDatabasesAsync(this.resourceGroupName(), this.name()), - SqlDatabaseImpl::new); + .listSqlDatabasesAsync(this.resourceGroupName(), this.name()), SqlDatabaseImpl::new); } @Override @@ -193,12 +185,10 @@ public List listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - return PagedConverter.mapPage(this - .manager() + return PagedConverter.mapPage(this.manager() .serviceClient() .getPrivateLinkResources() - .listByDatabaseAccountAsync(this.resourceGroupName(), this.name()), - PrivateLinkResourceImpl::new); + .listByDatabaseAccountAsync(this.resourceGroupName(), this.name()), PrivateLinkResourceImpl::new); } @Override @@ -208,8 +198,7 @@ public PrivateLinkResource getPrivateLinkResource(String groupName) { @Override public Mono getPrivateLinkResourceAsync(String groupName) { - return this - .manager() + return this.manager() .serviceClient() .getPrivateLinkResources() .getAsync(this.resourceGroupName(), this.name(), groupName) @@ -233,9 +222,7 @@ public PrivateEndpointConnection getPrivateEndpointConnection(String name) { @Override public Mono getPrivateEndpointConnectionAsync(String name) { - return this - .privateEndpointConnections - .getImplAsync(name) + return this.privateEndpointConnections.getImplAsync(name) .map(privateEndpointConnection -> privateEndpointConnection); } @@ -270,23 +257,24 @@ public List capabilities() { @Override public List virtualNetworkRules() { - List result = - (this.innerModel() != null && this.innerModel().virtualNetworkRules() != null) - ? this.innerModel().virtualNetworkRules() - : new ArrayList(); + List result = (this.innerModel() != null && this.innerModel().virtualNetworkRules() != null) + ? this.innerModel().virtualNetworkRules() + : new ArrayList(); return Collections.unmodifiableList(result); } @Override public void offlineRegion(Region region) { - this.manager().serviceClient().getDatabaseAccounts().offlineRegion(this.resourceGroupName(), this.name(), - new RegionForOnlineOffline().withRegion(region.label())); + this.manager() + .serviceClient() + .getDatabaseAccounts() + .offlineRegion(this.resourceGroupName(), this.name(), + new RegionForOnlineOffline().withRegion(region.label())); } @Override public Mono offlineRegionAsync(Region region) { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .offlineRegionAsync(this.resourceGroupName(), this.name(), @@ -295,14 +283,16 @@ public Mono offlineRegionAsync(Region region) { @Override public void onlineRegion(Region region) { - this.manager().serviceClient().getDatabaseAccounts().onlineRegion(this.resourceGroupName(), this.name(), - new RegionForOnlineOffline().withRegion(region.label())); + this.manager() + .serviceClient() + .getDatabaseAccounts() + .onlineRegion(this.resourceGroupName(), this.name(), + new RegionForOnlineOffline().withRegion(region.label())); } @Override public Mono onlineRegionAsync(Region region) { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .onlineRegionAsync(this.resourceGroupName(), this.name(), @@ -311,14 +301,16 @@ public Mono onlineRegionAsync(Region region) { @Override public void regenerateKey(KeyKind keyKind) { - this.manager().serviceClient().getDatabaseAccounts().regenerateKey(this.resourceGroupName(), this.name(), - new DatabaseAccountRegenerateKeyParameters().withKeyKind(keyKind)); + this.manager() + .serviceClient() + .getDatabaseAccounts() + .regenerateKey(this.resourceGroupName(), this.name(), + new DatabaseAccountRegenerateKeyParameters().withKeyKind(keyKind)); } @Override public Mono regenerateKeyAsync(KeyKind keyKind) { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), @@ -400,7 +392,10 @@ public CosmosDBAccountImpl withIpRules(List ipRules) { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getDatabaseAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); + return this.manager() + .serviceClient() + .getDatabaseAccounts() + .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override @@ -500,9 +495,8 @@ private DatabaseAccountCreateUpdateParameters createUpdateParametersInner(Databa createUpdateParametersInner.withCapabilities(inner.capabilities()); createUpdateParametersInner.withTags(inner.tags()); createUpdateParametersInner.withEnableMultipleWriteLocations(inner.enableMultipleWriteLocations()); - this - .addLocationsForParameters( - new CreateUpdateLocationParameters(createUpdateParametersInner), this.failoverPolicies); + this.addLocationsForParameters(new CreateUpdateLocationParameters(createUpdateParametersInner), + this.failoverPolicies); createUpdateParametersInner.withIsVirtualNetworkFilterEnabled(inner.isVirtualNetworkFilterEnabled()); createUpdateParametersInner.withEnableCassandraConnector(inner.enableCassandraConnector()); createUpdateParametersInner.withConnectorOffer(inner.connectorOffer()); @@ -546,8 +540,8 @@ private static String fixDBName(String name) { return name.toLowerCase(Locale.ROOT); } - private void setConsistencyPolicy( - DefaultConsistencyLevel level, long maxStalenessPrefix, int maxIntervalInSeconds) { + private void setConsistencyPolicy(DefaultConsistencyLevel level, long maxStalenessPrefix, + int maxIntervalInSeconds) { ConsistencyPolicy policy = new ConsistencyPolicy(); policy.withDefaultConsistencyLevel(level); if (level == DefaultConsistencyLevel.BOUNDED_STALENESS) { @@ -591,73 +585,61 @@ private Mono doDatabaseUpdateCreate() { HasLocations locationParameters = null; if (isInCreateMode()) { - final DatabaseAccountCreateUpdateParameters createUpdateParametersInner = - this.createUpdateParametersInner(this.innerModel()); - request = - this - .manager() - .serviceClient() - .getDatabaseAccounts() - .createOrUpdateAsync(resourceGroupName(), name(), createUpdateParametersInner); + final DatabaseAccountCreateUpdateParameters createUpdateParametersInner + = this.createUpdateParametersInner(this.innerModel()); + request = this.manager() + .serviceClient() + .getDatabaseAccounts() + .createOrUpdateAsync(resourceGroupName(), name(), createUpdateParametersInner); locationParameters = new CreateUpdateLocationParameters(createUpdateParametersInner); } else { final DatabaseAccountUpdateParameters updateParametersInner = this.updateParametersInner(this.innerModel()); - request = - this - .manager() - .serviceClient() - .getDatabaseAccounts() - .updateAsync(resourceGroupName(), name(), updateParametersInner); + request = this.manager() + .serviceClient() + .getDatabaseAccounts() + .updateAsync(resourceGroupName(), name(), updateParametersInner); locationParameters = new UpdateLocationParameters(updateParametersInner); } - Set locations = locationParameters.locations().stream() + Set locations = locationParameters.locations() + .stream() .map(location -> formatLocationName(location.locationName())) .collect(Collectors.toSet()); - return request - .flatMap( - databaseAccountInner -> { - self.failoverPolicies.clear(); - self.hasFailoverPolicyChanges = false; - return manager() - .databaseAccounts() - .getByResourceGroupAsync(resourceGroupName(), name()) - .flatMap( - databaseAccount -> { - if (MAX_DELAY_DUE_TO_MISSING_FAILOVERS > data.get(0) - && (databaseAccount.id() == null - || databaseAccount.id().length() == 0 - || locations.size() - != databaseAccount.innerModel().failoverPolicies().size())) { - return Mono.empty(); - } - - if (isAFinalProvisioningState(databaseAccount.innerModel().provisioningState())) { - for (Location location : databaseAccount.readableReplications()) { - if (!isAFinalProvisioningState(location.provisioningState())) { - return Mono.empty(); - } - if (!locations.contains(formatLocationName(location.locationName()))) { - return Mono.empty(); - } - } - } else { - return Mono.empty(); - } - - self.setInner(databaseAccount.innerModel()); - return Mono.just(databaseAccount); - }) - .repeatWhenEmpty( - longFlux -> - longFlux - .flatMap( - index -> { - data.set(0, data.get(0) + 30); - return Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( - manager().serviceClient().getDefaultPollInterval())); - })); - }); + return request.flatMap(databaseAccountInner -> { + self.failoverPolicies.clear(); + self.hasFailoverPolicyChanges = false; + return manager().databaseAccounts() + .getByResourceGroupAsync(resourceGroupName(), name()) + .flatMap(databaseAccount -> { + if (MAX_DELAY_DUE_TO_MISSING_FAILOVERS > data.get(0) + && (databaseAccount.id() == null + || databaseAccount.id().length() == 0 + || locations.size() != databaseAccount.innerModel().failoverPolicies().size())) { + return Mono.empty(); + } + + if (isAFinalProvisioningState(databaseAccount.innerModel().provisioningState())) { + for (Location location : databaseAccount.readableReplications()) { + if (!isAFinalProvisioningState(location.provisioningState())) { + return Mono.empty(); + } + if (!locations.contains(formatLocationName(location.locationName()))) { + return Mono.empty(); + } + } + } else { + return Mono.empty(); + } + + self.setInner(databaseAccount.innerModel()); + return Mono.just(databaseAccount); + }) + .repeatWhenEmpty(longFlux -> longFlux.flatMap(index -> { + data.set(0, data.get(0) + 30); + return Mono.delay(ResourceManagerUtils.InternalRuntimeContext + .getDelayDuration(manager().serviceClient().getDefaultPollInterval())); + })); + }); } private void ensureFailoverIsInitialized() { @@ -669,10 +651,7 @@ private void ensureFailoverIsInitialized() { this.failoverPolicies.clear(); FailoverPolicy[] policyInners = new FailoverPolicy[this.innerModel().failoverPolicies().size()]; this.innerModel().failoverPolicies().toArray(policyInners); - Arrays - .sort( - policyInners, - Comparator.comparing(FailoverPolicy::failoverPriority)); + Arrays.sort(policyInners, Comparator.comparing(FailoverPolicy::failoverPriority)); for (int i = 0; i < policyInners.length; i++) { this.failoverPolicies.add(policyInners[i]); @@ -688,6 +667,7 @@ private boolean isAFinalProvisioningState(String state) { case "canceled": case "failed": return true; + default: return false; } @@ -773,11 +753,12 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().createOrUpdateAsync( - resourceGroupName(), name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty() - .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString()))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .createOrUpdateAsync(resourceGroupName(), name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionStateProperty() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString()))) .then(); } @@ -788,11 +769,12 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().createOrUpdateAsync( - resourceGroupName(), name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty() - .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString()))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .createOrUpdateAsync(resourceGroupName(), name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionStateProperty() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString()))) .then(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountsImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountsImpl.java index 6d3c211bbaab4..2b9ddcf644e27 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/CosmosDBAccountsImpl.java @@ -27,9 +27,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** Implementation for Registries. */ -public class CosmosDBAccountsImpl - extends GroupableResourcesImpl< - CosmosDBAccount, CosmosDBAccountImpl, DatabaseAccountGetResultsInner, DatabaseAccountsClient, CosmosManager> +public class CosmosDBAccountsImpl extends + GroupableResourcesImpl implements CosmosDBAccounts { public CosmosDBAccountsImpl(final CosmosManager manager) { @@ -43,17 +42,15 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this - .inner() - .listAsync(), + return PagedConverter.mapPage(this.inner().listAsync(), inner -> new CosmosDBAccountImpl(inner.name(), inner, this.manager())); } @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } @@ -102,8 +99,8 @@ public void failoverPriorityChange(String groupName, String accountName, List failoverPriorityChangeAsync( - String groupName, String accountName, List failoverLocations) { + public Mono failoverPriorityChangeAsync(String groupName, String accountName, + List failoverLocations) { List policyInners = new ArrayList(); for (int i = 0; i < failoverLocations.size(); i++) { Location location = failoverLocations.get(i); @@ -113,8 +110,7 @@ public Mono failoverPriorityChangeAsync( policyInners.add(policyInner); } - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .failoverPriorityChangeAsync(groupName, accountName, @@ -133,26 +129,22 @@ public DatabaseAccountListReadOnlyKeysResult listReadOnlyKeys(String groupName, @Override public Mono listKeysAsync(String groupName, String accountName) { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .listKeysAsync(groupName, accountName) - .map( - databaseAccountListKeysResultInner -> - new DatabaseAccountListKeysResultImpl(databaseAccountListKeysResultInner)); + .map(databaseAccountListKeysResultInner -> new DatabaseAccountListKeysResultImpl( + databaseAccountListKeysResultInner)); } @Override public Mono listReadOnlyKeysAsync(String groupName, String accountName) { - return this - .manager() + return this.manager() .serviceClient() .getDatabaseAccounts() .listReadOnlyKeysAsync(groupName, accountName) - .map( - databaseAccountListReadOnlyKeysResultInner -> - new DatabaseAccountListReadOnlyKeysResultImpl(databaseAccountListReadOnlyKeysResultInner)); + .map(databaseAccountListReadOnlyKeysResultInner -> new DatabaseAccountListReadOnlyKeysResultImpl( + databaseAccountListReadOnlyKeysResultInner)); } @Override @@ -161,17 +153,14 @@ public DatabaseAccountListConnectionStringsResult listConnectionStrings(String g } @Override - public Mono listConnectionStringsAsync( - String groupName, String accountName) { - return this - .manager() + public Mono listConnectionStringsAsync(String groupName, + String accountName) { + return this.manager() .serviceClient() .getDatabaseAccounts() .listConnectionStringsAsync(groupName, accountName) - .map( - databaseAccountListConnectionStringsResultInner -> - new DatabaseAccountListConnectionStringsResultImpl( - databaseAccountListConnectionStringsResultInner)); + .map(databaseAccountListConnectionStringsResultInner -> new DatabaseAccountListConnectionStringsResultImpl( + databaseAccountListConnectionStringsResultInner)); } @Override @@ -181,7 +170,10 @@ public void regenerateKey(String groupName, String accountName, KeyKind keyKind) @Override public Mono regenerateKeyAsync(String groupName, String accountName, KeyKind keyKind) { - return this.manager().serviceClient().getDatabaseAccounts().regenerateKeyAsync(groupName, accountName, - new DatabaseAccountRegenerateKeyParameters().withKeyKind(keyKind)); + return this.manager() + .serviceClient() + .getDatabaseAccounts() + .regenerateKeyAsync(groupName, accountName, + new DatabaseAccountRegenerateKeyParameters().withKeyKind(keyKind)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/DatabaseAccountListConnectionStringsResultImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/DatabaseAccountListConnectionStringsResultImpl.java index 2a14a5fc153e3..da78dd62be635 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/DatabaseAccountListConnectionStringsResultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/DatabaseAccountListConnectionStringsResultImpl.java @@ -9,9 +9,8 @@ import java.util.List; /** The implementation for DatabaseAccountListConnectionStringsResult. */ -public class DatabaseAccountListConnectionStringsResultImpl - extends WrapperImpl - implements DatabaseAccountListConnectionStringsResult { +public class DatabaseAccountListConnectionStringsResultImpl extends + WrapperImpl implements DatabaseAccountListConnectionStringsResult { DatabaseAccountListConnectionStringsResultImpl(DatabaseAccountListConnectionStringsResultInner innerObject) { super(innerObject); } diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionImpl.java index 8e569fa76de9a..69d04692f325f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionImpl.java @@ -12,19 +12,15 @@ import reactor.core.publisher.Mono; /** A private endpoint connection. */ -public class PrivateEndpointConnectionImpl - extends ExternalChildResourceImpl< - PrivateEndpointConnection, PrivateEndpointConnectionInner, CosmosDBAccountImpl, CosmosDBAccount> +public class PrivateEndpointConnectionImpl extends + ExternalChildResourceImpl implements PrivateEndpointConnection, - PrivateEndpointConnection.Definition, - PrivateEndpointConnection.UpdateDefinition, - PrivateEndpointConnection.Update { + PrivateEndpointConnection.Definition, + PrivateEndpointConnection.UpdateDefinition, + PrivateEndpointConnection.Update { private final PrivateEndpointConnectionsClient client; - PrivateEndpointConnectionImpl( - String name, - CosmosDBAccountImpl parent, - PrivateEndpointConnectionInner inner, + PrivateEndpointConnectionImpl(String name, CosmosDBAccountImpl parent, PrivateEndpointConnectionInner inner, PrivateEndpointConnectionsClient client) { super(name, parent, inner); this.client = client; @@ -72,14 +68,13 @@ public PrivateEndpointConnectionImpl withDescription(String description) { @Override public Mono createResourceAsync() { final PrivateEndpointConnectionImpl self = this; - return this - .client - .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) - .map( - privateEndpointConnectionInner -> { - self.setInner(privateEndpointConnectionInner); - return self; - }); + return this.client + .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), + this.innerModel()) + .map(privateEndpointConnectionInner -> { + self.setInner(privateEndpointConnectionInner); + return self; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionsImpl.java index 349c3bbc85340..0039072b91546 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/PrivateEndpointConnectionsImpl.java @@ -17,13 +17,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** Represents a private endpoint connection collection. */ -class PrivateEndpointConnectionsImpl - extends ExternalChildResourcesCachedImpl< - PrivateEndpointConnectionImpl, - PrivateEndpointConnection, - PrivateEndpointConnectionInner, - CosmosDBAccountImpl, - CosmosDBAccount> { +class PrivateEndpointConnectionsImpl extends + ExternalChildResourcesCachedImpl { private final PrivateEndpointConnectionsClient client; PrivateEndpointConnectionsImpl(PrivateEndpointConnectionsClient client, CosmosDBAccountImpl parent) { @@ -54,43 +49,35 @@ public Map asMap() { } public Mono> asMapAsync() { - return listAsync() - .collectList() - .map( - privateEndpointConnections -> { - Map privateEndpointConnectionMap = new HashMap<>(); - for (PrivateEndpointConnectionImpl privateEndpointConnection : privateEndpointConnections) { - privateEndpointConnectionMap.put(privateEndpointConnection.name(), privateEndpointConnection); - } - return privateEndpointConnectionMap; - }); + return listAsync().collectList().map(privateEndpointConnections -> { + Map privateEndpointConnectionMap = new HashMap<>(); + for (PrivateEndpointConnectionImpl privateEndpointConnection : privateEndpointConnections) { + privateEndpointConnectionMap.put(privateEndpointConnection.name(), privateEndpointConnection); + } + return privateEndpointConnectionMap; + }); } public PagedFlux listAsync() { final PrivateEndpointConnectionsImpl self = this; - return PagedConverter.mapPage(this - .client - .listByDatabaseAccountAsync(this.getParent().resourceGroupName(), this.getParent().name()), - inner -> { - PrivateEndpointConnectionImpl childResource = - new PrivateEndpointConnectionImpl(inner.name(), self.getParent(), inner, client); - self.addPrivateEndpointConnection(childResource); - return childResource; - }); + return PagedConverter.mapPage( + this.client.listByDatabaseAccountAsync(this.getParent().resourceGroupName(), this.getParent().name()), + inner -> { + PrivateEndpointConnectionImpl childResource + = new PrivateEndpointConnectionImpl(inner.name(), self.getParent(), inner, client); + self.addPrivateEndpointConnection(childResource); + return childResource; + }); } public Mono getImplAsync(String name) { final PrivateEndpointConnectionsImpl self = this; - return this - .client - .getAsync(getParent().resourceGroupName(), getParent().name(), name) - .map( - inner -> { - PrivateEndpointConnectionImpl childResource = - new PrivateEndpointConnectionImpl(inner.name(), getParent(), inner, client); - self.addPrivateEndpointConnection(childResource); - return childResource; - }); + return this.client.getAsync(getParent().resourceGroupName(), getParent().name(), name).map(inner -> { + PrivateEndpointConnectionImpl childResource + = new PrivateEndpointConnectionImpl(inner.name(), getParent(), inner, client); + self.addPrivateEndpointConnection(childResource); + return childResource; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/SqlResourcesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/SqlResourcesClientImpl.java index 3dd2526ceefc7..a5ff9a5e4a651 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/SqlResourcesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/implementation/SqlResourcesClientImpl.java @@ -4515,7 +4515,7 @@ public Mono createUpdateClientEncryptionKeyA ClientEncryptionKeyCreateUpdateParameters createUpdateClientEncryptionKeyParameters) { return beginCreateUpdateClientEncryptionKeyAsync(resourceGroupName, accountName, databaseName, clientEncryptionKeyName, createUpdateClientEncryptionKeyParameters).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -4539,7 +4539,7 @@ private Mono createUpdateClientEncryptionKey ClientEncryptionKeyCreateUpdateParameters createUpdateClientEncryptionKeyParameters, Context context) { return beginCreateUpdateClientEncryptionKeyAsync(resourceGroupName, accountName, databaseName, clientEncryptionKeyName, createUpdateClientEncryptionKeyParameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -5168,7 +5168,7 @@ public Mono createUpdateSqlStoredProcedureAsy SqlStoredProcedureCreateUpdateParameters createUpdateSqlStoredProcedureParameters) { return beginCreateUpdateSqlStoredProcedureAsync(resourceGroupName, accountName, databaseName, containerName, storedProcedureName, createUpdateSqlStoredProcedureParameters).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -5192,7 +5192,7 @@ private Mono createUpdateSqlStoredProcedureAs SqlStoredProcedureCreateUpdateParameters createUpdateSqlStoredProcedureParameters, Context context) { return beginCreateUpdateSqlStoredProcedureAsync(resourceGroupName, accountName, databaseName, containerName, storedProcedureName, createUpdateSqlStoredProcedureParameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -6104,7 +6104,7 @@ public Mono createUpdateSqlUserDefinedFun SqlUserDefinedFunctionCreateUpdateParameters createUpdateSqlUserDefinedFunctionParameters) { return beginCreateUpdateSqlUserDefinedFunctionAsync(resourceGroupName, accountName, databaseName, containerName, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -6130,7 +6130,7 @@ private Mono createUpdateSqlUserDefinedFu SqlUserDefinedFunctionCreateUpdateParameters createUpdateSqlUserDefinedFunctionParameters, Context context) { return beginCreateUpdateSqlUserDefinedFunctionAsync(resourceGroupName, accountName, databaseName, containerName, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -7041,7 +7041,7 @@ private Mono createUpdateSqlTriggerAsync(String resou SqlTriggerCreateUpdateParameters createUpdateSqlTriggerParameters, Context context) { return beginCreateUpdateSqlTriggerAsync(resourceGroupName, accountName, databaseName, containerName, triggerName, createUpdateSqlTriggerParameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccount.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccount.java index 5687d1343d923..5b3ad29734521 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccount.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccount.java @@ -21,11 +21,8 @@ /** An immutable client-side representation of an Azure Cosmos DB. */ @Fluent -public interface CosmosDBAccount - extends GroupableResource, - Refreshable, - Updatable, - SupportsUpdatingPrivateEndpointConnection { +public interface CosmosDBAccount extends GroupableResource, + Refreshable, Updatable, SupportsUpdatingPrivateEndpointConnection { /** @return indicates the type of database account */ DatabaseAccountKind kind(); @@ -183,13 +180,8 @@ public interface CosmosDBAccount Mono regenerateKeyAsync(KeyKind keyKind); /** Grouping of cosmos db definition stages. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithKind, - DefinitionStages.WithWriteReplication, - DefinitionStages.WithReadReplication, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithKind, + DefinitionStages.WithWriteReplication, DefinitionStages.WithReadReplication, DefinitionStages.WithCreate { } /** Grouping of cosmos db definition stages. */ @@ -401,8 +393,8 @@ interface WithPrivateEndpointConnection { * @param name the reference name for the private endpoint connection * @return the first stage of a private endpoint connection definition */ - PrivateEndpointConnection.DefinitionStages.Blank defineNewPrivateEndpointConnection( - String name); + PrivateEndpointConnection.DefinitionStages.Blank + defineNewPrivateEndpointConnection(String name); } /** The stage of CosmosDB account definition allowing to configure network access settings. */ @@ -414,22 +406,14 @@ interface WithPublicNetworkAccess { */ WithCreate disablePublicNetworkAccess(); } + /** * The stage of the definition which contains all the minimum required inputs for the resource to be created, * but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - WithConsistencyPolicy, - WithReadReplication, - WithIpRules, - WithVirtualNetworkRule, - WithMultipleLocations, - WithConnector, - WithKeyBasedMetadataWriteAccess, - WithPrivateEndpointConnection, - DefinitionWithTags, - WithPublicNetworkAccess { + interface WithCreate extends Creatable, WithConsistencyPolicy, WithReadReplication, + WithIpRules, WithVirtualNetworkRule, WithMultipleLocations, WithConnector, WithKeyBasedMetadataWriteAccess, + WithPrivateEndpointConnection, DefinitionWithTags, WithPublicNetworkAccess { } } @@ -440,17 +424,10 @@ interface Update extends UpdateStages.WithReadLocations, UpdateStages.WithOption /** Grouping of cosmos db update stages. */ interface UpdateStages { /** Grouping of cosmos db update stages. */ - interface WithOptionals - extends Resource.UpdateWithTags, - Appliable, - UpdateStages.WithConsistencyPolicy, - UpdateStages.WithVirtualNetworkRule, - UpdateStages.WithMultipleLocations, - UpdateStages.WithConnector, - UpdateStages.WithKeyBasedMetadataWriteAccess, - UpdateStages.WithPrivateEndpointConnection, - UpdateStages.WithIpRules, - UpdateStages.WithPublicNetworkAccess { + interface WithOptionals extends Resource.UpdateWithTags, Appliable, + UpdateStages.WithConsistencyPolicy, UpdateStages.WithVirtualNetworkRule, UpdateStages.WithMultipleLocations, + UpdateStages.WithConnector, UpdateStages.WithKeyBasedMetadataWriteAccess, + UpdateStages.WithPrivateEndpointConnection, UpdateStages.WithIpRules, UpdateStages.WithPublicNetworkAccess { } /** The stage of the cosmos db definition allowing the definition of a write location. */ @@ -613,8 +590,8 @@ interface WithPrivateEndpointConnection { * @param name the reference name for the private endpoint connection * @return the first stage of a private endpoint connection definition */ - PrivateEndpointConnection.UpdateDefinitionStages.Blank defineNewPrivateEndpointConnection( - String name); + PrivateEndpointConnection.UpdateDefinitionStages.Blank + defineNewPrivateEndpointConnection(String name); /** * Start the update of an existing private endpoint connection. @@ -641,6 +618,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the CosmosDB account. * diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccounts.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccounts.java index ce35bf772f44a..01e2422005d08 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccounts.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/CosmosDBAccounts.java @@ -19,16 +19,10 @@ /** Entry point to Cosmos DB management API. */ @Fluent -public interface CosmosDBAccounts - extends SupportsCreating, - HasManager, - SupportsBatchCreation, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup { +public interface CosmosDBAccounts extends SupportsCreating, + HasManager, SupportsBatchCreation, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup { /** * Changes the failover priority for the Azure CosmosDB database account. A failover priority of 0 indicates a write diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/PrivateEndpointConnection.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/PrivateEndpointConnection.java index 71caaefd924d5..8994c2fd02195 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/PrivateEndpointConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/PrivateEndpointConnection.java @@ -11,9 +11,8 @@ /** A private endpoint connection. */ @Fluent -public interface PrivateEndpointConnection - extends HasInnerModel, - ExternalChildResource { +public interface PrivateEndpointConnection extends HasInnerModel, + ExternalChildResource { /** * Get private endpoint which the connection belongs to. * @@ -83,10 +82,8 @@ interface WithState { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithState, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithState, + DefinitionStages.WithAttach { } /** Grouping of private endpoint connection definition stages as part of parent cosmos db account update. */ @@ -144,10 +141,8 @@ interface WithState { * * @param the stage of the parent update to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithState, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithState, UpdateDefinitionStages.WithAttach { } /** Grouping of private endpoint connection update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/test/java/com/azure/resourcemanager/cosmos/CosmosDBTests.java b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/test/java/com/azure/resourcemanager/cosmos/CosmosDBTests.java index 91e84319e8a7b..d37432daaa03a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/src/test/java/com/azure/resourcemanager/cosmos/CosmosDBTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/src/test/java/com/azure/resourcemanager/cosmos/CosmosDBTests.java @@ -43,21 +43,10 @@ public class CosmosDBTests extends ResourceManagerTestProxyTestBase { protected NetworkManager networkManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -78,19 +67,17 @@ protected void cleanUpResources() { public void canCreateCosmosDbSqlAccount() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelSql() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST2) - .withMultipleWriteLocationsEnabled(true) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelSql() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST2) + .withMultipleWriteLocationsEnabled(true) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase()); Assertions.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.GLOBAL_DOCUMENT_DB); @@ -111,48 +98,45 @@ public void canCreateSqlPrivateEndpoint() { cosmosManager.resourceManager().resourceGroups().define(rgName).withRegion(region).create(); - Network network = - networkManager - .networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("10.0.0.0/16") - .defineSubnet(subnetName) - .withAddressPrefix("10.0.0.0/24") - .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) - .disableNetworkPoliciesOnPrivateEndpoint() - .attach() - .create(); - - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withDataModelSql() - .withStrongConsistency() - .withDisableKeyBaseMetadataWriteAccess(true) - .create(); + Network network = networkManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("10.0.0.0/16") + .defineSubnet(subnetName) + .withAddressPrefix("10.0.0.0/24") + .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) + .disableNetworkPoliciesOnPrivateEndpoint() + .attach() + .create(); + + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withDataModelSql() + .withStrongConsistency() + .withDisableKeyBaseMetadataWriteAccess(true) + .create(); Assertions.assertTrue(cosmosDBAccount.keyBasedMetadataWriteAccessDisabled()); // create network private endpoint. - PrivateEndpoint privateEndpoint = networkManager.privateEndpoints().define(pedName) + PrivateEndpoint privateEndpoint = networkManager.privateEndpoints() + .define(pedName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(plsConnectionName) - .withResource(cosmosDBAccount) - .withSubResource(PrivateLinkSubResourceName.COSMOS_SQL) - .attach() + .withResource(cosmosDBAccount) + .withSubResource(PrivateLinkSubResourceName.COSMOS_SQL) + .attach() .create(); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(plsConnectionName).state().status()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(plsConnectionName).state().status()); - cosmosDBAccount - .update() + cosmosDBAccount.update() .defineNewPrivateEndpointConnection(pedName) .withStatus("Rejected") .withDescription("Rej") @@ -165,37 +149,29 @@ public void canCreateSqlPrivateEndpoint() { Assertions.assertEquals(1, cosmosDBAccount.listPrivateLinkResources().size()); - cosmosDBAccount - .update() + cosmosDBAccount.update() .updatePrivateEndpointConnection(pedName) .withDescription("Test Update") .parent() .apply(); - Assertions - .assertEquals( - "Test Update", - cosmosDBAccount - .getPrivateEndpointConnection(pedName) - .privateLinkServiceConnectionState() - .description()); + Assertions.assertEquals("Test Update", + cosmosDBAccount.getPrivateEndpointConnection(pedName).privateLinkServiceConnectionState().description()); } @Test public void canCreateCosmosDbMongoDBAccount() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelMongoDB() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST2) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelMongoDB() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST2) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase()); Assertions.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.MONGO_DB); @@ -208,18 +184,16 @@ public void canCreateCosmosDbMongoDBAccount() { public void canCreateCosmosDbCassandraAccount() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelCassandra() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelCassandra() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase()); Assertions.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.GLOBAL_DOCUMENT_DB); @@ -235,17 +209,15 @@ public void canUpdateCosmosDbCassandraConnector() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); // CassandraConnector could only be used in West US and South Central US. - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withDataModelCassandra() - .withStrongConsistency() - .withCassandraConnector(ConnectorOffer.SMALL) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withDataModelCassandra() + .withStrongConsistency() + .withCassandraConnector(ConnectorOffer.SMALL) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals("value1", cosmosDBAccount.tags().get("tag1")); Assertions.assertTrue(cosmosDBAccount.cassandraConnectorEnabled()); @@ -260,18 +232,16 @@ public void canUpdateCosmosDbCassandraConnector() { public void canCreateCosmosDbAzureTableAccount() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelAzureTable() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelAzureTable() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase()); Assertions.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.GLOBAL_DOCUMENT_DB); @@ -285,19 +255,17 @@ public void canCreateCosmosDbAzureTableAccount() { public void canCreateCosmosDBAccountWithDisablePublicNetworkAccess() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelAzureTable() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST) - .withTag("tag1", "value1") - .disablePublicNetworkAccess() - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelAzureTable() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST) + .withTag("tag1", "value1") + .disablePublicNetworkAccess() + .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, cosmosDBAccount.publicNetworkAccess()); } @@ -306,18 +274,16 @@ public void canCreateCosmosDBAccountWithDisablePublicNetworkAccess() { public void canUpdatePublicNetworkAccess() { final String cosmosDbAccountName = generateRandomResourceName("cosmosdb", 22); - CosmosDBAccount cosmosDBAccount = - cosmosManager - .databaseAccounts() - .define(cosmosDbAccountName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withDataModelAzureTable() - .withEventualConsistency() - .withWriteReplication(Region.US_EAST2) - .withReadReplication(Region.US_WEST) - .withTag("tag1", "value1") - .create(); + CosmosDBAccount cosmosDBAccount = cosmosManager.databaseAccounts() + .define(cosmosDbAccountName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withDataModelAzureTable() + .withEventualConsistency() + .withWriteReplication(Region.US_EAST2) + .withReadReplication(Region.US_WEST) + .withTag("tag1", "value1") + .create(); cosmosDBAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, cosmosDBAccount.publicNetworkAccess()); diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml index 1d436113cffcf..4207aade3318a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml @@ -46,6 +46,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/DnsZoneManager.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/DnsZoneManager.java index 29a9cfacfa613..dc634dc886bd6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/DnsZoneManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/DnsZoneManager.java @@ -78,11 +78,8 @@ public DnsZoneManager authenticate(TokenCredential credential, AzureProfile prof } private DnsZoneManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new DnsManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new DnsManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/ARecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/ARecordSetsImpl.java index f8a2d795175a4..5218961f08c98 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/ARecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/ARecordSetsImpl.java @@ -25,8 +25,7 @@ public ARecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/AaaaRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/AaaaRecordSetsImpl.java index 8ee915368f82a..63c128ea86172 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/AaaaRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/AaaaRecordSetsImpl.java @@ -24,8 +24,7 @@ public AaaaRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -40,18 +39,12 @@ protected PagedIterable listIntern(String recordSetNameSuffix, In @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CaaRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CaaRecordSetsImpl.java index bf8883bfb2859..0da94aff35c51 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CaaRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CaaRecordSetsImpl.java @@ -25,8 +25,7 @@ public CaaRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CnameRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CnameRecordSetsImpl.java index 2c3f5ce344820..4a7b50ad0f327 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CnameRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/CnameRecordSetsImpl.java @@ -25,8 +25,7 @@ public CnameRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsRecordSetImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsRecordSetImpl.java index 0a82ae41eb527..26abad4a24a44 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsRecordSetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsRecordSetImpl.java @@ -27,10 +27,8 @@ /** Implementation of DnsRecordSet. */ class DnsRecordSetImpl extends ExternalChildResourceImpl - implements DnsRecordSet, - DnsRecordSet.Definition, - DnsRecordSet.UpdateDefinition, - DnsRecordSet.UpdateCombined { + implements DnsRecordSet, DnsRecordSet.Definition, + DnsRecordSet.UpdateDefinition, DnsRecordSet.UpdateCombined { protected final RecordSetInner recordSetRemoveInfo; protected final String type; private final ETagState etagState = new ETagState(); @@ -38,18 +36,16 @@ class DnsRecordSetImpl extends ExternalChildResourceImpl()) - .withAaaaRecords(new ArrayList<>()) - .withCaaRecords(new ArrayList<>()) - .withCnameRecord(new CnameRecord()) - .withMxRecords(new ArrayList<>()) - .withNsRecords(new ArrayList<>()) - .withPtrRecords(new ArrayList<>()) - .withSrvRecords(new ArrayList<>()) - .withTxtRecords(new ArrayList<>()) - .withMetadata(new LinkedHashMap<>()); + this.recordSetRemoveInfo = new RecordSetInner().withARecords(new ArrayList<>()) + .withAaaaRecords(new ArrayList<>()) + .withCaaRecords(new ArrayList<>()) + .withCnameRecord(new CnameRecord()) + .withMxRecords(new ArrayList<>()) + .withNsRecords(new ArrayList<>()) + .withPtrRecords(new ArrayList<>()) + .withSrvRecords(new ArrayList<>()) + .withTxtRecords(new ArrayList<>()) + .withMetadata(new LinkedHashMap<>()); } @Override @@ -127,9 +123,7 @@ public DnsRecordSetImpl withMailExchange(String mailExchangeHostName, int priori @Override public DnsRecordSetImpl withoutMailExchange(String mailExchangeHostName, int priority) { - this - .recordSetRemoveInfo - .mxRecords() + this.recordSetRemoveInfo.mxRecords() .add(new MxRecord().withExchange(mailExchangeHostName).withPreference(priority)); return this; } @@ -172,8 +166,7 @@ public DnsRecordSetImpl withoutRecord(int flags, String tag, String value) { @Override public DnsRecordSetImpl withRecord(String target, int port, int priority, int weight) { - this - .innerModel() + this.innerModel() .srvRecords() .add(new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); return this; @@ -181,9 +174,7 @@ public DnsRecordSetImpl withRecord(String target, int port, int priority, int we @Override public DnsRecordSetImpl withoutRecord(String target, int port, int priority, int weight) { - this - .recordSetRemoveInfo - .srvRecords() + this.recordSetRemoveInfo.srvRecords() .add(new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); return this; } @@ -295,8 +286,7 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -307,17 +297,13 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() - .deleteWithResponseAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - this.recordType(), - this.etagState.ifMatchValueOnDelete()).then(); + .deleteWithResponseAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), + this.recordType(), this.etagState.ifMatchValueOnDelete()) + .then(); } @Override @@ -332,8 +318,7 @@ public String childResourceKey() { @Override protected Mono getInnerAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -342,25 +327,18 @@ protected Mono getInnerAsync() { private Mono createOrUpdateAsync(RecordSetInner resource) { final DnsRecordSetImpl self = this; - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() - .createOrUpdateWithResponseAsync( - this.parent().resourceGroupName(), - this.parent().name(), - this.name(), - this.recordType(), - resource, - etagState.ifMatchValueOnUpdate(resource.etag()), + .createOrUpdateWithResponseAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), + this.recordType(), resource, etagState.ifMatchValueOnUpdate(resource.etag()), etagState.ifNonMatchValueOnCreate()) - .map( - recordSetInner -> { - setInner(recordSetInner.getValue()); - self.etagState.clear(); - return self; - }); + .map(recordSetInner -> { + setInner(recordSetInner.getValue()); + self.etagState.clear(); + return self; + }); } private RecordSetInner prepare(RecordSetInner resource) { diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZoneImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZoneImpl.java index 8ba21a19e04e1..3524b488e1b92 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZoneImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZoneImpl.java @@ -175,7 +175,9 @@ public TxtRecordSets txtRecordSets() { @Override public SoaRecordSet getSoaRecordSet() { - RecordSetInner inner = this.manager().serviceClient().getRecordSets() + RecordSetInner inner = this.manager() + .serviceClient() + .getRecordSets() .get(this.resourceGroupName(), this.name(), "@", RecordType.SOA); if (inner == null) { return null; @@ -399,51 +401,35 @@ public DnsZoneImpl withETagCheck(String etagValue) { @Override public Mono createResourceAsync() { - return Mono - .just(this) - .flatMap( - self -> - self - .manager() - .serviceClient() - .getZones() - .createOrUpdateWithResponseAsync( - self.resourceGroupName(), - self.name(), - self.innerModel(), - etagState.ifMatchValueOnUpdate(self.innerModel().etag()), - etagState.ifNonMatchValueOnCreate())) + return Mono.just(this) + .flatMap(self -> self.manager() + .serviceClient() + .getZones() + .createOrUpdateWithResponseAsync(self.resourceGroupName(), self.name(), self.innerModel(), + etagState.ifMatchValueOnUpdate(self.innerModel().etag()), etagState.ifNonMatchValueOnCreate())) .map(Response::getValue) .map(innerToFluentMap(this)) - .map( - dnsZone -> { - this.etagState.clear(); - return dnsZone; - }); + .map(dnsZone -> { + this.etagState.clear(); + return dnsZone; + }); } @Override public Mono afterPostRunAsync(boolean isGroupFaulted) { - return Mono - .just(true) - .map( - ignored -> { - recordSets.clear(); - return ignored; - }) - .then(); + return Mono.just(true).map(ignored -> { + recordSets.clear(); + return ignored; + }).then(); } @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - dnsZone -> { - DnsZoneImpl impl = (DnsZoneImpl) dnsZone; - impl.initRecordSets(); - return impl; - }); + return super.refreshAsync().map(dnsZone -> { + DnsZoneImpl impl = (DnsZoneImpl) dnsZone; + impl.initRecordSets(); + return impl; + }); } @Override @@ -466,41 +452,46 @@ private void initRecordSets() { private PagedIterable listRecordSetsIntern(String recordSetSuffix, Integer pageSize) { final DnsZoneImpl self = this; - PagedFlux recordSets = - PagedConverter - .flatMapPage( - this - .manager() - .serviceClient() - .getRecordSets() - .listByDnsZoneAsync(this.resourceGroupName(), this.name(), pageSize, recordSetSuffix), - inner -> { - DnsRecordSet recordSet = new DnsRecordSetImpl(inner.name(), inner.type(), self, inner); - switch (recordSet.recordType()) { - case A: - return Mono.just(new ARecordSetImpl(inner.name(), self, inner)); - case AAAA: - return Mono.just(new AaaaRecordSetImpl(inner.name(), self, inner)); - case CAA: - return Mono.just(new CaaRecordSetImpl(inner.name(), self, inner)); - case CNAME: - return Mono.just(new CnameRecordSetImpl(inner.name(), self, inner)); - case MX: - return Mono.just(new MxRecordSetImpl(inner.name(), self, inner)); - case NS: - return Mono.just(new NsRecordSetImpl(inner.name(), self, inner)); - case PTR: - return Mono.just(new PtrRecordSetImpl(inner.name(), self, inner)); - case SOA: - return Mono.just(new SoaRecordSetImpl(inner.name(), self, inner)); - case SRV: - return Mono.just(new SrvRecordSetImpl(inner.name(), self, inner)); - case TXT: - return Mono.just(new TxtRecordSetImpl(inner.name(), self, inner)); - default: - return Mono.just(recordSet); - } - }); + PagedFlux recordSets = PagedConverter.flatMapPage(this.manager() + .serviceClient() + .getRecordSets() + .listByDnsZoneAsync(this.resourceGroupName(), this.name(), pageSize, recordSetSuffix), inner -> { + DnsRecordSet recordSet = new DnsRecordSetImpl(inner.name(), inner.type(), self, inner); + switch (recordSet.recordType()) { + case A: + return Mono.just(new ARecordSetImpl(inner.name(), self, inner)); + + case AAAA: + return Mono.just(new AaaaRecordSetImpl(inner.name(), self, inner)); + + case CAA: + return Mono.just(new CaaRecordSetImpl(inner.name(), self, inner)); + + case CNAME: + return Mono.just(new CnameRecordSetImpl(inner.name(), self, inner)); + + case MX: + return Mono.just(new MxRecordSetImpl(inner.name(), self, inner)); + + case NS: + return Mono.just(new NsRecordSetImpl(inner.name(), self, inner)); + + case PTR: + return Mono.just(new PtrRecordSetImpl(inner.name(), self, inner)); + + case SOA: + return Mono.just(new SoaRecordSetImpl(inner.name(), self, inner)); + + case SRV: + return Mono.just(new SrvRecordSetImpl(inner.name(), self, inner)); + + case TXT: + return Mono.just(new TxtRecordSetImpl(inner.name(), self, inner)); + + default: + return Mono.just(recordSet); + } + }); return new PagedIterable<>(recordSets); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZonesImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZonesImpl.java index 3f5895387cfb5..b4acf20ee614b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZonesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/DnsZonesImpl.java @@ -12,9 +12,8 @@ import reactor.core.publisher.Mono; /** Implementation of DnsZones. */ -public class DnsZonesImpl - extends TopLevelModifiableResourcesImpl - implements DnsZones { +public class DnsZonesImpl extends + TopLevelModifiableResourcesImpl implements DnsZones { public DnsZonesImpl(final DnsZoneManager dnsZoneManager) { super(dnsZoneManager.serviceClient().getZones(), dnsZoneManager); @@ -56,14 +55,14 @@ public Mono deleteByResourceGroupNameAsync(String resourceGroupName, Strin @Override public Mono deleteByIdAsync(String id) { - return deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); + return deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono deleteByIdAsync(String id, String eTagValue) { - return deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), eTagValue); + return deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id), eTagValue); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/MxRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/MxRecordSetsImpl.java index 186df6dba1911..8be0ed0b6c276 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/MxRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/MxRecordSetsImpl.java @@ -25,8 +25,7 @@ public MxRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,43 +35,30 @@ public Mono getByNameAsync(String name) { @Override public PagedIterable list() { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/NsRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/NsRecordSetsImpl.java index 82e937c720987..cb87b9955cbb8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/NsRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/NsRecordSetsImpl.java @@ -25,8 +25,7 @@ public NsRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/PtrRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/PtrRecordSetsImpl.java index 78486e74bf050..e8d94eb29ff72 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/PtrRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/PtrRecordSetsImpl.java @@ -25,8 +25,7 @@ public PtrRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/SrvRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/SrvRecordSetsImpl.java index 2d101d5997aa3..9c3d63357cf2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/SrvRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/SrvRecordSetsImpl.java @@ -25,8 +25,7 @@ public SrvRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - this.recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/TxtRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/TxtRecordSetsImpl.java index b599b8e4852d3..33ea61090d9c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/TxtRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/implementation/TxtRecordSetsImpl.java @@ -25,8 +25,7 @@ public TxtRecordSet getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getRecordSets() @@ -36,31 +35,21 @@ public Mono getByNameAsync(String name) { @Override protected PagedIterable listIntern(String recordSetNameSuffix, Integer pageSize) { - return super - .wrapList( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByType( - this.dnsZone.resourceGroupName(), - this.dnsZone.name(), - recordType, - pageSize, - recordSetNameSuffix, - Context.NONE)); + return super.wrapList(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByType(this.dnsZone.resourceGroupName(), this.dnsZone.name(), recordType, pageSize, + recordSetNameSuffix, Context.NONE)); } @Override protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - this - .parent() - .manager() - .serviceClient() - .getRecordSets() - .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), recordType)); + return wrapPageAsync(this.parent() + .manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(this.dnsZone.resourceGroupName(), this.dnsZone.name(), recordType)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSet.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSet.java index a25df7243aa20..fc6d14273f25f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSet.java @@ -35,35 +35,22 @@ public interface DnsRecordSet extends ExternalChildResource the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.ARecordSetBlank, - DefinitionStages.WithARecordIPv4Address, - DefinitionStages.WithARecordIPv4AddressOrAttachable, - DefinitionStages.AaaaRecordSetBlank, - DefinitionStages.WithAaaaRecordIPv6Address, - DefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, - DefinitionStages.CaaRecordSetBlank, - DefinitionStages.WithCaaRecordEntry, - DefinitionStages.WithCaaRecordEntryOrAttachable, - DefinitionStages.CNameRecordSetBlank, - DefinitionStages.WithCNameRecordAlias, - DefinitionStages.WithCNameRecordSetAttachable, - DefinitionStages.MXRecordSetBlank, - DefinitionStages.WithMXRecordMailExchange, - DefinitionStages.WithMXRecordMailExchangeOrAttachable, - DefinitionStages.NSRecordSetBlank, - DefinitionStages.WithNSRecordNameServer, - DefinitionStages.WithNSRecordNameServerOrAttachable, - DefinitionStages.PtrRecordSetBlank, - DefinitionStages.WithPtrRecordTargetDomainName, - DefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, - DefinitionStages.SrvRecordSetBlank, - DefinitionStages.WithSrvRecordEntry, - DefinitionStages.WithSrvRecordEntryOrAttachable, - DefinitionStages.TxtRecordSetBlank, - DefinitionStages.WithTxtRecordTextValue, - DefinitionStages.WithTxtRecordTextValueOrAttachable, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.ARecordSetBlank, + DefinitionStages.WithARecordIPv4Address, DefinitionStages.WithARecordIPv4AddressOrAttachable, + DefinitionStages.AaaaRecordSetBlank, DefinitionStages.WithAaaaRecordIPv6Address, + DefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, DefinitionStages.CaaRecordSetBlank, + DefinitionStages.WithCaaRecordEntry, DefinitionStages.WithCaaRecordEntryOrAttachable, + DefinitionStages.CNameRecordSetBlank, DefinitionStages.WithCNameRecordAlias, + DefinitionStages.WithCNameRecordSetAttachable, DefinitionStages.MXRecordSetBlank, + DefinitionStages.WithMXRecordMailExchange, + DefinitionStages.WithMXRecordMailExchangeOrAttachable, DefinitionStages.NSRecordSetBlank, + DefinitionStages.WithNSRecordNameServer, DefinitionStages.WithNSRecordNameServerOrAttachable, + DefinitionStages.PtrRecordSetBlank, DefinitionStages.WithPtrRecordTargetDomainName, + DefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, + DefinitionStages.SrvRecordSetBlank, DefinitionStages.WithSrvRecordEntry, + DefinitionStages.WithSrvRecordEntryOrAttachable, DefinitionStages.TxtRecordSetBlank, + DefinitionStages.WithTxtRecordTextValue, DefinitionStages.WithTxtRecordTextValueOrAttachable, + DefinitionStages.WithAttach { } /** Grouping of DNS zone record set definition stages as a part of parent DNS zone definition. */ @@ -423,11 +410,8 @@ interface WithETagCheck { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithTtl, - DefinitionStages.WithMetadata, - DefinitionStages.WithETagCheck { + interface WithAttach extends Attachable.InDefinition, DefinitionStages.WithTtl, + DefinitionStages.WithMetadata, DefinitionStages.WithETagCheck { } } @@ -437,34 +421,25 @@ interface WithAttach * @param the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.ARecordSetBlank, - UpdateDefinitionStages.WithARecordIPv4Address, - UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable, - UpdateDefinitionStages.AaaaRecordSetBlank, - UpdateDefinitionStages.WithAaaaRecordIPv6Address, - UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, - UpdateDefinitionStages.CaaRecordSetBlank, - UpdateDefinitionStages.WithCaaRecordEntry, - UpdateDefinitionStages.WithCaaRecordEntryOrAttachable, - UpdateDefinitionStages.CNameRecordSetBlank, - UpdateDefinitionStages.WithCNameRecordAlias, - UpdateDefinitionStages.WithCNameRecordSetAttachable, - UpdateDefinitionStages.MXRecordSetBlank, - UpdateDefinitionStages.WithMXRecordMailExchange, - UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable, - UpdateDefinitionStages.NSRecordSetBlank, - UpdateDefinitionStages.WithNSRecordNameServer, - UpdateDefinitionStages.WithNSRecordNameServerOrAttachable, - UpdateDefinitionStages.PtrRecordSetBlank, - UpdateDefinitionStages.WithPtrRecordTargetDomainName, - UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, - UpdateDefinitionStages.SrvRecordSetBlank, - UpdateDefinitionStages.WithSrvRecordEntry, - UpdateDefinitionStages.WithSrvRecordEntryOrAttachable, - UpdateDefinitionStages.TxtRecordSetBlank, - UpdateDefinitionStages.WithTxtRecordTextValue, - UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.ARecordSetBlank, UpdateDefinitionStages.WithARecordIPv4Address, + UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable, + UpdateDefinitionStages.AaaaRecordSetBlank, UpdateDefinitionStages.WithAaaaRecordIPv6Address, + UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, + UpdateDefinitionStages.CaaRecordSetBlank, UpdateDefinitionStages.WithCaaRecordEntry, + UpdateDefinitionStages.WithCaaRecordEntryOrAttachable, + UpdateDefinitionStages.CNameRecordSetBlank, UpdateDefinitionStages.WithCNameRecordAlias, + UpdateDefinitionStages.WithCNameRecordSetAttachable, UpdateDefinitionStages.MXRecordSetBlank, + UpdateDefinitionStages.WithMXRecordMailExchange, + UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable, + UpdateDefinitionStages.NSRecordSetBlank, UpdateDefinitionStages.WithNSRecordNameServer, + UpdateDefinitionStages.WithNSRecordNameServerOrAttachable, + UpdateDefinitionStages.PtrRecordSetBlank, + UpdateDefinitionStages.WithPtrRecordTargetDomainName, + UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, + UpdateDefinitionStages.SrvRecordSetBlank, UpdateDefinitionStages.WithSrvRecordEntry, + UpdateDefinitionStages.WithSrvRecordEntryOrAttachable, + UpdateDefinitionStages.TxtRecordSetBlank, UpdateDefinitionStages.WithTxtRecordTextValue, + UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable, UpdateDefinitionStages.WithAttach { } /** Grouping of DNS zone record set definition stages as a part of parent DNS zone update. */ @@ -823,27 +798,15 @@ interface WithETagCheck { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithTtl, - UpdateDefinitionStages.WithMetadata, - UpdateDefinitionStages.WithETagCheck { + interface WithAttach extends Attachable.InUpdate, UpdateDefinitionStages.WithTtl, + UpdateDefinitionStages.WithMetadata, UpdateDefinitionStages.WithETagCheck { } } /** The entirety of a record sets update as a part of parent DNS zone update. */ interface UpdateCombined - extends UpdateARecordSet, - UpdateAaaaRecordSet, - UpdateCaaRecordSet, - UpdateCNameRecordSet, - UpdateMXRecordSet, - UpdatePtrRecordSet, - UpdateNSRecordSet, - UpdateSrvRecordSet, - UpdateTxtRecordSet, - UpdateSoaRecord, - Update { + extends UpdateARecordSet, UpdateAaaaRecordSet, UpdateCaaRecordSet, UpdateCNameRecordSet, UpdateMXRecordSet, + UpdatePtrRecordSet, UpdateNSRecordSet, UpdateSrvRecordSet, UpdateTxtRecordSet, UpdateSoaRecord, Update { } /** The entirety of an A record set update as a part of parent DNS zone update. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSets.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSets.java index f3571fd4f7801..53ad8a9e5840a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSets.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsRecordSets.java @@ -25,6 +25,7 @@ public interface DnsRecordSets * @return list of record sets */ PagedIterable list(String recordSetNameSuffix); + /** * Lists all the record sets, with number of entries in each page limited to given size. * @@ -32,6 +33,7 @@ public interface DnsRecordSets * @return list of record sets */ PagedIterable list(int pageSize); + /** * Lists all the record sets with the given suffix, also limits the number of entries per page to the given page * size. @@ -41,6 +43,7 @@ public interface DnsRecordSets * @return the record sets */ PagedIterable list(String recordSetNameSuffix, int pageSize); + /** * Lists all the record sets with the given suffix. * @@ -48,6 +51,7 @@ public interface DnsRecordSets * @return an observable that emits record sets */ PagedFlux listAsync(String recordSetNameSuffix); + /** * Lists all the record sets, with number of entries in each page limited to given size. * @@ -55,6 +59,7 @@ public interface DnsRecordSets * @return an observable that emits record sets */ PagedFlux listAsync(int pageSize); + /** * Lists all the record sets with the given suffix, also limits the number of entries per page to the given page * size. diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZone.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZone.java index 07411579d818d..9631dd33b1d3f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZone.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZone.java @@ -208,11 +208,8 @@ interface WithETagCheck { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithRecordSet, - DefinitionStages.WithETagCheck, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, DefinitionStages.WithRecordSet, DefinitionStages.WithETagCheck, + Resource.DefinitionWithTags { } } @@ -558,10 +555,7 @@ interface WithETagCheck { * *

Call {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - UpdateStages.WithRecordSet, - UpdateStages.WithETagCheck, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithRecordSet, UpdateStages.WithETagCheck, + Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZones.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZones.java index 2b6627278b092..11815aec52281 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZones.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/main/java/com/azure/resourcemanager/dns/models/DnsZones.java @@ -18,17 +18,10 @@ /** Entry point to DNS zone management API in Azure. */ @Fluent -public interface DnsZones - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface DnsZones extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, + HasManager { /** * Asynchronously deletes the zone from Azure, identifying it by its name and its resource group. * diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsTestBase.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsTestBase.java index 3388cfcee81b1..d4f0d9137ecdc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsTestBase.java @@ -27,21 +27,10 @@ public class DnsTestBase extends ResourceManagerTestProxyTestBase { protected DnsZoneManager zoneManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsZoneRecordSetETagTests.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsZoneRecordSetETagTests.java index b9fa25ddd4e9e..222a203a3e1db 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsZoneRecordSetETagTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/DnsZoneRecordSetETagTests.java @@ -24,18 +24,15 @@ public void canCreateZoneWithDefaultETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - DnsZone dnsZone = - zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + DnsZone dnsZone + = zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); Assertions.assertNotNull(dnsZone.etag()); - Runnable runnable = - () -> - zoneManager - .zones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .withETagCheck() - .create(); + Runnable runnable = () -> zoneManager.zones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withETagCheck() + .create(); ensureETagExceptionIsThrown(runnable); } @@ -44,8 +41,8 @@ public void canUpdateZoneWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - final DnsZone dnsZone = - zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + final DnsZone dnsZone + = zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); Assertions.assertNotNull(dnsZone.etag()); Runnable runnable = () -> dnsZone.update().withETagCheck(dnsZone.etag() + "-foo").apply(); @@ -58,8 +55,8 @@ public void canDeleteZoneWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - final DnsZone dnsZone = - zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + final DnsZone dnsZone + = zoneManager.zones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); Assertions.assertNotNull(dnsZone.etag()); Runnable runnable = () -> zoneManager.zones().deleteById(dnsZone.id(), dnsZone.etag() + "-foo"); @@ -72,34 +69,32 @@ public void canCreateRecordSetsWithDefaultETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - DnsZone dnsZone = - zoneManager - .zones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .defineCaaRecordSet("caaName") - .withRecord(4, "sometag", "someValue") - .attach() - .defineCNameRecordSet("documents") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .defineCNameRecordSet("userguide") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .create(); + DnsZone dnsZone = zoneManager.zones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .defineCaaRecordSet("caaName") + .withRecord(4, "sometag", "someValue") + .attach() + .defineCNameRecordSet("documents") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .defineCNameRecordSet("userguide") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -131,8 +126,7 @@ public void canCreateRecordSetsWithDefaultETag() throws Exception { Exception compositeException = null; try { - zoneManager - .zones() + zoneManager.zones() .define(topLevelDomain) .withNewResourceGroup(rgName, region) .defineARecordSet("www") @@ -177,23 +171,21 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - DnsZone dnsZone = - zoneManager - .zones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .create(); + DnsZone dnsZone = zoneManager.zones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -213,8 +205,7 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { // Exception compositeException = null; try { - dnsZone - .update() + dnsZone.update() .updateARecordSet("www") .withETagCheck(aRecordSet.etag() + "-foo") .parent() @@ -237,8 +228,7 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { } } // Try update with correct etags - dnsZone - .update() + dnsZone.update() .updateARecordSet("www") .withIPv4Address("24.97.105.45") .withETagCheck(aRecordSet.etag()) @@ -267,23 +257,21 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - DnsZone dnsZone = - zoneManager - .zones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .create(); + DnsZone dnsZone = zoneManager.zones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -301,8 +289,7 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { // Exception compositeException = null; try { - dnsZone - .update() + dnsZone.update() .withoutARecordSet("www", aRecordSet.etag() + "-foo") .withoutAaaaRecordSet("www", aaaaRecordSet.etag() + "-foo") .apply(); @@ -321,8 +308,7 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { } } // Try delete with correct etags - dnsZone - .update() + dnsZone.update() .withoutARecordSet("www", aRecordSet.etag()) .withoutAaaaRecordSet("www", aaaaRecordSet.etag()) .apply(); @@ -358,9 +344,7 @@ private void ensureETagExceptionIsThrown(final Runnable runnable) { } Assertions.assertTrue(isManagementExceptionThrown, "Expected ManagementException is not thrown"); Assertions.assertTrue(isCloudErrorSet, "Expected CloudError property is not set in ManagementException"); - Assertions - .assertTrue( - isPreconditionFailedCodeSet, - "Expected PreconditionFailed code is not set indicating ETag concurrency check failure"); + Assertions.assertTrue(isPreconditionFailedCodeSet, + "Expected PreconditionFailed code is not set indicating ETag concurrency check failure"); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/RecordSetTests.java b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/RecordSetTests.java index 3b2fe4124f394..be6b1a1a08db0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/RecordSetTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-dns/src/test/java/com/azure/resourcemanager/dns/RecordSetTests.java @@ -18,16 +18,14 @@ public void canCRUDCname() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + rgName + ".com"; - DnsZone dnsZone = - zoneManager - .zones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineCNameRecordSet("www") - .withAlias("cname.contoso.com") - .withTimeToLive(7200) - .attach() - .create(); + DnsZone dnsZone = zoneManager.zones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineCNameRecordSet("www") + .withAlias("cname.contoso.com") + .withTimeToLive(7200) + .attach() + .create(); // Check CNAME records dnsZone.refresh(); @@ -39,13 +37,7 @@ public void canCRUDCname() { Assertions.assertEquals("cname.contoso.com", cnameRecordSet.canonicalName()); // Update alias and ttl: - dnsZone - .update() - .updateCNameRecordSet("www") - .withAlias("new.contoso.com") - .withTimeToLive(3600) - .parent() - .apply(); + dnsZone.update().updateCNameRecordSet("www").withAlias("new.contoso.com").withTimeToLive(3600).parent().apply(); // Check CNAME records dnsZone.refresh(); diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml index 6c0e3e4b935e5..fc045ebddb990 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml @@ -47,6 +47,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/EventHubsManager.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/EventHubsManager.java index 09d5554f96553..b9ec14ae120c0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/EventHubsManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/EventHubsManager.java @@ -92,6 +92,7 @@ public interface Configurable extends AzureConfigurable { */ EventHubsManager authenticate(TokenCredential credential, AzureProfile profile); } + /** * The implementation for Configurable interface. */ @@ -100,12 +101,10 @@ public EventHubsManager authenticate(TokenCredential credential, AzureProfile pr return EventHubsManager.authenticate(buildHttpPipeline(credential, profile), profile); } } + private EventHubsManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new EventHubManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new EventHubManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRuleBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRuleBaseImpl.java index 5242aa3ad41e4..db799dae47732 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRuleBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRuleBaseImpl.java @@ -24,8 +24,7 @@ * @param rule fluent model * @param implementation of rule fluent model */ -abstract class AuthorizationRuleBaseImpl, - RuleImpl extends IndexableRefreshableWrapperImpl> +abstract class AuthorizationRuleBaseImpl, RuleImpl extends IndexableRefreshableWrapperImpl> extends NestedResourceImpl implements AuthorizationRule { protected AuthorizationRuleBaseImpl(String name, AuthorizationRuleInner inner, EventHubsManager manager) { @@ -34,8 +33,7 @@ protected AuthorizationRuleBaseImpl(String name, AuthorizationRuleInner inner, E @Override public Mono getKeysAsync() { - return this.getKeysInnerAsync() - .map(EventHubAuthorizationKeyImpl::new); + return this.getKeysInnerAsync().map(EventHubAuthorizationKeyImpl::new); } @Override @@ -45,8 +43,7 @@ public EventHubAuthorizationKey getKeys() { @Override public Mono regenerateKeyAsync(KeyType keyType) { - return this.regenerateKeysInnerAsync(keyType) - .map(EventHubAuthorizationKeyImpl::new); + return this.regenerateKeysInnerAsync(keyType).map(EventHubAuthorizationKeyImpl::new); } @Override @@ -62,7 +59,6 @@ public List rights() { return Collections.unmodifiableList(this.innerModel().rights()); } - @SuppressWarnings("unchecked") public RuleImpl withListenAccess() { if (this.innerModel().rights() == null) { @@ -103,7 +99,10 @@ public RuleImpl withManageAccess() { } protected abstract Mono getKeysInnerAsync(); + protected abstract Mono regenerateKeysInnerAsync(KeyType keyType); + protected abstract Mono getInnerAsync(); + public abstract Mono createResourceAsync(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRulesBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRulesBaseImpl.java index b1f59436df66c..6c6dc3a5cc590 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRulesBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/AuthorizationRulesBaseImpl.java @@ -11,11 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.model.implementation.WrapperImpl; import reactor.core.publisher.Mono; -abstract class AuthorizationRulesBaseImpl - extends WrapperImpl - implements HasManager, - SupportsGettingById, - SupportsDeletingById { +abstract class AuthorizationRulesBaseImpl extends WrapperImpl + implements HasManager, SupportsGettingById, SupportsDeletingById { protected final EventHubsManager manager; @@ -40,5 +37,6 @@ public void deleteById(String id) { } protected abstract RuleImpl wrapModel(AuthorizationRuleInner innerModel); + public abstract Mono getByIdAsync(String id); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationKeyImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationKeyImpl.java index 1fe0d206e8bae..36f6c46b1a157 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationKeyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationKeyImpl.java @@ -10,9 +10,8 @@ /** * Implementation for {@link DisasterRecoveryPairingAuthorizationKey}. */ -class DisasterRecoveryPairingAuthorizationKeyImpl - extends WrapperImpl - implements DisasterRecoveryPairingAuthorizationKey { +class DisasterRecoveryPairingAuthorizationKeyImpl extends WrapperImpl + implements DisasterRecoveryPairingAuthorizationKey { DisasterRecoveryPairingAuthorizationKeyImpl(AccessKeysInner inner) { super(inner); diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRuleImpl.java index 8cf423f75f691..8f8da83711aef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRuleImpl.java @@ -17,9 +17,8 @@ /** * Implementation for {@link DisasterRecoveryPairingAuthorizationRule}. */ -class DisasterRecoveryPairingAuthorizationRuleImpl - extends WrapperImpl - implements DisasterRecoveryPairingAuthorizationRule { +class DisasterRecoveryPairingAuthorizationRuleImpl extends WrapperImpl + implements DisasterRecoveryPairingAuthorizationRule { private final EventHubsManager manager; private final Ancestors.TwoAncestor ancestor; @@ -27,7 +26,7 @@ class DisasterRecoveryPairingAuthorizationRuleImpl protected DisasterRecoveryPairingAuthorizationRuleImpl(AuthorizationRuleInner inner, EventHubsManager manager) { super(inner); this.manager = manager; - this.ancestor = new Ancestors().new TwoAncestor(inner.id()); + this.ancestor = new Ancestors().new TwoAncestor(inner.id()); } @Override @@ -42,11 +41,10 @@ public List rights() { @Override public Mono getKeysAsync() { - return this.manager.serviceClient().getDisasterRecoveryConfigs() - .listKeysAsync(this.ancestor().resourceGroupName(), - this.ancestor.ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name()) + return this.manager.serviceClient() + .getDisasterRecoveryConfigs() + .listKeysAsync(this.ancestor().resourceGroupName(), this.ancestor.ancestor2Name(), + this.ancestor().ancestor1Name(), this.name()) .map(DisasterRecoveryPairingAuthorizationKeyImpl::new); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRulesImpl.java index 320032e5a269d..dcefd9ca13206 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/DisasterRecoveryPairingAuthorizationRulesImpl.java @@ -18,10 +18,8 @@ /** * Implementation for {@link DisasterRecoveryPairingAuthorizationRules}. */ -public final class DisasterRecoveryPairingAuthorizationRulesImpl - extends ReadableWrappersImpl +public final class DisasterRecoveryPairingAuthorizationRulesImpl extends + ReadableWrappersImpl implements DisasterRecoveryPairingAuthorizationRules { private final EventHubsManager manager; @@ -31,34 +29,31 @@ public DisasterRecoveryPairingAuthorizationRulesImpl(EventHubsManager manager) { } @Override - public PagedIterable listByDisasterRecoveryPairing( - String resourceGroupName, String namespaceName, String pairingName) { - return PagedConverter.mapPage(inner() - .listAuthorizationRules(resourceGroupName, namespaceName, pairingName), + public PagedIterable + listByDisasterRecoveryPairing(String resourceGroupName, String namespaceName, String pairingName) { + return PagedConverter.mapPage(inner().listAuthorizationRules(resourceGroupName, namespaceName, pairingName), this::wrapModel); } @Override - public PagedFlux listByDisasterRecoveryPairingAsync( - String resourceGroupName, String namespaceName, String pairingName) { - return PagedConverter.mapPage(inner() - .listAuthorizationRulesAsync(resourceGroupName, namespaceName, pairingName), - this::wrapModel); + public PagedFlux + listByDisasterRecoveryPairingAsync(String resourceGroupName, String namespaceName, String pairingName) { + return PagedConverter.mapPage( + inner().listAuthorizationRulesAsync(resourceGroupName, namespaceName, pairingName), this::wrapModel); } @Override - public Mono getByNameAsync( - String resourceGroupName, String namespaceName, String pairingName, String name) { - return this.manager.serviceClient().getDisasterRecoveryConfigs().getAuthorizationRuleAsync(resourceGroupName, - namespaceName, - pairingName, - name) + public Mono getByNameAsync(String resourceGroupName, String namespaceName, + String pairingName, String name) { + return this.manager.serviceClient() + .getDisasterRecoveryConfigs() + .getAuthorizationRuleAsync(resourceGroupName, namespaceName, pairingName, name) .map(this::wrapModel); } @Override - public DisasterRecoveryPairingAuthorizationRule getByName( - String resourceGroupName, String namespaceName, String pairingName, String name) { + public DisasterRecoveryPairingAuthorizationRule getByName(String resourceGroupName, String namespaceName, + String pairingName, String name) { return getByNameAsync(resourceGroupName, namespaceName, pairingName, name).block(); } @@ -70,10 +65,8 @@ public DisasterRecoveryPairingAuthorizationRule getById(String id) { @Override public Mono getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); - return this.getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.parent().parent().name(), - resourceId.name()); + return this.getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), + resourceId.parent().parent().name(), resourceId.name()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationKeyImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationKeyImpl.java index 3368f1f6785ea..59007af919c05 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationKeyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationKeyImpl.java @@ -10,9 +10,7 @@ /** * Implementation for AuthorizationKeys. */ -class EventHubAuthorizationKeyImpl - extends WrapperImpl - implements EventHubAuthorizationKey { +class EventHubAuthorizationKeyImpl extends WrapperImpl implements EventHubAuthorizationKey { EventHubAuthorizationKeyImpl(AccessKeysInner inner) { super(inner); diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRuleImpl.java index 97cd186824e8e..d74a42fd5b618 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRuleImpl.java @@ -17,18 +17,15 @@ /** * Implementation for {@link EventHubAuthorizationRule}. */ -class EventHubAuthorizationRuleImpl extends AuthorizationRuleBaseImpl - implements - EventHubAuthorizationRule, - EventHubAuthorizationRule.Definition, - EventHubAuthorizationRule.Update { +class EventHubAuthorizationRuleImpl + extends AuthorizationRuleBaseImpl + implements EventHubAuthorizationRule, EventHubAuthorizationRule.Definition, EventHubAuthorizationRule.Update { private Ancestors.TwoAncestor ancestor; EventHubAuthorizationRuleImpl(String name, AuthorizationRuleInner inner, EventHubsManager manager) { super(name, inner, manager); - this.ancestor = new Ancestors().new TwoAncestor(inner.id()); + this.ancestor = new Ancestors().new TwoAncestor(inner.id()); } EventHubAuthorizationRuleImpl(String name, EventHubsManager manager) { @@ -57,8 +54,8 @@ public EventHubAuthorizationRuleImpl withExistingEventHubId(String eventHubResou } @Override - public EventHubAuthorizationRuleImpl withExistingEventHub( - String resourceGroupName, String namespaceName, String eventHubName) { + public EventHubAuthorizationRuleImpl withExistingEventHub(String resourceGroupName, String namespaceName, + String eventHubName) { this.ancestor = new Ancestors().new TwoAncestor(resourceGroupName, eventHubName, namespaceName); return this; } @@ -71,43 +68,37 @@ public EventHubAuthorizationRuleImpl withExistingEventHub(EventHub eventHub) { @Override protected Mono getInnerAsync() { - return this.manager.serviceClient().getEventHubs() - .getAuthorizationRuleAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getEventHubs() + .getAuthorizationRuleAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name()); } @Override public Mono createResourceAsync() { - return this.manager.serviceClient().getEventHubs() - .createOrUpdateAuthorizationRuleAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name(), - new AuthorizationRuleInner().withRights(this.innerModel().rights())) - .map(innerToFluentMap(this)); + return this.manager.serviceClient() + .getEventHubs() + .createOrUpdateAuthorizationRuleAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name(), + new AuthorizationRuleInner().withRights(this.innerModel().rights())) + .map(innerToFluentMap(this)); } @Override protected Mono getKeysInnerAsync() { - return this.manager.serviceClient().getEventHubs() - .listKeysAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getEventHubs() + .listKeysAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name()); } @Override protected Mono regenerateKeysInnerAsync(KeyType keyType) { - final RegenerateAccessKeyParameters regenKeyInner = new RegenerateAccessKeyParameters() - .withKeyType(keyType); - return this.manager.serviceClient().getEventHubs() - .regenerateKeysAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name(), - regenKeyInner); + final RegenerateAccessKeyParameters regenKeyInner = new RegenerateAccessKeyParameters().withKeyType(keyType); + return this.manager.serviceClient() + .getEventHubs() + .regenerateKeysAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name(), regenKeyInner); } private Ancestors.TwoAncestor ancestor() { diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRulesImpl.java index 919cf2de61aec..0f7542c917f13 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubAuthorizationRulesImpl.java @@ -20,9 +20,7 @@ * Implementation for {@link EventHubAuthorizationRules}. */ public final class EventHubAuthorizationRulesImpl - extends AuthorizationRulesBaseImpl + extends AuthorizationRulesBaseImpl implements EventHubAuthorizationRules { public EventHubAuthorizationRulesImpl(EventHubsManager manager) { @@ -39,38 +37,36 @@ public Mono getByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } @Override - public EventHubAuthorizationRule getByName( - String resourceGroupName, String namespaceName, String eventHubName, String name) { + public EventHubAuthorizationRule getByName(String resourceGroupName, String namespaceName, String eventHubName, + String name) { return getByNameAsync(resourceGroupName, namespaceName, eventHubName, name).block(); } @Override - public Mono getByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name) { - return this.innerModel().getAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, name) + public Mono getByNameAsync(String resourceGroupName, String namespaceName, + String eventHubName, String name) { + return this.innerModel() + .getAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, name) .map(this::wrapModel); } @Override - public PagedIterable listByEventHub( - final String resourceGroupName, final String namespaceName, final String eventHubName) { - return PagedConverter.mapPage(innerModel() - .listAuthorizationRules(resourceGroupName, namespaceName, eventHubName), - this::wrapModel); + public PagedIterable listByEventHub(final String resourceGroupName, + final String namespaceName, final String eventHubName) { + return PagedConverter.mapPage( + innerModel().listAuthorizationRules(resourceGroupName, namespaceName, eventHubName), this::wrapModel); } @Override - public PagedFlux listByEventHubAsync( - String resourceGroupName, String namespaceName, final String eventHubName) { - return PagedConverter.mapPage(this.innerModel() - .listAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName), + public PagedFlux listByEventHubAsync(String resourceGroupName, String namespaceName, + final String eventHubName) { + return PagedConverter.mapPage( + this.innerModel().listAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName), this::wrapModel); } @@ -78,10 +74,8 @@ public PagedFlux listByEventHubAsync( public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return deleteByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return deleteByNameAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } @Override @@ -90,12 +84,9 @@ public void deleteByName(String resourceGroupName, String namespaceName, String } @Override - public Mono deleteByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name) { - return this.innerModel().deleteAuthorizationRuleAsync(resourceGroupName, - namespaceName, - eventHubName, - name); + public Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, + String name) { + return this.innerModel().deleteAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, name); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupImpl.java index 36470ffadfe71..a5b7c154f9adf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupImpl.java @@ -16,18 +16,14 @@ * Implementation for {@link EventHubConsumerGroup}. */ class EventHubConsumerGroupImpl - extends NestedResourceImpl - implements EventHubConsumerGroup, - EventHubConsumerGroup.Definition, - EventHubConsumerGroup.Update { + extends NestedResourceImpl + implements EventHubConsumerGroup, EventHubConsumerGroup.Definition, EventHubConsumerGroup.Update { private Ancestors.TwoAncestor ancestor; EventHubConsumerGroupImpl(String name, ConsumerGroupInner inner, EventHubsManager manager) { super(name, inner, manager); - this.ancestor = new Ancestors().new TwoAncestor(inner.id()); + this.ancestor = new Ancestors().new TwoAncestor(inner.id()); } EventHubConsumerGroupImpl(String name, EventHubsManager manager) { @@ -77,8 +73,8 @@ public EventHubConsumerGroupImpl withExistingEventHubId(String eventHubId) { } @Override - public EventHubConsumerGroupImpl withExistingEventHub( - String resourceGroupName, String namespaceName, String eventHubName) { + public EventHubConsumerGroupImpl withExistingEventHub(String resourceGroupName, String namespaceName, + String eventHubName) { this.ancestor = new Ancestors().new TwoAncestor(resourceGroupName, eventHubName, namespaceName); return this; } @@ -91,22 +87,20 @@ public EventHubConsumerGroupImpl withUserMetadata(String metadata) { @Override public Mono createResourceAsync() { - return this.manager.serviceClient().getConsumerGroups() - .createOrUpdateAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name(), - new ConsumerGroupInner().withUserMetadata(innerModel().userMetadata())) - .map(innerToFluentMap(this)); + return this.manager.serviceClient() + .getConsumerGroups() + .createOrUpdateAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name(), + new ConsumerGroupInner().withUserMetadata(innerModel().userMetadata())) + .map(innerToFluentMap(this)); } @Override protected Mono getInnerAsync() { - return this.manager.serviceClient().getConsumerGroups() - .getAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor2Name(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getConsumerGroups() + .getAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor2Name(), + this.ancestor().ancestor1Name(), this.name()); } private Ancestors.TwoAncestor ancestor() { diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupsImpl.java index 84cead3b06281..2ea59638c4e44 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubConsumerGroupsImpl.java @@ -20,8 +20,7 @@ /** * Implementation for {@link EventHubConsumerGroups}. */ -public final class EventHubConsumerGroupsImpl - extends WrapperImpl +public final class EventHubConsumerGroupsImpl extends WrapperImpl implements EventHubConsumerGroups { private final EventHubsManager manager; @@ -50,37 +49,33 @@ public Mono getByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } @Override - public Mono getByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name) { + public Mono getByNameAsync(String resourceGroupName, String namespaceName, + String eventHubName, String name) { return this.innerModel().getAsync(resourceGroupName, namespaceName, eventHubName, name).map(this::wrapModel); } @Override - public EventHubConsumerGroup getByName( - String resourceGroupName, String namespaceName, String eventHubName, String name) { + public EventHubConsumerGroup getByName(String resourceGroupName, String namespaceName, String eventHubName, + String name) { return getByNameAsync(resourceGroupName, namespaceName, eventHubName, name).block(); } @Override - public PagedIterable listByEventHub( - String resourceGroupName, String namespaceName, String eventHubName) { - return PagedConverter.mapPage(innerModel() - .listByEventHub(resourceGroupName, namespaceName, eventHubName), + public PagedIterable listByEventHub(String resourceGroupName, String namespaceName, + String eventHubName) { + return PagedConverter.mapPage(innerModel().listByEventHub(resourceGroupName, namespaceName, eventHubName), this::wrapModel); } @Override - public PagedFlux listByEventHubAsync( - String resourceGroupName, String namespaceName, String eventHubName) { - return PagedConverter.mapPage(innerModel() - .listByEventHubAsync(resourceGroupName, namespaceName, eventHubName), + public PagedFlux listByEventHubAsync(String resourceGroupName, String namespaceName, + String eventHubName) { + return PagedConverter.mapPage(innerModel().listByEventHubAsync(resourceGroupName, namespaceName, eventHubName), this::wrapModel); } @@ -94,19 +89,14 @@ public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return deleteByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return deleteByNameAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } @Override - public Mono deleteByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name) { - return this.innerModel().deleteAsync(resourceGroupName, - namespaceName, - eventHubName, - name); + public Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, + String name) { + return this.innerModel().deleteAsync(resourceGroupName, namespaceName, eventHubName, name); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingImpl.java index 8f3b9e6a1282e..05e4a127d14d7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingImpl.java @@ -22,13 +22,10 @@ /** * Implementation for {@link EventHubDisasterRecoveryPairing}. */ -class EventHubDisasterRecoveryPairingImpl - extends NestedResourceImpl - implements EventHubDisasterRecoveryPairing, - EventHubDisasterRecoveryPairing.Definition, - EventHubDisasterRecoveryPairing.Update { +class EventHubDisasterRecoveryPairingImpl extends + NestedResourceImpl + implements EventHubDisasterRecoveryPairing, EventHubDisasterRecoveryPairing.Definition, + EventHubDisasterRecoveryPairing.Update { private Ancestors.OneAncestor ancestor; private final ClientLogger logger = new ClientLogger(EventHubDisasterRecoveryPairingImpl.class); @@ -68,8 +65,8 @@ public ProvisioningStateDR provisioningState() { } @Override - public EventHubDisasterRecoveryPairingImpl withNewPrimaryNamespace( - Creatable namespaceCreatable) { + public EventHubDisasterRecoveryPairingImpl + withNewPrimaryNamespace(Creatable namespaceCreatable) { this.addDependency(namespaceCreatable); if (namespaceCreatable instanceof EventHubNamespaceImpl) { EventHubNamespaceImpl namespace = ((EventHubNamespaceImpl) namespaceCreatable); @@ -87,8 +84,8 @@ public EventHubDisasterRecoveryPairingImpl withExistingPrimaryNamespace(EventHub } @Override - public EventHubDisasterRecoveryPairingImpl withExistingPrimaryNamespace( - String resourceGroupName, String primaryNamespaceName) { + public EventHubDisasterRecoveryPairingImpl withExistingPrimaryNamespace(String resourceGroupName, + String primaryNamespaceName) { this.ancestor = new Ancestors().new OneAncestor(resourceGroupName, primaryNamespaceName); return this; } @@ -100,8 +97,8 @@ public EventHubDisasterRecoveryPairingImpl withExistingPrimaryNamespaceId(String } @Override - public EventHubDisasterRecoveryPairingImpl withNewSecondaryNamespace( - Creatable namespaceCreatable) { + public EventHubDisasterRecoveryPairingImpl + withNewSecondaryNamespace(Creatable namespaceCreatable) { this.addDependency(namespaceCreatable); if (namespaceCreatable instanceof EventHubNamespaceImpl) { EventHubNamespaceImpl namespace = ((EventHubNamespaceImpl) namespaceCreatable); @@ -128,21 +125,21 @@ public EventHubDisasterRecoveryPairingImpl withExistingSecondaryNamespaceId(Stri @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getDisasterRecoveryConfigs() - .createOrUpdateAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name(), + return this.manager() + .serviceClient() + .getDisasterRecoveryConfigs() + .createOrUpdateAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name(), this.innerModel()) - .map(innerToFluentMap(this)); + .map(innerToFluentMap(this)); } @Override public Mono breakPairingAsync() { - return this.manager().serviceClient().getDisasterRecoveryConfigs() - .breakPairingAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name()) - .then(refreshAsync()) + return this.manager() + .serviceClient() + .getDisasterRecoveryConfigs() + .breakPairingAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()) + .then(refreshAsync()) .then(); } @@ -156,7 +153,9 @@ public Mono failOverAsync() { // Fail over is run against secondary namespace (because primary might be down at time of failover) // ResourceId secondaryNs = ResourceId.fromString(this.innerModel().partnerNamespace()); - return this.manager().serviceClient().getDisasterRecoveryConfigs() + return this.manager() + .serviceClient() + .getDisasterRecoveryConfigs() .failOverAsync(secondaryNs.resourceGroupName(), secondaryNs.name(), this.name()) .then(refreshAsync()) .then(); @@ -169,25 +168,26 @@ public void failOver() { @Override public PagedFlux listAuthorizationRulesAsync() { - return this.manager().disasterRecoveryPairingAuthorizationRules() - .listByDisasterRecoveryPairingAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), + return this.manager() + .disasterRecoveryPairingAuthorizationRules() + .listByDisasterRecoveryPairingAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()); } @Override public PagedIterable listAuthorizationRules() { - return this.manager().disasterRecoveryPairingAuthorizationRules() - .listByDisasterRecoveryPairing(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), + return this.manager() + .disasterRecoveryPairingAuthorizationRules() + .listByDisasterRecoveryPairing(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()); } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getDisasterRecoveryConfigs().getAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager() + .serviceClient() + .getDisasterRecoveryConfigs() + .getAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()); } private Ancestors.OneAncestor ancestor() { diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingsImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingsImpl.java index 112bda8f129ac..e99159b5a6185 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubDisasterRecoveryPairingsImpl.java @@ -21,8 +21,7 @@ /** * Implementation for {@link EventHubDisasterRecoveryPairings}. */ -public final class EventHubDisasterRecoveryPairingsImpl - extends WrapperImpl +public final class EventHubDisasterRecoveryPairingsImpl extends WrapperImpl implements EventHubDisasterRecoveryPairings { private EventHubsManager manager; @@ -55,39 +54,30 @@ public EventHubDisasterRecoveryPairing getById(String id) { public Mono getByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override - public Mono getByNameAsync( - String resourceGroupName, String namespaceName, String name) { - return this.innerModel().getAsync(resourceGroupName, - namespaceName, - name) - .map(this::wrapModel); + public Mono getByNameAsync(String resourceGroupName, String namespaceName, + String name) { + return this.innerModel().getAsync(resourceGroupName, namespaceName, name).map(this::wrapModel); } @Override - public EventHubDisasterRecoveryPairing getByName( - String resourceGroupName, String namespaceName, String name) { + public EventHubDisasterRecoveryPairing getByName(String resourceGroupName, String namespaceName, String name) { return getByNameAsync(resourceGroupName, namespaceName, name).block(); } @Override - public PagedIterable listByNamespace( - String resourceGroupName, String namespaceName) { - return PagedConverter.mapPage(innerModel() - .list(resourceGroupName, namespaceName), - this::wrapModel); + public PagedIterable listByNamespace(String resourceGroupName, + String namespaceName) { + return PagedConverter.mapPage(innerModel().list(resourceGroupName, namespaceName), this::wrapModel); } @Override - public PagedFlux listByNamespaceAsync( - String resourceGroupName, String namespaceName) { - return PagedConverter.mapPage(this.innerModel().listAsync(resourceGroupName, namespaceName), - this::wrapModel); + public PagedFlux listByNamespaceAsync(String resourceGroupName, + String namespaceName) { + return PagedConverter.mapPage(this.innerModel().listAsync(resourceGroupName, namespaceName), this::wrapModel); } @Override @@ -99,16 +89,12 @@ public void deleteById(String id) { public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return deleteByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return deleteByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String name) { - return this.innerModel().deleteAsync(resourceGroupName, - namespaceName, - name); + return this.innerModel().deleteAsync(resourceGroupName, namespaceName, name); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubImpl.java index 2dccf5f77e73b..751905da8bbeb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubImpl.java @@ -34,8 +34,7 @@ /** * Implementation for {@link EventHub}. */ -class EventHubImpl - extends NestedResourceImpl +class EventHubImpl extends NestedResourceImpl implements EventHub, EventHub.Definition, EventHub.Update { private Ancestors.OneAncestor ancestor; @@ -170,22 +169,20 @@ public EventHubImpl withExistingNamespaceId(String namespaceId) { } @Override - public EventHubImpl withNewStorageAccountForCapturedData( - Creatable storageAccountCreatable, String containerName) { + public EventHubImpl withNewStorageAccountForCapturedData(Creatable storageAccountCreatable, + String containerName) { this.captureSettings.withNewStorageAccountForCapturedData(storageAccountCreatable, containerName); return this; } @Override - public EventHubImpl withExistingStorageAccountForCapturedData( - StorageAccount storageAccount, String containerName) { + public EventHubImpl withExistingStorageAccountForCapturedData(StorageAccount storageAccount, String containerName) { this.captureSettings.withExistingStorageAccountForCapturedData(storageAccount, containerName); return this; } @Override - public EventHubImpl withExistingStorageAccountForCapturedData( - String storageAccountId, String containerName) { + public EventHubImpl withExistingStorageAccountForCapturedData(String storageAccountId, String containerName) { this.captureSettings.withExistingStorageAccountForCapturedData(storageAccountId, containerName); return this; } @@ -335,10 +332,10 @@ public void beforeGroupCreateOrUpdate() { @Override public Mono createResourceAsync() { - return this.manager.serviceClient().getEventHubs() - .createOrUpdateAsync( - ancestor().resourceGroupName(), ancestor().ancestor1Name(), name(), this.innerModel()) - .map(innerToFluentMap(this)); + return this.manager.serviceClient() + .getEventHubs() + .createOrUpdateAsync(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name(), this.innerModel()) + .map(innerToFluentMap(this)); } @Override @@ -349,33 +346,33 @@ public Mono afterPostRunAsync(boolean isGroupFaulted) { @Override protected Mono getInnerAsync() { - return this.manager.serviceClient().getEventHubs().getAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getEventHubs() + .getAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()); } @Override public PagedFlux listConsumerGroupsAsync() { return this.manager.consumerGroups() - .listByEventHubAsync(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); + .listByEventHubAsync(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); } @Override public PagedFlux listAuthorizationRulesAsync() { return this.manager.eventHubAuthorizationRules() - .listByEventHubAsync(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); + .listByEventHubAsync(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); } @Override public PagedIterable listConsumerGroups() { return this.manager.consumerGroups() - .listByEventHub(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); + .listByEventHub(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); } @Override public PagedIterable listAuthorizationRules() { return this.manager.eventHubAuthorizationRules() - .listByEventHub(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); + .listByEventHub(ancestor().resourceGroupName(), ancestor().ancestor1Name(), name()); } private Ancestors.OneAncestor ancestor() { @@ -409,18 +406,16 @@ public CaptureSettings withNewStorageAccountForCapturedData( // // Schedule task to create storage account and container. // - addDependency(context -> creatableStorageAccount - .createAsync() - .flatMap(indexable -> { - StorageAccount storageAccount = indexable; - ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); - return createContainerIfNotExistsAsync(storageAccount, containerName); - })); + addDependency(context -> creatableStorageAccount.createAsync().flatMap(indexable -> { + StorageAccount storageAccount = indexable; + ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); + return createContainerIfNotExistsAsync(storageAccount, containerName); + })); return this; } - public CaptureSettings withExistingStorageAccountForCapturedData( - final StorageAccount storageAccount, final String containerName) { + public CaptureSettings withExistingStorageAccountForCapturedData(final StorageAccount storageAccount, + final String containerName) { this.ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); this.ensureSettings().destination().withBlobContainer(containerName); // @@ -430,16 +425,15 @@ public CaptureSettings withExistingStorageAccountForCapturedData( return this; } - public CaptureSettings withExistingStorageAccountForCapturedData( - final String storageAccountId, final String containerName) { + public CaptureSettings withExistingStorageAccountForCapturedData(final String storageAccountId, + final String containerName) { this.ensureSettings().destination().withStorageAccountResourceId(storageAccountId); this.ensureSettings().destination().withBlobContainer(containerName); // // Schedule task to create container if not exists. // - addDependency(context -> storageManager.storageAccounts() - .getByIdAsync(storageAccountId) - .flatMap(storageAccount -> { + addDependency( + context -> storageManager.storageAccounts().getByIdAsync(storageAccountId).flatMap(storageAccount -> { ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); return createContainerIfNotExistsAsync(storageAccount, containerName); })); @@ -480,10 +474,10 @@ public CaptureDescription validateAndGetSettings() { if (this.newSettings == null) { return this.currentSettings; } else if (this.newSettings.destination() == null - || this.newSettings.destination().storageAccountResourceId() == null - || this.newSettings.destination().blobContainer() == null) { - throw logger.logExceptionAsError(new IllegalStateException( - "Setting any of the capture properties requires " + || this.newSettings.destination().storageAccountResourceId() == null + || this.newSettings.destination().blobContainer() == null) { + throw logger + .logExceptionAsError(new IllegalStateException("Setting any of the capture properties requires " + "capture destination [StorageAccount, DataLake] to be specified")); } if (this.newSettings.destination().name() == null) { @@ -510,7 +504,7 @@ private CaptureDescription ensureSettings() { } private Mono createContainerIfNotExistsAsync(final StorageAccount storageAccount, - final String containerName) { + final String containerName) { return storageManager.blobContainers() .getAsync(storageAccount.resourceGroupName(), storageAccount.name(), containerName) .cast(Indexable.class) @@ -534,8 +528,8 @@ private CaptureDescription cloneCurrentSettings() { clone.destination().withArchiveNameFormat(this.currentSettings.destination().archiveNameFormat()); clone.destination().withBlobContainer(this.currentSettings.destination().blobContainer()); clone.destination().withName(this.currentSettings.destination().name()); - clone.destination().withStorageAccountResourceId( - this.currentSettings.destination().storageAccountResourceId()); + clone.destination() + .withStorageAccountResourceId(this.currentSettings.destination().storageAccountResourceId()); } else { clone.withDestination(new Destination()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRuleImpl.java index 584b932b4f3a2..0c12d5d9051ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRuleImpl.java @@ -17,12 +17,10 @@ /** * Implementation for {@link EventHubNamespaceAuthorizationRule}. */ -class EventHubNamespaceAuthorizationRuleImpl extends AuthorizationRuleBaseImpl - implements - EventHubNamespaceAuthorizationRule, - EventHubNamespaceAuthorizationRule.Definition, - EventHubNamespaceAuthorizationRule.Update { +class EventHubNamespaceAuthorizationRuleImpl + extends AuthorizationRuleBaseImpl + implements EventHubNamespaceAuthorizationRule, EventHubNamespaceAuthorizationRule.Definition, + EventHubNamespaceAuthorizationRule.Update { private Ancestors.OneAncestor ancestor; @@ -52,8 +50,8 @@ public EventHubNamespaceAuthorizationRuleImpl withExistingNamespaceId(String nam } @Override - public EventHubNamespaceAuthorizationRuleImpl withExistingNamespace( - String resourceGroupName, String namespaceName) { + public EventHubNamespaceAuthorizationRuleImpl withExistingNamespace(String resourceGroupName, + String namespaceName) { this.ancestor = new Ancestors().new OneAncestor(resourceGroupName, namespaceName); return this; } @@ -66,39 +64,35 @@ public EventHubNamespaceAuthorizationRuleImpl withExistingNamespace(EventHubName @Override protected Mono getInnerAsync() { - return this.manager.serviceClient().getNamespaces() - .getAuthorizationRuleAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getNamespaces() + .getAuthorizationRuleAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), + this.name()); } @Override public Mono createResourceAsync() { - return this.manager.serviceClient().getNamespaces() - .createOrUpdateAuthorizationRuleAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name(), - new AuthorizationRuleInner().withRights(this.innerModel().rights())) - .map(innerToFluentMap(this)); + return this.manager.serviceClient() + .getNamespaces() + .createOrUpdateAuthorizationRuleAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), + this.name(), new AuthorizationRuleInner().withRights(this.innerModel().rights())) + .map(innerToFluentMap(this)); } @Override protected Mono getKeysInnerAsync() { - return this.manager.serviceClient().getNamespaces() - .listKeysAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name()); + return this.manager.serviceClient() + .getNamespaces() + .listKeysAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name()); } @Override protected Mono regenerateKeysInnerAsync(KeyType keyType) { - final RegenerateAccessKeyParameters regenKeyInner = new RegenerateAccessKeyParameters() - .withKeyType(keyType); - return this.manager.serviceClient().getNamespaces() - .regenerateKeysAsync(this.ancestor().resourceGroupName(), - this.ancestor().ancestor1Name(), - this.name(), - regenKeyInner); + final RegenerateAccessKeyParameters regenKeyInner = new RegenerateAccessKeyParameters().withKeyType(keyType); + return this.manager.serviceClient() + .getNamespaces() + .regenerateKeysAsync(this.ancestor().resourceGroupName(), this.ancestor().ancestor1Name(), this.name(), + regenKeyInner); } private Ancestors.OneAncestor ancestor() { diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRulesImpl.java index 4eb91ff7ff033..7caf5672e5d79 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceAuthorizationRulesImpl.java @@ -19,10 +19,8 @@ /** * Implementation for {@link EventHubNamespaceAuthorizationRules}. */ -public final class EventHubNamespaceAuthorizationRulesImpl - extends AuthorizationRulesBaseImpl +public final class EventHubNamespaceAuthorizationRulesImpl extends + AuthorizationRulesBaseImpl implements EventHubNamespaceAuthorizationRules { public EventHubNamespaceAuthorizationRulesImpl(EventHubsManager manager) { @@ -38,9 +36,7 @@ public EventHubNamespaceAuthorizationRuleImpl define(String name) { public Mono getByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override @@ -49,27 +45,22 @@ public EventHubNamespaceAuthorizationRule getByName(String resourceGroupName, St } @Override - public Mono getByNameAsync( - String resourceGroupName, String namespaceName, String name) { - return this.innerModel().getAuthorizationRuleAsync(resourceGroupName, - namespaceName, - name) - .map(this::wrapModel); + public Mono getByNameAsync(String resourceGroupName, String namespaceName, + String name) { + return this.innerModel().getAuthorizationRuleAsync(resourceGroupName, namespaceName, name).map(this::wrapModel); } @Override - public PagedIterable listByNamespace( - final String resourceGroupName, final String namespaceName) { - return PagedConverter.mapPage(innerModel() - .listAuthorizationRules(resourceGroupName, namespaceName), + public PagedIterable listByNamespace(final String resourceGroupName, + final String namespaceName) { + return PagedConverter.mapPage(innerModel().listAuthorizationRules(resourceGroupName, namespaceName), this::wrapModel); } @Override - public PagedFlux listByNamespaceAsync( - String resourceGroupName, String namespaceName) { - return PagedConverter.mapPage(this.innerModel() - .listAuthorizationRulesAsync(resourceGroupName, namespaceName), + public PagedFlux listByNamespaceAsync(String resourceGroupName, + String namespaceName) { + return PagedConverter.mapPage(this.innerModel().listAuthorizationRulesAsync(resourceGroupName, namespaceName), this::wrapModel); } @@ -78,16 +69,12 @@ public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return deleteByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return deleteByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String name) { - return this.innerModel().deleteAuthorizationRuleAsync(resourceGroupName, - namespaceName, - name); + return this.innerModel().deleteAuthorizationRuleAsync(resourceGroupName, namespaceName, name); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceImpl.java index 7f2d7bdfa2a9e..b8a483fb0f9c8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespaceImpl.java @@ -28,11 +28,8 @@ * Implementation for {@link EventHubNamespace}. */ class EventHubNamespaceImpl - extends GroupableResourceImpl - implements - EventHubNamespace, - EventHubNamespace.Definition, - EventHubNamespace.Update { + extends GroupableResourceImpl + implements EventHubNamespace, EventHubNamespace.Definition, EventHubNamespace.Update { private Flux postRunTasks; @@ -107,8 +104,8 @@ public EventHubNamespaceImpl withNewEventHub(final String eventHubName, final in } @Override - public EventHubNamespaceImpl withNewEventHub( - final String eventHubName, final int partitionCount, final int retentionPeriodInDays) { + public EventHubNamespaceImpl withNewEventHub(final String eventHubName, final int partitionCount, + final int retentionPeriodInDays) { concatPostRunTask(manager().eventHubs() .define(eventHubName) .withExistingNamespace(resourceGroupName(), name()) @@ -182,10 +179,7 @@ public EventHubNamespaceImpl withAutoScaling() { @Override public EventHubNamespaceImpl withSku(EventHubNamespaceSkuType namespaceSku) { - Sku newSkuInner = new Sku() - .withName(namespaceSku.name()) - .withTier(namespaceSku.tier()) - .withCapacity(null); + Sku newSkuInner = new Sku().withName(namespaceSku.name()).withTier(namespaceSku.tier()).withCapacity(null); Sku currentSkuInner = this.innerModel().sku(); boolean isDifferent = currentSkuInner == null || !currentSkuInner.name().equals(newSkuInner.name()); @@ -220,9 +214,11 @@ public void beforeGroupCreateOrUpdate() { @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getNamespaces() - .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) - .map(innerToFluentMap(this)); + return this.manager() + .serviceClient() + .getNamespaces() + .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) + .map(innerToFluentMap(this)); } @Override @@ -238,8 +234,7 @@ public PagedFlux listEventHubsAsync() { @Override public PagedFlux listAuthorizationRulesAsync() { - return this.manager().namespaceAuthorizationRules() - .listByNamespaceAsync(this.resourceGroupName(), this.name()); + return this.manager().namespaceAuthorizationRules().listByNamespaceAsync(this.resourceGroupName(), this.name()); } @Override @@ -249,8 +244,7 @@ public PagedIterable listEventHubs() { @Override public PagedIterable listAuthorizationRules() { - return this.manager().namespaceAuthorizationRules() - .listByNamespace(this.resourceGroupName(), this.name()); + return this.manager().namespaceAuthorizationRules().listByNamespace(this.resourceGroupName(), this.name()); } @Override @@ -265,7 +259,9 @@ public boolean zoneRedundant() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getNamespaces() + return this.manager() + .serviceClient() + .getNamespaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespacesImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespacesImpl.java index 8af7de0398029..6d64af27aa84c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespacesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubNamespacesImpl.java @@ -15,13 +15,8 @@ /** * Implementation for {@link EventHubNamespaces}. */ -public final class EventHubNamespacesImpl - extends TopLevelModifiableResourcesImpl< - EventHubNamespace, - EventHubNamespaceImpl, - EHNamespaceInner, - NamespacesClient, - EventHubsManager> +public final class EventHubNamespacesImpl extends + TopLevelModifiableResourcesImpl implements EventHubNamespaces { public EventHubNamespacesImpl(EventHubsManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubsImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubsImpl.java index b2f70d58c9325..1db51377427c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/EventHubsImpl.java @@ -60,17 +60,12 @@ public EventHub getById(String id) { public Mono getByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return getByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return getByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public Mono getByNameAsync(String resourceGroupName, String namespaceName, String name) { - return this.innerModel().getAsync(resourceGroupName, - namespaceName, - name) - .map(this::wrapModel); + return this.innerModel().getAsync(resourceGroupName, namespaceName, name).map(this::wrapModel); } @Override @@ -80,15 +75,12 @@ public EventHub getByName(String resourceGroupName, String namespaceName, String @Override public PagedIterable listByNamespace(String resourceGroupName, String namespaceName) { - return PagedConverter.mapPage(innerModel() - .listByNamespace(resourceGroupName, namespaceName), - this::wrapModel); + return PagedConverter.mapPage(innerModel().listByNamespace(resourceGroupName, namespaceName), this::wrapModel); } @Override public PagedFlux listByNamespaceAsync(String resourceGroupName, String namespaceName) { - return PagedConverter.mapPage(innerModel() - .listByNamespaceAsync(resourceGroupName, namespaceName), + return PagedConverter.mapPage(innerModel().listByNamespaceAsync(resourceGroupName, namespaceName), this::wrapModel); } @@ -101,16 +93,12 @@ public void deleteById(String id) { public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); ResourceId resourceId = ResourceId.fromString(id); - return deleteByNameAsync(resourceId.resourceGroupName(), - resourceId.parent().name(), - resourceId.name()); + return deleteByNameAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String name) { - return this.innerModel().deleteAsync(resourceGroupName, - namespaceName, - name); + return this.innerModel().deleteAsync(resourceGroupName, namespaceName, name); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/NestedResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/NestedResourceImpl.java index e7598c60e6ecb..a1e25e4751831 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/NestedResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/implementation/NestedResourceImpl.java @@ -19,10 +19,7 @@ * @param the inner model of the nested resource * @param the fluent model implementation of the nested resource */ -public abstract class NestedResourceImpl< - FluentModelT extends Indexable, - InnerModelT extends ProxyResource, - FluentModelImplT extends IndexableRefreshableWrapperImpl> +public abstract class NestedResourceImpl> extends CreatableUpdatableImpl implements HasManager, NestedResource { protected final EventHubsManager manager; diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/AuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/AuthorizationRule.java index a78b77bf05f2e..6d62beecb229b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/AuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/AuthorizationRule.java @@ -18,22 +18,24 @@ * @param the specific authorization rule type */ @Fluent -public interface AuthorizationRule> extends - NestedResource, HasInnerModel, HasManager, - Refreshable { +public interface AuthorizationRule> + extends NestedResource, HasInnerModel, HasManager, Refreshable { /** * @return rights associated with the authorization rule */ List rights(); + /** * @return a representation of the deferred computation of this call, * returning access keys (primary, secondary) and the connection strings */ Mono getKeysAsync(); + /** * @return the access keys (primary, secondary) and the connection strings */ EventHubAuthorizationKey getKeys(); + /** * Regenerates primary or secondary access keys. * @@ -42,6 +44,7 @@ public interface AuthorizationRule> exten * returning access keys (primary, secondary) and the connection strings */ Mono regenerateKeyAsync(KeyType keyType); + /** * Regenerates primary or secondary keys. * diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationKey.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationKey.java index 1089cb9301e25..5f49523501e68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationKey.java @@ -10,8 +10,7 @@ * Type representing access key of {@link DisasterRecoveryPairingAuthorizationRule}. */ @Fluent -public interface DisasterRecoveryPairingAuthorizationKey - extends HasInnerModel { +public interface DisasterRecoveryPairingAuthorizationKey extends HasInnerModel { /** * @return primary access key */ diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRule.java index 318565d5beee6..73519c74dd6aa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRule.java @@ -27,6 +27,7 @@ public interface DisasterRecoveryPairingAuthorizationRule * @return an observable that emits a single entity containing access keys (primary and secondary) */ Mono getKeysAsync(); + /** * @return entity containing access keys (primary and secondary) */ diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRules.java index ebfbe51718980..cf64307dc32f2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/DisasterRecoveryPairingAuthorizationRules.java @@ -14,9 +14,8 @@ * Entry point to manage disaster recovery pairing authorization rules. */ @Fluent -public interface DisasterRecoveryPairingAuthorizationRules extends - SupportsGettingById, - HasManager { +public interface DisasterRecoveryPairingAuthorizationRules + extends SupportsGettingById, HasManager { /** * Lists the authorization rules that can be used to access the disaster recovery pairing. * @@ -25,8 +24,8 @@ public interface DisasterRecoveryPairingAuthorizationRules extends * @param pairingName pairing name * @return list of authorization rules */ - PagedIterable listByDisasterRecoveryPairing( - String resourceGroupName, String namespaceName, String pairingName); + PagedIterable listByDisasterRecoveryPairing(String resourceGroupName, + String namespaceName, String pairingName); /** * Lists the authorization rules that can be used to access the disaster recovery pairing. @@ -36,8 +35,8 @@ PagedIterable listByDisasterRecoveryPa * @param pairingName pairing name * @return observable that emits the authorization rules */ - PagedFlux listByDisasterRecoveryPairingAsync( - String resourceGroupName, String namespaceName, String pairingName); + PagedFlux listByDisasterRecoveryPairingAsync(String resourceGroupName, + String namespaceName, String pairingName); /** * Gets an authorization rule that can be used to access the disaster recovery pairing. @@ -48,8 +47,8 @@ PagedFlux listByDisasterRecoveryPairin * @param name rule name * @return observable that emits the authorization rule */ - Mono getByNameAsync( - String resourceGroupName, String namespaceName, String pairingName, String name); + Mono getByNameAsync(String resourceGroupName, String namespaceName, + String pairingName, String name); /** * Gets an authorization rule that can be used to access the disaster recovery pairing. @@ -60,6 +59,6 @@ Mono getByNameAsync( * @param name rule name * @return the authorization rule */ - DisasterRecoveryPairingAuthorizationRule getByName( - String resourceGroupName, String namespaceName, String pairingName, String name); + DisasterRecoveryPairingAuthorizationRule getByName(String resourceGroupName, String namespaceName, + String pairingName, String name); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHub.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHub.java index a3221474fb581..f9af6277951bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHub.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHub.java @@ -21,12 +21,8 @@ * Type representing an Azure EventHub. */ @Fluent -public interface EventHub extends - NestedResource, - HasManager, - Refreshable, - Updatable, - HasInnerModel { +public interface EventHub extends NestedResource, HasManager, Refreshable, + Updatable, HasInnerModel { /** * @return the resource group of the parent namespace */ @@ -81,14 +77,17 @@ public interface EventHub extends * @return consumer group in the event hub */ PagedFlux listConsumerGroupsAsync(); + /** * @return authorization rules enabled for the event hub */ PagedFlux listAuthorizationRulesAsync(); + /** * @return consumer group in the event hub */ PagedIterable listConsumerGroups(); + /** * @return authorization rules enabled for the event hub */ @@ -97,13 +96,9 @@ public interface EventHub extends /** * The entirety of the event hub definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithNamespace, - DefinitionStages.WithCaptureProviderOrCreate, - DefinitionStages.WithCaptureEnabledDisabled, - DefinitionStages.WithCaptureOptionalSettingsOrCreate, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithNamespace, + DefinitionStages.WithCaptureProviderOrCreate, DefinitionStages.WithCaptureEnabledDisabled, + DefinitionStages.WithCaptureOptionalSettingsOrCreate, DefinitionStages.WithCreate { } /** @@ -177,8 +172,8 @@ WithCaptureEnabledDisabled withNewStorageAccountForCapturedData( * @param containerName an existing or new container to store the files containing captured data * @return next stage of the event hub definition */ - WithCaptureEnabledDisabled withExistingStorageAccountForCapturedData( - StorageAccount storageAccount, String containerName); + WithCaptureEnabledDisabled withExistingStorageAccountForCapturedData(StorageAccount storageAccount, + String containerName); /** * Specifies an existing storage account to store the captured data when data capturing is enabled. @@ -187,8 +182,8 @@ WithCaptureEnabledDisabled withExistingStorageAccountForCapturedData( * @param containerName an existing or new container to store the files containing captured data * @return next stage of the event hub definition */ - WithCaptureEnabledDisabled withExistingStorageAccountForCapturedData( - String storageAccountId, String containerName); + WithCaptureEnabledDisabled withExistingStorageAccountForCapturedData(String storageAccountId, + String containerName); } /** @@ -289,7 +284,7 @@ interface WithAuthorizationRule { /** * The stage of the event hub definition allowing to add consumer group for the event hub. */ - interface WithConsumerGroup { + interface WithConsumerGroup { /** * Specifies that a new consumer group should be created for the event hub. * @@ -339,12 +334,9 @@ interface WithRetentionPeriod { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - DefinitionStages.WithAuthorizationRule, - DefinitionStages.WithConsumerGroup, - DefinitionStages.WithPartitionCount, - DefinitionStages.WithRetentionPeriod { + interface WithCreate + extends Creatable, DefinitionStages.WithAuthorizationRule, DefinitionStages.WithConsumerGroup, + DefinitionStages.WithPartitionCount, DefinitionStages.WithRetentionPeriod { } } @@ -402,7 +394,7 @@ interface WithAuthorizationRule { /** * The stage of the event hub update allowing to add consumer group for event hub. */ - interface WithConsumerGroup { + interface WithConsumerGroup { /** * Specifies that a new consumer group should be created for the event hub. * @@ -440,8 +432,8 @@ interface WithCapture { * @param containerName container to store the files containing captured data * @return next stage of the event hub update */ - Update withNewStorageAccountForCapturedData( - Creatable storageAccountCreatable, String containerName); + Update withNewStorageAccountForCapturedData(Creatable storageAccountCreatable, + String containerName); /** * Specifies an existing storage account to store the captured data when data capturing is enabled. @@ -483,7 +475,7 @@ Update withNewStorageAccountForCapturedData( */ Update withDataCaptureWindowSizeInSeconds(int sizeInSeconds); - /** + /** * Specified the capture whether to Skip Empty Archives. * * @param skipEmptyArchives the skipEmptyArchives value to set @@ -498,6 +490,7 @@ Update withNewStorageAccountForCapturedData( * @return next stage of the event hub update */ Update withDataCaptureWindowSizeInMB(int sizeInMB); + /** * Specifies the format of the file containing captured data. * @@ -537,12 +530,7 @@ interface WithRetentionPeriod { /** * The template for a event hub update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithConsumerGroup, - UpdateStages.WithAuthorizationRule, - UpdateStages.WithCapture, - UpdateStages.WithPartitionCount, - UpdateStages.WithRetentionPeriod { + interface Update extends Appliable, UpdateStages.WithConsumerGroup, UpdateStages.WithAuthorizationRule, + UpdateStages.WithCapture, UpdateStages.WithPartitionCount, UpdateStages.WithRetentionPeriod { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationKey.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationKey.java index 3a9c22b6d4821..89eb1dc4eba90 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationKey.java @@ -10,8 +10,7 @@ * Type representing access key of {@link EventHubNamespaceAuthorizationRule}. */ @Fluent -public interface EventHubAuthorizationKey - extends HasInnerModel { +public interface EventHubAuthorizationKey extends HasInnerModel { /** * @return primary access key */ diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRule.java index b53c2c0f6b56d..74035f7cb6732 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRule.java @@ -10,17 +10,17 @@ * Type representing authorization rule of an event hub. */ @Fluent -public interface EventHubAuthorizationRule - extends - AuthorizationRule { +public interface EventHubAuthorizationRule extends AuthorizationRule { /** * @return the resource group of the namespace where parent event hub resides */ String namespaceResourceGroupName(); + /** * @return the namespace name of parent event hub */ String namespaceName(); + /** * @return the name of the parent event hub */ @@ -47,6 +47,7 @@ interface WithEventHub { * @return the next stage of the definition */ WithAccessPolicy withExistingEventHubId(String eventHubResourceId); + /** * Specifies that authorization rule needs to be created for the given event hub. * @@ -56,6 +57,7 @@ interface WithEventHub { * @return the next stage of the definition */ WithAccessPolicy withExistingEventHub(String resourceGroupName, String namespaceName, String eventHubName); + /** * Specifies that authorization rule needs to be created for the given event hub. * @@ -68,9 +70,7 @@ interface WithEventHub { /** * Stage of the authorization rule definition allowing to specify access policy. */ - interface WithAccessPolicy extends AuthorizationRule - .DefinitionStages - .WithListenOrSendOrManage { + interface WithAccessPolicy extends AuthorizationRule.DefinitionStages.WithListenOrSendOrManage { } @@ -86,18 +86,14 @@ interface WithCreate extends Creatable { /** * The entirety of the event hub namespace authorization rule definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithEventHub, - DefinitionStages.WithAccessPolicy, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithEventHub, + DefinitionStages.WithAccessPolicy, DefinitionStages.WithCreate { } /** * The entirety of the event hub authorization rule update. */ - interface Update extends - Appliable, + interface Update extends Appliable, UpdateStages.WithListenOrSendOrManage { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRules.java index 77533544563b9..1d18dd92cb6bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubAuthorizationRules.java @@ -16,11 +16,8 @@ * Entry point to manage event hub authorization rules. */ @Fluent -public interface EventHubAuthorizationRules extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - HasManager { +public interface EventHubAuthorizationRules extends SupportsCreating, + SupportsDeletingById, SupportsGettingById, HasManager { /** * Lists the authorization rules of an event hub in a namespace under a resource group. * @@ -29,8 +26,9 @@ public interface EventHubAuthorizationRules extends * @param eventHubName event hub name * @return list of authorization rules */ - PagedIterable listByEventHub( - String resourceGroupName, String namespaceName, String eventHubName); + PagedIterable listByEventHub(String resourceGroupName, String namespaceName, + String eventHubName); + /** * Lists the authorization rules of an event hub in a namespace under a resource group. * @@ -39,8 +37,9 @@ PagedIterable listByEventHub( * @param eventHubName event hub name * @return observable that emits the authorization rules */ - PagedFlux listByEventHubAsync( - String resourceGroupName, String namespaceName, String eventHubName); + PagedFlux listByEventHubAsync(String resourceGroupName, String namespaceName, + String eventHubName); + /** * Gets an authorization rule of an event hub in a namespace in a resource group. * @@ -50,8 +49,9 @@ PagedFlux listByEventHubAsync( * @param name authorization rule name * @return observable that emits the authorization rule */ - Mono getByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name); + Mono getByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, + String name); + /** * Gets an authorization rule of an event hub in a namespace under a resource group. * @@ -61,8 +61,8 @@ Mono getByNameAsync( * @param name authorization rule name * @return the authorization rule */ - EventHubAuthorizationRule getByName( - String resourceGroupName, String namespaceName, String eventHubName, String name); + EventHubAuthorizationRule getByName(String resourceGroupName, String namespaceName, String eventHubName, + String name); /** * Deletes an authorization rule of an event hub in a namespace under a resource group. @@ -73,8 +73,7 @@ EventHubAuthorizationRule getByName( * @param name authorization rule name * @return the completable representing the task */ - Mono deleteByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name); + Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, String name); /** * Deletes an authorization rule of an event hub in a namespace under a resource group. diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroup.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroup.java index c641dcacc0714..eedbc35fe813f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroup.java @@ -18,12 +18,8 @@ * Type representing consumer group of an event hub. */ @Fluent -public interface EventHubConsumerGroup extends - NestedResource, - HasManager, - Refreshable, - HasInnerModel, - Updatable { +public interface EventHubConsumerGroup extends NestedResource, HasManager, + Refreshable, HasInnerModel, Updatable { /** * @return the resource group of the namespace where parent event hub resides */ @@ -57,11 +53,8 @@ public interface EventHubConsumerGroup extends /** * The entirety of the consumer group definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithEventHub, - DefinitionStages.WithUserMetadata, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithEventHub, + DefinitionStages.WithUserMetadata, DefinitionStages.WithCreate { } /** @@ -124,9 +117,7 @@ interface WithUserMetadata { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - DefinitionStages.WithUserMetadata { + interface WithCreate extends Creatable, DefinitionStages.WithUserMetadata { } } @@ -134,9 +125,7 @@ interface WithCreate extends * The template for a consumer group update operation, containing all the settings * that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithUserMetadata { + interface Update extends Appliable, UpdateStages.WithUserMetadata { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroups.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroups.java index 8e4372fa9c207..a2138ed311d1f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubConsumerGroups.java @@ -16,11 +16,8 @@ * Entry point to manage event hub consumer groups. */ @Fluent -public interface EventHubConsumerGroups extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - HasManager { +public interface EventHubConsumerGroups extends SupportsCreating, + SupportsDeletingById, SupportsGettingById, HasManager { /** * Lists the consumer groups of an event hub in a namespace under a resource group. * @@ -29,8 +26,8 @@ public interface EventHubConsumerGroups extends * @param eventHubName event hub name * @return list of consumer groups */ - PagedIterable listByEventHub( - String resourceGroupName, String namespaceName, String eventHubName); + PagedIterable listByEventHub(String resourceGroupName, String namespaceName, + String eventHubName); /** * Lists the consumer groups of an event hub in a namespace under a resource group. @@ -40,8 +37,8 @@ PagedIterable listByEventHub( * @param eventHubName event hub name * @return observable that emits the consumer groups */ - PagedFlux listByEventHubAsync( - String resourceGroupName, String namespaceName, String eventHubName); + PagedFlux listByEventHubAsync(String resourceGroupName, String namespaceName, + String eventHubName); /** * Gets a consumer group of an event hub in a namespace in a resource group. @@ -52,8 +49,8 @@ PagedFlux listByEventHubAsync( * @param name consumer group name * @return observable that emits the consumer group */ - Mono getByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name); + Mono getByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, + String name); /** * Gets a consumer group of an event hub in a namespace under a resource group. @@ -64,8 +61,7 @@ Mono getByNameAsync( * @param name consumer group name * @return the consumer group */ - EventHubConsumerGroup getByName( - String resourceGroupName, String namespaceName, String eventHubName, String name); + EventHubConsumerGroup getByName(String resourceGroupName, String namespaceName, String eventHubName, String name); /** * Deletes a consumer group of an event hub in a namespace under a resource group. @@ -76,8 +72,7 @@ EventHubConsumerGroup getByName( * @param name consumer group name * @return the completable representing the task */ - Mono deleteByNameAsync( - String resourceGroupName, String namespaceName, String eventHubName, String name); + Mono deleteByNameAsync(String resourceGroupName, String namespaceName, String eventHubName, String name); /** * Deletes a consumer group of an event hub in a namespace under a resource group. @@ -87,6 +82,5 @@ Mono deleteByNameAsync( * @param eventHubName event hub name * @param name consumer group name */ - void deleteByName( - String resourceGroupName, String namespaceName, String eventHubName, String name); + void deleteByName(String resourceGroupName, String namespaceName, String eventHubName, String name); } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairing.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairing.java index 185d118943eb2..70152068bc48c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairing.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairing.java @@ -19,12 +19,9 @@ * Type representing disaster recovery pairing for event hub namespaces. */ @Fluent -public interface EventHubDisasterRecoveryPairing extends - NestedResource, - HasManager, - Refreshable, - Updatable, - HasInnerModel { +public interface EventHubDisasterRecoveryPairing + extends NestedResource, HasManager, Refreshable, + Updatable, HasInnerModel { /** * @return primary event hub namespace resource group */ @@ -87,11 +84,8 @@ public interface EventHubDisasterRecoveryPairing extends /** * The entirety of the event hub disaster recovery pairing definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithPrimaryNamespace, - DefinitionStages.WithSecondaryNamespace, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithPrimaryNamespace, + DefinitionStages.WithSecondaryNamespace, DefinitionStages.WithCreate { } /** @@ -176,8 +170,7 @@ interface WithSecondaryNamespace { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable { + interface WithCreate extends Creatable { } } @@ -219,8 +212,6 @@ interface WithSecondaryNamespace { * The template for a disaster recovery pairing update operation, containing all the settings * that can be modified. */ - interface Update extends - UpdateStages.WithSecondaryNamespace, - Appliable { + interface Update extends UpdateStages.WithSecondaryNamespace, Appliable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairings.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairings.java index 6180d9f2ea4d0..323f18bf64a37 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairings.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubDisasterRecoveryPairings.java @@ -16,15 +16,14 @@ * Entry point to manage disaster recovery pairing of event hub namespaces. */ @Fluent -public interface EventHubDisasterRecoveryPairings extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - HasManager { +public interface EventHubDisasterRecoveryPairings + extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, HasManager { /** * @return entry point to manage authorization rules of a disaster recovery pairing. */ DisasterRecoveryPairingAuthorizationRules authorizationRules(); + /** * Lists the disaster recovery pairings of a namespace under a resource group. * @@ -33,6 +32,7 @@ public interface EventHubDisasterRecoveryPairings extends * @return list of disaster recovery pairings */ PagedIterable listByNamespace(String resourceGroupName, String namespaceName); + /** * Lists the disaster recovery pairings of a namespace under a resource group. * @@ -41,6 +41,7 @@ public interface EventHubDisasterRecoveryPairings extends * @return observable that emits disaster recovery pairings */ PagedFlux listByNamespaceAsync(String resourceGroupName, String namespaceName); + /** * Gets a disaster recovery pairings of a namespace under a resource group. * diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespace.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespace.java index b82ea6cdae115..530b9a469ffa7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespace.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespace.java @@ -20,10 +20,8 @@ * Type representing an Azure EventHub namespace. */ @Fluent -public interface EventHubNamespace extends - GroupableResource, - Refreshable, - Updatable { +public interface EventHubNamespace extends GroupableResource, + Refreshable, Updatable { /** * @return namespace sku */ @@ -74,9 +72,9 @@ public interface EventHubNamespace extends */ PagedFlux listEventHubsAsync(); - /** - * @return the authorization rules for the event hub namespace - */ + /** + * @return the authorization rules for the event hub namespace + */ PagedFlux listAuthorizationRulesAsync(); /** @@ -107,10 +105,8 @@ public interface EventHubNamespace extends /** * The entirety of the event hub namespace definition. */ - interface Definition extends - EventHubNamespace.DefinitionStages.Blank, - EventHubNamespace.DefinitionStages.WithGroup, - EventHubNamespace.DefinitionStages.WithCreate { + interface Definition extends EventHubNamespace.DefinitionStages.Blank, EventHubNamespace.DefinitionStages.WithGroup, + EventHubNamespace.DefinitionStages.WithCreate { } /** @@ -218,6 +214,7 @@ interface WithThroughputConfiguration { * @return next stage of the event hub namespace definition */ WithCreate withAutoScaling(); + /** * Specifies the current throughput units. * @@ -266,11 +263,8 @@ interface WithZoneRedundant { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Resource.DefinitionWithTags, - EventHubNamespace.DefinitionStages.WithSku, - EventHubNamespace.DefinitionStages.WithEventHub, + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + EventHubNamespace.DefinitionStages.WithSku, EventHubNamespace.DefinitionStages.WithEventHub, EventHubNamespace.DefinitionStages.WithAuthorizationRule, EventHubNamespace.DefinitionStages.WithThroughputConfiguration, EventHubNamespace.DefinitionStages.WithMinimumTlsVersion, @@ -281,12 +275,9 @@ interface WithCreate extends /** * The template for a event hub namespace update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - Resource.UpdateWithTags, - EventHubNamespace.UpdateStages.WithSku, - EventHubNamespace.UpdateStages.WithEventHub, - EventHubNamespace.UpdateStages.WithAuthorizationRule, + interface Update + extends Appliable, Resource.UpdateWithTags, EventHubNamespace.UpdateStages.WithSku, + EventHubNamespace.UpdateStages.WithEventHub, EventHubNamespace.UpdateStages.WithAuthorizationRule, EventHubNamespace.UpdateStages.WithThroughputConfiguration, EventHubNamespace.UpdateStages.WithMinimumTlsVersion { } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRule.java index 4f38078cdc5f3..ec1ef7fe2914e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRule.java @@ -10,8 +10,7 @@ * Type representing authorization rule of an event hub namespace. */ @Fluent -public interface EventHubNamespaceAuthorizationRule - extends AuthorizationRule { +public interface EventHubNamespaceAuthorizationRule extends AuthorizationRule { /** * @return the resource group of the namespace where parent event hub resides. */ @@ -66,9 +65,7 @@ interface WithNamespace { /** * Stage of the authorization rule definition allowing to specify access policy. */ - interface WithAccessPolicy extends AuthorizationRule - .DefinitionStages - .WithListenOrSendOrManage { + interface WithAccessPolicy extends AuthorizationRule.DefinitionStages.WithListenOrSendOrManage { } @@ -84,18 +81,14 @@ interface WithCreate extends Creatable { /** * The entirety of the event hub namespace authorization rule definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithNamespace, - DefinitionStages.WithAccessPolicy, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithNamespace, + DefinitionStages.WithAccessPolicy, DefinitionStages.WithCreate { } /** * The entirety of the event hub namespace authorization rule update. */ - interface Update extends - Appliable, + interface Update extends Appliable, AuthorizationRule.UpdateStages.WithListenOrSendOrManage { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRules.java index f29f3e5f9821f..20ba21a3285cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceAuthorizationRules.java @@ -16,11 +16,9 @@ * Entry point to manage event hub namespace authorization rules. */ @Fluent -public interface EventHubNamespaceAuthorizationRules extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - HasManager { +public interface EventHubNamespaceAuthorizationRules + extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, HasManager { /** * Lists the authorization rules under a namespace in a resource group. * @@ -47,8 +45,8 @@ public interface EventHubNamespaceAuthorizationRules extends * @param name authorization rule name * @return observable that emits the authorization rule */ - Mono getByNameAsync( - String resourceGroupName, String namespaceName, String name); + Mono getByNameAsync(String resourceGroupName, String namespaceName, + String name); /** * Gets an authorization rule under a namespace in a resource group. diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceSkuType.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceSkuType.java index f8983cea5be42..513a70ba46496 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceSkuType.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaceSkuType.java @@ -11,15 +11,15 @@ */ public class EventHubNamespaceSkuType implements HasInnerModel { /** Static value NamespaceSku for BASIC. */ - public static final EventHubNamespaceSkuType BASIC = - new EventHubNamespaceSkuType(new Sku().withName(SkuName.BASIC).withTier(SkuTier.BASIC)); + public static final EventHubNamespaceSkuType BASIC + = new EventHubNamespaceSkuType(new Sku().withName(SkuName.BASIC).withTier(SkuTier.BASIC)); /** Static value NamespaceSku for STANDARD. */ - public static final EventHubNamespaceSkuType STANDARD = - new EventHubNamespaceSkuType(new Sku().withName(SkuName.STANDARD).withTier(SkuTier.STANDARD)); + public static final EventHubNamespaceSkuType STANDARD + = new EventHubNamespaceSkuType(new Sku().withName(SkuName.STANDARD).withTier(SkuTier.STANDARD)); /** Static value NamespaceSku for STANDARD. */ - public static final EventHubNamespaceSkuType PREMIUM = - new EventHubNamespaceSkuType(new Sku().withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); - + public static final EventHubNamespaceSkuType PREMIUM + = new EventHubNamespaceSkuType(new Sku().withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); + private final Sku sku; /** diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaces.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaces.java index fa2ddfac72257..2463a30a37b80 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaces.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubNamespaces.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.eventhubs.models; - import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsBatchDeletion; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup; @@ -20,17 +19,11 @@ * Entry point to manage EventHub namespaces. */ @Fluent -public interface EventHubNamespaces extends - SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface EventHubNamespaces + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * @return entry point to manage authorization rules of event hub namespaces. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubs.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubs.java index 636c6a935651c..51af2a7b369b3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubs.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/main/java/com/azure/resourcemanager/eventhubs/models/EventHubs.java @@ -16,11 +16,8 @@ * Entry point to manage event hubs. */ @Fluent -public interface EventHubs extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - HasManager { +public interface EventHubs extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, HasManager { /** * @return entry point to manage authorization rules of event hubs. */ @@ -31,6 +28,7 @@ public interface EventHubs extends */ EventHubConsumerGroups consumerGroups(); + /** * Lists the event hubs in a namespace under a resource group. * diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/test/java/com/azure/resourcemanager/eventhubs/EventHubTests.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/test/java/com/azure/resourcemanager/eventhubs/EventHubTests.java index 665f0b6982acc..d05bbe762fea7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/test/java/com/azure/resourcemanager/eventhubs/EventHubTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/test/java/com/azure/resourcemanager/eventhubs/EventHubTests.java @@ -55,21 +55,10 @@ public class EventHubTests extends ResourceManagerTestProxyTestBase { private final Region region = Region.US_EAST; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -95,12 +84,12 @@ public void canManageEventHubNamespaceBasicSettings() { final String namespaceName3 = generateRandomResourceName("ns", 14); EventHubNamespace namespace1 = eventHubsManager.namespaces() - .define(namespaceName1) - .withRegion(region) - .withNewResourceGroup(rgName) - // SDK should use Sku as 'Standard' and set capacity.capacity in it as 1 - .withAutoScaling() - .create(); + .define(namespaceName1) + .withRegion(region) + .withNewResourceGroup(rgName) + // SDK should use Sku as 'Standard' and set capacity.capacity in it as 1 + .withAutoScaling() + .create(); Assertions.assertNotNull(namespace1); Assertions.assertNotNull(namespace1.innerModel()); @@ -111,12 +100,12 @@ public void canManageEventHubNamespaceBasicSettings() { Assertions.assertNotNull(namespace1.innerModel().sku().capacity()); EventHubNamespace namespace2 = eventHubsManager.namespaces() - .define(namespaceName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - // SDK should use Sku as 'Standard' and set capacity.capacity in it as 11 - .withCurrentThroughputUnits(11) - .create(); + .define(namespaceName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + // SDK should use Sku as 'Standard' and set capacity.capacity in it as 11 + .withCurrentThroughputUnits(11) + .create(); Assertions.assertNotNull(namespace2); Assertions.assertNotNull(namespace2.innerModel()); @@ -127,21 +116,18 @@ public void canManageEventHubNamespaceBasicSettings() { Assertions.assertEquals(11, namespace2.currentThroughputUnits()); EventHubNamespace namespace3 = eventHubsManager.namespaces() - .define(namespaceName3) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(EventHubNamespaceSkuType.BASIC) - .create(); + .define(namespaceName3) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(EventHubNamespaceSkuType.BASIC) + .create(); Assertions.assertNotNull(namespace3); Assertions.assertNotNull(namespace3.innerModel()); Assertions.assertNotNull(namespace3.sku()); Assertions.assertTrue(namespace3.sku().equals(EventHubNamespaceSkuType.BASIC)); - namespace3.update() - .withSku(EventHubNamespaceSkuType.STANDARD) - .withTag("aa", "bb") - .apply(); + namespace3.update().withSku(EventHubNamespaceSkuType.STANDARD).withTag("aa", "bb").apply(); Assertions.assertNotNull(namespace3.sku()); Assertions.assertTrue(namespace3.sku().equals(EventHubNamespaceSkuType.STANDARD)); @@ -158,12 +144,12 @@ public void canManageEventHubNamespaceEventHubs() { final String eventHubName3 = generateRandomResourceName("eh", 14); EventHubNamespace namespace = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewEventHub(eventHubName1) - .withNewEventHub(eventHubName2) - .create(); + .define(namespaceName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewEventHub(eventHubName1) + .withNewEventHub(eventHubName2) + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); @@ -177,8 +163,8 @@ public void canManageEventHubNamespaceEventHubs() { Assertions.assertTrue(set.contains(eventHubName2)); hubs = eventHubsManager.namespaces() - .eventHubs() - .listByNamespace(namespace.resourceGroupName(), namespace.name()); + .eventHubs() + .listByNamespace(namespace.resourceGroupName(), namespace.name()); set.clear(); for (EventHub hub : hubs) { @@ -188,12 +174,12 @@ public void canManageEventHubNamespaceEventHubs() { Assertions.assertTrue(set.contains(eventHubName2)); eventHubsManager.namespaces() - .eventHubs() - .define(eventHubName3) - .withExistingNamespaceId(namespace.id()) - .withPartitionCount(5) - .withRetentionPeriodInDays(6) - .create(); + .eventHubs() + .define(eventHubName3) + .withExistingNamespaceId(namespace.id()) + .withPartitionCount(5) + .withRetentionPeriodInDays(6) + .create(); hubs = namespace.listEventHubs(); set.clear(); @@ -211,12 +197,12 @@ public void canManageEventHubNamespaceAuthorizationRules() { final String namespaceName = generateRandomResourceName("ns", 14); EventHubNamespace namespace = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewManageRule("mngRule1") - .withNewSendRule("sndRule1") - .create(); + .define(namespaceName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewManageRule("mngRule1") + .withNewSendRule("sndRule1") + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); @@ -230,8 +216,8 @@ public void canManageEventHubNamespaceAuthorizationRules() { Assertions.assertTrue(set.contains("sndRule1")); rules = eventHubsManager.namespaces() - .authorizationRules() - .listByNamespace(namespace.resourceGroupName(), namespace.name()); + .authorizationRules() + .listByNamespace(namespace.resourceGroupName(), namespace.name()); set.clear(); for (EventHubNamespaceAuthorizationRule rule : rules) { @@ -241,11 +227,11 @@ public void canManageEventHubNamespaceAuthorizationRules() { Assertions.assertTrue(set.contains("sndRule1")); eventHubsManager.namespaces() - .authorizationRules() - .define("sndRule2") - .withExistingNamespaceId(namespace.id()) - .withSendAccess() - .create(); + .authorizationRules() + .define("sndRule2") + .withExistingNamespaceId(namespace.id()) + .withSendAccess() + .create(); rules = namespace.listAuthorizationRules(); set.clear(); @@ -257,11 +243,11 @@ public void canManageEventHubNamespaceAuthorizationRules() { Assertions.assertTrue(set.contains("sndRule2")); eventHubsManager.namespaces() - .authorizationRules() - .define("sndLsnRule3") - .withExistingNamespaceId(namespace.id()) - .withSendAndListenAccess() - .create(); + .authorizationRules() + .define("sndLsnRule3") + .withExistingNamespaceId(namespace.id()) + .withSendAndListenAccess() + .create(); rules = namespace.listAuthorizationRules(); Map rulesMap = new HashMap<>(); @@ -269,9 +255,8 @@ public void canManageEventHubNamespaceAuthorizationRules() { rulesMap.put(rule.name(), rule); } Assertions.assertTrue(rulesMap.containsKey("sndLsnRule3")); - Assertions.assertEquals( - new HashSet<>(Arrays.asList(AccessRights.SEND, AccessRights.LISTEN)), - new HashSet<>(rulesMap.get("sndLsnRule3").rights())); + Assertions.assertEquals(new HashSet<>(Arrays.asList(AccessRights.SEND, AccessRights.LISTEN)), + new HashSet<>(rulesMap.get("sndLsnRule3").rights())); } @Test @@ -280,17 +265,15 @@ public void canManageEventHubConsumerGroups() { final String namespaceName = generateRandomResourceName("ns", 14); final String eventHubName = generateRandomResourceName("eh", 14); - Creatable namespaceCreatable = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName); + Creatable namespaceCreatable + = eventHubsManager.namespaces().define(namespaceName).withRegion(region).withNewResourceGroup(rgName); EventHub eventHub = eventHubsManager.eventHubs() - .define(eventHubName) - .withNewNamespace(namespaceCreatable) - .withNewConsumerGroup("grp1") - .withNewConsumerGroup("grp2", "metadata111") - .create(); + .define(eventHubName) + .withNewNamespace(namespaceCreatable) + .withNewConsumerGroup("grp1") + .withNewConsumerGroup("grp2", "metadata111") + .create(); Assertions.assertNotNull(eventHub); Assertions.assertNotNull(eventHub.innerModel()); @@ -304,8 +287,8 @@ public void canManageEventHubConsumerGroups() { Assertions.assertTrue(set.contains("grp2")); cGroups = eventHubsManager.eventHubs() - .consumerGroups() - .listByEventHub(eventHub.namespaceResourceGroupName(), eventHub.namespaceName(), eventHub.name()); + .consumerGroups() + .listByEventHub(eventHub.namespaceResourceGroupName(), eventHub.namespaceName(), eventHub.name()); set.clear(); for (EventHubConsumerGroup rule : cGroups) { @@ -315,11 +298,11 @@ public void canManageEventHubConsumerGroups() { Assertions.assertTrue(set.contains("grp2")); eventHubsManager.eventHubs() - .consumerGroups() - .define("grp3") - .withExistingEventHubId(eventHub.id()) - .withUserMetadata("metadata222") - .create(); + .consumerGroups() + .define("grp3") + .withExistingEventHubId(eventHub.id()) + .withUserMetadata("metadata222") + .create(); cGroups = eventHub.listConsumerGroups(); set.clear(); @@ -337,17 +320,15 @@ public void canManageEventHubAuthorizationRules() { final String namespaceName = generateRandomResourceName("ns", 14); final String eventHubName = generateRandomResourceName("eh", 14); - Creatable namespaceCreatable = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName); + Creatable namespaceCreatable + = eventHubsManager.namespaces().define(namespaceName).withRegion(region).withNewResourceGroup(rgName); EventHub eventHub = eventHubsManager.eventHubs() - .define(eventHubName) - .withNewNamespace(namespaceCreatable) - .withNewManageRule("mngRule1") - .withNewSendRule("sndRule1") - .create(); + .define(eventHubName) + .withNewNamespace(namespaceCreatable) + .withNewManageRule("mngRule1") + .withNewSendRule("sndRule1") + .create(); Assertions.assertNotNull(eventHub); Assertions.assertNotNull(eventHub.innerModel()); @@ -361,8 +342,8 @@ public void canManageEventHubAuthorizationRules() { Assertions.assertTrue(set.contains("sndRule1")); rules = eventHubsManager.eventHubs() - .authorizationRules() - .listByEventHub(eventHub.namespaceResourceGroupName(), eventHub.namespaceName(), eventHub.name()); + .authorizationRules() + .listByEventHub(eventHub.namespaceResourceGroupName(), eventHub.namespaceName(), eventHub.name()); set.clear(); for (EventHubAuthorizationRule rule : rules) { @@ -372,11 +353,11 @@ public void canManageEventHubAuthorizationRules() { Assertions.assertTrue(set.contains("sndRule1")); eventHubsManager.eventHubs() - .authorizationRules() - .define("sndRule2") - .withExistingEventHubId(eventHub.id()) - .withSendAccess() - .create(); + .authorizationRules() + .define("sndRule2") + .withExistingEventHubId(eventHub.id()) + .withSendAccess() + .create(); rules = eventHub.listAuthorizationRules(); set.clear(); @@ -397,29 +378,27 @@ public void canConfigureEventHubDataCapturing() { final String eventHubName2 = generateRandomResourceName("eh", 14); Creatable storageAccountCreatable = storageManager.storageAccounts() - .define(stgName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS); + .define(stgName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS); - Creatable namespaceCreatable = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName); + Creatable namespaceCreatable + = eventHubsManager.namespaces().define(namespaceName).withRegion(region).withNewResourceGroup(rgName); final String containerName1 = "eventsctr1"; EventHub eventHub1 = eventHubsManager.eventHubs() - .define(eventHubName1) - .withNewNamespace(namespaceCreatable) - .withNewStorageAccountForCapturedData(storageAccountCreatable, containerName1) - .withDataCaptureEnabled() - // Window config is optional if not set service will choose default for it2 - // - .withDataCaptureWindowSizeInSeconds(120) - .withDataCaptureWindowSizeInMB(300) - .withDataCaptureSkipEmptyArchives(true) - .create(); + .define(eventHubName1) + .withNewNamespace(namespaceCreatable) + .withNewStorageAccountForCapturedData(storageAccountCreatable, containerName1) + .withDataCaptureEnabled() + // Window config is optional if not set service will choose default for it2 + // + .withDataCaptureWindowSizeInSeconds(120) + .withDataCaptureWindowSizeInMB(300) + .withDataCaptureSkipEmptyArchives(true) + .create(); Assertions.assertNotNull(eventHub1); Assertions.assertNotNull(eventHub1.innerModel()); @@ -442,11 +421,11 @@ public void canConfigureEventHubDataCapturing() { final String containerName2 = "eventsctr2"; EventHub eventHub2 = eventHubsManager.eventHubs() - .define(eventHubName2) - .withNewNamespace(namespaceCreatable) - .withExistingStorageAccountForCapturedData(stgAccountId, containerName2) - .withDataCaptureEnabled() - .create(); + .define(eventHubName2) + .withNewNamespace(namespaceCreatable) + .withExistingStorageAccountForCapturedData(stgAccountId, containerName2) + .withDataCaptureEnabled() + .create(); Assertions.assertTrue(eventHub2.isDataCaptureEnabled()); Assertions.assertNotNull(eventHub2.captureDestination()); @@ -454,9 +433,7 @@ public void canConfigureEventHubDataCapturing() { Assertions.assertTrue(eventHub2.captureDestination().storageAccountResourceId().contains(stgName)); Assertions.assertTrue(eventHub2.captureDestination().blobContainer().equalsIgnoreCase(containerName2)); - eventHub2.update() - .withDataCaptureDisabled() - .apply(); + eventHub2.update().withDataCaptureDisabled().apply(); Assertions.assertFalse(eventHub2.isDataCaptureEnabled()); } @@ -468,21 +445,15 @@ public void canEnableEventHubDataCaptureOnUpdate() { final String namespaceName = generateRandomResourceName("ns", 14); final String eventHubName = generateRandomResourceName("eh", 14); - Creatable namespaceCreatable = eventHubsManager.namespaces() - .define(namespaceName) - .withRegion(region) - .withNewResourceGroup(rgName); + Creatable namespaceCreatable + = eventHubsManager.namespaces().define(namespaceName).withRegion(region).withNewResourceGroup(rgName); - EventHub eventHub = eventHubsManager.eventHubs() - .define(eventHubName) - .withNewNamespace(namespaceCreatable) - .create(); + EventHub eventHub + = eventHubsManager.eventHubs().define(eventHubName).withNewNamespace(namespaceCreatable).create(); boolean exceptionThrown = false; try { - eventHub.update() - .withDataCaptureEnabled() - .apply(); + eventHub.update().withDataCaptureEnabled().apply(); } catch (IllegalStateException ex) { exceptionThrown = true; } @@ -491,15 +462,15 @@ public void canEnableEventHubDataCaptureOnUpdate() { eventHub = eventHub.refresh(); Creatable storageAccountCreatable = storageManager.storageAccounts() - .define(stgName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS); + .define(stgName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS); eventHub.update() - .withDataCaptureEnabled() - .withNewStorageAccountForCapturedData(storageAccountCreatable, "eventctr") - .apply(); + .withDataCaptureEnabled() + .withNewStorageAccountForCapturedData(storageAccountCreatable, "eventctr") + .apply(); Assertions.assertTrue(eventHub.isDataCaptureEnabled()); Assertions.assertNotNull(eventHub.captureDestination()); @@ -516,26 +487,26 @@ public void canManageGeoDisasterRecoveryPairing() throws Throwable { final String namespaceName2 = generateRandomResourceName("ns", 14); EventHubNamespace primaryNamespace = eventHubsManager.namespaces() - .define(namespaceName1) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .create(); + .define(namespaceName1) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .create(); EventHubNamespace secondaryNamespace = eventHubsManager.namespaces() - .define(namespaceName2) - .withRegion(Region.US_NORTH_CENTRAL) - .withExistingResourceGroup(rgName) - .create(); + .define(namespaceName2) + .withRegion(Region.US_NORTH_CENTRAL) + .withExistingResourceGroup(rgName) + .create(); Exception exception = null; Exception breakingFailed = null; EventHubDisasterRecoveryPairing pairing = null; try { pairing = eventHubsManager.eventHubDisasterRecoveryPairings() - .define(geodrName) - .withExistingPrimaryNamespace(primaryNamespace) - .withExistingSecondaryNamespace(secondaryNamespace) - .create(); + .define(geodrName) + .withExistingPrimaryNamespace(primaryNamespace) + .withExistingSecondaryNamespace(secondaryNamespace) + .create(); while (pairing.provisioningState() != ProvisioningStateDR.SUCCEEDED) { pairing = pairing.refresh(); @@ -545,7 +516,6 @@ public void canManageGeoDisasterRecoveryPairing() throws Throwable { } } - Assertions.assertTrue(pairing.name().equalsIgnoreCase(geodrName)); Assertions.assertTrue(pairing.primaryNamespaceResourceGroupName().equalsIgnoreCase(rgName)); Assertions.assertTrue(pairing.primaryNamespaceName().equalsIgnoreCase(primaryNamespace.name())); @@ -562,8 +532,8 @@ public void canManageGeoDisasterRecoveryPairing() throws Throwable { } EventHubDisasterRecoveryPairings pairingsCol = eventHubsManager.eventHubDisasterRecoveryPairings(); - PagedIterable pairings = pairingsCol - .listByNamespace(primaryNamespace.resourceGroupName(), primaryNamespace.name()); + PagedIterable pairings + = pairingsCol.listByNamespace(primaryNamespace.resourceGroupName(), primaryNamespace.name()); Assertions.assertTrue(TestUtilities.getSize(pairings) > 0); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml index 80d4cf58489b1..5bd569c151c24 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml @@ -47,6 +47,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/KeyVaultManager.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/KeyVaultManager.java index 04736f2270d49..47d73b1ef5f49 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/KeyVaultManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/KeyVaultManager.java @@ -49,8 +49,7 @@ public static Configurable configure() { public static KeyVaultManager authenticate(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); - return authenticate( - HttpPipelineProvider.buildHttpPipeline(credential, profile), profile); + return authenticate(HttpPipelineProvider.buildHttpPipeline(credential, profile), profile); } /** @@ -81,19 +80,13 @@ public interface Configurable extends AzureConfigurable { /** The implementation for Configurable interface. */ private static final class ConfigurableImpl extends AzureConfigurableImpl implements Configurable { public KeyVaultManager authenticate(TokenCredential credential, AzureProfile profile) { - return KeyVaultManager - .authenticate( - buildHttpPipeline(credential, profile), profile); + return KeyVaultManager.authenticate(buildHttpPipeline(credential, profile), profile); } } - private KeyVaultManager( - final HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new KeyVaultManagementClientBuilder() - .pipeline(httpPipeline) + private KeyVaultManager(final HttpPipeline httpPipeline, AzureProfile profile) { + super(httpPipeline, profile, + new KeyVaultManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); @@ -117,12 +110,12 @@ public ManagedHsms managedHsms() { return managedHsms; } -// /** -// * Creates a new RestClientBuilder instance from the RestClient used by Manager. -// * -// * @return the new RestClientBuilder instance created from the RestClient used by Manager -// */ -// RestClientBuilder newRestClientBuilder() { -// return restClient.newBuilder(); -// } + // /** + // * Creates a new RestClientBuilder instance from the RestClient used by Manager. + // * + // * @return the new RestClientBuilder instance created from the RestClient used by Manager + // */ + // RestClientBuilder newRestClientBuilder() { + // return restClient.newBuilder(); + // } } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/AccessPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/AccessPolicyImpl.java index 4e1e733e1d7d5..ccf714eb3a741 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/AccessPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/AccessPolicyImpl.java @@ -22,10 +22,8 @@ /** Implementation for AccessPolicy and its parent interfaces. */ class AccessPolicyImpl extends ChildResourceImpl - implements AccessPolicy, - AccessPolicy.Definition, - AccessPolicy.UpdateDefinition, - AccessPolicy.Update { + implements AccessPolicy, AccessPolicy.Definition, + AccessPolicy.UpdateDefinition, AccessPolicy.Update { private String userPrincipalName; private String servicePrincipalName; diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeyImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeyImpl.java index 98bfc7558bf78..cf8caf408a31a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeyImpl.java @@ -86,12 +86,10 @@ private void init(boolean createNewCryptographyClient) { if (innerModel() != null) { updateKeyRequest.keyProperties = innerModel(); if (createNewCryptographyClient) { - cryptographyClient = - new CryptographyClientBuilder() - .keyIdentifier(innerModel().getId()) - .pipeline(httpPipeline) - .serviceVersion(CryptographyServiceVersion.V7_2) - .buildAsyncClient(); + cryptographyClient = new CryptographyClientBuilder().keyIdentifier(innerModel().getId()) + .pipeline(httpPipeline) + .serviceVersion(CryptographyServiceVersion.V7_2) + .buildAsyncClient(); } } } @@ -141,9 +139,7 @@ public PagedIterable listVersions() { @Override public PagedFlux listVersionsAsync() { - return PagedConverter.mapPage(keyClient - .listPropertiesOfKeyVersions(this.name()), - this::wrapModel); + return PagedConverter.mapPage(keyClient.listPropertiesOfKeyVersions(this.name()), this::wrapModel); } @Override @@ -257,14 +253,12 @@ public Mono createResourceAsync() { } else { mono = keyClient.importKey(importKeyRequest); } - return mono - .map( - keyVaultKey -> { - this.setInner(keyVaultKey.getProperties()); - this.jsonWebKey = keyVaultKey.getKey(); - init(true); - return this; - }); + return mono.map(keyVaultKey -> { + this.setInner(keyVaultKey.getProperties()); + this.jsonWebKey = keyVaultKey.getKey(); + init(true); + return this; + }); } @Override @@ -272,39 +266,26 @@ public Mono updateResourceAsync() { UpdateKeyOptions optionsToUpdate = updateKeyRequest; Mono mono = Mono.just(this); if (createKeyRequest != null || importKeyRequest != null) { - mono = - createResourceAsync() - .then( - Mono - .fromCallable( - () -> { - // merge optionsToUpdate into refreshed updateKeyRequest - updateKeyRequest - .keyProperties - .setEnabled(optionsToUpdate.keyProperties.isEnabled()); - updateKeyRequest - .keyProperties - .setExpiresOn(optionsToUpdate.keyProperties.getExpiresOn()); - updateKeyRequest - .keyProperties - .setNotBefore(optionsToUpdate.keyProperties.getNotBefore()); - updateKeyRequest.keyProperties.setTags(optionsToUpdate.keyProperties.getTags()); - updateKeyRequest.keyOperations = optionsToUpdate.keyOperations; - return this; - })); + mono = createResourceAsync().then(Mono.fromCallable(() -> { + // merge optionsToUpdate into refreshed updateKeyRequest + updateKeyRequest.keyProperties.setEnabled(optionsToUpdate.keyProperties.isEnabled()); + updateKeyRequest.keyProperties.setExpiresOn(optionsToUpdate.keyProperties.getExpiresOn()); + updateKeyRequest.keyProperties.setNotBefore(optionsToUpdate.keyProperties.getNotBefore()); + updateKeyRequest.keyProperties.setTags(optionsToUpdate.keyProperties.getTags()); + updateKeyRequest.keyOperations = optionsToUpdate.keyOperations; + return this; + })); } - return mono - .then( - keyClient - .updateKeyProperties( - updateKeyRequest.keyProperties, updateKeyRequest.keyOperations.toArray(new KeyOperation[0])) - .map( - keyVaultKey -> { - this.setInner(keyVaultKey.getProperties()); - this.jsonWebKey = keyVaultKey.getKey(); - init(false); - return this; - })); + return mono.then( + keyClient + .updateKeyProperties(updateKeyRequest.keyProperties, + updateKeyRequest.keyOperations.toArray(new KeyOperation[0])) + .map(keyVaultKey -> { + this.setInner(keyVaultKey.getProperties()); + this.jsonWebKey = keyVaultKey.getKey(); + init(false); + return this; + })); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeysImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeysImpl.java index 70cd8c16269a9..9f4addb5b0ade 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeysImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/KeysImpl.java @@ -41,6 +41,7 @@ public KeyImpl define(String name) { protected KeyImpl wrapModel(String name) { return new KeyImpl(name, new KeyProperties(), httpPipeline, keyClient); } + @Override public Key getById(String id) { return getByIdAsync(id).block(); @@ -71,20 +72,14 @@ protected KeyImpl wrapModel(KeyVaultKey keyVaultKey) { @Override public Mono deleteByIdAsync(String id) { String name = nameFromId(id); - return inner - .beginDeleteKey(name) - .last() - .flatMap( - asyncPollResponse -> { - if (asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - return asyncPollResponse.getFinalResult(); - } else { - return Mono - .error( - new RuntimeException( - "polling completed unsuccessfully with status:" + asyncPollResponse.getStatus())); - } - }); + return inner.beginDeleteKey(name).last().flatMap(asyncPollResponse -> { + if (asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + return asyncPollResponse.getFinalResult(); + } else { + return Mono.error(new RuntimeException( + "polling completed unsuccessfully with status:" + asyncPollResponse.getStatus())); + } + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmImpl.java index b0a28067a2b17..2429f251afe5e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmImpl.java @@ -35,8 +35,7 @@ /** * Implementation for Managed Hardware Security Module and its parent interfaces. */ -class ManagedHsmImpl - extends GroupableResourceImpl +class ManagedHsmImpl extends GroupableResourceImpl implements ManagedHsm { private KeyAsyncClient keyClient; private final HttpPipeline mhsmHttpPipeline; @@ -45,8 +44,7 @@ class ManagedHsmImpl super(name, innerObject, manager); mhsmHttpPipeline = manager().httpPipeline(); if (innerModel().properties() != null && innerModel().properties().hsmUri() != null) { - keyClient = new KeyClientBuilder() - .pipeline(mhsmHttpPipeline) + keyClient = new KeyClientBuilder().pipeline(mhsmHttpPipeline) .vaultUrl(innerModel().properties().hsmUri()) .serviceVersion(KeyServiceVersion.V7_2) .buildAsyncClient(); @@ -59,7 +57,8 @@ class ManagedHsmImpl */ @Override public Mono createResourceAsync() { - throw new UnsupportedOperationException("method [createResourceAsync] not implemented in class [com.azure.resourcemanager.keyvault.implementation.ManagedHsmImpl]"); + throw new UnsupportedOperationException( + "method [createResourceAsync] not implemented in class [com.azure.resourcemanager.keyvault.implementation.ManagedHsmImpl]"); } @Override @@ -156,11 +155,16 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - Mono>> retList = this.manager().serviceClient().getPrivateLinkResources() + Mono>> retList = this.manager() + .serviceClient() + .getPrivateLinkResources() .listByVaultWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(ManagedHsmImpl.PrivateLinkResourceImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue() + .value() + .stream() + .map(ManagedHsmImpl.PrivateLinkResourceImpl::new) + .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -171,10 +175,12 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().putAsync( - this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .putAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED))) .then(); } @@ -185,10 +191,12 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().putAsync( - this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.REJECTED))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .putAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED))) .then(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmsImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmsImpl.java index df80105a373a5..096904faad50c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/ManagedHsmsImpl.java @@ -63,8 +63,8 @@ public PagedIterable listByResourceGroup(String resourceGroupName) { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretImpl.java index c82dd6f664b5b..8e44eb1769c0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretImpl.java @@ -97,10 +97,7 @@ public PagedIterable listVersions() { @Override public PagedFlux listVersionsAsync() { - return PagedConverter.mapPage(vault - .secretClient() - .listPropertiesOfSecretVersions(name()), - this::wrapModel); + return PagedConverter.mapPage(vault.secretClient().listPropertiesOfSecretVersions(name()), this::wrapModel); } @Override @@ -126,33 +123,25 @@ public boolean isInCreateMode() { public Mono createResourceAsync() { KeyVaultSecret newSecret = new KeyVaultSecret(this.name(), secretValueToSet); newSecret.setProperties(this.attributes()); - return vault - .secretClient() - .setSecret(newSecret) - .map( - keyVaultSecret -> { - this.setInner(keyVaultSecret.getProperties()); - this.secretValue = keyVaultSecret.getValue(); - secretValueToSet = null; - return this; - }); + return vault.secretClient().setSecret(newSecret).map(keyVaultSecret -> { + this.setInner(keyVaultSecret.getProperties()); + this.secretValue = keyVaultSecret.getValue(); + secretValueToSet = null; + return this; + }); } @Override public Mono updateResourceAsync() { if (secretValueToSet == null) { // if no update on value, just update properties - return vault - .secretClient() - .updateSecretProperties(this.innerModel()) - .map( - p -> { - this.setInner(p); - if (!p.isEnabled()) { - secretValue = null; - } - return this; - }); + return vault.secretClient().updateSecretProperties(this.innerModel()).map(p -> { + this.setInner(p); + if (!p.isEnabled()) { + secretValue = null; + } + return this; + }); } else { return this.createResourceAsync(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretsImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretsImpl.java index fef022b714bf5..a6772a6d354c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/SecretsImpl.java @@ -81,20 +81,14 @@ protected SecretImpl wrapModel(KeyVaultSecret keyVaultSecret) { @Override public Mono deleteByIdAsync(String id) { String name = nameFromId(id); - return inner - .beginDeleteSecret(name) - .last() - .flatMap( - asyncPollResponse -> { - if (asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - return asyncPollResponse.getFinalResult(); - } else { - return Mono - .error( - new RuntimeException( - "polling completed unsuccessfully with status:" + asyncPollResponse.getStatus())); - } - }); + return inner.beginDeleteSecret(name).last().flatMap(asyncPollResponse -> { + if (asyncPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + return asyncPollResponse.getFinalResult(); + } else { + return Mono.error(new RuntimeException( + "polling completed unsuccessfully with status:" + asyncPollResponse.getStatus())); + } + }); } @Override @@ -161,8 +155,8 @@ private Mono updateSecretEnableDisableAsync(String name, String version, mockSecret.put("id", mockId); SerializerAdapter serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); String json = serializerAdapter.serialize(mockSecret, SerializerEncoding.JSON); - SecretProperties secretProperties = serializerAdapter.deserialize(json, SecretProperties.class, - SerializerEncoding.JSON); + SecretProperties secretProperties + = serializerAdapter.deserialize(json, SecretProperties.class, SerializerEncoding.JSON); secretProperties.setEnabled(enabled); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultImpl.java index 70bc5eaff5c57..9e5bb60d99333 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultImpl.java @@ -88,18 +88,14 @@ class VaultImpl extends GroupableResourceImpl> populateAccessPolicies() { if (accessPolicy.userPrincipalName() != null) { observables .add( - authorizationManager - .users() + authorizationManager.users() .getByNameAsync(accessPolicy.userPrincipalName()) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) .doOnNext(user -> accessPolicy.forObjectId(user.id())) .switchIfEmpty( - Mono - .error( - new ManagementException( - String - .format( - "User principal name %s is not found in tenant %s", - accessPolicy.userPrincipalName(), - authorizationManager.tenantId()), - null)))); + Mono.error(new ManagementException( + String.format("User principal name %s is not found in tenant %s", + accessPolicy.userPrincipalName(), authorizationManager.tenantId()), + null)))); } else if (accessPolicy.servicePrincipalName() != null) { observables .add( - authorizationManager - .servicePrincipals() + authorizationManager.servicePrincipals() .getByNameAsync(accessPolicy.servicePrincipalName()) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) .doOnNext(sp -> accessPolicy.forObjectId(sp.id())) .switchIfEmpty( - Mono - .error( - new ManagementException( - String - .format( - "Service principal name %s is not found in tenant %s", - accessPolicy.servicePrincipalName(), - authorizationManager.tenantId()), - null)))); + Mono.error(new ManagementException( + String.format("Service principal name %s is not found in tenant %s", + accessPolicy.servicePrincipalName(), authorizationManager.tenantId()), + null)))); } else { - throw logger.logExceptionAsError( - new IllegalArgumentException("Access policy must specify object ID.")); + throw logger + .logExceptionAsError(new IllegalArgumentException("Access policy must specify object ID.")); } } } @@ -385,27 +369,21 @@ private Mono> populateAccessPolicies() { @Override public Mono createResourceAsync() { final VaultsClient client = this.manager().serviceClient().getVaults(); - return populateAccessPolicies() - .then( - Mono - .defer( - () -> { - VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters(); - parameters.withLocation(regionName()); - parameters.withProperties(innerModel().properties()); - parameters.withTags(innerModel().tags()); - parameters.properties().withAccessPolicies(new ArrayList<>()); - for (AccessPolicy accessPolicy : accessPolicies) { - parameters.properties().accessPolicies().add(accessPolicy.innerModel()); - } - return client.createOrUpdateAsync(resourceGroupName(), this.name(), parameters); - })) - .map( - inner -> { - this.setInner(inner); - init(); - return this; - }); + return populateAccessPolicies().then(Mono.defer(() -> { + VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters(); + parameters.withLocation(regionName()); + parameters.withProperties(innerModel().properties()); + parameters.withTags(innerModel().tags()); + parameters.properties().withAccessPolicies(new ArrayList<>()); + for (AccessPolicy accessPolicy : accessPolicies) { + parameters.properties().accessPolicies().add(accessPolicy.innerModel()); + } + return client.createOrUpdateAsync(resourceGroupName(), this.name(), parameters); + })).map(inner -> { + this.setInner(inner); + init(); + return this; + }); } @Override @@ -536,11 +514,12 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - Mono>> retList = this.manager().serviceClient().getPrivateLinkResources() + Mono>> retList = this.manager() + .serviceClient() + .getPrivateLinkResources() .listByVaultWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(PrivateLinkResourceImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue().value().stream().map(PrivateLinkResourceImpl::new).collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -552,10 +531,12 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().putAsync( - this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .putAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED))) .then(); } @@ -566,10 +547,12 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return manager().serviceClient().getPrivateEndpointConnections().putAsync( - this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.REJECTED))) + return manager().serviceClient() + .getPrivateEndpointConnections() + .putAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED))) .then(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultsImpl.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultsImpl.java index af16384098e33..261728373ef1f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/implementation/VaultsImpl.java @@ -34,8 +34,8 @@ public class VaultsImpl extends GroupableResourcesImpl listByResourceGroup(String resourceGroupName) { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName, null)); } @@ -68,12 +68,11 @@ protected Mono deleteInnerAsync(String resourceGroupName, String name) { @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } return this.inner().deleteAsync(resourceGroupName, name); } @@ -134,8 +133,8 @@ public PagedFlux listDeletedAsync() { @Override public CheckNameAvailabilityResult checkNameAvailability(String name) { - return new CheckNameAvailabilityResultImpl(inner().checkNameAvailability( - new VaultCheckNameAvailabilityParameters().withName(name))); + return new CheckNameAvailabilityResultImpl( + inner().checkNameAvailability(new VaultCheckNameAvailabilityParameters().withName(name))); } @Override @@ -150,24 +149,18 @@ public Vault recoverSoftDeletedVault(String resourceGroupName, String vaultName, } @Override - public Mono recoverSoftDeletedVaultAsync( - final String resourceGroupName, final String vaultName, String location) { + public Mono recoverSoftDeletedVaultAsync(final String resourceGroupName, final String vaultName, + String location) { final KeyVaultManager manager = this.manager(); - return getDeletedAsync(vaultName, location) - .flatMap( - deletedVault -> { - VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters(); - parameters.withLocation(deletedVault.location()); - parameters.withTags(deletedVault.innerModel().properties().tags()); - parameters - .withProperties( - new VaultProperties() - .withCreateMode(CreateMode.RECOVER) - .withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.A)) - .withTenantId(UUID.fromString(tenantId))); - return inner() - .createOrUpdateAsync(resourceGroupName, vaultName, parameters) - .map(inner -> (Vault) new VaultImpl(inner.id(), inner, manager, authorizationManager)); - }); + return getDeletedAsync(vaultName, location).flatMap(deletedVault -> { + VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters(); + parameters.withLocation(deletedVault.location()); + parameters.withTags(deletedVault.innerModel().properties().tags()); + parameters.withProperties(new VaultProperties().withCreateMode(CreateMode.RECOVER) + .withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.A)) + .withTenantId(UUID.fromString(tenantId))); + return inner().createOrUpdateAsync(resourceGroupName, vaultName, parameters) + .map(inner -> (Vault) new VaultImpl(inner.id(), inner, manager, authorizationManager)); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Key.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Key.java index 288d5ea9a9092..6ab04bda9214c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Key.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Key.java @@ -375,12 +375,8 @@ interface WithTags { } /** The template for a key update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithKey, - UpdateStages.WithKeyOperations, - UpdateStages.WithAttributes, - UpdateStages.WithTags { + interface Update extends Appliable, UpdateStages.WithKey, UpdateStages.WithKeyOperations, + UpdateStages.WithAttributes, UpdateStages.WithTags { } /** The template for a key vault update operation, with a new key version to be created. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Keys.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Keys.java index 1d4b76a593b25..b735529c683fc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Keys.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Keys.java @@ -13,12 +13,8 @@ /** Entry point for Key Vault keys API. */ @Fluent -public interface Keys - extends SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - SupportsGettingByName, - SupportsListing { +public interface Keys extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, SupportsGettingByName, SupportsListing { /** * Gets a Key Vault key. * diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsm.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsm.java index f89c7f84fe334..2953b778f00c3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsm.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsm.java @@ -16,10 +16,8 @@ /** An immutable client-side representation of an Azure Managed Hardware Security Module. */ @Fluent -public interface ManagedHsm - extends GroupableResource, Refreshable, - SupportsListingPrivateLinkResource, - SupportsUpdatingPrivateEndpointConnection { +public interface ManagedHsm extends GroupableResource, Refreshable, + SupportsListingPrivateLinkResource, SupportsUpdatingPrivateEndpointConnection { /** @return the AAD tenant ID that should be used for authenticating requests to the managed HSM */ String tenantId(); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsms.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsms.java index da4f9d19c9d42..dd4f5ce8200e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsms.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/ManagedHsms.java @@ -14,11 +14,7 @@ /** Entry point for managed HSM management API. */ @Fluent -public interface ManagedHsms - extends SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsDeletingById, - HasManager { +public interface ManagedHsms extends SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingByResourceGroup, + SupportsDeletingById, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secret.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secret.java index dc54e70a7b675..86d1b3e4e8bcd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secret.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secret.java @@ -165,11 +165,7 @@ interface WithTags { } /** The template for a secret update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithValue, - UpdateStages.WithAttributes, - UpdateStages.WithContentType, - UpdateStages.WithTags { + interface Update extends Appliable, UpdateStages.WithValue, UpdateStages.WithAttributes, + UpdateStages.WithContentType, UpdateStages.WithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secrets.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secrets.java index 41e18fd83a1d9..a114c3c7b29d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secrets.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Secrets.java @@ -13,12 +13,8 @@ /** Entry point for Key Vault secrets API. */ @Fluent -public interface Secrets - extends SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - SupportsGettingByName, - SupportsListing { +public interface Secrets extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, SupportsGettingByName, SupportsListing { /** * Gets a Key Vault secret when the secret is enabled. * diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vault.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vault.java index 824b6b15ef8bd..dfc33acb75db1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vault.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vault.java @@ -20,10 +20,8 @@ /** An immutable client-side representation of an Azure Key Vault. */ @Fluent -public interface Vault - extends GroupableResource, Refreshable, Updatable, - SupportsListingPrivateLinkResource, - SupportsUpdatingPrivateEndpointConnection { +public interface Vault extends GroupableResource, Refreshable, + Updatable, SupportsListingPrivateLinkResource, SupportsUpdatingPrivateEndpointConnection { /** @return an authenticated Key Vault secret client */ SecretAsyncClient secretClient(); @@ -109,11 +107,8 @@ public interface Vault **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithAccessPolicy, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithAccessPolicy, + DefinitionStages.WithCreate { } /** Grouping of all the key vault definition stages. */ @@ -311,13 +306,9 @@ interface WithConfigurations { * A key vault definition with sufficient inputs to create a new storage account in the cloud, but exposing * additional optional inputs to specify. */ - interface WithCreate - extends Creatable, - GroupableResource.DefinitionWithTags, - DefinitionStages.WithSku, - DefinitionStages.WithNetworkRuleSet, - DefinitionStages.WithConfigurations, - DefinitionStages.WithAccessPolicy { + interface WithCreate extends Creatable, GroupableResource.DefinitionWithTags, + DefinitionStages.WithSku, DefinitionStages.WithNetworkRuleSet, DefinitionStages.WithConfigurations, + DefinitionStages.WithAccessPolicy { } } @@ -518,11 +509,7 @@ interface WithConfigurations { } /** The template for a key vault update operation, containing all the settings that can be modified. */ - interface Update - extends GroupableResource.UpdateWithTags, - Appliable, - UpdateStages.WithAccessPolicy, - UpdateStages.WithNetworkRuleSet, - UpdateStages.WithConfigurations { + interface Update extends GroupableResource.UpdateWithTags, Appliable, UpdateStages.WithAccessPolicy, + UpdateStages.WithNetworkRuleSet, UpdateStages.WithConfigurations { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vaults.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vaults.java index 86e710586bf21..fe84cc1a6408b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vaults.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/main/java/com/azure/resourcemanager/keyvault/models/Vaults.java @@ -19,14 +19,9 @@ /** Entry point for key vaults management API. */ @Fluent -public interface Vaults - extends SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface Vaults extends SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingByResourceGroup, HasManager { /** * Gets information about the deleted vaults in a subscription. diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyTests.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyTests.java index 3e4a9f8703b85..eb6096167ffec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyTests.java @@ -40,13 +40,11 @@ public void canCRUDKey() throws Exception { String keyName = generateRandomResourceName("key", 20); // Create - Key key = - vault - .keys() - .define(keyName) - .withKeyTypeToCreate(KeyType.RSA) - .withKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) - .create(); + Key key = vault.keys() + .define(keyName) + .withKeyTypeToCreate(KeyType.RSA) + .withKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) + .create(); Assertions.assertNotNull(key); Assertions.assertNotNull(key.id()); @@ -63,12 +61,10 @@ public void canCRUDKey() throws Exception { Assertions.assertEquals(1, key.getJsonWebKey().getKeyOps().size()); // New version - key = - key - .update() - .withKeyTypeToCreate(KeyType.RSA) - .withKeyOperations(KeyOperation.ENCRYPT, KeyOperation.DECRYPT, KeyOperation.SIGN) - .apply(); + key = key.update() + .withKeyTypeToCreate(KeyType.RSA) + .withKeyOperations(KeyOperation.ENCRYPT, KeyOperation.DECRYPT, KeyOperation.SIGN) + .apply(); Assertions.assertEquals(3, key.getJsonWebKey().getKeyOps().size()); @@ -77,8 +73,7 @@ public void canCRUDKey() throws Exception { Assertions.assertEquals(2, TestUtilities.getSize(keys)); // Create RSA key with size - key = vault - .keys() + key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.RSA) .withKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) @@ -90,8 +85,7 @@ public void canCRUDKey() throws Exception { Assertions.assertEquals(KeyType.RSA, key.getJsonWebKey().getKeyType()); // Create EC key with curve - key = vault - .keys() + key = vault.keys() .define(keyName) .withKeyTypeToCreate(KeyType.EC) .withKeyOperations(KeyOperation.SIGN, KeyOperation.VERIFY) @@ -114,12 +108,10 @@ public void canImportKey() throws Exception { Vault vault = createVault(); String keyName = generateRandomResourceName("key", 20); - Key key = - vault - .keys() - .define(keyName) - .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) - .create(); + Key key = vault.keys() + .define(keyName) + .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) + .create(); Assertions.assertNotNull(key); Assertions.assertNotNull(key.id()); @@ -135,12 +127,10 @@ public void canBackupAndRestore() throws Exception { Vault vault = createVault(); String keyName = generateRandomResourceName("key", 20); - Key key = - vault - .keys() - .define(keyName) - .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) - .create(); + Key key = vault.keys() + .define(keyName) + .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) + .create(); Assertions.assertNotNull(key); @@ -239,12 +229,10 @@ public void canWrapAndUnwrap() throws Exception { Vault vault = createVault(); String keyName = generateRandomResourceName("key", 20); - Key key = - vault - .keys() - .define(keyName) - .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) - .create(); + Key key = vault.keys() + .define(keyName) + .withLocalKeyToImport(JsonWebKey.fromRsa(KeyPairGenerator.getInstance("RSA").generateKeyPair())) + .create(); SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); @@ -259,17 +247,15 @@ public void canWrapAndUnwrap() throws Exception { private Vault createVault() throws Exception { String vaultName = generateRandomResourceName("vault", 20); - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowKeyAllPermissions() - .attach() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowKeyAllPermissions() + .attach() + .create(); Assertions.assertNotNull(vault); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyVaultManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyVaultManagementTest.java index 6f3af53267884..39c430a982eeb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyVaultManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/KeyVaultManagementTest.java @@ -29,21 +29,10 @@ public class KeyVaultManagementTest extends ResourceManagerTestProxyTestBase { protected String vaultName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/ManagedHsmTests.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/ManagedHsmTests.java index 792ab2d03e05a..111fd731b7ad7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/ManagedHsmTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/ManagedHsmTests.java @@ -52,13 +52,11 @@ public void canCrudManagedHsms() { try { // listByResourceGroups - PagedIterable hsms = keyVaultManager.managedHsms() - .listByResourceGroup(rgName); + PagedIterable hsms = keyVaultManager.managedHsms().listByResourceGroup(rgName); Assertions.assertTrue(hsms.stream().anyMatch(mhsm -> mhsm.name().equals(mhsmName))); // getByResourceGroup - ManagedHsm hsm = keyVaultManager.managedHsms() - .getByResourceGroup(rgName, managedHsm.name()); + ManagedHsm hsm = keyVaultManager.managedHsms().getByResourceGroup(rgName, managedHsm.name()); // ManagedHsm properties // The Azure Active Directory tenant ID that should be used for authenticating requests to the managed HSM pool. @@ -113,27 +111,21 @@ private ManagedHsm createManagedHsm(String mhsmName) { String objectId = azureCliSignedInUser().id(); keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create(); - ManagedHsmInner inner = keyVaultManager.serviceClient() - .getManagedHsms() - .createOrUpdate( - rgName, - mhsmName, - new ManagedHsmInner() - .withLocation(Region.US_EAST2.name()) + ManagedHsmInner inner + = keyVaultManager.serviceClient() + .getManagedHsms() + .createOrUpdate(rgName, mhsmName, new ManagedHsmInner().withLocation(Region.US_EAST2.name()) .withSku( new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1)) .withProperties( - new ManagedHsmProperties() - .withTenantId(UUID.fromString(authorizationManager.tenantId())) + new ManagedHsmProperties().withTenantId(UUID.fromString(authorizationManager.tenantId())) .withInitialAdminObjectIds(Arrays.asList(objectId)) .withEnableSoftDelete(true) .withSoftDeleteRetentionInDays(7) .withEnablePurgeProtection(false)), // DO NOT set it to true, otherwise you can't purge the instance - Context.NONE); + Context.NONE); - keyVaultManager.serviceClient() - .getManagedHsms() - .createOrUpdate(rgName, inner.name(), inner); + keyVaultManager.serviceClient().getManagedHsms().createOrUpdate(rgName, inner.name(), inner); return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/SecretTests.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/SecretTests.java index cdd3c0add94ed..a8c541c07f791 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/SecretTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/SecretTests.java @@ -24,17 +24,15 @@ public void canCRUDSecret() throws Exception { String vaultName = generateRandomResourceName("vault", 20); String secretName = generateRandomResourceName("secret", 20); - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowSecretAllPermissions() - .attach() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowSecretAllPermissions() + .attach() + .create(); Assertions.assertNotNull(vault); @@ -70,17 +68,15 @@ public void canDisableSecret() throws Exception { String vaultName = generateRandomResourceName("vault", 20); String secretName = generateRandomResourceName("secret", 20); - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowSecretAllPermissions() - .attach() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowSecretAllPermissions() + .attach() + .create(); Assertions.assertNotNull(vault); @@ -91,19 +87,14 @@ public void canDisableSecret() throws Exception { final String type2 = "Other type"; // version - Secret secret = vault.secrets().define(secretName) - .withValue(value1) - .create(); + Secret secret = vault.secrets().define(secretName).withValue(value1).create(); String version1 = secret.attributes().getVersion(); Assertions.assertNotNull(secret); Assertions.assertNotNull(secret.id()); // new version - Secret secret2 = vault.secrets().define(secretName) - .withValue(value2) - .withContentType(type2) - .create(); + Secret secret2 = vault.secrets().define(secretName).withValue(value2).withContentType(type2).create(); String version2 = secret2.attributes().getVersion(); // disable secret diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/VaultTests.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/VaultTests.java index b644e8d12ee0c..edd251b3b24f4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/VaultTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/test/java/com/azure/resourcemanager/keyvault/VaultTests.java @@ -27,37 +27,35 @@ public void canCRUDVault() throws Exception { // Create user service principal String sp = generateRandomResourceName("sp", 20); String us = generateRandomResourceName("us", 20); - ServicePrincipal servicePrincipal = - authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); + ServicePrincipal servicePrincipal + = authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); - ActiveDirectoryUser user = - authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); + ActiveDirectoryUser user + = authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); try { // CREATE - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(sp) - .allowKeyPermissions(KeyPermissions.LIST) - .allowSecretAllPermissions() - .allowCertificatePermissions(CertificatePermissions.GET) - .attach() - .defineAccessPolicy() - .forUser(us) - .allowKeyAllPermissions() - .allowSecretAllPermissions() - .allowCertificatePermissions( - CertificatePermissions.GET, CertificatePermissions.LIST, CertificatePermissions.CREATE) - .attach() - // .withBypass(NetworkRuleBypassOptions.AZURE_SERVICES) - .withAccessFromAzureServices() - .withAccessFromIpAddress("0.0.0.0/0") - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(sp) + .allowKeyPermissions(KeyPermissions.LIST) + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET) + .attach() + .defineAccessPolicy() + .forUser(us) + .allowKeyAllPermissions() + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST, + CertificatePermissions.CREATE) + .attach() + // .withBypass(NetworkRuleBypassOptions.AZURE_SERVICES) + .withAccessFromAzureServices() + .withAccessFromIpAddress("0.0.0.0/0") + .create(); Assertions.assertNotNull(vault); //Assertions.assertFalse(vault.softDeleteEnabled()); Assertions.assertEquals(vault.networkRuleSet().bypass(), NetworkRuleBypassOptions.AZURE_SERVICES); @@ -67,14 +65,11 @@ public void canCRUDVault() throws Exception { Assertions.assertNotNull(vault); for (AccessPolicy policy : vault.accessPolicies()) { if (policy.objectId().equals(servicePrincipal.id())) { - Assertions - .assertArrayEquals( - new KeyPermissions[] {KeyPermissions.LIST}, policy.permissions().keys().toArray()); + Assertions.assertArrayEquals(new KeyPermissions[] { KeyPermissions.LIST }, + policy.permissions().keys().toArray()); Assertions.assertEquals(SecretPermissions.values().size(), policy.permissions().secrets().size()); - Assertions - .assertArrayEquals( - new CertificatePermissions[] {CertificatePermissions.GET}, - policy.permissions().certificates().toArray()); + Assertions.assertArrayEquals(new CertificatePermissions[] { CertificatePermissions.GET }, + policy.permissions().certificates().toArray()); } if (policy.objectId().equals(user.id())) { Assertions.assertEquals(KeyPermissions.values().size(), policy.permissions().keys().size()); @@ -92,8 +87,7 @@ public void canCRUDVault() throws Exception { } Assertions.assertNotNull(vault); // UPDATE - vault - .update() + vault.update() .updateAccessPolicy(servicePrincipal.id()) .allowKeyAllPermissions() .disallowSecretAllPermissions() @@ -105,9 +99,8 @@ public void canCRUDVault() throws Exception { if (policy.objectId().equals(servicePrincipal.id())) { Assertions.assertEquals(KeyPermissions.values().size(), policy.permissions().keys().size()); Assertions.assertEquals(0, policy.permissions().secrets().size()); - Assertions - .assertEquals( - CertificatePermissions.values().size(), policy.permissions().certificates().size()); + Assertions.assertEquals(CertificatePermissions.values().size(), + policy.permissions().certificates().size()); } } @@ -121,8 +114,10 @@ public void canCRUDVault() throws Exception { } } - @Test void canCRUDVaultWithRbac() { - Vault vault = keyVaultManager.vaults().define(vaultName) + @Test + void canCRUDVaultWithRbac() { + Vault vault = keyVaultManager.vaults() + .define(vaultName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withRoleBasedAccessControl() @@ -130,9 +125,7 @@ public void canCRUDVault() throws Exception { Assertions.assertTrue(vault.roleBasedAccessControlEnabled()); - vault.update() - .withoutRoleBasedAccessControl() - .apply(); + vault.update().withoutRoleBasedAccessControl().apply(); Assertions.assertFalse(vault.roleBasedAccessControlEnabled()); } @@ -142,34 +135,32 @@ public void canCRUDVaultAsync() throws Exception { // Create user service principal String sp = generateRandomResourceName("sp", 20); String us = generateRandomResourceName("us", 20); - ServicePrincipal servicePrincipal = - authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); + ServicePrincipal servicePrincipal + = authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); - ActiveDirectoryUser user = - authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); + ActiveDirectoryUser user + = authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); try { // CREATE - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(sp) - .allowKeyPermissions(KeyPermissions.LIST) - .allowSecretAllPermissions() - .allowCertificatePermissions(CertificatePermissions.GET) - .attach() - .defineAccessPolicy() - .forUser(us) - .allowKeyAllPermissions() - .allowSecretAllPermissions() - .allowCertificatePermissions( - CertificatePermissions.GET, CertificatePermissions.LIST, CertificatePermissions.CREATE) - .attach() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(sp) + .allowKeyPermissions(KeyPermissions.LIST) + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET) + .attach() + .defineAccessPolicy() + .forUser(us) + .allowKeyAllPermissions() + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST, + CertificatePermissions.CREATE) + .attach() + .create(); Assertions.assertNotNull(vault); //Assertions.assertFalse(vault.softDeleteEnabled()); // GET @@ -177,14 +168,11 @@ public void canCRUDVaultAsync() throws Exception { Assertions.assertNotNull(vault); for (AccessPolicy policy : vault.accessPolicies()) { if (policy.objectId().equals(servicePrincipal.id())) { - Assertions - .assertArrayEquals( - new KeyPermissions[] {KeyPermissions.LIST}, policy.permissions().keys().toArray()); + Assertions.assertArrayEquals(new KeyPermissions[] { KeyPermissions.LIST }, + policy.permissions().keys().toArray()); Assertions.assertEquals(SecretPermissions.values().size(), policy.permissions().secrets().size()); - Assertions - .assertArrayEquals( - new CertificatePermissions[] {CertificatePermissions.GET}, - policy.permissions().certificates().toArray()); + Assertions.assertArrayEquals(new CertificatePermissions[] { CertificatePermissions.GET }, + policy.permissions().certificates().toArray()); } if (policy.objectId().equals(user.id())) { Assertions.assertEquals(KeyPermissions.values().size(), policy.permissions().keys().size()); @@ -193,8 +181,8 @@ public void canCRUDVaultAsync() throws Exception { } } // LIST - PagedIterable vaults = - new PagedIterable<>(keyVaultManager.vaults().listByResourceGroupAsync(rgName)); + PagedIterable vaults + = new PagedIterable<>(keyVaultManager.vaults().listByResourceGroupAsync(rgName)); for (Vault v : vaults) { if (vaultName.equals(v.name())) { vault = v; @@ -203,8 +191,7 @@ public void canCRUDVaultAsync() throws Exception { } Assertions.assertNotNull(vault); // UPDATE - vault - .update() + vault.update() .updateAccessPolicy(servicePrincipal.id()) .allowKeyAllPermissions() .disallowSecretAllPermissions() @@ -216,9 +203,8 @@ public void canCRUDVaultAsync() throws Exception { if (policy.objectId().equals(servicePrincipal.id())) { Assertions.assertEquals(KeyPermissions.values().size(), policy.permissions().keys().size()); Assertions.assertEquals(0, policy.permissions().secrets().size()); - Assertions - .assertEquals( - CertificatePermissions.values().size(), policy.permissions().certificates().size()); + Assertions.assertEquals(CertificatePermissions.values().size(), + policy.permissions().certificates().size()); } } @@ -238,33 +224,31 @@ public void canEnableSoftDeleteAndPurge() throws InterruptedException { String sp = generateRandomResourceName("sp", 20); String us = generateRandomResourceName("us", 20); - ServicePrincipal servicePrincipal = - authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); + ServicePrincipal servicePrincipal + = authorizationManager.servicePrincipals().define(sp).withNewApplication().create(); - ActiveDirectoryUser user = - authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); + ActiveDirectoryUser user + = authorizationManager.users().define(us).withEmailAlias(us).withPassword(password()).create(); try { - Vault vault = - keyVaultManager - .vaults() - .define(otherVaultName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(sp) - .allowKeyPermissions(KeyPermissions.LIST) - .allowSecretAllPermissions() - .allowCertificatePermissions(CertificatePermissions.GET) - .attach() - .defineAccessPolicy() - .forUser(us) - .allowKeyAllPermissions() - .allowSecretAllPermissions() - .allowCertificatePermissions( - CertificatePermissions.GET, CertificatePermissions.LIST, CertificatePermissions.CREATE) - .attach() - .create(); + Vault vault = keyVaultManager.vaults() + .define(otherVaultName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(sp) + .allowKeyPermissions(KeyPermissions.LIST) + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET) + .attach() + .defineAccessPolicy() + .forUser(us) + .allowKeyAllPermissions() + .allowSecretAllPermissions() + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST, + CertificatePermissions.CREATE) + .attach() + .create(); Assertions.assertTrue(vault.softDeleteEnabled()); keyVaultManager.vaults().deleteByResourceGroup(rgName, otherVaultName); @@ -285,7 +269,8 @@ public void canEnableSoftDeleteAndPurge() throws InterruptedException { @Test public void canDisablePublicNetworkAccess() { - Vault vault = keyVaultManager.vaults().define(vaultName) + Vault vault = keyVaultManager.vaults() + .define(vaultName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() @@ -293,14 +278,14 @@ public void canDisablePublicNetworkAccess() { .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, vault.publicNetworkAccess()); - Assertions.assertEquals(PublicNetworkAccess.DISABLED, keyVaultManager.vaults().getById(vault.id()).publicNetworkAccess()); + Assertions.assertEquals(PublicNetworkAccess.DISABLED, + keyVaultManager.vaults().getById(vault.id()).publicNetworkAccess()); - vault.update() - .enablePublicNetworkAccess() - .apply(); + vault.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, vault.publicNetworkAccess()); - Assertions.assertEquals(PublicNetworkAccess.ENABLED, keyVaultManager.vaults().getById(vault.id()).publicNetworkAccess()); + Assertions.assertEquals(PublicNetworkAccess.ENABLED, + keyVaultManager.vaults().getById(vault.id()).publicNetworkAccess()); } private void assertVaultDeleted(String name, String location) { diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml index f891ca4459b06..6a7d5cee7a3ab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml @@ -49,6 +49,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/MonitorManager.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/MonitorManager.java index 4cc5fc531b51f..04ad654729fab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/MonitorManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/MonitorManager.java @@ -45,6 +45,7 @@ public final class MonitorManager extends Manager { public static Configurable configure() { return new MonitorManager.ConfigurableImpl(); } + /** * Creates an instance of MonitorManager that exposes Monitor API entry points. * @@ -57,6 +58,7 @@ public static MonitorManager authenticate(TokenCredential credential, AzureProfi Objects.requireNonNull(profile, "'profile' cannot be null."); return authenticate(HttpPipelineProvider.buildHttpPipeline(credential, profile), profile); } + /** * Creates an instance of MonitorManager that exposes Monitor API entry points. * @@ -138,11 +140,8 @@ public MonitorManager authenticate(TokenCredential credential, AzureProfile prof } private MonitorManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new MonitorClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new MonitorClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupImpl.java index 55df278cb2b0b..269ae2c27cf5a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupImpl.java @@ -25,10 +25,8 @@ /** Implementation for ActionGroup. */ class ActionGroupImpl extends GroupableResourceImpl - implements ActionGroup, - ActionGroup.Definition, - ActionGroup.Update, - ActionGroup.UpdateStages.WithActionUpdateDefinition { + implements ActionGroup, ActionGroup.Definition, ActionGroup.Update, + ActionGroup.UpdateStages.WithActionUpdateDefinition { private static final String EMAIL_SUFFIX = "_-EmailAction-"; private static final String SMS_SUFFIX = "_-SMSAction-"; private static final String APP_ACTION_SUFFIX = "_-AzureAppAction-"; @@ -64,8 +62,7 @@ class ActionGroupImpl this.itsmReceivers = new TreeMap<>(); if (isInCreateMode()) { this.innerModel().withEnabled(true); - this - .innerModel() + this.innerModel() .withGroupShortName(this.name().substring(0, (this.name().length() > 12) ? 12 : this.name().length())); } else { this.withExistingResourceGroup(ResourceUtils.groupFromResourceId(this.id())); @@ -221,8 +218,7 @@ public ActionGroupImpl withShortName(String shortName) { @Override public Mono createResourceAsync() { this.innerModel().withLocation("global"); - return this - .manager() + return this.manager() .serviceClient() .getActionGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -231,7 +227,9 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getActionGroups() + return this.manager() + .serviceClient() + .getActionGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @@ -276,8 +274,8 @@ public ActionGroupImpl withWebhook(String serviceUri) { } @Override - public ActionGroupImpl withItsm( - String workspaceId, String connectionId, String ticketConfiguration, String region) { + public ActionGroupImpl withItsm(String workspaceId, String connectionId, String ticketConfiguration, + String region) { this.withoutItsm(); String compositeKey = this.actionReceiverPrefix + ITSM_SUFFIX; @@ -306,8 +304,8 @@ public ActionGroupImpl withPushNotification(String emailAddress) { } @Override - public ActionGroupImpl withAutomationRunbook( - String automationAccountId, String runbookName, String webhookResourceId, boolean isGlobalRunbook) { + public ActionGroupImpl withAutomationRunbook(String automationAccountId, String runbookName, + String webhookResourceId, boolean isGlobalRunbook) { this.withoutAutomationRunbook(); String compositeKey = this.actionReceiverPrefix + RUN_BOOK_SUFFIX; diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupsImpl.java index 3e4c2f1731d20..9a7e889e41430 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActionGroupsImpl.java @@ -13,9 +13,8 @@ import reactor.core.publisher.Mono; /** Implementation for {@link ActionGroups}. */ -public class ActionGroupsImpl - extends TopLevelModifiableResourcesImpl< - ActionGroup, ActionGroupImpl, ActionGroupResourceInner, ActionGroupsClient, MonitorManager> +public class ActionGroupsImpl extends + TopLevelModifiableResourcesImpl implements ActionGroups { public ActionGroupsImpl(final MonitorManager monitorManager) { @@ -42,11 +41,14 @@ public ActionGroupImpl define(String name) { @Override public void enableReceiver(String resourceGroupName, String actionGroupName, String receiverName) { - this.inner().enableReceiver(resourceGroupName, actionGroupName, new EnableRequest().withReceiverName(receiverName)); + this.inner() + .enableReceiver(resourceGroupName, actionGroupName, new EnableRequest().withReceiverName(receiverName)); } @Override public Mono enableReceiverAsync(String resourceGroupName, String actionGroupName, String receiverName) { - return this.inner().enableReceiverAsync(resourceGroupName, actionGroupName, new EnableRequest().withReceiverName(receiverName)); + return this.inner() + .enableReceiverAsync(resourceGroupName, actionGroupName, + new EnableRequest().withReceiverName(receiverName)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertImpl.java index 92bad715ae83a..e24022d1e9e6d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertImpl.java @@ -24,15 +24,13 @@ /** Implementation for ActivityLogAlert. */ class ActivityLogAlertImpl extends GroupableResourceImpl - implements ActivityLogAlert, - ActivityLogAlert.Definition, - ActivityLogAlert.Update, - ActivityLogAlert.UpdateStages.WithActivityLogUpdate { + implements ActivityLogAlert, ActivityLogAlert.Definition, ActivityLogAlert.Update, + ActivityLogAlert.UpdateStages.WithActivityLogUpdate { private Map conditions; - ActivityLogAlertImpl( - String name, final ActivityLogAlertResourceInner innerModel, final MonitorManager monitorManager) { + ActivityLogAlertImpl(String name, final ActivityLogAlertResourceInner innerModel, + final MonitorManager monitorManager) { super(name, innerModel, monitorManager); this.conditions = new TreeMap<>(); if (innerModel.condition() != null && innerModel.condition().allOf() != null) { @@ -90,8 +88,7 @@ public Mono createResourceAsync() { condition.allOf().add(alalc); } this.innerModel().withCondition(condition); - return this - .manager() + return this.manager() .serviceClient() .getActivityLogAlerts() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -100,8 +97,7 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getActivityLogAlerts() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertsImpl.java index c330e5bae4998..65b08864d3702 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogAlertsImpl.java @@ -11,9 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for {@link ActivityLogAlerts}. */ -class ActivityLogAlertsImpl - extends TopLevelModifiableResourcesImpl< - ActivityLogAlert, ActivityLogAlertImpl, ActivityLogAlertResourceInner, ActivityLogAlertsClient, MonitorManager> +class ActivityLogAlertsImpl extends + TopLevelModifiableResourcesImpl implements ActivityLogAlerts { ActivityLogAlertsImpl(final MonitorManager monitorManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogsImpl.java index 4aead50dcf084..51d7d3f7e6b43 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ActivityLogsImpl.java @@ -48,12 +48,14 @@ public ActivityLogsClient inner() { @Override public PagedIterable listEventCategories() { - return PagedConverter.mapPage(this.manager().serviceClient().getEventCategories().list(), LocalizableStringImpl::new); + return PagedConverter.mapPage(this.manager().serviceClient().getEventCategories().list(), + LocalizableStringImpl::new); } @Override public PagedFlux listEventCategoriesAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getEventCategories().listAsync(), LocalizableStringImpl::new); + return PagedConverter.mapPage(this.manager().serviceClient().getEventCategories().listAsync(), + LocalizableStringImpl::new); } @Override @@ -86,10 +88,8 @@ public ActivityLogsImpl withAllPropertiesInResponse() { public ActivityLogsImpl withResponseProperties(EventDataPropertyName... responseProperties) { this.responsePropertySelector.clear(); - this - .responsePropertySelector - .addAll( - Arrays.stream(responseProperties).map(EventDataPropertyName::toString).collect(Collectors.toList())); + this.responsePropertySelector.addAll( + Arrays.stream(responseProperties).map(EventDataPropertyName::toString).collect(Collectors.toList())); return this; } @@ -142,23 +142,19 @@ public PagedFlux executeAsync() { } private String getOdataFilterString() { - return String - .format( - "eventTimestamp ge '%s' and eventTimestamp le '%s'", - DateTimeFormatter.ISO_INSTANT.format(this.queryStartTime.atZoneSameInstant(ZoneOffset.UTC)), - DateTimeFormatter.ISO_INSTANT.format(this.queryEndTime.atZoneSameInstant(ZoneOffset.UTC))); + return String.format("eventTimestamp ge '%s' and eventTimestamp le '%s'", + DateTimeFormatter.ISO_INSTANT.format(this.queryStartTime.atZoneSameInstant(ZoneOffset.UTC)), + DateTimeFormatter.ISO_INSTANT.format(this.queryEndTime.atZoneSameInstant(ZoneOffset.UTC))); } private PagedIterable listEventData(String filter) { - return PagedConverter.mapPage(this.inner().list(filter, createPropertyFilter(), Context.NONE), EventDataImpl::new); + return PagedConverter.mapPage(this.inner().list(filter, createPropertyFilter(), Context.NONE), + EventDataImpl::new); } private PagedIterable listEventDataForTenant(String filter) { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getTenantActivityLogs() - .list(filter, createPropertyFilter(), Context.NONE), + return PagedConverter.mapPage( + this.manager().serviceClient().getTenantActivityLogs().list(filter, createPropertyFilter(), Context.NONE), EventDataImpl::new); } @@ -167,17 +163,14 @@ private PagedFlux listEventDataAsync(String filter) { } private PagedFlux listEventDataForTenantAsync(String filter) { - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getTenantActivityLogs() - .listAsync(filter, createPropertyFilter()), + return PagedConverter.mapPage( + this.manager().serviceClient().getTenantActivityLogs().listAsync(filter, createPropertyFilter()), EventDataImpl::new); } private String createPropertyFilter() { - String propertyFilter = - this.responsePropertySelector == null ? null : String.join(",", this.responsePropertySelector); + String propertyFilter + = this.responsePropertySelector == null ? null : String.join(",", this.responsePropertySelector); if (propertyFilter != null && propertyFilter.trim().isEmpty()) { propertyFilter = null; } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleProfileImpl.java index a3f2dc2bd6769..5865f84132e77 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleProfileImpl.java @@ -20,11 +20,8 @@ import java.util.List; /** Implementation for AutoscaleProfile. */ -class AutoscaleProfileImpl extends WrapperImpl - implements AutoscaleProfile, - AutoscaleProfile.Definition, - AutoscaleProfile.UpdateDefinition, - AutoscaleProfile.Update { +class AutoscaleProfileImpl extends WrapperImpl implements AutoscaleProfile, + AutoscaleProfile.Definition, AutoscaleProfile.UpdateDefinition, AutoscaleProfile.Update { private final ClientLogger logger = new ClientLogger(getClass()); @@ -103,8 +100,8 @@ public AutoscaleSettingImpl attach() { } @Override - public AutoscaleProfileImpl withMetricBasedScale( - int minimumInstanceCount, int maximumInstanceCount, int defaultInstanceCount) { + public AutoscaleProfileImpl withMetricBasedScale(int minimumInstanceCount, int maximumInstanceCount, + int defaultInstanceCount) { this.innerModel().capacity().withMinimum(Integer.toString(minimumInstanceCount)); this.innerModel().capacity().withMaximum(Integer.toString(maximumInstanceCount)); this.innerModel().capacity().withDefaultProperty(Integer.toString(defaultInstanceCount)); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingImpl.java index ee241af1140ae..35ebfd7a8258d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingImpl.java @@ -26,8 +26,8 @@ class AutoscaleSettingImpl private final ClientLogger logger = new ClientLogger(getClass()); - AutoscaleSettingImpl( - String name, final AutoscaleSettingResourceInner innerModel, final MonitorManager monitorManager) { + AutoscaleSettingImpl(String name, final AutoscaleSettingResourceInner innerModel, + final MonitorManager monitorManager) { super(name, innerModel, monitorManager); if (isInCreateMode()) { this.innerModel().withEnabled(true); @@ -215,8 +215,7 @@ public AutoscaleSettingImpl withAutoscaleDisabled() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAutoscaleSettings() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -225,8 +224,7 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getAutoscaleSettings() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingsImpl.java index 2bf4f86c4aaff..142c2997261b1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/AutoscaleSettingsImpl.java @@ -11,9 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for {@link AutoscaleSettings}. */ -public class AutoscaleSettingsImpl - extends TopLevelModifiableResourcesImpl< - AutoscaleSetting, AutoscaleSettingImpl, AutoscaleSettingResourceInner, AutoscaleSettingsClient, MonitorManager> +public class AutoscaleSettingsImpl extends + TopLevelModifiableResourcesImpl implements AutoscaleSettings { public AutoscaleSettingsImpl(final MonitorManager monitorManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingImpl.java index 71f6bd144e5af..a35f22390a672 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingImpl.java @@ -39,8 +39,8 @@ class DiagnosticSettingImpl private TreeMap logCategoryGroupSet; private final MonitorManager myManager; - DiagnosticSettingImpl( - String name, DiagnosticSettingsResourceInner innerModel, final MonitorManager monitorManager) { + DiagnosticSettingImpl(String name, DiagnosticSettingsResourceInner innerModel, + final MonitorManager monitorManager) { super(name, innerModel); this.myManager = monitorManager; initializeSets(); @@ -126,16 +126,16 @@ public DiagnosticSettingImpl withLog(String category, int retentionDays) { } @Override - public DiagnosticSettingImpl withLogsAndMetrics( - List categories, Duration timeGrain, int retentionDays) { + public DiagnosticSettingImpl withLogsAndMetrics(List 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.")); + throw logger + .logExceptionAsError(new UnsupportedOperationException(dsc.type().toString() + " is unsupported.")); } } return this; @@ -224,12 +224,11 @@ public boolean isInCreateMode() { @Override public Mono createResourceAsync() { this.innerModel() - .withLogs(new ArrayList<>( - Stream.concat(logSet.values().stream(), - logCategoryGroupSet.values().stream()).distinct().collect(Collectors.toList()))); + .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() + return this.manager() .serviceClient() .getDiagnosticSettingsOperations() .createOrUpdateAsync(ResourceUtils.encodeResourceId(this.resourceId), this.name(), this.innerModel()) @@ -238,7 +237,9 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getDiagnosticSettingsOperations() + return this.manager() + .serviceClient() + .getDiagnosticSettingsOperations() .getAsync(ResourceUtils.encodeResourceId(this.resourceId), this.name()); } @@ -249,13 +250,9 @@ public void setInner(DiagnosticSettingsResourceInner inner) { 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()); + 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); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingsImpl.java index e5f4c4a2559e7..5eba4ae741899 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/DiagnosticSettingsImpl.java @@ -73,8 +73,10 @@ public DiagnosticSettingsOperationsClient inner() { @Override public List listCategoriesByResource(String resourceId) { List categories = new ArrayList<>(); - PagedIterable collection = - this.manager().serviceClient().getDiagnosticSettingsCategories().list(ResourceUtils.encodeResourceId(resourceId)); + PagedIterable collection = this.manager() + .serviceClient() + .getDiagnosticSettingsCategories() + .list(ResourceUtils.encodeResourceId(resourceId)); if (collection != null) { for (DiagnosticSettingsCategoryResourceInner category : collection) { categories.add(new DiagnosticSettingsCategoryImpl(category)); @@ -85,24 +87,22 @@ public List listCategoriesByResource(String resource @Override public PagedFlux listCategoriesByResourceAsync(String resourceId) { - return PagedConverter.mapPage(this - .manager - .serviceClient() - .getDiagnosticSettingsCategories() - .listAsync(ResourceUtils.encodeResourceId(resourceId)), - DiagnosticSettingsCategoryImpl::new); + 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)); + return new DiagnosticSettingsCategoryImpl(this.manager() + .serviceClient() + .getDiagnosticSettingsCategories() + .get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono getCategoryAsync(String resourceId, String name) { - return this - .manager() + return this.manager() .serviceClient() .getDiagnosticSettingsCategories() .getAsync(ResourceUtils.encodeResourceId(resourceId), name) @@ -117,8 +117,7 @@ public PagedIterable listByResource(String resourceId) { @Override public PagedFlux listByResourceAsync(String resourceId) { return PagedConverter.mapPage( - this - .manager() + this.manager() .serviceClient() .getDiagnosticSettingsOperations() .listAsync(ResourceUtils.encodeResourceId(resourceId)), @@ -127,28 +126,40 @@ public PagedFlux listByResourceAsync(String resourceId) { @Override public void delete(String resourceId, String name) { - this.manager().serviceClient().getDiagnosticSettingsOperations().delete(ResourceUtils.encodeResourceId(resourceId), name); + this.manager() + .serviceClient() + .getDiagnosticSettingsOperations() + .delete(ResourceUtils.encodeResourceId(resourceId), name); } @Override public Mono deleteAsync(String resourceId, String name) { - return this.manager().serviceClient().getDiagnosticSettingsOperations().deleteAsync(ResourceUtils.encodeResourceId(resourceId), 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)); + return wrapModel(this.manager() + .serviceClient() + .getDiagnosticSettingsOperations() + .get(ResourceUtils.encodeResourceId(resourceId), name)); } @Override public Mono getAsync(String resourceId, String name) { - return this.manager().serviceClient().getDiagnosticSettingsOperations().getAsync(ResourceUtils.encodeResourceId(resourceId), name).map(this::wrapModel); + return this.manager() + .serviceClient() + .getDiagnosticSettingsOperations() + .getAsync(ResourceUtils.encodeResourceId(resourceId), name) + .map(this::wrapModel); } @Override public Mono deleteByIdAsync(String id) { - return this - .manager() + return this.manager() .serviceClient() .getDiagnosticSettingsOperations() .deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)); @@ -160,8 +171,9 @@ public Flux deleteByIdsAsync(Collection ids) { return Flux.empty(); } return Flux.fromIterable(ids) - .flatMapDelayError(id -> - deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, 32) + .flatMapDelayError( + id -> deleteAsync(getResourceIdFromSettingsId(id), getNameFromSettingsId(id)).then(Mono.just(id)), 32, + 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @@ -222,8 +234,7 @@ private String getResourceIdFromSettingsId(String diagnosticSettingId, boolean e if (dsIdx == -1) { throw logger.logExceptionAsError(new IllegalArgumentException( "Parameter 'resourceId' does not represent a valid Diagnostic Settings resource Id [" - + diagnosticSettingId - + "].")); + + diagnosticSettingId + "].")); } return diagnosticSettingId.substring(0, dsIdx); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/EventDataImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/EventDataImpl.java index 193c6436be274..1eb98010f1721 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/EventDataImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/EventDataImpl.java @@ -25,18 +25,19 @@ class EventDataImpl extends WrapperImpl implements EventData { EventDataImpl(EventDataInner innerObject) { super(innerObject); - this.eventName = - (innerModel().eventName() == null) ? null : new LocalizableStringImpl(innerModel().eventName()); + this.eventName + = (innerModel().eventName() == null) ? null : new LocalizableStringImpl(innerModel().eventName()); this.category = (innerModel().category() == null) ? null : new LocalizableStringImpl(innerModel().category()); this.resourceProviderName = (innerModel().resourceProviderName() == null) - ? null : new LocalizableStringImpl(innerModel().resourceProviderName()); - this.resourceType = - (innerModel().resourceType() == null) ? null : new LocalizableStringImpl(innerModel().resourceType()); - this.operationName = - (innerModel().operationName() == null) ? null : new LocalizableStringImpl(innerModel().operationName()); + ? null + : new LocalizableStringImpl(innerModel().resourceProviderName()); + this.resourceType + = (innerModel().resourceType() == null) ? null : new LocalizableStringImpl(innerModel().resourceType()); + this.operationName + = (innerModel().operationName() == null) ? null : new LocalizableStringImpl(innerModel().operationName()); this.status = (innerModel().status() == null) ? null : new LocalizableStringImpl(innerModel().status()); - this.subStatus = - (innerModel().subStatus() == null) ? null : new LocalizableStringImpl(innerModel().subStatus()); + this.subStatus + = (innerModel().subStatus() == null) ? null : new LocalizableStringImpl(innerModel().subStatus()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionBaseImpl.java index 4bed754485444..c823c61fa507d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionBaseImpl.java @@ -19,8 +19,7 @@ * @param inner class, MetricCriteria or DynamicMetricCriteria * @param subclass, i.e., MetricAlertConditionImpl or MetricDynamicAlertConditionImpl */ -class MetricAlertConditionBaseImpl< - InnerT extends MultiMetricCriteria, SubclassT extends MetricAlertConditionBaseImpl> +class MetricAlertConditionBaseImpl> extends WrapperImpl { protected final MetricAlertImpl parent; diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionImpl.java index 6c5f2552a671d..2d8acd0994e6d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionImpl.java @@ -14,24 +14,23 @@ /** Implementation for MetricAlertCondition. */ class MetricAlertConditionImpl extends MetricAlertConditionBaseImpl - implements MetricAlertCondition, - MetricAlertCondition.DefinitionStages, - MetricAlertCondition.DefinitionStages.Blank.MetricName, - MetricAlertCondition.DefinitionStages.WithCriteriaOperator, - MetricAlertCondition.DefinitionStages.WithConditionAttach, - MetricAlertCondition.UpdateDefinitionStages, - MetricAlertCondition.UpdateDefinitionStages.Blank.MetricName, - MetricAlertCondition.UpdateDefinitionStages.WithCriteriaOperator, - MetricAlertCondition.UpdateDefinitionStages.WithConditionAttach, - MetricAlertCondition.UpdateStages { + implements MetricAlertCondition, MetricAlertCondition.DefinitionStages, + MetricAlertCondition.DefinitionStages.Blank.MetricName, + MetricAlertCondition.DefinitionStages.WithCriteriaOperator, + MetricAlertCondition.DefinitionStages.WithConditionAttach, + MetricAlertCondition.UpdateDefinitionStages, + MetricAlertCondition.UpdateDefinitionStages.Blank.MetricName, + MetricAlertCondition.UpdateDefinitionStages.WithCriteriaOperator, + MetricAlertCondition.UpdateDefinitionStages.WithConditionAttach, + MetricAlertCondition.UpdateStages { MetricAlertConditionImpl(String name, MetricCriteria innerObject, MetricAlertImpl parent) { super(name, innerObject, parent); } @Override - public MetricAlertConditionImpl withCondition( - MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold) { + public MetricAlertConditionImpl withCondition(MetricAlertRuleTimeAggregation timeAggregation, + MetricAlertRuleCondition condition, double threshold) { this.innerModel().withOperator(Operator.fromString(condition.toString())); this.innerModel().withTimeAggregation(AggregationTypeEnum.fromString(timeAggregation.toString())); this.innerModel().withThreshold(threshold); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertImpl.java index eb831435dfc1d..9fb61480d1577 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertImpl.java @@ -32,11 +32,8 @@ /** Implementation for MetricAlert. */ class MetricAlertImpl extends GroupableResourceImpl - implements MetricAlert, - MetricAlert.Definition, - MetricAlert.DefinitionMultipleResource, - MetricAlert.Update, - MetricAlert.UpdateStages.WithMetricUpdate { + implements MetricAlert, MetricAlert.Definition, MetricAlert.DefinitionMultipleResource, MetricAlert.Update, + MetricAlert.UpdateStages.WithMetricUpdate { private final ClientLogger logger = new ClientLogger(getClass()); @@ -57,8 +54,8 @@ class MetricAlertImpl if (innerCriteria instanceof MetricAlertSingleResourceMultipleMetricCriteria) { multipleResource = false; // single resource with multiple static criteria - MetricAlertSingleResourceMultipleMetricCriteria crits = - (MetricAlertSingleResourceMultipleMetricCriteria) innerCriteria; + MetricAlertSingleResourceMultipleMetricCriteria crits + = (MetricAlertSingleResourceMultipleMetricCriteria) innerCriteria; List criteria = crits.allOf(); if (criteria != null) { for (MetricCriteria crit : criteria) { @@ -68,24 +65,17 @@ class MetricAlertImpl } else if (innerCriteria instanceof MetricAlertMultipleResourceMultipleMetricCriteria) { multipleResource = true; // multiple resource with either multiple static criteria, or (currently single) dynamic criteria - MetricAlertMultipleResourceMultipleMetricCriteria crits = - (MetricAlertMultipleResourceMultipleMetricCriteria) innerCriteria; + MetricAlertMultipleResourceMultipleMetricCriteria crits + = (MetricAlertMultipleResourceMultipleMetricCriteria) innerCriteria; List criteria = crits.allOf(); if (criteria != null) { for (MultiMetricCriteria crit : criteria) { if (crit instanceof MetricCriteria) { - this - .conditions - .put( - crit.name(), - new MetricAlertConditionImpl(crit.name(), (MetricCriteria) crit, this)); + this.conditions.put(crit.name(), + new MetricAlertConditionImpl(crit.name(), (MetricCriteria) crit, this)); } else if (crit instanceof DynamicMetricCriteria) { - this - .dynamicConditions - .put( - crit.name(), - new MetricDynamicAlertConditionImpl( - crit.name(), (DynamicMetricCriteria) crit, this)); + this.dynamicConditions.put(crit.name(), + new MetricDynamicAlertConditionImpl(crit.name(), (DynamicMetricCriteria) crit, this)); } } } @@ -105,16 +95,16 @@ public Mono createResourceAsync() { this.innerModel().withLocation("global"); if (!this.conditions.isEmpty()) { if (!multipleResource) { - MetricAlertSingleResourceMultipleMetricCriteria crit = - new MetricAlertSingleResourceMultipleMetricCriteria(); + MetricAlertSingleResourceMultipleMetricCriteria crit + = new MetricAlertSingleResourceMultipleMetricCriteria(); crit.withAllOf(new ArrayList<>()); for (MetricAlertCondition mc : conditions.values()) { crit.allOf().add(mc.innerModel()); } this.innerModel().withCriteria(crit); } else { - MetricAlertMultipleResourceMultipleMetricCriteria crit = - new MetricAlertMultipleResourceMultipleMetricCriteria(); + MetricAlertMultipleResourceMultipleMetricCriteria crit + = new MetricAlertMultipleResourceMultipleMetricCriteria(); crit.withAllOf(new ArrayList<>()); for (MetricAlertCondition mc : conditions.values()) { crit.allOf().add(mc.innerModel()); @@ -122,16 +112,15 @@ public Mono createResourceAsync() { this.innerModel().withCriteria(crit); } } else if (!this.dynamicConditions.isEmpty()) { - MetricAlertMultipleResourceMultipleMetricCriteria crit = - new MetricAlertMultipleResourceMultipleMetricCriteria(); + MetricAlertMultipleResourceMultipleMetricCriteria crit + = new MetricAlertMultipleResourceMultipleMetricCriteria(); crit.withAllOf(new ArrayList<>()); for (MetricDynamicAlertCondition mc : dynamicConditions.values()) { crit.allOf().add(mc.innerModel()); } this.innerModel().withCriteria(crit); } - return this - .manager() + return this.manager() .serviceClient() .getMetricAlerts() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -140,7 +129,9 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getMetricAlerts() + return this.manager() + .serviceClient() + .getMetricAlerts() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertsImpl.java index 0c19473e59369..d2ec722109b7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertsImpl.java @@ -11,9 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for {@link MetricAlerts}. */ -class MetricAlertsImpl - extends TopLevelModifiableResourcesImpl< - MetricAlert, MetricAlertImpl, MetricAlertResourceInner, MetricAlertsClient, MonitorManager> +class MetricAlertsImpl extends + TopLevelModifiableResourcesImpl implements MetricAlerts { MetricAlertsImpl(final MonitorManager monitorManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionImpl.java index f337f591bb1a2..29dacfc49c6c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionImpl.java @@ -177,25 +177,15 @@ public MetricCollection execute() { @Override public Mono executeAsync() { - return this - .manager() + return this.manager() .serviceClient() .getMetrics() - .listWithResponseAsync( - ResourceUtils.encodeResourceId(this.inner.resourceId()), - String - .format( - "%s/%s", - DateTimeFormatter.ISO_INSTANT.format(this.queryStartTime.atZoneSameInstant(ZoneOffset.UTC)), - DateTimeFormatter.ISO_INSTANT.format(this.queryEndTime.atZoneSameInstant(ZoneOffset.UTC))), - this.interval, - this.inner.name().value(), - this.aggreagation, - this.top, - this.orderBy, - this.odataFilter, - this.resultType, - this.namespaceFilter) + .listWithResponseAsync(ResourceUtils.encodeResourceId(this.inner.resourceId()), + String.format("%s/%s", + DateTimeFormatter.ISO_INSTANT.format(this.queryStartTime.atZoneSameInstant(ZoneOffset.UTC)), + DateTimeFormatter.ISO_INSTANT.format(this.queryEndTime.atZoneSameInstant(ZoneOffset.UTC))), + this.interval, this.inner.name().value(), this.aggreagation, this.top, this.orderBy, this.odataFilter, + this.resultType, this.namespaceFilter) .map(Response::getValue) .map(MetricCollectionImpl::new); } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionsImpl.java index 98b179093a841..8bbd714025419 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDefinitionsImpl.java @@ -32,11 +32,13 @@ public MetricDefinitionsClient inner() { @Override public PagedIterable listByResource(String resourceId) { - return PagedConverter.mapPage(this.inner().list(ResourceUtils.encodeResourceId(resourceId)), inner -> new MetricDefinitionImpl(inner, myManager)); + return PagedConverter.mapPage(this.inner().list(ResourceUtils.encodeResourceId(resourceId)), + inner -> new MetricDefinitionImpl(inner, myManager)); } @Override public PagedFlux listByResourceAsync(String resourceId) { - return PagedConverter.mapPage(this.inner().listAsync(ResourceUtils.encodeResourceId(resourceId)), inner -> new MetricDefinitionImpl(inner, myManager)); + return PagedConverter.mapPage(this.inner().listAsync(ResourceUtils.encodeResourceId(resourceId)), + inner -> new MetricDefinitionImpl(inner, myManager)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDynamicAlertConditionImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDynamicAlertConditionImpl.java index 0d2e4c1b0c5e2..6ebb674c9e369 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDynamicAlertConditionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricDynamicAlertConditionImpl.java @@ -17,18 +17,17 @@ class MetricDynamicAlertConditionImpl extends MetricAlertConditionBaseImpl - implements MetricDynamicAlertCondition, - MetricDynamicAlertCondition.DefinitionStages, - MetricDynamicAlertCondition.DefinitionStages.Blank.MetricName, - MetricDynamicAlertCondition.DefinitionStages.WithCriteriaOperator, - MetricDynamicAlertCondition.DefinitionStages.WithFailingPeriods, - MetricDynamicAlertCondition.DefinitionStages.WithConditionAttach, - MetricDynamicAlertCondition.UpdateDefinitionStages, - MetricDynamicAlertCondition.UpdateDefinitionStages.Blank.MetricName, - MetricDynamicAlertCondition.UpdateDefinitionStages.WithCriteriaOperator, - MetricDynamicAlertCondition.UpdateDefinitionStages.WithFailingPeriods, - MetricDynamicAlertCondition.UpdateDefinitionStages.WithConditionAttach, - MetricDynamicAlertCondition.UpdateStages { + implements MetricDynamicAlertCondition, MetricDynamicAlertCondition.DefinitionStages, + MetricDynamicAlertCondition.DefinitionStages.Blank.MetricName, + MetricDynamicAlertCondition.DefinitionStages.WithCriteriaOperator, + MetricDynamicAlertCondition.DefinitionStages.WithFailingPeriods, + MetricDynamicAlertCondition.DefinitionStages.WithConditionAttach, + MetricDynamicAlertCondition.UpdateDefinitionStages, + MetricDynamicAlertCondition.UpdateDefinitionStages.Blank.MetricName, + MetricDynamicAlertCondition.UpdateDefinitionStages.WithCriteriaOperator, + MetricDynamicAlertCondition.UpdateDefinitionStages.WithFailingPeriods, + MetricDynamicAlertCondition.UpdateDefinitionStages.WithConditionAttach, + MetricDynamicAlertCondition.UpdateStages { private final ClientLogger logger = new ClientLogger(getClass()); @@ -63,10 +62,8 @@ public MetricAlertImpl attach() { } @Override - public MetricDynamicAlertConditionImpl withCondition( - MetricAlertRuleTimeAggregation timeAggregation, - DynamicThresholdOperator condition, - DynamicThresholdSensitivity alertSensitivity) { + public MetricDynamicAlertConditionImpl withCondition(MetricAlertRuleTimeAggregation timeAggregation, + DynamicThresholdOperator condition, DynamicThresholdSensitivity alertSensitivity) { this.innerModel().withOperator(condition); this.innerModel().withTimeAggregation(AggregationTypeEnum.fromString(timeAggregation.toString())); this.innerModel().withAlertSensitivity(alertSensitivity); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ScaleRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ScaleRuleImpl.java index 6bcaba20adbbc..9e25cd19ead4c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ScaleRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/ScaleRuleImpl.java @@ -16,12 +16,8 @@ import java.time.Duration; /** Implementation for ScaleRule. */ -class ScaleRuleImpl extends WrapperImpl - implements ScaleRule, - ScaleRule.Definition, - ScaleRule.ParentUpdateDefinition, - ScaleRule.UpdateDefinition, - ScaleRule.Update { +class ScaleRuleImpl extends WrapperImpl implements ScaleRule, ScaleRule.Definition, + ScaleRule.ParentUpdateDefinition, ScaleRule.UpdateDefinition, ScaleRule.Update { private final AutoscaleProfileImpl parent; @@ -179,8 +175,8 @@ public ScaleRuleImpl withStatistic(Duration duration, MetricStatisticType statis } @Override - public ScaleRuleImpl withCondition( - TimeAggregationType timeAggregation, ComparisonOperationType condition, double threshold) { + public ScaleRuleImpl withCondition(TimeAggregationType timeAggregation, ComparisonOperationType condition, + double threshold) { this.innerModel().metricTrigger().withOperator(condition); this.innerModel().metricTrigger().withTimeAggregation(timeAggregation); this.innerModel().metricTrigger().withThreshold(threshold); @@ -188,8 +184,8 @@ public ScaleRuleImpl withCondition( } @Override - public ScaleRuleImpl withScaleAction( - ScaleDirection direction, ScaleType type, int instanceCountChange, Duration cooldown) { + public ScaleRuleImpl withScaleAction(ScaleDirection direction, ScaleType type, int instanceCountChange, + Duration cooldown) { this.innerModel().scaleAction().withDirection(direction); this.innerModel().scaleAction().withType(type); this.innerModel().scaleAction().withValue(Integer.toString(instanceCountChange)); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroup.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroup.java index c06bb3d34a0b0..f6e0d1d2c4877 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroup.java @@ -16,10 +16,8 @@ /** An immutable client-side representation of an Azure Action Group. */ @Fluent -public interface ActionGroup - extends GroupableResource, - Refreshable, - Updatable { +public interface ActionGroup extends GroupableResource, + Refreshable, Updatable { /** * Get the groupShortName value. * @@ -130,8 +128,8 @@ interface ActionDefinition { * @param region the region value to set * @return the next stage of the definition */ - ActionDefinition withItsm( - String workspaceId, String connectionId, String ticketConfiguration, String region); + ActionDefinition withItsm(String workspaceId, String connectionId, String ticketConfiguration, + String region); /** * Sets the Azure Mobile App Push Notification receiver. @@ -150,8 +148,8 @@ ActionDefinition withItsm( * @param isGlobalRunbook the isGlobalRunbook value to set * @return the next stage of the definition */ - ActionDefinition withAutomationRunbook( - String automationAccountId, String runbookName, String webhookResourceId, boolean isGlobalRunbook); + ActionDefinition withAutomationRunbook(String automationAccountId, String runbookName, + String webhookResourceId, boolean isGlobalRunbook); /** * Sets the Voice notification receiver. @@ -179,8 +177,8 @@ ActionDefinition withAutomationRunbook( * @param httpTriggerUrl the httpTriggerUrl value to set * @return the next stage of the definition */ - ActionDefinition withAzureFunction( - String functionAppResourceId, String functionName, String httpTriggerUrl); + ActionDefinition withAzureFunction(String functionAppResourceId, String functionName, + String httpTriggerUrl); /** * Attaches the defined receivers to the Action Group configuration. @@ -191,9 +189,7 @@ ActionDefinition withAzureFunction( } /** The entirety of a Action Group definition. */ - interface Definition extends DefinitionStages.Blank, - ActionDefinition, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, ActionDefinition, DefinitionStages.WithCreate { } /** Grouping of Action Group definition stages. */ @@ -365,8 +361,8 @@ interface WithActionUpdateDefinition { * @param region the region value to set * @return the next stage of the update */ - WithActionUpdateDefinition withItsm( - String workspaceId, String connectionId, String ticketConfiguration, String region); + WithActionUpdateDefinition withItsm(String workspaceId, String connectionId, String ticketConfiguration, + String region); /** * Sets the Azure Mobile App Push Notification receiver. @@ -385,8 +381,8 @@ WithActionUpdateDefinition withItsm( * @param isGlobalRunbook the isGlobalRunbook value to set * @return the next stage of the update */ - WithActionUpdateDefinition withAutomationRunbook( - String automationAccountId, String runbookName, String webhookResourceId, boolean isGlobalRunbook); + WithActionUpdateDefinition withAutomationRunbook(String automationAccountId, String runbookName, + String webhookResourceId, boolean isGlobalRunbook); /** * Sets the Voice notification receiver. @@ -414,8 +410,8 @@ WithActionUpdateDefinition withAutomationRunbook( * @param httpTriggerUrl the httpTriggerUrl value to set * @return the next stage of the update */ - WithActionUpdateDefinition withAzureFunction( - String functionAppResourceId, String functionName, String httpTriggerUrl); + WithActionUpdateDefinition withAzureFunction(String functionAppResourceId, String functionName, + String httpTriggerUrl); /** * Returns to the Action Group update flow. diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroups.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroups.java index 91c52b0bed484..3f62fbf437cbb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActionGroups.java @@ -19,15 +19,9 @@ /** Entry point for Action Group management API. */ @Fluent public interface ActionGroups - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsBatchCreation, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingById, SupportsBatchCreation, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchDeletion, HasManager { /** * Enable a receiver in an action group. This changes the receiver's status from Disabled to Enabled. This operation diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlert.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlert.java index 724c0e97a074b..e1df83c7c4a94 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlert.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlert.java @@ -18,10 +18,8 @@ /** An immutable client-side representation of an Azure Activity Log Alert. */ @Fluent -public interface ActivityLogAlert - extends GroupableResource, - Refreshable, - Updatable { +public interface ActivityLogAlert extends GroupableResource, + Refreshable, Updatable { /** * Get a list of resourceIds that will be used as prefixes. The alert will only apply to activityLogs with @@ -61,14 +59,9 @@ public interface ActivityLogAlert String description(); /** The entirety of a activity log alerts definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithCreate, - DefinitionStages.WithScopes, - DefinitionStages.WithDescription, - DefinitionStages.WithAlertEnabled, - DefinitionStages.WithActionGroup, - DefinitionStages.WithCriteriaDefinition { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate, DefinitionStages.WithScopes, + DefinitionStages.WithDescription, DefinitionStages.WithAlertEnabled, DefinitionStages.WithActionGroup, + DefinitionStages.WithCriteriaDefinition { } /** Grouping of activity log alerts definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlerts.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlerts.java index 27a7b5b5bc38b..41b0390a113ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogAlerts.java @@ -17,14 +17,8 @@ /** Entry point for Activity Log Alert management API. */ @Fluent -public interface ActivityLogAlerts - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface ActivityLogAlerts extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogs.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogs.java index 21dd3a318ea76..ee75b3063532b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ActivityLogs.java @@ -34,12 +34,11 @@ public interface ActivityLogs extends HasManager { ActivityLogsQueryDefinitionStages.WithEventDataStartTimeFilter defineQuery(); /** The entirety of a Activity Logs query definition. */ - interface ActivityLogsQueryDefinition - extends ActivityLogsQueryDefinitionStages.WithEventDataStartTimeFilter, - ActivityLogsQueryDefinitionStages.WithEventDataEndFilter, - ActivityLogsQueryDefinitionStages.WithEventDataFieldFilter, - ActivityLogsQueryDefinitionStages.WithActivityLogsSelectFilter, - ActivityLogsQueryDefinitionStages.WithActivityLogsQueryExecute { + interface ActivityLogsQueryDefinition extends ActivityLogsQueryDefinitionStages.WithEventDataStartTimeFilter, + ActivityLogsQueryDefinitionStages.WithEventDataEndFilter, + ActivityLogsQueryDefinitionStages.WithEventDataFieldFilter, + ActivityLogsQueryDefinitionStages.WithActivityLogsSelectFilter, + ActivityLogsQueryDefinitionStages.WithActivityLogsQueryExecute { } /** Grouping of Activity log query stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleProfile.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleProfile.java index 07f0195338a3c..ff95214e5203b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleProfile.java @@ -62,12 +62,8 @@ public interface AutoscaleProfile extends HasInnerModel, List rules(); /** The entirety of an autoscale profile definition. */ - interface Definition - extends DefinitionStages.WithAttach, - DefinitionStages.Blank, - DefinitionStages.WithScaleRule, - DefinitionStages.WithScaleRuleOptional, - DefinitionStages.WithScaleSchedule { + interface Definition extends DefinitionStages.WithAttach, DefinitionStages.Blank, DefinitionStages.WithScaleRule, + DefinitionStages.WithScaleRuleOptional, DefinitionStages.WithScaleSchedule { } /** Grouping of autoscale profile definition stages. */ @@ -88,8 +84,8 @@ interface Blank { * evaluation. The default is only used if the current instance count is lower than the default. * @return the next stage of the definition. */ - WithScaleRule withMetricBasedScale( - int minimumInstanceCount, int maximumInstanceCount, int defaultInstanceCount); + WithScaleRule withMetricBasedScale(int minimumInstanceCount, int maximumInstanceCount, + int defaultInstanceCount); /** * Selects schedule based autoscale profile. @@ -174,8 +170,8 @@ interface WithScaleRuleOptional extends WithAttach { * @param weekday list of week days when the schedule should be active. * @return the next stage of the definition. */ - WithScaleRuleOptional withRecurrentSchedule( - String scheduleTimeZone, String startTime, DayOfWeek... weekday); + WithScaleRuleOptional withRecurrentSchedule(String scheduleTimeZone, String startTime, + DayOfWeek... weekday); } /** The stage of the definition which specifies autoscale profile schedule. */ @@ -231,11 +227,8 @@ interface WithScaleSchedule { /** The entirety of an autoscale profile definition during current autoscale settings update. */ interface UpdateDefinition - extends UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithScaleRule, - UpdateDefinitionStages.WithScaleRuleOptional, - UpdateDefinitionStages.WithScaleSchedule { + extends UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithScaleRule, + UpdateDefinitionStages.WithScaleRuleOptional, UpdateDefinitionStages.WithScaleSchedule { } /** Grouping of autoscale profile definition stages during current autoscale settings update stage. */ @@ -256,8 +249,8 @@ interface Blank { * evaluation. The default is only used if the current instance count is lower than the default. * @return the next stage of the definition. */ - WithScaleRule withMetricBasedScale( - int minimumInstanceCount, int maximumInstanceCount, int defaultInstanceCount); + WithScaleRule withMetricBasedScale(int minimumInstanceCount, int maximumInstanceCount, + int defaultInstanceCount); /** * Selects schedule based autoscale profile. @@ -333,8 +326,8 @@ interface WithScaleRuleOptional extends WithAttach { * @param weekday list of week days when the schedule should be active. * @return the next stage of the definition. */ - WithScaleRuleOptional withRecurrentSchedule( - String scheduleTimeZone, String startTime, DayOfWeek... weekday); + WithScaleRuleOptional withRecurrentSchedule(String scheduleTimeZone, String startTime, + DayOfWeek... weekday); } /** The stage of the definition which specifies autoscale profile schedule. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSetting.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSetting.java index c19b01126ba67..c17a22b86a4a3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSetting.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSetting.java @@ -17,10 +17,8 @@ /** An immutable client-side representation of an Azure autoscale setting. */ @Fluent -public interface AutoscaleSetting - extends GroupableResource, - Refreshable, - Updatable { +public interface AutoscaleSetting extends GroupableResource, + Refreshable, Updatable { /** * Get the resource identifier of the resource that the autoscale setting should be added to. @@ -73,13 +71,10 @@ public interface AutoscaleSetting String webhookNotification(); /** The entirety of an autoscale setting definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.DefineAutoscaleSettingResourceProfiles, - DefinitionStages.WithAutoscaleSettingResourceTargetResourceUri, - DefinitionStages.WithAutoscaleSettingResourceEnabled { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.DefineAutoscaleSettingResourceProfiles, + DefinitionStages.WithAutoscaleSettingResourceTargetResourceUri, + DefinitionStages.WithAutoscaleSettingResourceEnabled { } /** Grouping of autoscale setting definition stages. */ @@ -164,11 +159,8 @@ interface WithAutoscaleSettingResourceEnabled { } /** The stage of the definition which allows autoscale setting creation. */ - interface WithCreate - extends Creatable, - DefineAutoscaleSettingResourceProfiles, - DefineAutoscaleSettingResourceNotifications, - WithAutoscaleSettingResourceEnabled { + interface WithCreate extends Creatable, DefineAutoscaleSettingResourceProfiles, + DefineAutoscaleSettingResourceNotifications, WithAutoscaleSettingResourceEnabled { } } @@ -279,10 +271,7 @@ interface UpdateAutoscaleSettings { } /** Grouping of autoscale setting update stages. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.DefineAutoscaleSettingProfiles, - UpdateStages.UpdateAutoscaleSettings { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.DefineAutoscaleSettingProfiles, UpdateStages.UpdateAutoscaleSettings { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSettings.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSettings.java index 68482c0028da8..2f8126d551ce1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSettings.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/AutoscaleSettings.java @@ -16,14 +16,8 @@ /** Entry point to autoscale management API in Azure. */ @Fluent -public interface AutoscaleSettings - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsBatchCreation, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchDeletion, - HasManager { +public interface AutoscaleSettings extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingById, SupportsBatchCreation, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DayOfWeek.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DayOfWeek.java index 3f35700fbcc61..6ab136aec399f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DayOfWeek.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DayOfWeek.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.monitor.models; - /** Defines values for DayOfWeek. */ public enum DayOfWeek { /** Enum value Monday. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSetting.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSetting.java index f125641066e69..c0baf5161b7aa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSetting.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSetting.java @@ -21,13 +21,8 @@ /** An immutable client-side representation of an Azure diagnostic settings. */ @Fluent public interface DiagnosticSetting - extends Indexable, - HasId, - HasName, - HasManager, - HasInnerModel, - Refreshable, - Updatable { + extends Indexable, HasId, HasName, HasManager, HasInnerModel, + Refreshable, Updatable { /** * Get the associated resource Id value. * @@ -172,8 +167,8 @@ interface WithCreate extends WithDiagnosticLogRecipient, Creatable categories, Duration timeGrain, int retentionDays); + WithCreate withLogsAndMetrics(List categories, Duration timeGrain, + int retentionDays); } } @@ -279,8 +274,8 @@ interface WithMetricAndLogs { * indefinitely. * @return the next stage of the Diagnostic Settings update. */ - Update withLogsAndMetrics( - List categories, Duration timeGrain, int retentionDays); + Update withLogsAndMetrics(List categories, Duration timeGrain, + int retentionDays); /** * Removes the Metric Setting from the Diagnostic Setting. @@ -315,11 +310,7 @@ Update withLogsAndMetrics( } /** The template for an update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithStorageAccount, - UpdateStages.WithEventHub, - UpdateStages.WithLogAnalytics, - UpdateStages.WithMetricAndLogs { + interface Update extends Appliable, UpdateStages.WithStorageAccount, UpdateStages.WithEventHub, + UpdateStages.WithLogAnalytics, UpdateStages.WithMetricAndLogs { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSettings.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSettings.java index 0d4b0922a842f..900dc45e2247b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSettings.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/DiagnosticSettings.java @@ -19,12 +19,8 @@ /** Entry point for diagnostic settings management API. */ @Fluent public interface DiagnosticSettings - extends SupportsCreating, - SupportsBatchCreation, - SupportsGettingById, - SupportsDeletingById, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsBatchCreation, + SupportsGettingById, SupportsDeletingById, SupportsBatchDeletion, HasManager { /** * Lists all the Diagnostic Settings categories for Log and Metric Settings for a specific resource. diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlert.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlert.java index 5c83148274ab0..22740cf1a6daa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlert.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlert.java @@ -20,10 +20,8 @@ /** An immutable client-side representation of a Metric Alert. */ @Fluent -public interface MetricAlert - extends GroupableResource, - Refreshable, - Updatable { +public interface MetricAlert extends GroupableResource, + Refreshable, Updatable { /** * Get the description of the metric alert that will be included in the alert email. @@ -97,27 +95,16 @@ public interface MetricAlert OffsetDateTime lastUpdatedTime(); /** The entirety of a Metric Alert definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithCreate, - DefinitionStages.WithScopes, - DefinitionStages.WithWindowSize, - DefinitionStages.WithEvaluationFrequency, - DefinitionStages.WithSeverity, - DefinitionStages.WithActionGroup, - DefinitionStages.WithCriteriaDefinition { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate, DefinitionStages.WithScopes, + DefinitionStages.WithWindowSize, DefinitionStages.WithEvaluationFrequency, DefinitionStages.WithSeverity, + DefinitionStages.WithActionGroup, DefinitionStages.WithCriteriaDefinition { } /** Metric Alert definition for multiple resource. */ - interface DefinitionMultipleResource - extends DefinitionStages.Blank, - DefinitionStages.WithCreateDynamicCondition, - DefinitionStages.WithScopes, - DefinitionStages.WithWindowSizeMultipleResource, - DefinitionStages.WithEvaluationFrequencyMultipleResource, - DefinitionStages.WithSeverityMultipleResource, - DefinitionStages.WithActionGroupMultipleResource, - DefinitionStages.WithCriteriaDefinitionMultipleResource { + interface DefinitionMultipleResource extends DefinitionStages.Blank, DefinitionStages.WithCreateDynamicCondition, + DefinitionStages.WithScopes, DefinitionStages.WithWindowSizeMultipleResource, + DefinitionStages.WithEvaluationFrequencyMultipleResource, DefinitionStages.WithSeverityMultipleResource, + DefinitionStages.WithActionGroupMultipleResource, DefinitionStages.WithCriteriaDefinitionMultipleResource { } /** Grouping of metric alerts definition stages. */ @@ -153,8 +140,8 @@ interface WithScopes { * @param regionName resource region. * @return the next stage of metric alert definition. */ - WithWindowSizeMultipleResource withMultipleTargetResources( - Collection resourceIds, String type, String regionName); + WithWindowSizeMultipleResource withMultipleTargetResources(Collection resourceIds, String type, + String regionName); /** * Sets specified resources as target to alert on metric. All resources must be of the same type and in the @@ -292,8 +279,8 @@ interface WithCriteriaDefinitionMultipleResource { * @param name sets the name of the dynamic condition. * @return the next stage of metric alert condition definition. */ - MetricDynamicAlertCondition.DefinitionStages.Blank.MetricName defineDynamicAlertCriteria( - String name); + MetricDynamicAlertCondition.DefinitionStages.Blank.MetricName + defineDynamicAlertCriteria(String name); } /** @@ -418,8 +405,8 @@ interface WithMetricUpdate { * @param name sets the name of the condition. * @return the next stage of the metric alert update. */ - MetricDynamicAlertCondition.UpdateDefinitionStages.Blank.MetricName defineDynamicAlertCriteria( - String name); + MetricDynamicAlertCondition.UpdateDefinitionStages.Blank.MetricName + defineDynamicAlertCriteria(String name); /** * Starts update of the previously defined metric alert condition. diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlertCondition.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlertCondition.java index 4dc6fea9da664..49c061654454a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlertCondition.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlertCondition.java @@ -107,8 +107,8 @@ interface WithCriteriaOperator { * @param threshold the criteria threshold value that activates the alert. * @return the next stage of metric alert condition definition. */ - WithConditionAttach withCondition( - MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold); + WithConditionAttach withCondition(MetricAlertRuleTimeAggregation timeAggregation, + MetricAlertRuleCondition condition, double threshold); } /** @@ -181,8 +181,8 @@ interface WithCriteriaOperator { * @param threshold the criteria threshold value that activates the alert. * @return the next stage of metric alert condition definition. */ - WithConditionAttach withCondition( - MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold); + WithConditionAttach withCondition(MetricAlertRuleTimeAggregation timeAggregation, + MetricAlertRuleCondition condition, double threshold); } /** @@ -221,8 +221,8 @@ interface UpdateStages { * @param threshold the criteria threshold value that activates the alert. * @return the next stage of the metric alert condition update. */ - UpdateStages withCondition( - MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold); + UpdateStages withCondition(MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, + double threshold); /** * Adds a metric dimension filter. diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlerts.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlerts.java index 1a3ac4a54d547..bb0597a7aa05c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricAlerts.java @@ -17,14 +17,8 @@ /** Entry point for Metric Alert management API. */ @Fluent -public interface MetricAlerts - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface MetricAlerts extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, + HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDefinition.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDefinition.java index 8aa0dc7a5c59b..2571baa661f9c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDefinition.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDefinition.java @@ -93,10 +93,8 @@ public interface MetricDefinition extends HasManager, HasInnerMo MetricsQueryDefinitionStages.WithMetricStartTimeFilter defineQuery(); /** The entirety of a Metrics query definition. */ - interface MetricsQueryDefinition - extends MetricsQueryDefinitionStages.WithMetricStartTimeFilter, - MetricsQueryDefinitionStages.WithMetricEndFilter, - MetricsQueryDefinitionStages.WithMetricsQueryExecute { + interface MetricsQueryDefinition extends MetricsQueryDefinitionStages.WithMetricStartTimeFilter, + MetricsQueryDefinitionStages.WithMetricEndFilter, MetricsQueryDefinitionStages.WithMetricsQueryExecute { } /** Grouping of Metric query stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDynamicAlertCondition.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDynamicAlertCondition.java index d7679846e2f49..5fb2233426a63 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDynamicAlertCondition.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/MetricDynamicAlertCondition.java @@ -123,10 +123,8 @@ interface WithCriteriaOperator { * @param alertSensitivity the extent of deviation required to trigger an alert. * @return the next stage of metric alert condition definition. */ - WithFailingPeriods withCondition( - MetricAlertRuleTimeAggregation timeAggregation, - DynamicThresholdOperator condition, - DynamicThresholdSensitivity alertSensitivity); + WithFailingPeriods withCondition(MetricAlertRuleTimeAggregation timeAggregation, + DynamicThresholdOperator condition, DynamicThresholdSensitivity alertSensitivity); } /** @@ -222,10 +220,8 @@ interface WithCriteriaOperator { * @param alertSensitivity the extent of deviation required to trigger an alert. * @return the next stage of metric alert condition definition. */ - WithFailingPeriods withCondition( - MetricAlertRuleTimeAggregation timeAggregation, - DynamicThresholdOperator condition, - DynamicThresholdSensitivity alertSensitivity); + WithFailingPeriods withCondition(MetricAlertRuleTimeAggregation timeAggregation, + DynamicThresholdOperator condition, DynamicThresholdSensitivity alertSensitivity); } /** @@ -287,9 +283,7 @@ interface UpdateStages { * @param sensitivity the threshold sensitivity that activates the alert. * @return the next stage of metric alert condition definition. */ - UpdateStages withCondition( - MetricAlertRuleTimeAggregation timeAggregation, - DynamicThresholdOperator condition, + UpdateStages withCondition(MetricAlertRuleTimeAggregation timeAggregation, DynamicThresholdOperator condition, DynamicThresholdSensitivity sensitivity); /** diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ScaleRule.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ScaleRule.java index 3f22be232412f..6d0d127da254b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ScaleRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ScaleRule.java @@ -108,12 +108,8 @@ public interface ScaleRule extends HasInnerModel, HasParent alertsInRg = - monitorManager.alertRules().metricAlerts().listByResourceGroup(rgName); + PagedIterable alertsInRg + = monitorManager.alertRules().metricAlerts().listByResourceGroup(rgName); Assertions.assertEquals(1, TestUtilities.getSize(alertsInRg)); maFromGet = alertsInRg.iterator().next(); @@ -281,10 +270,9 @@ public void canCRUDMetricAlerts() throws Exception { Assertions.assertNotNull(maFromGet); Assertions.assertEquals(1, maFromGet.scopes().size()); assertResourceIdEquals(sa.id(), maFromGet.scopes().iterator().next()); - Assertions - .assertEquals( - "This alert rule is for U3 - Single resource multiple-criteria with dimensions-single timeseries", - ma.description()); + Assertions.assertEquals( + "This alert rule is for U3 - Single resource multiple-criteria with dimensions-single timeseries", + ma.description()); Assertions.assertEquals(Duration.ofMinutes(15), maFromGet.windowSize()); Assertions.assertEquals(Duration.ofMinutes(1), maFromGet.evaluationFrequency()); Assertions.assertEquals(3, maFromGet.severity()); @@ -340,50 +328,44 @@ public void canCRUDMultipleResourceMetricAlerts() throws Exception { String vmName1 = generateRandomResourceName("jMonitorVM1", 18); String vmName2 = generateRandomResourceName("jMonitorVM2", 18); - VirtualMachine vm1 = - computeManager - .virtualMachines() - .define(vmName1) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey()) - .create(); - - VirtualMachine vm2 = - computeManager - .virtualMachines() - .define(vmName2) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey()) - .create(); - - MetricAlert ma = - monitorManager - .alertRules() - .metricAlerts() - .define(alertName) - .withExistingResourceGroup(rgName) - .withMultipleTargetResources(Arrays.asList(vm1, vm2)) - .withPeriod(Duration.ofMinutes(15)) - .withFrequency(Duration.ofMinutes(5)) - .withAlertDetails(3, "This alert rule is for U3 - Multiple resource, static criteria") - .withActionGroups() - .defineAlertCriteria("Metric1") - .withMetricName("Percentage CPU", vm1.type()) - .withCondition(MetricAlertRuleTimeAggregation.AVERAGE, MetricAlertRuleCondition.GREATER_THAN, 80) - .attach() - .create(); + VirtualMachine vm1 = computeManager.virtualMachines() + .define(vmName1) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey()) + .create(); + + VirtualMachine vm2 = computeManager.virtualMachines() + .define(vmName2) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey()) + .create(); + + MetricAlert ma = monitorManager.alertRules() + .metricAlerts() + .define(alertName) + .withExistingResourceGroup(rgName) + .withMultipleTargetResources(Arrays.asList(vm1, vm2)) + .withPeriod(Duration.ofMinutes(15)) + .withFrequency(Duration.ofMinutes(5)) + .withAlertDetails(3, "This alert rule is for U3 - Multiple resource, static criteria") + .withActionGroups() + .defineAlertCriteria("Metric1") + .withMetricName("Percentage CPU", vm1.type()) + .withCondition(MetricAlertRuleTimeAggregation.AVERAGE, MetricAlertRuleCondition.GREATER_THAN, 80) + .attach() + .create(); ma.refresh(); Assertions.assertEquals(2, ma.scopes().size()); @@ -397,20 +379,15 @@ public void canCRUDMultipleResourceMetricAlerts() throws Exception { Assertions.assertEquals("Percentage CPU", ma.alertCriterias().get("Metric1").metricName()); OffsetDateTime time30MinBefore = OffsetDateTime.now().minusMinutes(30); - ma - .update() + ma.update() .withDescription("This alert rule is for U3 - Multiple resource, dynamic criteria") .withoutAlertCriteria("Metric1") .defineDynamicAlertCriteria("Metric2") .withMetricName("Percentage CPU", vm1.type()) - .withCondition( - MetricAlertRuleTimeAggregation.AVERAGE, - DynamicThresholdOperator.GREATER_THAN, + .withCondition(MetricAlertRuleTimeAggregation.AVERAGE, DynamicThresholdOperator.GREATER_THAN, DynamicThresholdSensitivity.HIGH) - .withFailingPeriods( - new DynamicThresholdFailingPeriods() - .withNumberOfEvaluationPeriods(4) - .withMinFailingPeriodsToAlert(2)) + .withFailingPeriods(new DynamicThresholdFailingPeriods().withNumberOfEvaluationPeriods(4) + .withMinFailingPeriodsToAlert(2)) .withIgnoreDataBefore(time30MinBefore) .attach() .apply(); @@ -442,49 +419,44 @@ public void canCRUDMultipleResourceMetricAlerts() throws Exception { @Test public void canCRUDActivityLogAlerts() { Region region = Region.US_EAST2; - ActionGroup ag = - monitorManager - .actionGroups() - .define("simpleActionGroup") - .withNewResourceGroup(rgName, region) - .defineReceiver("first") - .withPushNotification("azurepush@outlook.com") - .withEmail("justemail@outlook.com") - .withSms("1", "4255655665") - .withVoice("1", "2062066050") - .withWebhook("https://www.rate.am") - .attach() - .defineReceiver("second") - .withEmail("secondemail@outlook.com") - .withWebhook("https://www.spyur.am") - .attach() - .create(); + ActionGroup ag = monitorManager.actionGroups() + .define("simpleActionGroup") + .withNewResourceGroup(rgName, region) + .defineReceiver("first") + .withPushNotification("azurepush@outlook.com") + .withEmail("justemail@outlook.com") + .withSms("1", "4255655665") + .withVoice("1", "2062066050") + .withWebhook("https://www.rate.am") + .attach() + .defineReceiver("second") + .withEmail("secondemail@outlook.com") + .withWebhook("https://www.spyur.am") + .attach() + .create(); String vmName = generateRandomResourceName("jMonitorVm_", 18); - VirtualMachine justAvm = ensureVM(region, - resourceManager.resourceGroups().getByName(rgName), - vmName, - "10.0.0.0/28"); - - ActivityLogAlert ala = - monitorManager - .alertRules() - .activityLogAlerts() - .define("somename") - .withExistingResourceGroup(rgName) - .withTargetSubscription(monitorManager.subscriptionId()) - .withDescription("AutoScale-VM-Creation-Failed") - .withRuleEnabled() - .withActionGroups(ag.id()) - .withEqualsCondition("category", "Administrative") - .withEqualsCondition("resourceId", justAvm.id()) - .withEqualsCondition("operationName", "Microsoft.Compute/virtualMachines/delete") - .create(); + VirtualMachine justAvm + = ensureVM(region, resourceManager.resourceGroups().getByName(rgName), vmName, "10.0.0.0/28"); + + ActivityLogAlert ala = monitorManager.alertRules() + .activityLogAlerts() + .define("somename") + .withExistingResourceGroup(rgName) + .withTargetSubscription(monitorManager.subscriptionId()) + .withDescription("AutoScale-VM-Creation-Failed") + .withRuleEnabled() + .withActionGroups(ag.id()) + .withEqualsCondition("category", "Administrative") + .withEqualsCondition("resourceId", justAvm.id()) + .withEqualsCondition("operationName", "Microsoft.Compute/virtualMachines/delete") + .create(); Assertions.assertNotNull(ala); Assertions.assertEquals(1, ala.scopes().size()); if (!isPlaybackMode()) { - Assertions.assertEquals("/subscriptions/" + monitorManager.subscriptionId(), ala.scopes().iterator().next()); + Assertions.assertEquals("/subscriptions/" + monitorManager.subscriptionId(), + ala.scopes().iterator().next()); } Assertions.assertEquals("AutoScale-VM-Creation-Failed", ala.description()); Assertions.assertEquals(true, ala.enabled()); @@ -493,8 +465,8 @@ public void canCRUDActivityLogAlerts() { Assertions.assertEquals(3, ala.equalsConditions().size()); Assertions.assertEquals("Administrative", ala.equalsConditions().get("category")); Assertions.assertEquals(justAvm.id(), ala.equalsConditions().get("resourceId")); - Assertions - .assertEquals("Microsoft.Compute/virtualMachines/delete", ala.equalsConditions().get("operationName")); + Assertions.assertEquals("Microsoft.Compute/virtualMachines/delete", + ala.equalsConditions().get("operationName")); ActivityLogAlert alaFromGet = monitorManager.alertRules().activityLogAlerts().getById(ala.id()); @@ -503,18 +475,15 @@ public void canCRUDActivityLogAlerts() { Assertions.assertEquals(ala.description(), alaFromGet.description()); Assertions.assertEquals(ala.enabled(), alaFromGet.enabled()); Assertions.assertEquals(ala.actionGroupIds().size(), alaFromGet.actionGroupIds().size()); - Assertions - .assertEquals(ala.actionGroupIds().iterator().next(), alaFromGet.actionGroupIds().iterator().next()); + Assertions.assertEquals(ala.actionGroupIds().iterator().next(), alaFromGet.actionGroupIds().iterator().next()); Assertions.assertEquals(ala.equalsConditions().size(), alaFromGet.equalsConditions().size()); - Assertions - .assertEquals(ala.equalsConditions().get("category"), alaFromGet.equalsConditions().get("category")); - assertResourceIdEquals(ala.equalsConditions().get("resourceId"), alaFromGet.equalsConditions().get("resourceId")); - Assertions - .assertEquals( - ala.equalsConditions().get("operationName"), alaFromGet.equalsConditions().get("operationName")); - - ala - .update() + Assertions.assertEquals(ala.equalsConditions().get("category"), alaFromGet.equalsConditions().get("category")); + assertResourceIdEquals(ala.equalsConditions().get("resourceId"), + alaFromGet.equalsConditions().get("resourceId")); + Assertions.assertEquals(ala.equalsConditions().get("operationName"), + alaFromGet.equalsConditions().get("operationName")); + + ala.update() .withRuleDisabled() .withoutEqualsCondition("operationName") .withEqualsCondition("status", "Failed") @@ -522,7 +491,8 @@ public void canCRUDActivityLogAlerts() { Assertions.assertEquals(1, ala.scopes().size()); if (!isPlaybackMode()) { - Assertions.assertEquals("/subscriptions/" + monitorManager.subscriptionId(), ala.scopes().iterator().next()); + Assertions.assertEquals("/subscriptions/" + monitorManager.subscriptionId(), + ala.scopes().iterator().next()); } Assertions.assertEquals("AutoScale-VM-Creation-Failed", ala.description()); Assertions.assertEquals(false, ala.enabled()); @@ -534,8 +504,8 @@ public void canCRUDActivityLogAlerts() { Assertions.assertEquals("Failed", ala.equalsConditions().get("status")); Assertions.assertEquals(false, ala.equalsConditions().containsKey("operationName")); - PagedIterable alertsInRg = - monitorManager.alertRules().activityLogAlerts().listByResourceGroup(rgName); + PagedIterable alertsInRg + = monitorManager.alertRules().activityLogAlerts().listByResourceGroup(rgName); Assertions.assertEquals(1, TestUtilities.getSize(alertsInRg)); alaFromGet = alertsInRg.iterator().next(); @@ -545,17 +515,14 @@ public void canCRUDActivityLogAlerts() { Assertions.assertEquals(ala.description(), alaFromGet.description()); Assertions.assertEquals(ala.enabled(), alaFromGet.enabled()); Assertions.assertEquals(ala.actionGroupIds().size(), alaFromGet.actionGroupIds().size()); - Assertions - .assertEquals(ala.actionGroupIds().iterator().next(), alaFromGet.actionGroupIds().iterator().next()); + Assertions.assertEquals(ala.actionGroupIds().iterator().next(), alaFromGet.actionGroupIds().iterator().next()); Assertions.assertEquals(ala.equalsConditions().size(), alaFromGet.equalsConditions().size()); - Assertions - .assertEquals(ala.equalsConditions().get("category"), alaFromGet.equalsConditions().get("category")); - assertResourceIdEquals(ala.equalsConditions().get("resourceId"), alaFromGet.equalsConditions().get("resourceId")); + Assertions.assertEquals(ala.equalsConditions().get("category"), alaFromGet.equalsConditions().get("category")); + assertResourceIdEquals(ala.equalsConditions().get("resourceId"), + alaFromGet.equalsConditions().get("resourceId")); Assertions.assertEquals(ala.equalsConditions().get("status"), alaFromGet.equalsConditions().get("status")); - Assertions - .assertEquals( - ala.equalsConditions().containsKey("operationName"), - alaFromGet.equalsConditions().containsKey("operationName")); + Assertions.assertEquals(ala.equalsConditions().containsKey("operationName"), + alaFromGet.equalsConditions().containsKey("operationName")); monitorManager.alertRules().activityLogAlerts().deleteById(ala.id()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/AutoscaleTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/AutoscaleTests.java index 0e6bc47ef6083..89a5d501d7336 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/AutoscaleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/AutoscaleTests.java @@ -46,67 +46,60 @@ protected void cleanUpResources() { public void canCRUDAutoscale() throws Exception { try { - resourceManager - .resourceGroups() + resourceManager.resourceGroups() .define(rgName) .withRegion(Region.US_EAST2) .withTag("type", "autoscale") .withTag("tagname", "tagvalue") .create(); - AppServicePlan servicePlan = - appServiceManager - .appServicePlans() - .define("HighlyAvailableWebApps") - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withPricingTier(PricingTier.PREMIUM_P1) - .withOperatingSystem(OperatingSystem.WINDOWS) - .create(); - - AutoscaleSetting setting = - monitorManager - .autoscaleSettings() - .define("somesettingZ") - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withTargetResource(servicePlan.id()) - .defineAutoscaleProfile("Default") - .withScheduleBasedScale(3) - .withRecurrentSchedule("UTC", "18:00", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.SATURDAY) - .attach() - .defineAutoscaleProfile("AutoScaleProfile1") - .withMetricBasedScale(1, 10, 1) - .defineScaleRule() - .withMetricSource(servicePlan.id()) - // current swagger does not support namespace selection - // .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms") - .withMetricName("CPUPercentage") - .withStatistic(Duration.ofMinutes(10), Duration.ofMinutes(1), MetricStatisticType.AVERAGE) - .withCondition(TimeAggregationType.AVERAGE, ComparisonOperationType.GREATER_THAN, 70) - .withScaleAction(ScaleDirection.INCREASE, ScaleType.EXACT_COUNT, 10, Duration.ofHours(12)) - .attach() - .withFixedDateSchedule( - "UTC", - OffsetDateTime.parse("2050-10-12T20:15:10Z"), - OffsetDateTime.parse("2051-09-11T16:08:04Z")) - .attach() - .defineAutoscaleProfile("AutoScaleProfile2") - .withMetricBasedScale(1, 5, 3) - .defineScaleRule() - .withMetricSource(servicePlan.id()) - .withMetricName("CPUPercentage") - .withStatistic(Duration.ofMinutes(10), Duration.ofMinutes(1), MetricStatisticType.AVERAGE) - .withCondition(TimeAggregationType.AVERAGE, ComparisonOperationType.LESS_THAN, 20) - .withScaleAction(ScaleDirection.DECREASE, ScaleType.EXACT_COUNT, 1, Duration.ofHours(3)) - .attach() - .withRecurrentSchedule("UTC", "12:13", DayOfWeek.FRIDAY) - .attach() - .withAdminEmailNotification() - .withCoAdminEmailNotification() - .withCustomEmailsNotification("me@mycorp.com", "you@mycorp.com", "him@mycorp.com") - .withAutoscaleDisabled() - .create(); + AppServicePlan servicePlan = appServiceManager.appServicePlans() + .define("HighlyAvailableWebApps") + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.PREMIUM_P1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); + + AutoscaleSetting setting = monitorManager.autoscaleSettings() + .define("somesettingZ") + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withTargetResource(servicePlan.id()) + .defineAutoscaleProfile("Default") + .withScheduleBasedScale(3) + .withRecurrentSchedule("UTC", "18:00", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.SATURDAY) + .attach() + .defineAutoscaleProfile("AutoScaleProfile1") + .withMetricBasedScale(1, 10, 1) + .defineScaleRule() + .withMetricSource(servicePlan.id()) + // current swagger does not support namespace selection + // .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms") + .withMetricName("CPUPercentage") + .withStatistic(Duration.ofMinutes(10), Duration.ofMinutes(1), MetricStatisticType.AVERAGE) + .withCondition(TimeAggregationType.AVERAGE, ComparisonOperationType.GREATER_THAN, 70) + .withScaleAction(ScaleDirection.INCREASE, ScaleType.EXACT_COUNT, 10, Duration.ofHours(12)) + .attach() + .withFixedDateSchedule("UTC", OffsetDateTime.parse("2050-10-12T20:15:10Z"), + OffsetDateTime.parse("2051-09-11T16:08:04Z")) + .attach() + .defineAutoscaleProfile("AutoScaleProfile2") + .withMetricBasedScale(1, 5, 3) + .defineScaleRule() + .withMetricSource(servicePlan.id()) + .withMetricName("CPUPercentage") + .withStatistic(Duration.ofMinutes(10), Duration.ofMinutes(1), MetricStatisticType.AVERAGE) + .withCondition(TimeAggregationType.AVERAGE, ComparisonOperationType.LESS_THAN, 20) + .withScaleAction(ScaleDirection.DECREASE, ScaleType.EXACT_COUNT, 1, Duration.ofHours(3)) + .attach() + .withRecurrentSchedule("UTC", "12:13", DayOfWeek.FRIDAY) + .attach() + .withAdminEmailNotification() + .withCoAdminEmailNotification() + .withCustomEmailsNotification("me@mycorp.com", "you@mycorp.com", "him@mycorp.com") + .withAutoscaleDisabled() + .create(); Assertions.assertNotNull(setting); Assertions.assertEquals("somesettingZ", setting.name()); @@ -154,10 +147,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertEquals(1, tempProfile.minInstanceCount()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2050-10-12T20:15:10Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2051-09-11T16:08:04Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2050-10-12T20:15:10Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2051-09-11T16:08:04Z"), + tempProfile.fixedDateSchedule().end()); Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.rules()); Assertions.assertEquals(1, tempProfile.rules().size()); @@ -256,10 +249,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertEquals(1, tempProfile.minInstanceCount()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2050-10-12T20:15:10Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2051-09-11T16:08:04Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2050-10-12T20:15:10Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2051-09-11T16:08:04Z"), + tempProfile.fixedDateSchedule().end()); Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.rules()); Assertions.assertEquals(1, tempProfile.rules().size()); @@ -311,12 +304,11 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertEquals(Duration.ofHours(3), rule.cooldown()); // Update - setting - .update() + setting.update() .defineAutoscaleProfile("very new profile") .withScheduleBasedScale(10) - .withFixedDateSchedule( - "UTC", OffsetDateTime.parse("2030-02-12T20:15:10Z"), OffsetDateTime.parse("2030-02-12T20:45:10Z")) + .withFixedDateSchedule("UTC", OffsetDateTime.parse("2030-02-12T20:15:10Z"), + OffsetDateTime.parse("2030-02-12T20:45:10Z")) .attach() .defineAutoscaleProfile("a new profile") .withMetricBasedScale(5, 7, 6) @@ -332,8 +324,8 @@ public void canCRUDAutoscale() throws Exception { .updateScaleRule(0) .withStatistic(Duration.ofMinutes(15), Duration.ofMinutes(1), MetricStatisticType.AVERAGE) .parent() - .withFixedDateSchedule( - "UTC", OffsetDateTime.parse("2025-02-02T02:02:02Z"), OffsetDateTime.parse("2025-02-02T03:03:03Z")) + .withFixedDateSchedule("UTC", OffsetDateTime.parse("2025-02-02T02:02:02Z"), + OffsetDateTime.parse("2025-02-02T03:03:03Z")) .defineScaleRule() .withMetricSource(servicePlan.id()) .withMetricName("CPUPercentage") @@ -397,10 +389,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2030-02-12T20:15:10Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2030-02-12T20:45:10Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2030-02-12T20:15:10Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2030-02-12T20:45:10Z"), + tempProfile.fixedDateSchedule().end()); tempProfile = setting.profiles().get("a new profile"); Assertions.assertNotNull(tempProfile); @@ -435,10 +427,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2025-02-02T02:02:02Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2025-02-02T03:03:03Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2025-02-02T02:02:02Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2025-02-02T03:03:03Z"), + tempProfile.fixedDateSchedule().end()); Assertions.assertNotNull(tempProfile.rules()); Assertions.assertEquals(1, tempProfile.rules().size()); @@ -508,10 +500,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2030-02-12T20:15:10Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2030-02-12T20:45:10Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2030-02-12T20:15:10Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2030-02-12T20:45:10Z"), + tempProfile.fixedDateSchedule().end()); tempProfile = settingFromGet.profiles().get("a new profile"); Assertions.assertNotNull(tempProfile); @@ -546,10 +538,10 @@ public void canCRUDAutoscale() throws Exception { Assertions.assertNull(tempProfile.recurrentSchedule()); Assertions.assertNotNull(tempProfile.fixedDateSchedule()); Assertions.assertTrue(tempProfile.fixedDateSchedule().timeZone().equalsIgnoreCase("UTC")); - Assertions - .assertEquals(OffsetDateTime.parse("2025-02-02T02:02:02Z"), tempProfile.fixedDateSchedule().start()); - Assertions - .assertEquals(OffsetDateTime.parse("2025-02-02T03:03:03Z"), tempProfile.fixedDateSchedule().end()); + Assertions.assertEquals(OffsetDateTime.parse("2025-02-02T02:02:02Z"), + tempProfile.fixedDateSchedule().start()); + Assertions.assertEquals(OffsetDateTime.parse("2025-02-02T03:03:03Z"), + tempProfile.fixedDateSchedule().end()); Assertions.assertNotNull(tempProfile.rules()); Assertions.assertEquals(1, tempProfile.rules().size()); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/DiagnosticSettingsTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/DiagnosticSettingsTests.java index 5eda027733700..bbbf351e1b6bf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/DiagnosticSettingsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/DiagnosticSettingsTests.java @@ -61,43 +61,44 @@ public void canCRUDDiagnosticSettings() { VirtualMachine vm = ensureVM(region, resourceGroup, vmName, "10.0.0.0/28"); // clean all diagnostic settings. - List dsList = monitorManager.diagnosticSettings().listByResource(vm.id()).stream().collect(Collectors.toList()); + List dsList + = monitorManager.diagnosticSettings().listByResource(vm.id()).stream().collect(Collectors.toList()); for (DiagnosticSetting dsd : dsList) { monitorManager.diagnosticSettings().deleteById(dsd.id()); } StorageAccount sa = storageManager.storageAccounts() - .define(saName) - // Storage Account should be in the same region as resource - .withRegion(vm.region()) - .withNewResourceGroup(rgName) - .withTag("tag1", "value1") - .create(); + .define(saName) + // Storage Account should be in the same region as resource + .withRegion(vm.region()) + .withNewResourceGroup(rgName) + .withTag("tag1", "value1") + .create(); EventHubNamespace namespace = eventHubManager.namespaces() - .define(ehName) - // EventHub should be in the same region as resource - .withRegion(vm.region()) - .withNewResourceGroup(rgName) - .withNewManageRule("mngRule1") - .withNewSendRule("sndRule1") - .create(); + .define(ehName) + // EventHub should be in the same region as resource + .withRegion(vm.region()) + .withNewResourceGroup(rgName) + .withNewManageRule("mngRule1") + .withNewSendRule("sndRule1") + .create(); EventHubNamespaceAuthorizationRule evenHubNsRule = namespace.listAuthorizationRules().iterator().next(); - List categories = monitorManager.diagnosticSettings() - .listCategoriesByResource(vm.id()); + List categories + = monitorManager.diagnosticSettings().listCategoriesByResource(vm.id()); Assertions.assertNotNull(categories); Assertions.assertFalse(categories.isEmpty()); DiagnosticSetting setting = monitorManager.diagnosticSettings() - .define(dsName) - .withResource(vm.id()) - .withStorageAccount(sa.id()) - .withEventHub(evenHubNsRule.id()) - .withLogsAndMetrics(categories, Duration.ofMinutes(5), 7) - .create(); + .define(dsName) + .withResource(vm.id()) + .withStorageAccount(sa.id()) + .withEventHub(evenHubNsRule.id()) + .withLogsAndMetrics(categories, Duration.ofMinutes(5), 7) + .create(); assertResourceIdEquals(vm.id(), setting.resourceId()); assertResourceIdEquals(sa.id(), setting.storageAccountId()); @@ -107,10 +108,7 @@ public void canCRUDDiagnosticSettings() { Assertions.assertTrue(setting.logs().isEmpty()); Assertions.assertFalse(setting.metrics().isEmpty()); - setting.update() - .withoutStorageAccount() - .withoutLogs() - .apply(); + setting.update().withoutStorageAccount().withoutLogs().apply(); assertResourceIdEquals(vm.id(), setting.resourceId()); assertResourceIdEquals(evenHubNsRule.id(), setting.eventHubAuthorizationRuleId()); @@ -174,30 +172,24 @@ public void canCRUDDiagnosticSettingsForSubscription() { checkDiagnosticSettingValues(setting, ds2); // removing all metrics and logs from a diagnostic setting, is equivalent to deleting the setting itself - setting.update() - .withoutLog("Security") - .apply(); + setting.update().withoutLog("Security").apply(); // "get" will throw 404 since the setting is deleted Assertions.assertThrows(ManagementException.class, setting::refresh); - Assertions.assertFalse( - monitorManager.diagnosticSettings() - .listByResource(resourceId) - .stream() - .anyMatch(s -> s.name().equals(dsName))); + Assertions.assertFalse(monitorManager.diagnosticSettings() + .listByResource(resourceId) + .stream() + .anyMatch(s -> s.name().equals(dsName))); - setting.update() - .withLog("Security", 7) - .apply(); + setting.update().withLog("Security", 7).apply(); setting.refresh(); - Assertions.assertTrue( - monitorManager.diagnosticSettings() - .listByResource(resourceId) - .stream() - .anyMatch(s -> s.name().equals(dsName))); + Assertions.assertTrue(monitorManager.diagnosticSettings() + .listByResource(resourceId) + .stream() + .anyMatch(s -> s.name().equals(dsName))); } finally { monitorManager.diagnosticSettings().deleteById(setting.id()); } @@ -209,32 +201,33 @@ public void canCRUDDiagnosticSettingsForVault() { Region region = Region.US_WEST; StorageAccount sa = storageManager.storageAccounts() - .define(saName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withTag("tag1", "value1") - .create(); + .define(saName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withTag("tag1", "value1") + .create(); Vault vault = ensureVault(region, rgName); // clean all diagnostic settings. - List dsList = monitorManager.diagnosticSettings().listByResource(vault.id()).stream().collect(Collectors.toList()); + List dsList + = monitorManager.diagnosticSettings().listByResource(vault.id()).stream().collect(Collectors.toList()); for (DiagnosticSetting dsd : dsList) { monitorManager.diagnosticSettings().deleteById(dsd.id()); } - List categories = monitorManager.diagnosticSettings() - .listCategoriesByResource(vault.id()); + List categories + = monitorManager.diagnosticSettings().listCategoriesByResource(vault.id()); Assertions.assertNotNull(categories); Assertions.assertFalse(categories.isEmpty()); DiagnosticSetting setting = monitorManager.diagnosticSettings() - .define(dsName) - .withResource(vault.id()) - .withStorageAccount(sa.id()) - .withLogsAndMetrics(categories, Duration.ofMinutes(5), 7) - .create(); + .define(dsName) + .withResource(vault.id()) + .withStorageAccount(sa.id()) + .withLogsAndMetrics(categories, Duration.ofMinutes(5), 7) + .create(); Assertions.assertTrue(vault.id().equalsIgnoreCase(setting.resourceId())); Assertions.assertNotNull(setting.storageAccountId()); @@ -244,9 +237,7 @@ public void canCRUDDiagnosticSettingsForVault() { Assertions.assertFalse(setting.logs().isEmpty()); Assertions.assertFalse(setting.metrics().isEmpty()); - setting.update() - .withoutLogs() - .apply(); + setting.update().withoutLogs().apply(); Assertions.assertTrue(vault.id().equalsIgnoreCase(setting.resourceId())); Assertions.assertNotNull(setting.storageAccountId()); @@ -269,26 +260,27 @@ public void canCRUDDiagnosticSettingsForVault() { checkDiagnosticSettingValues(setting, ds3); DiagnosticSettingsResourceInner inner = setting.innerModel(); - inner.withLogs(new ArrayList<>()) - .logs().add(new LogSettings().withEnabled(true).withCategoryGroup("audit")); - monitorManager.serviceClient().getDiagnosticSettingsOperations().createOrUpdate(vault.id(), setting.name(), inner); + inner.withLogs(new ArrayList<>()).logs().add(new LogSettings().withEnabled(true).withCategoryGroup("audit")); + monitorManager.serviceClient() + .getDiagnosticSettingsOperations() + .createOrUpdate(vault.id(), setting.name(), inner); setting.refresh(); - Assertions.assertTrue(setting.logs().stream().anyMatch(logSettings -> "audit".equals(logSettings.categoryGroup()))); + Assertions + .assertTrue(setting.logs().stream().anyMatch(logSettings -> "audit".equals(logSettings.categoryGroup()))); // verify category logs and category group logs can both be present during update // issue: https://github.com/Azure/azure-sdk-for-java/issues/35425 // mixture of category group and category logs aren't supported - Assertions.assertThrows(ManagementException.class, - () -> setting.update() - .withLog("AuditEvent", 7) - .apply()); + Assertions.assertThrows(ManagementException.class, () -> setting.update().withLog("AuditEvent", 7).apply()); setting.refresh(); - Assertions.assertTrue(setting.logs().stream().anyMatch(logSettings -> "audit".equals(logSettings.categoryGroup()))); - Assertions.assertTrue(setting.logs().stream().noneMatch(logSettings -> "AuditEvent".equals(logSettings.category()))); + Assertions + .assertTrue(setting.logs().stream().anyMatch(logSettings -> "audit".equals(logSettings.categoryGroup()))); + Assertions + .assertTrue(setting.logs().stream().noneMatch(logSettings -> "AuditEvent".equals(logSettings.category()))); Assertions.assertTrue(setting.logs().stream().allMatch(logSettings -> logSettings.category() == null)); Assertions.assertFalse(setting.metrics().isEmpty()); @@ -306,7 +298,8 @@ public void canCRUDDiagnosticSettingsLogsCategoryGroup() { String wpsName = generateRandomResourceName("jMonitorWps", 18); // resource (webpubsub) to monitor - GenericResource wpsResource = monitorManager.resourceManager().genericResources() + GenericResource wpsResource = monitorManager.resourceManager() + .genericResources() .define(wpsName) .withRegion(region) .withNewResourceGroup(rgName) @@ -336,17 +329,20 @@ public void canCRUDDiagnosticSettingsLogsCategoryGroup() { // add category group "audit" to log settings DiagnosticSettingsResourceInner inner = setting.innerModel(); inner.logs().clear(); // Remove category "MessagingLogs". Diagnostic setting does not support mix of log category and log category group. - inner.logs().add(new LogSettings().withCategoryGroup("audit").withEnabled(true).withRetentionPolicy(new RetentionPolicy().withEnabled(false))); - monitorManager.serviceClient().getDiagnosticSettingsOperations().createOrUpdate(wpsResource.id(), dsName, inner); + inner.logs() + .add(new LogSettings().withCategoryGroup("audit") + .withEnabled(true) + .withRetentionPolicy(new RetentionPolicy().withEnabled(false))); + monitorManager.serviceClient() + .getDiagnosticSettingsOperations() + .createOrUpdate(wpsResource.id(), dsName, inner); // verify category group "audit" setting = monitorManager.diagnosticSettings().listByResource(wpsResource.id()).iterator().next(); Assertions.assertTrue(setting.logs().stream().anyMatch(ls -> "audit".equals(ls.categoryGroup()))); // update to add metric - setting.update() - .withMetric("AllMetrics", Duration.ofMinutes(5), 7) - .apply(); + setting.update().withMetric("AllMetrics", Duration.ofMinutes(5), 7).apply(); // verify category group "audit" setting = monitorManager.diagnosticSettings().listByResource(wpsResource.id()).iterator().next(); @@ -369,13 +365,16 @@ public void canCRUDDiagnosticSettingsWithResourceIdWhiteSpace() { SqlElasticPool sqlElasticPool = ensureElasticPoolWithWhiteSpace(region, rgName); // clean all diagnostic settings. - List dsList = monitorManager.diagnosticSettings().listByResource(sqlElasticPool.id()).stream().collect(Collectors.toList()); + List dsList = monitorManager.diagnosticSettings() + .listByResource(sqlElasticPool.id()) + .stream() + .collect(Collectors.toList()); for (DiagnosticSetting dsd : dsList) { monitorManager.diagnosticSettings().deleteById(dsd.id()); } - List categories = monitorManager.diagnosticSettings() - .listCategoriesByResource(sqlElasticPool.id()); + List categories + = monitorManager.diagnosticSettings().listCategoriesByResource(sqlElasticPool.id()); Assertions.assertNotNull(categories); Assertions.assertFalse(categories.isEmpty()); @@ -394,9 +393,7 @@ public void canCRUDDiagnosticSettingsWithResourceIdWhiteSpace() { Assertions.assertNull(setting.workspaceId()); Assertions.assertFalse(setting.metrics().isEmpty()); - setting.update() - .withoutMetric("InstanceAndAppAdvanced") - .apply(); + setting.update().withoutMetric("InstanceAndAppAdvanced").apply(); Assertions.assertTrue(sqlElasticPool.id().equalsIgnoreCase(setting.resourceId())); Assertions.assertNotNull(setting.storageAccountId()); @@ -412,7 +409,10 @@ public void canCRUDDiagnosticSettingsWithResourceIdWhiteSpace() { DiagnosticSetting ds2 = monitorManager.diagnosticSettings().getById(setting.id()); checkDiagnosticSettingValues(setting, ds2); - dsList = monitorManager.diagnosticSettings().listByResource(sqlElasticPool.id()).stream().collect(Collectors.toList()); + dsList = monitorManager.diagnosticSettings() + .listByResource(sqlElasticPool.id()) + .stream() + .collect(Collectors.toList()); Assertions.assertNotNull(dsList); Assertions.assertEquals(1, dsList.size()); DiagnosticSetting ds3 = dsList.get(0); @@ -420,7 +420,10 @@ public void canCRUDDiagnosticSettingsWithResourceIdWhiteSpace() { monitorManager.diagnosticSettings().deleteById(setting.id()); - dsList = monitorManager.diagnosticSettings().listByResource(sqlElasticPool.id()).stream().collect(Collectors.toList()); + dsList = monitorManager.diagnosticSettings() + .listByResource(sqlElasticPool.id()) + .stream() + .collect(Collectors.toList()); Assertions.assertNotNull(dsList); Assertions.assertTrue(dsList.isEmpty()); @@ -432,13 +435,19 @@ public void canCRUDDiagnosticSettingsWithResourceIdWhiteSpace() { .withLogsAndMetrics(categories, Duration.ofMinutes(5), 7) .create(); - dsList = monitorManager.diagnosticSettings().listByResource(sqlElasticPool.id()).stream().collect(Collectors.toList()); + dsList = monitorManager.diagnosticSettings() + .listByResource(sqlElasticPool.id()) + .stream() + .collect(Collectors.toList()); Assertions.assertNotNull(dsList); Assertions.assertEquals(1, dsList.size()); monitorManager.diagnosticSettings().deleteByIds(setting.id()); - dsList = monitorManager.diagnosticSettings().listByResource(sqlElasticPool.id()).stream().collect(Collectors.toList()); + dsList = monitorManager.diagnosticSettings() + .listByResource(sqlElasticPool.id()) + .stream() + .collect(Collectors.toList()); Assertions.assertNotNull(dsList); Assertions.assertTrue(dsList.isEmpty()); } @@ -460,9 +469,8 @@ private void checkDiagnosticSettingValues(DiagnosticSetting expected, Diagnostic if (expected.eventHubAuthorizationRuleId() == null) { Assertions.assertNull(actual.eventHubAuthorizationRuleId()); } else { - Assertions - .assertTrue( - expected.eventHubAuthorizationRuleId().equalsIgnoreCase(actual.eventHubAuthorizationRuleId())); + Assertions.assertTrue( + expected.eventHubAuthorizationRuleId().equalsIgnoreCase(actual.eventHubAuthorizationRuleId())); } if (expected.eventHubName() == null) { Assertions.assertNull(actual.eventHubName()); @@ -473,15 +481,13 @@ private void checkDiagnosticSettingValues(DiagnosticSetting expected, Diagnostic if (expected.logs() == null) { Assertions.assertNull(actual.logs()); } else { - Assertions.assertEquals( - expected.logs().stream().filter(LogSettings::enabled).count(), + Assertions.assertEquals(expected.logs().stream().filter(LogSettings::enabled).count(), actual.logs().stream().filter(LogSettings::enabled).count()); } if (expected.metrics() == null) { Assertions.assertNull(actual.metrics()); } else { - Assertions.assertEquals( - expected.metrics().stream().filter(MetricSettings::enabled).count(), + Assertions.assertEquals(expected.metrics().stream().filter(MetricSettings::enabled).count(), actual.metrics().stream().filter(MetricSettings::enabled).count()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java index dee1fa063b696..e177c610c4471 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java @@ -29,6 +29,7 @@ public class MonitorActivityAndMetricsTests extends MonitorManagementTest { private static final ClientLogger LOGGER = new ClientLogger(MonitorActivityAndMetricsTests.class); private String rgName = ""; + @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("jMonitor_", 18); @@ -48,9 +49,7 @@ public void canListEventsAndMetrics() { Region region = Region.US_WEST; String vmName = generateRandomResourceName("jMonitorVm_", 18); VirtualMachine vm = ensureVM(region, - resourceManager.resourceGroups().define(rgName).withRegion(region).create(), - vmName, - "10.0.0.0/28"); + resourceManager.resourceGroups().define(rgName).withRegion(region).create(), vmName, "10.0.0.0/28"); OffsetDateTime now = OffsetDateTime.now(); LOGGER.log(LogLevel.VERBOSE, () -> "record timestamp: " + now); @@ -67,13 +66,11 @@ public void canListEventsAndMetrics() { Assertions.assertNotNull(mDef.supportedAggregationTypes()); // Metric - MetricCollection metrics = - mDef - .defineQuery() - .startingFrom(recordDateTime.minusDays(30)) - .endsBefore(recordDateTime) - .withResultType(ResultType.DATA) - .execute(); + MetricCollection metrics = mDef.defineQuery() + .startingFrom(recordDateTime.minusDays(30)) + .endsBefore(recordDateTime) + .withResultType(ResultType.DATA) + .execute(); Assertions.assertNotNull(metrics); Assertions.assertNotNull(metrics.namespace()); @@ -81,19 +78,14 @@ public void canListEventsAndMetrics() { Assertions.assertEquals("Microsoft.Compute/virtualMachines", metrics.namespace()); // Activity Logs - PagedIterable retVal = - monitorManager - .activityLogs() - .defineQuery() - .startingFrom(recordDateTime.minusDays(30)) - .endsBefore(recordDateTime) - .withResponseProperties( - EventDataPropertyName.RESOURCEID, - EventDataPropertyName.EVENTTIMESTAMP, - EventDataPropertyName.OPERATIONNAME, - EventDataPropertyName.EVENTNAME) - .filterByResource(vm.id()) - .execute(); + PagedIterable retVal = monitorManager.activityLogs() + .defineQuery() + .startingFrom(recordDateTime.minusDays(30)) + .endsBefore(recordDateTime) + .withResponseProperties(EventDataPropertyName.RESOURCEID, EventDataPropertyName.EVENTTIMESTAMP, + EventDataPropertyName.OPERATIONNAME, EventDataPropertyName.EVENTNAME) + .filterByResource(vm.id()) + .execute(); Assertions.assertNotNull(retVal); for (EventData event : retVal) { @@ -119,16 +111,12 @@ public void canListEventsAndMetrics() { // List Activity logs at tenant level is not allowed for the current tenant try { - monitorManager - .activityLogs() + monitorManager.activityLogs() .defineQuery() .startingFrom(recordDateTime.minusDays(30)) .endsBefore(recordDateTime) - .withResponseProperties( - EventDataPropertyName.RESOURCEID, - EventDataPropertyName.EVENTTIMESTAMP, - EventDataPropertyName.OPERATIONNAME, - EventDataPropertyName.EVENTNAME) + .withResponseProperties(EventDataPropertyName.RESOURCEID, EventDataPropertyName.EVENTTIMESTAMP, + EventDataPropertyName.OPERATIONNAME, EventDataPropertyName.EVENTNAME) .filterByResource(vm.id()) .filterAtTenantLevel() .execute(); @@ -161,13 +149,11 @@ public void canListEventsAndMetricsWithWhiteSpaceInResourceId() { Assertions.assertNotNull(mDef.supportedAggregationTypes()); // Metric - MetricCollection metrics = - mDef - .defineQuery() - .startingFrom(recordDateTime.minusDays(30)) - .endsBefore(recordDateTime) - .withResultType(ResultType.DATA) - .execute(); + MetricCollection metrics = mDef.defineQuery() + .startingFrom(recordDateTime.minusDays(30)) + .endsBefore(recordDateTime) + .withResultType(ResultType.DATA) + .execute(); Assertions.assertNotNull(metrics); Assertions.assertNotNull(metrics.namespace()); @@ -175,19 +161,14 @@ public void canListEventsAndMetricsWithWhiteSpaceInResourceId() { Assertions.assertEquals("Microsoft.Sql/servers/elasticPools", metrics.namespace()); // Activity Logs - PagedIterable retVal = - monitorManager - .activityLogs() - .defineQuery() - .startingFrom(recordDateTime.minusDays(30)) - .endsBefore(recordDateTime) - .withResponseProperties( - EventDataPropertyName.RESOURCEID, - EventDataPropertyName.EVENTTIMESTAMP, - EventDataPropertyName.OPERATIONNAME, - EventDataPropertyName.EVENTNAME) - .filterByResource(pool.id()) - .execute(); + PagedIterable retVal = monitorManager.activityLogs() + .defineQuery() + .startingFrom(recordDateTime.minusDays(30)) + .endsBefore(recordDateTime) + .withResponseProperties(EventDataPropertyName.RESOURCEID, EventDataPropertyName.EVENTTIMESTAMP, + EventDataPropertyName.OPERATIONNAME, EventDataPropertyName.EVENTNAME) + .filterByResource(pool.id()) + .execute(); Assertions.assertNotNull(retVal); for (EventData event : retVal) { @@ -213,16 +194,12 @@ public void canListEventsAndMetricsWithWhiteSpaceInResourceId() { // List Activity logs at tenant level is not allowed for the current tenant try { - monitorManager - .activityLogs() + monitorManager.activityLogs() .defineQuery() .startingFrom(recordDateTime.minusDays(30)) .endsBefore(recordDateTime) - .withResponseProperties( - EventDataPropertyName.RESOURCEID, - EventDataPropertyName.EVENTTIMESTAMP, - EventDataPropertyName.OPERATIONNAME, - EventDataPropertyName.EVENTNAME) + .withResponseProperties(EventDataPropertyName.RESOURCEID, EventDataPropertyName.EVENTTIMESTAMP, + EventDataPropertyName.OPERATIONNAME, EventDataPropertyName.EVENTNAME) .filterByResource(pool.id()) .filterAtTenantLevel() .execute(); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorManagementTest.java index 9acbda0c63fdb..573382048e3fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorManagementTest.java @@ -45,21 +45,10 @@ public class MonitorManagementTest extends ResourceManagerTestProxyTestBase { protected SqlServerManager sqlServerManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -83,7 +72,8 @@ protected void cleanUpResources() { } protected VirtualMachine ensureVM(Region region, ResourceGroup resourceGroup, String vmName, String addressSpace) { - return computeManager.virtualMachines().define(vmName) + return computeManager.virtualMachines() + .define(vmName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withNewPrimaryNetwork(addressSpace) @@ -96,8 +86,7 @@ protected VirtualMachine ensureVM(Region region, ResourceGroup resourceGroup, St } protected Vault ensureVault(Region region, String rgName) { - return keyVaultManager - .vaults() + return keyVaultManager.vaults() .define(generateRandomResourceName("jmonitorvt", 18)) .withRegion(region) .withExistingResourceGroup(rgName) @@ -108,8 +97,7 @@ protected Vault ensureVault(Region region, String rgName) { protected SqlElasticPool ensureElasticPoolWithWhiteSpace(Region region, String rgName) { String sqlServerName = generateRandomResourceName("JMonitorSql-", 18); - SqlServer sqlServer = sqlServerManager - .sqlServers() + SqlServer sqlServer = sqlServerManager.sqlServers() .define(sqlServerName) .withRegion(region) .withNewResourceGroup(rgName) @@ -118,10 +106,7 @@ protected SqlElasticPool ensureElasticPoolWithWhiteSpace(Region region, String r .create(); // white space in pool name - SqlElasticPool pool = sqlServer.elasticPools() - .define("name with space") - .withBasicPool() - .create(); + SqlElasticPool pool = sqlServer.elasticPools().define("name with space").withBasicPool().create(); return pool; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/ScheduledQueryTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/ScheduledQueryTests.java index 6540f67279595..3717796d15569 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/ScheduledQueryTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/ScheduledQueryTests.java @@ -42,25 +42,22 @@ protected void cleanUpResources() { public void createScheduledQuery() { Region region = Region.AUSTRALIA_SOUTHEAST; String actionGroupName = generateRandomResourceName("ag", 15); - ActionGroup ag = - monitorManager - .actionGroups() - .define(actionGroupName) - .withNewResourceGroup(rgName, region) - .defineReceiver("first") - .withPushNotification("azurepush@outlook.com") - .withEmail("justemail@outlook.com") - .withSms("1", "4255655665") - .withVoice("1", "2062066050") - .withWebhook("https://www.rate.am") - .attach() - .defineReceiver("second") - .withEmail("secondemail@outlook.com") - .withWebhook("https://www.spyur.am") - .attach() - .create(); - ScheduledQueryRuleResourceInner resourceInner = monitorManager - .serviceClient() + ActionGroup ag = monitorManager.actionGroups() + .define(actionGroupName) + .withNewResourceGroup(rgName, region) + .defineReceiver("first") + .withPushNotification("azurepush@outlook.com") + .withEmail("justemail@outlook.com") + .withSms("1", "4255655665") + .withVoice("1", "2062066050") + .withWebhook("https://www.rate.am") + .attach() + .defineReceiver("second") + .withEmail("secondemail@outlook.com") + .withWebhook("https://www.spyur.am") + .attach() + .create(); + ScheduledQueryRuleResourceInner resourceInner = monitorManager.serviceClient() .getScheduledQueryRules() .createOrUpdateWithResponse(rgName, generateRandomResourceName("perf", 15), new ScheduledQueryRuleResourceInner().withLocation(region.name()) @@ -92,8 +89,10 @@ public void createScheduledQuery() { .withCheckWorkspaceAlertsStorageConfigured(false) .withSkipQueryValidation(true) .withAutoMitigate(false), - com.azure.core.util.Context.NONE).getValue(); - resourceInner = monitorManager.serviceClient().getScheduledQueryRules().getByResourceGroup(rgName, resourceInner.name()); + com.azure.core.util.Context.NONE) + .getValue(); + resourceInner + = monitorManager.serviceClient().getScheduledQueryRules().getByResourceGroup(rgName, resourceInner.name()); Assertions.assertEquals(AlertSeverity.FOUR, resourceInner.severity()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/TypeSerializationTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/TypeSerializationTests.java index 656373e9645d9..2bc3a3e201c4f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/TypeSerializationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/TypeSerializationTests.java @@ -30,8 +30,10 @@ public void testDiscriminatorSerialization() throws Exception { String metricAlertInnerJson = adapter.serialize(metricAlertInner, SerializerEncoding.JSON); checkOdatatypeJson(metricAlertInnerJson); - MetricAlertResourceInner metricAlertInner2 = adapter.deserialize(metricAlertInnerJson, MetricAlertResourceInner.class, SerializerEncoding.JSON); - Assertions.assertTrue(metricAlertInner2.criteria() instanceof MetricAlertMultipleResourceMultipleMetricCriteria); + MetricAlertResourceInner metricAlertInner2 + = adapter.deserialize(metricAlertInnerJson, MetricAlertResourceInner.class, SerializerEncoding.JSON); + Assertions + .assertTrue(metricAlertInner2.criteria() instanceof MetricAlertMultipleResourceMultipleMetricCriteria); AlertRuleResourceInner alertRuleInner = new AlertRuleResourceInner(); alertRuleInner.withActions(Arrays.asList(new RuleEmailAction())); @@ -39,10 +41,10 @@ public void testDiscriminatorSerialization() throws Exception { String alertRuleInnerJson = adapter.serialize(alertRuleInner, SerializerEncoding.JSON); checkOdatatypeJson(alertRuleInnerJson); -// LogSearchRuleResourceInner logSearchRuleInner = new LogSearchRuleResourceInner(); -// logSearchRuleInner.withAction(new AlertingAction()); -// String logSearchRuleInnerJson = adapter.serialize(logSearchRuleInner, SerializerEncoding.JSON); -// checkOdatatypeJson(logSearchRuleInnerJson); + // LogSearchRuleResourceInner logSearchRuleInner = new LogSearchRuleResourceInner(); + // logSearchRuleInner.withAction(new AlertingAction()); + // String logSearchRuleInnerJson = adapter.serialize(logSearchRuleInner, SerializerEncoding.JSON); + // checkOdatatypeJson(logSearchRuleInnerJson); } private void checkOdatatypeJson(String json) { diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml index 3ac644b4619c5..a7cc6de39f33c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml @@ -45,6 +45,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/MsiManager.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/MsiManager.java index 97e29d8722e2e..47a96b9f55288 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/MsiManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/MsiManager.java @@ -88,8 +88,8 @@ public MsiManager authenticate(TokenCredential credential, AzureProfile profile) } private MsiManager(HttpPipeline httpPipeline, AzureProfile profile) { - super(httpPipeline, profile, new ManagedServiceIdentityClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new ManagedServiceIdentityClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentitesImpl.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentitesImpl.java index a79610bb3422e..3493ed0006f63 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentitesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentitesImpl.java @@ -13,12 +13,8 @@ /** * The implementation for Identities. */ -public final class IdentitesImpl - extends TopLevelModifiableResourcesImpl +public final class IdentitesImpl extends + TopLevelModifiableResourcesImpl implements Identities { public IdentitesImpl(UserAssignedIdentitiesClient innerCollection, MsiManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentityImpl.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentityImpl.java index 4b490e15cc339..2e930cad8fafd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentityImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/implementation/IdentityImpl.java @@ -18,17 +18,15 @@ /** * The implementation for Identity and its create and update interfaces. */ -public final class IdentityImpl - extends GroupableResourceImpl - implements Identity, Identity.Definition, Identity.Update { +public final class IdentityImpl extends GroupableResourceImpl + implements Identity, Identity.Definition, Identity.Update { private RoleAssignmentHelper roleAssignmentHelper; public IdentityImpl(String name, IdentityInner innerObject, MsiManager manager) { super(name, innerObject, manager); - this.roleAssignmentHelper = new RoleAssignmentHelper(manager.authorizationManager(), - this.taskGroup(), - this.idProvider()); + this.roleAssignmentHelper + = new RoleAssignmentHelper(manager.authorizationManager(), this.taskGroup(), this.idProvider()); } @Override @@ -108,17 +106,18 @@ public IdentityImpl withoutAccessTo(String resourceId, BuiltInRole role) { @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getUserAssignedIdentities() - .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) - .map(innerToFluentMap(this)); + return this.manager() + .serviceClient() + .getUserAssignedIdentities() + .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) + .map(innerToFluentMap(this)); } @Override protected Mono getInnerAsync() { - return this.myManager - .serviceClient() - .getUserAssignedIdentities() - .getByResourceGroupAsync(this.resourceGroupName(), this.name()); + return this.myManager.serviceClient() + .getUserAssignedIdentities() + .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } private RoleAssignmentHelper.IdProvider idProvider() { @@ -129,6 +128,7 @@ public String principalId() { Objects.requireNonNull(innerModel().principalId()); return innerModel().principalId().toString(); } + @Override public String resourceId() { Objects.requireNonNull(innerModel()); diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identities.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identities.java index 89d6328d911a3..232a599e0573b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identities.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identities.java @@ -20,15 +20,8 @@ * Entry point to Azure Managed Service Identity (MSI) Identity resource management API. */ @Fluent -public interface Identities extends - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsCreating, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface Identities extends SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsCreating, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identity.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identity.java index 8072e9bc37e15..f6dd57ee1cdda 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identity.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/main/java/com/azure/resourcemanager/msi/models/Identity.java @@ -15,15 +15,12 @@ import com.azure.resourcemanager.resources.fluentcore.model.Refreshable; import com.azure.resourcemanager.resources.fluentcore.model.Updatable; - /** * An immutable client-side representation of an Azure Managed Service Identity (MSI) Identity resource. */ @Fluent public interface Identity - extends GroupableResource, - Refreshable, - Updatable { + extends GroupableResource, Refreshable, Updatable { /** * @return id of the Azure Active Directory tenant to which the identity belongs to */ @@ -42,10 +39,7 @@ public interface Identity /** * Container interface for all the definitions related to identity. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { } /** @@ -140,10 +134,8 @@ interface WithAccess { * The stage of the identity definition which contains all the minimum required inputs for * the resource to be created but also allows for any other optional settings to be specified. */ - interface WithCreate extends - Resource.DefinitionWithTags, - Creatable, - DefinitionStages.WithAccess { + interface WithCreate + extends Resource.DefinitionWithTags, Creatable, DefinitionStages.WithAccess { } } @@ -244,9 +236,6 @@ interface WithAccess { /** * The template for an identity update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithAccess, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithAccess, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/test/java/com/azure/resourcemanager/msi/MSIIdentityManagementTests.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/test/java/com/azure/resourcemanager/msi/MSIIdentityManagementTests.java index 685dded9c2d03..0f03f956b4db0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/test/java/com/azure/resourcemanager/msi/MSIIdentityManagementTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/test/java/com/azure/resourcemanager/msi/MSIIdentityManagementTests.java @@ -39,21 +39,10 @@ public class MSIIdentityManagementTests extends ResourceManagerTestProxyTestBase private ResourceManager resourceManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -76,20 +65,20 @@ public void canCreateGetListDeleteIdentity() throws Exception { rgName = generateRandomResourceName("javaismrg", 15); String identityName = generateRandomResourceName("msi-id", 15); - Creatable creatableRG = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); Identity identity = msiManager.identities() - .define(identityName) - .withRegion(region) - .withNewResourceGroup(creatableRG) - .create(); + .define(identityName) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .create(); Assertions.assertNotNull(identity); Assertions.assertNotNull(identity.innerModel()); - Assertions.assertTrue(identityName.equalsIgnoreCase(identity.name()), String.format("%s == %s", identityName, identity.name())); - Assertions.assertTrue(rgName.equalsIgnoreCase(identity.resourceGroupName()), String.format("%s == %s", rgName, identity.resourceGroupName())); + Assertions.assertTrue(identityName.equalsIgnoreCase(identity.name()), + String.format("%s == %s", identityName, identity.name())); + Assertions.assertTrue(rgName.equalsIgnoreCase(identity.resourceGroupName()), + String.format("%s == %s", rgName, identity.resourceGroupName())); Assertions.assertNotNull(identity.clientId()); Assertions.assertNotNull(identity.principalId()); @@ -101,8 +90,7 @@ public void canCreateGetListDeleteIdentity() throws Exception { Assertions.assertNotNull(identity); Assertions.assertNotNull(identity.innerModel()); - PagedIterable identities = msiManager.identities() - .listByResourceGroup(rgName); + PagedIterable identities = msiManager.identities().listByResourceGroup(rgName); Assertions.assertNotNull(identities); @@ -121,8 +109,7 @@ public void canCreateGetListDeleteIdentity() throws Exception { Assertions.assertTrue(found); - msiManager.identities() - .deleteById(identity.id()); + msiManager.identities().deleteById(identity.id()); } @Test @@ -133,33 +120,32 @@ public void canAssignCurrentResourceGroupAccessRoleToIdentity() throws Exception rgName = generateRandomResourceName("javaismrg", 15); String identityName = generateRandomResourceName("msi-id", 15); - Creatable creatableRG = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); Identity identity = msiManager.identities() - .define(identityName) - .withRegion(region) - .withNewResourceGroup(creatableRG) - .withAccessToCurrentResourceGroup(BuiltInRole.READER) - .create(); + .define(identityName) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .withAccessToCurrentResourceGroup(BuiltInRole.READER) + .create(); // Ensure role assigned // ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(identity.resourceGroupName()); - PagedIterable roleAssignments = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); + PagedIterable roleAssignments + = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignments) { - if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { + if (roleAssignment.principalId() != null + && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } - Assertions.assertTrue(found, "Expected role assignment not found for the resource group that identity belongs to"); + Assertions.assertTrue(found, + "Expected role assignment not found for the resource group that identity belongs to"); - identity.update() - .withoutAccessTo(resourceGroup.id(), BuiltInRole.READER) - .apply(); + identity.update().withoutAccessTo(resourceGroup.id(), BuiltInRole.READER).apply(); ResourceManagerUtils.sleep(Duration.ofSeconds(30)); @@ -168,15 +154,15 @@ public void canAssignCurrentResourceGroupAccessRoleToIdentity() throws Exception roleAssignments = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); boolean notFound = true; for (RoleAssignment roleAssignment : roleAssignments) { - if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { + if (roleAssignment.principalId() != null + && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { notFound = false; break; } } Assertions.assertTrue(notFound, "Role assignment to access resource group is not removed"); - msiManager.identities() - .deleteById(identity.id()); + msiManager.identities().deleteById(identity.id()); } @@ -187,53 +173,51 @@ public void canAssignRolesToIdentity() throws Exception { String anotherRgName = generateRandomResourceName("rg", 15); - ResourceGroup anotherResourceGroup = resourceManager.resourceGroups() - .define(anotherRgName) - .withRegion(region) - .create(); + ResourceGroup anotherResourceGroup + = resourceManager.resourceGroups().define(anotherRgName).withRegion(region).create(); - Creatable creatableRG = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); Identity identity = msiManager.identities() - .define(identityName) - .withRegion(region) - .withNewResourceGroup(creatableRG) - .withAccessToCurrentResourceGroup(BuiltInRole.READER) - .withAccessTo(anotherResourceGroup, BuiltInRole.CONTRIBUTOR) - .createAsync() - .block(); + .define(identityName) + .withRegion(region) + .withNewResourceGroup(creatableRG) + .withAccessToCurrentResourceGroup(BuiltInRole.READER) + .withAccessTo(anotherResourceGroup, BuiltInRole.CONTRIBUTOR) + .createAsync() + .block(); Assertions.assertNotNull(identity); // Ensure roles are assigned // ResourceGroup resourceGroup = this.resourceManager.resourceGroups().getByName(identity.resourceGroupName()); - PagedIterable roleAssignments = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); + PagedIterable roleAssignments + = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignments) { - if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { + if (roleAssignment.principalId() != null + && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } - Assertions.assertTrue(found, "Expected role assignment not found for the resource group that identity belongs to"); + Assertions.assertTrue(found, + "Expected role assignment not found for the resource group that identity belongs to"); - roleAssignments = this.msiManager.authorizationManager().roleAssignments().listByScope(anotherResourceGroup.id()); + roleAssignments + = this.msiManager.authorizationManager().roleAssignments().listByScope(anotherResourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignments) { - if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { + if (roleAssignment.principalId() != null + && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions.assertTrue(found, "Expected role assignment not found for the resource group resource"); - identity = identity - .update() - .withTag("a", "bb") - .apply(); + identity = identity.update().withTag("a", "bb").apply(); Assertions.assertNotNull(identity.tags()); Assertions.assertTrue(identity.tags().containsKey("a")); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml index 969401f7e36df..bd573e20b53c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml @@ -52,6 +52,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/NetworkManager.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/NetworkManager.java index b74f76cd5a475..ea2aebee3143e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/NetworkManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/NetworkManager.java @@ -135,11 +135,8 @@ public NetworkManager authenticate(TokenCredential credential, AzureProfile prof } private NetworkManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new NetworkManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new NetworkManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayAuthenticationCertificateImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayAuthenticationCertificateImpl.java index 22157b23069e4..8c50c47185b66 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayAuthenticationCertificateImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayAuthenticationCertificateImpl.java @@ -13,16 +13,15 @@ import java.util.Base64; /** Implementation for ApplicationGatewayAuthenticationCertificate. */ -class ApplicationGatewayAuthenticationCertificateImpl - extends ChildResourceImpl< - ApplicationGatewayAuthenticationCertificateInner, ApplicationGatewayImpl, ApplicationGateway> +class ApplicationGatewayAuthenticationCertificateImpl extends + ChildResourceImpl implements ApplicationGatewayAuthenticationCertificate, - ApplicationGatewayAuthenticationCertificate.Definition, - ApplicationGatewayAuthenticationCertificate.UpdateDefinition, - ApplicationGatewayAuthenticationCertificate.Update { + ApplicationGatewayAuthenticationCertificate.Definition, + ApplicationGatewayAuthenticationCertificate.UpdateDefinition, + ApplicationGatewayAuthenticationCertificate.Update { - ApplicationGatewayAuthenticationCertificateImpl( - ApplicationGatewayAuthenticationCertificateInner inner, ApplicationGatewayImpl parent) { + ApplicationGatewayAuthenticationCertificateImpl(ApplicationGatewayAuthenticationCertificateInner inner, + ApplicationGatewayImpl parent) { super(inner, parent); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHealthImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHealthImpl.java index b073a10ad488b..130090277171e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHealthImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHealthImpl.java @@ -25,8 +25,8 @@ public class ApplicationGatewayBackendHealthImpl implements ApplicationGatewayBa this.appGateway = appGateway; if (inner != null) { for (ApplicationGatewayBackendHealthHttpSettings httpConfigInner : inner.backendHttpSettingsCollection()) { - ApplicationGatewayBackendHttpConfigurationHealthImpl httpConfigHealth = - new ApplicationGatewayBackendHttpConfigurationHealthImpl(httpConfigInner, this); + ApplicationGatewayBackendHttpConfigurationHealthImpl httpConfigHealth + = new ApplicationGatewayBackendHttpConfigurationHealthImpl(httpConfigInner, this); this.httpConfigHealths.put(httpConfigHealth.name(), httpConfigHealth); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationHealthImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationHealthImpl.java index 86c9a38d2cef0..349b0746c1c36 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationHealthImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationHealthImpl.java @@ -21,15 +21,15 @@ public class ApplicationGatewayBackendHttpConfigurationHealthImpl private final ApplicationGatewayBackendHealthImpl backendHealth; private final Map serverHealths = new TreeMap<>(); - ApplicationGatewayBackendHttpConfigurationHealthImpl( - ApplicationGatewayBackendHealthHttpSettings inner, ApplicationGatewayBackendHealthImpl backendHealth) { + ApplicationGatewayBackendHttpConfigurationHealthImpl(ApplicationGatewayBackendHealthHttpSettings inner, + ApplicationGatewayBackendHealthImpl backendHealth) { this.inner = inner; this.backendHealth = backendHealth; if (inner.servers() != null) { for (ApplicationGatewayBackendHealthServerInner serverHealthInner : this.innerModel().servers()) { - ApplicationGatewayBackendServerHealth serverHealth = - new ApplicationGatewayBackendServerHealthImpl(serverHealthInner, this); + ApplicationGatewayBackendServerHealth serverHealth + = new ApplicationGatewayBackendServerHealthImpl(serverHealthInner, this); this.serverHealths.put(serverHealth.ipAddress(), serverHealth); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationImpl.java index 4007b73cc2650..ec48f284352ac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendHttpConfigurationImpl.java @@ -30,12 +30,12 @@ class ApplicationGatewayBackendHttpConfigurationImpl extends ChildResourceImpl implements ApplicationGatewayBackendHttpConfiguration, - ApplicationGatewayBackendHttpConfiguration.Definition, - ApplicationGatewayBackendHttpConfiguration.UpdateDefinition, - ApplicationGatewayBackendHttpConfiguration.Update { + ApplicationGatewayBackendHttpConfiguration.Definition, + ApplicationGatewayBackendHttpConfiguration.UpdateDefinition, + ApplicationGatewayBackendHttpConfiguration.Update { - ApplicationGatewayBackendHttpConfigurationImpl( - ApplicationGatewayBackendHttpSettings inner, ApplicationGatewayImpl parent) { + ApplicationGatewayBackendHttpConfigurationImpl(ApplicationGatewayBackendHttpSettings inner, + ApplicationGatewayImpl parent) { super(inner, parent); } @@ -48,8 +48,8 @@ public Map authenticationCe return Collections.unmodifiableMap(certs); } else { for (SubResource ref : this.innerModel().authenticationCertificates()) { - ApplicationGatewayAuthenticationCertificate cert = - this.parent().authenticationCertificates().get(ResourceUtils.nameFromResourceId(ref.id())); + ApplicationGatewayAuthenticationCertificate cert + = this.parent().authenticationCertificates().get(ResourceUtils.nameFromResourceId(ref.id())); if (cert != null) { certs.put(cert.name(), cert); } @@ -230,8 +230,8 @@ public ApplicationGatewayBackendHttpConfigurationImpl withAuthenticationCertific if (name == null) { return this; } - SubResource certRef = - new SubResource().withId(this.parent().futureResourceId() + "/authenticationCertificates/" + name); + SubResource certRef + = new SubResource().withId(this.parent().futureResourceId() + "/authenticationCertificates/" + name); List refs = this.innerModel().authenticationCertificates(); if (refs == null) { refs = new ArrayList<>(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendImpl.java index cf95812d48448..a5026ab54ee4d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendImpl.java @@ -17,12 +17,10 @@ import java.util.TreeMap; /** Implementation for ApplicationGatewayBackend. */ -class ApplicationGatewayBackendImpl - extends ChildResourceImpl - implements ApplicationGatewayBackend, - ApplicationGatewayBackend.Definition, - ApplicationGatewayBackend.UpdateDefinition, - ApplicationGatewayBackend.Update { +class ApplicationGatewayBackendImpl extends + ChildResourceImpl implements + ApplicationGatewayBackend, ApplicationGatewayBackend.Definition, + ApplicationGatewayBackend.UpdateDefinition, ApplicationGatewayBackend.Update { ApplicationGatewayBackendImpl(ApplicationGatewayBackendAddressPool inner, ApplicationGatewayImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendServerHealthImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendServerHealthImpl.java index 5f95f05fa70a7..d70478886e297 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendServerHealthImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayBackendServerHealthImpl.java @@ -16,8 +16,7 @@ public class ApplicationGatewayBackendServerHealthImpl implements ApplicationGat private final ApplicationGatewayBackendHealthServerInner inner; private final ApplicationGatewayBackendHttpConfigurationHealthImpl httpConfigHealth; - ApplicationGatewayBackendServerHealthImpl( - ApplicationGatewayBackendHealthServerInner inner, + ApplicationGatewayBackendServerHealthImpl(ApplicationGatewayBackendHealthServerInner inner, ApplicationGatewayBackendHttpConfigurationHealthImpl httpConfigHealth) { this.inner = inner; this.httpConfigHealth = httpConfigHealth; diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayFrontendImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayFrontendImpl.java index 84050801eb4d5..b2f883976cbd9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayFrontendImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayFrontendImpl.java @@ -15,12 +15,10 @@ import reactor.core.publisher.Mono; /** Implementation for ApplicationGatewayFrontend. */ -class ApplicationGatewayFrontendImpl - extends ChildResourceImpl - implements ApplicationGatewayFrontend, - ApplicationGatewayFrontend.Definition, - ApplicationGatewayFrontend.UpdateDefinition, - ApplicationGatewayFrontend.Update { +class ApplicationGatewayFrontendImpl extends + ChildResourceImpl implements + ApplicationGatewayFrontend, ApplicationGatewayFrontend.Definition, + ApplicationGatewayFrontend.UpdateDefinition, ApplicationGatewayFrontend.Update { ApplicationGatewayFrontendImpl(ApplicationGatewayFrontendIpConfiguration inner, ApplicationGatewayImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java index 14afa35a394f1..558c7bbd7d54a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java @@ -80,9 +80,8 @@ /** * Implementation of the ApplicationGateway interface. */ -class ApplicationGatewayImpl - extends GroupableParentResourceWithTagsImpl< - ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> +class ApplicationGatewayImpl extends + GroupableParentResourceWithTagsImpl implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map ipConfigs; @@ -115,20 +114,16 @@ class ApplicationGatewayImpl @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - applicationGateway -> { - ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(applicationGateway -> { + ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -136,8 +131,7 @@ protected Mono getInnerAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -169,8 +163,8 @@ private void initializeAuthCertificatesFromInner() { List inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { - ApplicationGatewayAuthenticationCertificateImpl cert = - new ApplicationGatewayAuthenticationCertificateImpl(inner, this); + ApplicationGatewayAuthenticationCertificateImpl cert + = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } @@ -225,8 +219,8 @@ private void initializeBackendHttpConfigsFromInner() { List inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { - ApplicationGatewayBackendHttpConfigurationImpl httpConfig = - new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); + ApplicationGatewayBackendHttpConfigurationImpl httpConfig + = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } @@ -248,8 +242,8 @@ private void initializeRedirectConfigurationsFromInner() { List inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { - ApplicationGatewayRedirectConfigurationImpl redirectConfig = - new ApplicationGatewayRedirectConfigurationImpl(inner, this); + ApplicationGatewayRedirectConfigurationImpl redirectConfig + = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } @@ -271,8 +265,8 @@ private void initializeRequestRoutingRulesFromInner() { List inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { - ApplicationGatewayRequestRoutingRuleImpl rule = - new ApplicationGatewayRequestRoutingRuleImpl(inner, this); + ApplicationGatewayRequestRoutingRuleImpl rule + = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } @@ -441,8 +435,7 @@ protected SubResource ensureBackendRef(String name) { } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { - String name = this.manager().resourceManager().internalContext() - .randomResourceName("backend", 20); + String name = this.manager().resourceManager().internalContext().randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; @@ -468,8 +461,8 @@ private void ensureNoMixedWaf() { } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { - ApplicationGatewayIpConfigurationImpl ipConfig = - (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); + ApplicationGatewayIpConfigurationImpl ipConfig + = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); @@ -509,16 +502,14 @@ protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { private Creatable ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); - this.creatableNetwork = - this - .manager() - .networks() - .define(vnetName) - .withRegion(this.region()) - .withExistingResourceGroup(this.resourceGroupName()) - .withAddressSpace("10.0.0.0/24") - .withSubnet(DEFAULT, "10.0.0.0/25") - .withSubnet("apps", "10.0.0.128/25"); + this.creatableNetwork = this.manager() + .networks() + .define(vnetName) + .withRegion(this.region()) + .withExistingResourceGroup(this.resourceGroupName()) + .withAddressSpace("10.0.0.0/24") + .withSubnet(DEFAULT, "10.0.0.0/25") + .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; @@ -529,13 +520,11 @@ private Creatable ensureDefaultNetworkDefinition() { private Creatable ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); - this.creatablePip = - this - .manager() - .publicIpAddresses() - .define(pipName) - .withRegion(this.regionName()) - .withExistingResourceGroup(this.resourceGroupName()); + this.creatablePip = this.manager() + .publicIpAddresses() + .define(pipName) + .withRegion(this.regionName()) + .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; @@ -557,19 +546,15 @@ private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( @Override protected Mono createInner() { // Determine if a default public frontend PIP should be created - final ApplicationGatewayFrontendImpl defaultPublicFrontend = - (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); + final ApplicationGatewayFrontendImpl defaultPublicFrontend + = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { // If public frontend requested but no PIP specified, then create a default PIP - pipObservable = - ensureDefaultPipDefinition() - .createAsync() - .map( - publicIPAddress -> { - defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); - return publicIPAddress; - }); + pipObservable = ensureDefaultPipDefinition().createAsync().map(publicIPAddress -> { + defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); + return publicIPAddress; + }); } else { // If no public frontend requested, skip creating the PIP pipObservable = Mono.empty(); @@ -577,8 +562,8 @@ protected Mono createInner() { // Determine if default VNet should be created final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); - final ApplicationGatewayFrontendImpl defaultPrivateFrontend = - (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); + final ApplicationGatewayFrontendImpl defaultPrivateFrontend + = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono networkObservable; if (defaultIPConfig.subnetName() != null) { // If default IP config already has a subnet assigned to it... @@ -590,35 +575,30 @@ protected Mono createInner() { networkObservable = Mono.empty(); // ...and don't create another VNet } else { // But if default IP config does not have a subnet specified, then create a default VNet - networkObservable = - ensureDefaultNetworkDefinition() - .createAsync() - .map( - network -> { - // ... and assign the created VNet to the default IP config - defaultIPConfig.withExistingSubnet(network, DEFAULT); - if (defaultPrivateFrontend != null) { - // If a private frontend is also requested, then use the same VNet for the private - // frontend as for the IP config - /* TODO: Not sure if the assumption of the same subnet for the frontend and - * the IP config will hold in - * the future, but the existing ARM template for App Gateway for some reason uses - * the same subnet for the - * IP config and the private frontend. Also, trying to use different subnets results - * in server error today saying they - * have to be the same. This may need to be revisited in the future however, - * as this is somewhat inconsistent - * with what the documentation says. - */ - useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); - } - return network; - }); + networkObservable = ensureDefaultNetworkDefinition().createAsync().map(network -> { + // ... and assign the created VNet to the default IP config + defaultIPConfig.withExistingSubnet(network, DEFAULT); + if (defaultPrivateFrontend != null) { + // If a private frontend is also requested, then use the same VNet for the private + // frontend as for the IP config + /* TODO: Not sure if the assumption of the same subnet for the frontend and + * the IP config will hold in + * the future, but the existing ARM template for App Gateway for some reason uses + * the same subnet for the + * IP config and the private frontend. Also, trying to use different subnets results + * in server error today saying they + * have to be the same. This may need to be revisited in the future however, + * as this is somewhat inconsistent + * with what the documentation says. + */ + useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); + } + return network; + }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); - return Flux - .merge(networkObservable, pipObservable) + return Flux.merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } @@ -678,7 +658,8 @@ public ApplicationGatewayImpl withExistingWebApplicationFirewallPolicy(String re @Override public ApplicationGatewayImpl withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode mode) { ensureWafV2(); - WebApplicationFirewallPolicy.DefinitionStages.WithCreate wafPolicyCreatable = this.manager().webApplicationFirewallPolicies() + WebApplicationFirewallPolicy.DefinitionStages.WithCreate wafPolicyCreatable = this.manager() + .webApplicationFirewallPolicies() .define(this.manager().resourceManager().internalContext().randomResourceName("wafpolicy", 14)) .withRegion(region()) .withExistingResourceGroup(this.resourceGroupName()) @@ -688,7 +669,8 @@ public ApplicationGatewayImpl withNewWebApplicationFirewallPolicy(WebApplication } @Override - public ApplicationGatewayImpl withNewWebApplicationFirewallPolicy(Creatable creatable) { + public ApplicationGatewayImpl + withNewWebApplicationFirewallPolicy(Creatable creatable) { ensureWafV2(); this.creatableWafPolicy = this.addDependency(creatable); return this; @@ -696,19 +678,16 @@ public ApplicationGatewayImpl withNewWebApplicationFirewallPolicy(Creatable cipherSuites) { - return withSslPolicy( - new ApplicationGatewaySslPolicy() - .withPolicyType(ApplicationGatewaySslPolicyType.CUSTOM_V2) - .withMinProtocolVersion(minProtocolVersion) - .withCipherSuites(cipherSuites)); + public ApplicationGatewayImpl withCustomV2SslPolicy(ApplicationGatewaySslProtocol minProtocolVersion, + List cipherSuites) { + return withSslPolicy(new ApplicationGatewaySslPolicy().withPolicyType(ApplicationGatewaySslPolicyType.CUSTOM_V2) + .withMinProtocolVersion(minProtocolVersion) + .withCipherSuites(cipherSuites)); } @Override @@ -718,14 +697,11 @@ public ApplicationGatewayImpl withSslPolicy(ApplicationGatewaySslPolicy sslPolic } enum CreationState { - Found, - NeedToCreate, - InvalidState, + Found, NeedToCreate, InvalidState, } String futureResourceId() { - return new StringBuilder() - .append(super.resourceIdBase()) + return new StringBuilder().append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); @@ -794,11 +770,9 @@ public ApplicationGatewayImpl withInstanceCount(int capacity) { @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { - this - .innerModel() + this.innerModel() .withWebApplicationFirewallConfiguration( - new ApplicationGatewayWebApplicationFirewallConfiguration() - .withEnabled(enabled) + new ApplicationGatewayWebApplicationFirewallConfiguration().withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); @@ -807,8 +781,8 @@ public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, Applic } @Override - public ApplicationGatewayImpl withWebApplicationFirewall( - ApplicationGatewayWebApplicationFirewallConfiguration config) { + public ApplicationGatewayImpl + withWebApplicationFirewall(ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); this.legacyWafConfigurationSpecifiedInCreate = true; return this; @@ -817,12 +791,9 @@ public ApplicationGatewayImpl withWebApplicationFirewall( @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); - this - .innerModel() - .withAutoscaleConfiguration( - new ApplicationGatewayAutoscaleConfiguration() - .withMinCapacity(minCapacity) - .withMaxCapacity(maxCapacity)); + this.innerModel() + .withAutoscaleConfiguration(new ApplicationGatewayAutoscaleConfiguration().withMinCapacity(minCapacity) + .withMaxCapacity(maxCapacity)); return this; } @@ -914,13 +885,14 @@ public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); - if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { - this.innerModel().withWebApplicationFirewallConfiguration( - new ApplicationGatewayWebApplicationFirewallConfiguration() - .withEnabled(true) - .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) - .withRuleSetType("OWASP") - .withRuleSetVersion("3.0")); + if (skuTier == ApplicationGatewayTier.WAF_V2 + && this.innerModel().webApplicationFirewallConfiguration() == null) { + this.innerModel() + .withWebApplicationFirewallConfiguration( + new ApplicationGatewayWebApplicationFirewallConfiguration().withEnabled(true) + .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) + .withRuleSetType("OWASP") + .withRuleSetVersion("3.0")); } return this; } @@ -968,63 +940,45 @@ ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { - return defineChild( - name, - this.sslCerts, - ApplicationGatewaySslCertificateInner.class, + return defineChild(name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } // TODO(future) @Override - since app gateways don't support more than one today, no need to expose this private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { - return defineChild( - name, - this.ipConfigs, - ApplicationGatewayIpConfigurationInner.class, + return defineChild(name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } // TODO(future) @Override - since app gateways don't support more than one today, no need to expose this private ApplicationGatewayFrontendImpl defineFrontend(String name) { - return defineChild( - name, - this.frontends, - ApplicationGatewayFrontendIpConfiguration.class, + return defineChild(name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { - return defineChild( - name, - this.redirectConfigs, - ApplicationGatewayRedirectConfigurationInner.class, + return defineChild(name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { - ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( - name, - this.rules, - ApplicationGatewayRequestRoutingRuleInner.class, - ApplicationGatewayRequestRoutingRuleImpl.class); + ApplicationGatewayRequestRoutingRuleImpl rule = defineChild(name, this.rules, + ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { - return defineChild( - name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); + return defineChild(name, this.backends, ApplicationGatewayBackendAddressPool.class, + ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { - return defineChild( - name, - this.authCertificates, - ApplicationGatewayAuthenticationCertificateInner.class, + return defineChild(name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @@ -1035,20 +989,15 @@ public ApplicationGatewayProbeImpl defineProbe(String name) { @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { - ApplicationGatewayUrlPathMapImpl urlPathMap = - defineChild( - name, - this.urlPathMaps, - ApplicationGatewayUrlPathMapInner.class, - ApplicationGatewayUrlPathMapImpl.class); + ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild(name, this.urlPathMaps, + ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); // create corresponding request routing rule - ApplicationGatewayRequestRoutingRuleInner inner = - new ApplicationGatewayRequestRoutingRuleInner() - .withName(name) - .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) - .withUrlPathMap(ref); - ApplicationGatewayRequestRoutingRuleImpl requestRoutingRule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); + ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner().withName(name) + .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) + .withUrlPathMap(ref); + ApplicationGatewayRequestRoutingRuleImpl requestRoutingRule + = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); rules.put(name, requestRoutingRule); addedRuleCollection.addRule(requestRoutingRule); return urlPathMap; @@ -1056,18 +1005,14 @@ public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) @Override public ApplicationGatewayListenerImpl defineListener(String name) { - return defineChild( - name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); + return defineChild(name, this.listeners, ApplicationGatewayHttpListener.class, + ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { - ApplicationGatewayBackendHttpConfigurationImpl config = - defineChild( - name, - this.backendConfigs, - ApplicationGatewayBackendHttpSettings.class, - ApplicationGatewayBackendHttpConfigurationImpl.class); + ApplicationGatewayBackendHttpConfigurationImpl config = defineChild(name, this.backendConfigs, + ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); // Default port } else { @@ -1076,23 +1021,18 @@ public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfigura } @SuppressWarnings("unchecked") - private ChildImplT defineChild( - String name, Map children, Class innerClass, Class implClass) { + private ChildImplT defineChild(String name, Map children, + Class innerClass, Class implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); - return implClass - .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) + return implClass.getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); - } catch (InstantiationException - | IllegalAccessException - | IllegalArgumentException - | InvocationTargetException - | NoSuchMethodException - | SecurityException e1) { + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { @@ -1523,10 +1463,7 @@ public Mono getWebApplicationFirewallPolicyAsync() if (getWebApplicationFirewallPolicyId() == null) { return Mono.empty(); } - return this - .manager() - .webApplicationFirewallPolicies() - .getByIdAsync(this.innerModel().firewallPolicy().id()); + return this.manager().webApplicationFirewallPolicies().getByIdAsync(this.innerModel().firewallPolicy().id()); } @Override @@ -1787,8 +1724,8 @@ public void stop() { @Override public Mono startAsync() { - Mono startObservable = - this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); + Mono startObservable + = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono refreshObservable = refreshAsync(); // Refresh after start to ensure the app gateway operational state is updated @@ -1797,8 +1734,8 @@ public Mono startAsync() { @Override public Mono stopAsync() { - Mono stopObservable = - this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); + Mono stopObservable + = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono refreshObservable = refreshAsync(); // Refresh after stop to ensure the app gateway operational state is updated @@ -1828,24 +1765,22 @@ public Map checkBackendHealth() { @Override public Mono> checkBackendHealthAsync() { - return this - .manager() + return this.manager() .serviceClient() .getApplicationGateways() // TODO(not known): Last minutes .backendHealthAsync(this.resourceGroupName(), this.name(), null) - .map( - inner -> { - Map backendHealths = new TreeMap<>(); - if (inner != null) { - for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { - ApplicationGatewayBackendHealth backendHealth = - new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); - backendHealths.put(backendHealth.name(), backendHealth); - } + .map(inner -> { + Map backendHealths = new TreeMap<>(); + if (inner != null) { + for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { + ApplicationGatewayBackendHealth backendHealth + = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); + backendHealths.put(backendHealth.name(), backendHealth); } - return Collections.unmodifiableMap(backendHealths); - }); + } + return Collections.unmodifiableMap(backendHealths); + }); } /* @@ -1856,8 +1791,10 @@ private boolean supportsRulePriority() { ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && tier != ApplicationGatewayTier.WAF - && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM - && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM + && sku != ApplicationGatewaySkuName.STANDARD_SMALL + && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM + && sku != ApplicationGatewaySkuName.STANDARD_LARGE + && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } @@ -1896,8 +1833,7 @@ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { */ void autoAssignPriorities(Collection existingRules, String gatewayName) { // list all existing rule priorities - Set existingPriorities = existingRules - .stream() + Set existingPriorities = existingRules.stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); @@ -1920,8 +1856,8 @@ void autoAssignPriorities(Collection exist break; } if (!assigned) { - throw new IllegalStateException( - String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); + throw new IllegalStateException(String + .format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayIpConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayIpConfigurationImpl.java index 030500235a79f..d16588814e204 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayIpConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayIpConfigurationImpl.java @@ -15,9 +15,9 @@ class ApplicationGatewayIpConfigurationImpl extends ChildResourceImpl implements ApplicationGatewayIpConfiguration, - ApplicationGatewayIpConfiguration.Definition, - ApplicationGatewayIpConfiguration.UpdateDefinition, - ApplicationGatewayIpConfiguration.Update { + ApplicationGatewayIpConfiguration.Definition, + ApplicationGatewayIpConfiguration.UpdateDefinition, + ApplicationGatewayIpConfiguration.Update { ApplicationGatewayIpConfigurationImpl(ApplicationGatewayIpConfigurationInner inner, ApplicationGatewayImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayListenerImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayListenerImpl.java index 170bc88a0d372..4142276836e32 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayListenerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayListenerImpl.java @@ -23,11 +23,9 @@ /** Implementation for ApplicationGatewayListener. */ class ApplicationGatewayListenerImpl - extends ChildResourceImpl - implements ApplicationGatewayListener, - ApplicationGatewayListener.Definition, - ApplicationGatewayListener.UpdateDefinition, - ApplicationGatewayListener.Update { + extends ChildResourceImpl implements + ApplicationGatewayListener, ApplicationGatewayListener.Definition, + ApplicationGatewayListener.UpdateDefinition, ApplicationGatewayListener.Update { ApplicationGatewayListenerImpl(ApplicationGatewayHttpListener inner, ApplicationGatewayImpl parent) { super(inner, parent); @@ -170,8 +168,8 @@ public ApplicationGatewayImpl attach() { // Helpers private ApplicationGatewayListenerImpl withFrontend(String name) { - SubResource frontendRef = - new SubResource().withId(this.parent().futureResourceId() + "/frontendIPConfigurations/" + name); + SubResource frontendRef + = new SubResource().withId(this.parent().futureResourceId() + "/frontendIPConfigurations/" + name); this.innerModel().withFrontendIpConfiguration(frontendRef); return this; } @@ -191,8 +189,7 @@ public ApplicationGatewayListenerImpl withFrontendPort(int portNumber) { String portName = this.parent().frontendPortNameFromNumber(portNumber); if (portName == null) { // Existing frontend port with this number not found so create one - portName = this.parent().manager().resourceManager().internalContext() - .randomResourceName("port", 9); + portName = this.parent().manager().resourceManager().internalContext().randomResourceName("port", 9); this.parent().withFrontendPort(portNumber, portName); } @@ -211,11 +208,10 @@ public ApplicationGatewayListenerImpl withSslCertificateFromKeyVaultSecretId(Str return withSslCertificateFromKeyVaultSecretId(keyVaultSecretId, null); } - private ApplicationGatewayListenerImpl withSslCertificateFromKeyVaultSecretId( - String keyVaultSecretId, String name) { + private ApplicationGatewayListenerImpl withSslCertificateFromKeyVaultSecretId(String keyVaultSecretId, + String name) { if (name == null) { - name = this.parent().manager().resourceManager().internalContext() - .randomResourceName("cert", 10); + name = this.parent().manager().resourceManager().internalContext().randomResourceName("cert", 10); } this.parent().defineSslCertificate(name).withKeyVaultSecretId(keyVaultSecretId).attach(); return this; @@ -228,8 +224,7 @@ public ApplicationGatewayListenerImpl withSslCertificateFromPfxFile(File pfxFile private ApplicationGatewayListenerImpl withSslCertificateFromPfxFile(File pfxFile, String name) throws IOException { if (name == null) { - name = this.parent().manager().resourceManager().internalContext() - .randomResourceName("cert", 10); + name = this.parent().manager().resourceManager().internalContext().randomResourceName("cert", 10); } this.parent().defineSslCertificate(name).withPfxFromFile(pfxFile).attach(); return this.withSslCertificate(name); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayPathRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayPathRuleImpl.java index 658ccdc8d9c65..cac458b240259 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayPathRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayPathRuleImpl.java @@ -18,16 +18,12 @@ import java.util.List; /** Implementation for application gateway path rule. */ -class ApplicationGatewayPathRuleImpl - extends ChildResourceImpl< - ApplicationGatewayPathRuleInner, ApplicationGatewayUrlPathMapImpl, ApplicationGatewayUrlPathMap> +class ApplicationGatewayPathRuleImpl extends + ChildResourceImpl implements ApplicationGatewayPathRule, - ApplicationGatewayPathRule.Definition< - ApplicationGatewayUrlPathMap.DefinitionStages.WithAttach< - ApplicationGateway.DefinitionStages.WithRequestRoutingRuleOrCreate>>, - ApplicationGatewayPathRule.UpdateDefinition< - ApplicationGatewayUrlPathMap.UpdateDefinitionStages.WithAttach>, - ApplicationGatewayPathRule.Update { + ApplicationGatewayPathRule.Definition>, + ApplicationGatewayPathRule.UpdateDefinition>, + ApplicationGatewayPathRule.Update { ApplicationGatewayPathRuleImpl(ApplicationGatewayPathRuleInner inner, ApplicationGatewayUrlPathMapImpl parent) { super(inner, parent); @@ -45,9 +41,8 @@ public ApplicationGatewayUrlPathMapImpl attach() { @Override public ApplicationGatewayPathRuleImpl toBackendHttpConfiguration(String name) { - SubResource httpConfigRef = - new SubResource() - .withId(this.parent().parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); + SubResource httpConfigRef = new SubResource() + .withId(this.parent().parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); this.innerModel().withBackendHttpSettings(httpConfigRef); return this; } @@ -63,8 +58,8 @@ public ApplicationGatewayPathRuleImpl withRedirectConfiguration(String name) { if (name == null) { this.innerModel().withRedirectConfiguration(null); } else { - SubResource ref = - new SubResource().withId(this.parent().parent().futureResourceId() + "/redirectConfigurations/" + name); + SubResource ref = new SubResource() + .withId(this.parent().parent().futureResourceId() + "/redirectConfigurations/" + name); this.innerModel().withRedirectConfiguration(ref); } return this; diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayProbeImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayProbeImpl.java index 2bc86762e8fa9..c97c9d915549f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayProbeImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayProbeImpl.java @@ -17,11 +17,9 @@ /** Implementation for ApplicationGatewayProbe. */ class ApplicationGatewayProbeImpl - extends ChildResourceImpl - implements ApplicationGatewayProbe, - ApplicationGatewayProbe.Definition, - ApplicationGatewayProbe.UpdateDefinition, - ApplicationGatewayProbe.Update { + extends ChildResourceImpl implements + ApplicationGatewayProbe, ApplicationGatewayProbe.Definition, + ApplicationGatewayProbe.UpdateDefinition, ApplicationGatewayProbe.Update { private final ClientLogger logger = new ClientLogger(getClass()); ApplicationGatewayProbeImpl(ApplicationGatewayProbeInner inner, ApplicationGatewayImpl parent) { @@ -189,13 +187,11 @@ public ApplicationGatewayProbeImpl withHealthyHttpResponseStatusCodeRange(String @Override public ApplicationGatewayProbeImpl withHealthyHttpResponseStatusCodeRange(int from, int to) { if (from < 0 || to < 0) { - throw logger - .logExceptionAsError( - new IllegalArgumentException("The start and end of a range cannot be negative numbers.")); + throw logger.logExceptionAsError( + new IllegalArgumentException("The start and end of a range cannot be negative numbers.")); } else if (to < from) { - throw logger - .logExceptionAsError( - new IllegalArgumentException("The end of the range cannot be less than the start of the range.")); + throw logger.logExceptionAsError( + new IllegalArgumentException("The end of the range cannot be less than the start of the range.")); } else { return this.withHealthyHttpResponseStatusCodeRange(String.valueOf(from) + "-" + String.valueOf(to)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRedirectConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRedirectConfigurationImpl.java index bb64e6b303b14..d5fdb962cad96 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRedirectConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRedirectConfigurationImpl.java @@ -21,12 +21,12 @@ class ApplicationGatewayRedirectConfigurationImpl extends ChildResourceImpl implements ApplicationGatewayRedirectConfiguration, - ApplicationGatewayRedirectConfiguration.Definition, - ApplicationGatewayRedirectConfiguration.UpdateDefinition, - ApplicationGatewayRedirectConfiguration.Update { + ApplicationGatewayRedirectConfiguration.Definition, + ApplicationGatewayRedirectConfiguration.UpdateDefinition, + ApplicationGatewayRedirectConfiguration.Update { - ApplicationGatewayRedirectConfigurationImpl( - ApplicationGatewayRedirectConfigurationInner inner, ApplicationGatewayImpl parent) { + ApplicationGatewayRedirectConfigurationImpl(ApplicationGatewayRedirectConfigurationInner inner, + ApplicationGatewayImpl parent) { super(inner, parent); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRequestRoutingRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRequestRoutingRuleImpl.java index fc2922044f973..64b8f0fc710ad 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRequestRoutingRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayRequestRoutingRuleImpl.java @@ -32,13 +32,12 @@ class ApplicationGatewayRequestRoutingRuleImpl extends ChildResourceImpl implements ApplicationGatewayRequestRoutingRule, - ApplicationGatewayRequestRoutingRule.Definition< - ApplicationGateway.DefinitionStages.WithRequestRoutingRuleOrCreate>, - ApplicationGatewayRequestRoutingRule.UpdateDefinition, - ApplicationGatewayRequestRoutingRule.Update { + ApplicationGatewayRequestRoutingRule.Definition, + ApplicationGatewayRequestRoutingRule.UpdateDefinition, + ApplicationGatewayRequestRoutingRule.Update { - ApplicationGatewayRequestRoutingRuleImpl( - ApplicationGatewayRequestRoutingRuleInner inner, ApplicationGatewayImpl parent) { + ApplicationGatewayRequestRoutingRuleImpl(ApplicationGatewayRequestRoutingRuleInner inner, + ApplicationGatewayImpl parent) { super(inner, parent); } @@ -163,8 +162,9 @@ public ApplicationGatewayBackendHttpConfigurationImpl backendHttpConfiguration() SubResource configRef = this.innerModel().backendHttpSettings(); if (configRef != null) { String configName = ResourceUtils.nameFromResourceId(configRef.id()); - return (ApplicationGatewayBackendHttpConfigurationImpl) - this.parent().backendHttpConfigurations().get(configName); + return (ApplicationGatewayBackendHttpConfigurationImpl) this.parent() + .backendHttpConfigurations() + .get(configName); } else { return null; } @@ -228,8 +228,8 @@ public ApplicationGatewayRequestRoutingRuleImpl fromFrontendHttpsPort(int portNu @Override public ApplicationGatewayRequestRoutingRuleImpl toBackendHttpConfiguration(String name) { - SubResource httpConfigRef = - new SubResource().withId(this.parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); + SubResource httpConfigRef + = new SubResource().withId(this.parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); this.innerModel().withBackendHttpSettings(httpConfigRef); return this; } @@ -237,8 +237,8 @@ public ApplicationGatewayRequestRoutingRuleImpl toBackendHttpConfiguration(Strin private ApplicationGatewayBackendHttpConfigurationImpl ensureBackendHttpConfig() { ApplicationGatewayBackendHttpConfigurationImpl config = this.backendHttpConfiguration(); if (config == null) { - final String name = this.parent().manager().resourceManager().internalContext() - .randomResourceName("bckcfg", 11); + final String name + = this.parent().manager().resourceManager().internalContext().randomResourceName("bckcfg", 11); config = this.parent().defineBackendHttpConfiguration(name); config.attach(); this.toBackendHttpConfiguration(name); @@ -274,18 +274,18 @@ public ApplicationGatewayRequestRoutingRuleImpl fromListener(String name) { return this; } - private ApplicationGatewayRequestRoutingRuleImpl fromFrontendPort( - int portNumber, ApplicationGatewayProtocol protocol, String name) { + private ApplicationGatewayRequestRoutingRuleImpl fromFrontendPort(int portNumber, + ApplicationGatewayProtocol protocol, String name) { // Verify no conflicting listener exists - ApplicationGatewayListenerImpl listenerByPort = - (ApplicationGatewayListenerImpl) this.parent().listenerByPortNumber(portNumber); + ApplicationGatewayListenerImpl listenerByPort + = (ApplicationGatewayListenerImpl) this.parent().listenerByPortNumber(portNumber); ApplicationGatewayListenerImpl listenerByName = null; if (name != null) { listenerByName = (ApplicationGatewayListenerImpl) this.parent().listeners().get(name); } - ApplicationGatewayImpl.CreationState needToCreate = - this.parent().needToCreate(listenerByName, listenerByPort, name); + ApplicationGatewayImpl.CreationState needToCreate + = this.parent().needToCreate(listenerByName, listenerByPort, name); if (needToCreate == ApplicationGatewayImpl.CreationState.NeedToCreate) { // If no listener exists for the requested port number yet and the name, create one if (name == null) { @@ -321,8 +321,8 @@ private ApplicationGatewayRequestRoutingRuleImpl fromFrontendPort( private ApplicationGatewayListenerImpl ensureListener() { ApplicationGatewayListenerImpl listener = this.listener(); if (listener == null) { - final String name = this.parent().manager().resourceManager().internalContext() - .randomResourceName("listener", 13); + final String name + = this.parent().manager().resourceManager().internalContext().randomResourceName("listener", 13); listener = this.parent().defineListener(name); listener.attach(); this.fromListener(name); @@ -426,8 +426,8 @@ public ApplicationGatewayRequestRoutingRuleImpl withRedirectConfiguration(String if (name == null) { this.innerModel().withRedirectConfiguration(null); } else { - SubResource ref = - new SubResource().withId(this.parent().futureResourceId() + "/redirectConfigurations/" + name); + SubResource ref + = new SubResource().withId(this.parent().futureResourceId() + "/redirectConfigurations/" + name); this.innerModel().withRedirectConfiguration(ref).withBackendAddressPool(null).withBackendHttpSettings(null); } return this; @@ -445,8 +445,8 @@ public ApplicationGatewayRequestRoutingRuleImpl withoutRedirectConfiguration() { if (urlPathMapName == null) { this.innerModel().withUrlPathMap(null); } else { - SubResource ref = - new SubResource().withId(this.parent().futureResourceId() + "/urlPathMaps/" + urlPathMapName); + SubResource ref + = new SubResource().withId(this.parent().futureResourceId() + "/urlPathMaps/" + urlPathMapName); this.innerModel().withUrlPathMap(ref); } return this; diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaySslCertificateImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaySslCertificateImpl.java index c6e8a11c8577d..1b65e820ebd0c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaySslCertificateImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaySslCertificateImpl.java @@ -16,9 +16,9 @@ class ApplicationGatewaySslCertificateImpl extends ChildResourceImpl implements ApplicationGatewaySslCertificate, - ApplicationGatewaySslCertificate.Definition, - ApplicationGatewaySslCertificate.UpdateDefinition, - ApplicationGatewaySslCertificate.Update { + ApplicationGatewaySslCertificate.Definition, + ApplicationGatewaySslCertificate.UpdateDefinition, + ApplicationGatewaySslCertificate.Update { ApplicationGatewaySslCertificateImpl(ApplicationGatewaySslCertificateInner inner, ApplicationGatewayImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayUrlPathMapImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayUrlPathMapImpl.java index 6db65dace6826..384081eddf9c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayUrlPathMapImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayUrlPathMapImpl.java @@ -22,9 +22,8 @@ class ApplicationGatewayUrlPathMapImpl extends ChildResourceImpl implements ApplicationGatewayUrlPathMap, - ApplicationGatewayUrlPathMap.Definition, - ApplicationGatewayUrlPathMap.UpdateDefinition, - ApplicationGatewayUrlPathMap.Update { + ApplicationGatewayUrlPathMap.Definition, + ApplicationGatewayUrlPathMap.UpdateDefinition, ApplicationGatewayUrlPathMap.Update { private Map pathRules; ApplicationGatewayUrlPathMapImpl(ApplicationGatewayUrlPathMapInner inner, ApplicationGatewayImpl parent) { @@ -85,8 +84,8 @@ public ApplicationGatewayImpl attach() { @Override public ApplicationGatewayUrlPathMapImpl toBackendHttpConfiguration(String name) { - SubResource httpConfigRef = - new SubResource().withId(this.parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); + SubResource httpConfigRef + = new SubResource().withId(this.parent().futureResourceId() + "/backendHttpSettingsCollection/" + name); this.innerModel().withDefaultBackendHttpSettings(httpConfigRef); return this; } @@ -109,10 +108,9 @@ public ApplicationGatewayUrlPathMapImpl withRedirectConfiguration(String name) { if (name == null) { this.innerModel().withDefaultRedirectConfiguration(null); } else { - SubResource ref = - new SubResource().withId(this.parent().futureResourceId() + "/redirectConfigurations/" + name); - this - .innerModel() + SubResource ref + = new SubResource().withId(this.parent().futureResourceId() + "/redirectConfigurations/" + name); + this.innerModel() .withDefaultRedirectConfiguration(ref) .withDefaultBackendAddressPool(null) .withDefaultBackendHttpSettings(null); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaysImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaysImpl.java index b7a1d100ebbfb..46dda8fd4a2b1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaysImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewaysImpl.java @@ -21,9 +21,8 @@ import java.util.Collection; /** Implementation for ApplicationGateways. */ -public class ApplicationGatewaysImpl - extends TopLevelModifiableResourcesImpl< - ApplicationGateway, ApplicationGatewayImpl, ApplicationGatewayInner, ApplicationGatewaysClient, NetworkManager> +public class ApplicationGatewaysImpl extends + TopLevelModifiableResourcesImpl implements ApplicationGateways { public ApplicationGatewaysImpl(final NetworkManager networkManager) { @@ -32,8 +31,7 @@ public ApplicationGatewaysImpl(final NetworkManager networkManager) { @Override public ApplicationGatewayImpl define(String name) { - return wrapModel(name) - .withSize(ApplicationGatewaySkuName.BASIC) + return wrapModel(name).withSize(ApplicationGatewaySkuName.BASIC) .withTier(ApplicationGatewayTier.BASIC) .withInstanceCount(1); } @@ -92,16 +90,11 @@ public Flux startAsync(Collection applicationGatewayResourceIds) if (applicationGatewayResourceIds == null) { return Flux.empty(); } else { - return Flux - .fromIterable(applicationGatewayResourceIds) - .flatMapDelayError( - id -> { - final String resourceGroupName = ResourceUtils.groupFromResourceId(id); - final String name = ResourceUtils.nameFromResourceId(id); - return this.inner().startAsync(resourceGroupName, name).then(Mono.just(id)); - }, - 32, - 32) + return Flux.fromIterable(applicationGatewayResourceIds).flatMapDelayError(id -> { + final String resourceGroupName = ResourceUtils.groupFromResourceId(id); + final String name = ResourceUtils.nameFromResourceId(id); + return this.inner().startAsync(resourceGroupName, name).then(Mono.just(id)); + }, 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } @@ -112,16 +105,11 @@ public Flux stopAsync(Collection applicationGatewayResourceIds) if (applicationGatewayResourceIds == null) { return Flux.empty(); } else { - return Flux - .fromIterable(applicationGatewayResourceIds) - .flatMapDelayError( - id -> { - final String resourceGroupName = ResourceUtils.groupFromResourceId(id); - final String name = ResourceUtils.nameFromResourceId(id); - return this.inner().stopAsync(resourceGroupName, name).then(Mono.just(id)); - }, - 32, - 32) + return Flux.fromIterable(applicationGatewayResourceIds).flatMapDelayError(id -> { + final String resourceGroupName = ResourceUtils.groupFromResourceId(id); + final String name = ResourceUtils.nameFromResourceId(id); + return this.inner().stopAsync(resourceGroupName, name).then(Mono.just(id)); + }, 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupImpl.java index e24c13564dfb7..d5d7a002f51e3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupImpl.java @@ -9,20 +9,18 @@ import reactor.core.publisher.Mono; /** Implementation for ApplicationSecurityGroup and its create and update interfaces. */ -class ApplicationSecurityGroupImpl - extends GroupableResourceImpl< - ApplicationSecurityGroup, ApplicationSecurityGroupInner, ApplicationSecurityGroupImpl, NetworkManager> +class ApplicationSecurityGroupImpl extends + GroupableResourceImpl implements ApplicationSecurityGroup, ApplicationSecurityGroup.Definition, ApplicationSecurityGroup.Update { - ApplicationSecurityGroupImpl( - final String name, final ApplicationSecurityGroupInner innerModel, final NetworkManager networkManager) { + ApplicationSecurityGroupImpl(final String name, final ApplicationSecurityGroupInner innerModel, + final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getApplicationSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -30,8 +28,7 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getApplicationSecurityGroups() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupsImpl.java index 20e49816ac653..42c6a7cefdd94 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationSecurityGroupsImpl.java @@ -10,13 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for ApplicationSecurityGroups. */ -public class ApplicationSecurityGroupsImpl - extends TopLevelModifiableResourcesImpl< - ApplicationSecurityGroup, - ApplicationSecurityGroupImpl, - ApplicationSecurityGroupInner, - ApplicationSecurityGroupsClient, - NetworkManager> +public class ApplicationSecurityGroupsImpl extends + TopLevelModifiableResourcesImpl implements ApplicationSecurityGroups { public ApplicationSecurityGroupsImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AvailableProvidersImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AvailableProvidersImpl.java index 1a75dca8dc98c..176138f00f784 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AvailableProvidersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AvailableProvidersImpl.java @@ -60,18 +60,16 @@ public AvailableProvidersListInner innerModel() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .listAvailableProvidersAsync(parent().resourceGroupName(), parent().name(), parameters) - .map( - availableProvidersListInner -> { - AvailableProvidersImpl.this.inner = availableProvidersListInner; - AvailableProvidersImpl.this.initializeResourcesFromInner(); - return AvailableProvidersImpl.this; - }); + .map(availableProvidersListInner -> { + AvailableProvidersImpl.this.inner = availableProvidersListInner; + AvailableProvidersImpl.this.initializeResourcesFromInner(); + return AvailableProvidersImpl.this; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureReachabilityReportImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureReachabilityReportImpl.java index 4c1402fade552..b17698caf6704 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureReachabilityReportImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureReachabilityReportImpl.java @@ -58,17 +58,15 @@ public AzureReachabilityReportInner innerModel() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .getAzureReachabilityReportAsync(parent().resourceGroupName(), parent().name(), parameters) - .map( - azureReachabilityReportListInner -> { - AzureReachabilityReportImpl.this.inner = azureReachabilityReportListInner; - return AzureReachabilityReportImpl.this; - }); + .map(azureReachabilityReportListInner -> { + AzureReachabilityReportImpl.this.inner = azureReachabilityReportListInner; + return AzureReachabilityReportImpl.this; + }); } @Override @@ -85,9 +83,8 @@ public AzureReachabilityReportImpl withProviderLocation(String country, String s @Override public AzureReachabilityReportImpl withProviderLocation(String country, String state, String city) { - parameters - .withProviderLocation( - new AzureReachabilityReportLocation().withCountry(country).withState(state).withCity(city)); + parameters.withProviderLocation( + new AzureReachabilityReportLocation().withCountry(country).withState(state).withCity(city)); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectionMonitorImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectionMonitorImpl.java index ae10aea11f03b..d7d1d55ed93c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectionMonitorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectionMonitorImpl.java @@ -30,10 +30,7 @@ public class ConnectionMonitorImpl private final ConnectionMonitorInner createParameters; private final NetworkWatcher parent; - ConnectionMonitorImpl( - String name, - NetworkWatcherImpl parent, - ConnectionMonitorResultInner innerObject, + ConnectionMonitorImpl(String name, NetworkWatcherImpl parent, ConnectionMonitorResultInner innerObject, ConnectionMonitorsClient client) { super(name, innerObject); this.client = client; @@ -102,9 +99,7 @@ public void stop() { @Override public Mono stopAsync() { - return this - .client - .stopAsync(parent.resourceGroupName(), parent.name(), name()) + return this.client.stopAsync(parent.resourceGroupName(), parent.name(), name()) .flatMap(aVoid -> refreshAsync()) .then(); } @@ -116,9 +111,7 @@ public void start() { @Override public Mono startAsync() { - return this - .client - .startAsync(parent.resourceGroupName(), parent.name(), name()) + return this.client.startAsync(parent.resourceGroupName(), parent.name(), name()) .flatMap(aVoid -> refreshAsync()) .then(); } @@ -130,9 +123,7 @@ public ConnectionMonitorQueryResult query() { @Override public Mono queryAsync() { - return this - .client - .queryAsync(parent.resourceGroupName(), parent.name(), name()) + return this.client.queryAsync(parent.resourceGroupName(), parent.name(), name()) .map(inner -> new ConnectionMonitorQueryResultImpl(inner)); } @@ -143,9 +134,7 @@ public boolean isInCreateMode() { @Override public Mono createResourceAsync() { - return this - .client - .createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), createParameters) + return this.client.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), createParameters) .map(innerToFluentMap(this)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectivityCheckImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectivityCheckImpl.java index 8fbe90a56a106..2bf3fc93712ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectivityCheckImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ConnectivityCheckImpl.java @@ -127,16 +127,14 @@ public int probesFailed() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .checkConnectivityAsync(parent.resourceGroupName(), parent.name(), parameters) - .map( - connectivityInformation -> { - ConnectivityCheckImpl.this.result = connectivityInformation; - return ConnectivityCheckImpl.this; - }); + .map(connectivityInformation -> { + ConnectivityCheckImpl.this.result = connectivityInformation; + return ConnectivityCheckImpl.this; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlanImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlanImpl.java index 1c250d1a74f26..28c1c7117228b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlanImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlanImpl.java @@ -16,15 +16,14 @@ class DdosProtectionPlanImpl extends GroupableResourceImpl implements DdosProtectionPlan, DdosProtectionPlan.Definition, DdosProtectionPlan.Update { - DdosProtectionPlanImpl( - final String name, final DdosProtectionPlanInner innerModel, final NetworkManager networkManager) { + DdosProtectionPlanImpl(final String name, final DdosProtectionPlanInner innerModel, + final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getDdosProtectionPlans() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -32,8 +31,7 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getDdosProtectionPlans() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlansImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlansImpl.java index 93ca6fefc23a3..29d4997e58426 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlansImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/DdosProtectionPlansImpl.java @@ -10,9 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for DdosProtectionPlans. */ -public class DdosProtectionPlansImpl - extends TopLevelModifiableResourcesImpl< - DdosProtectionPlan, DdosProtectionPlanImpl, DdosProtectionPlanInner, DdosProtectionPlansClient, NetworkManager> +public class DdosProtectionPlansImpl extends + TopLevelModifiableResourcesImpl implements DdosProtectionPlans { public DdosProtectionPlansImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitImpl.java index 33517133c3242..a32f438b3f76c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitImpl.java @@ -21,9 +21,8 @@ import java.util.Map; import reactor.core.publisher.Mono; -class ExpressRouteCircuitImpl - extends GroupableParentResourceWithTagsImpl< - ExpressRouteCircuit, ExpressRouteCircuitInner, ExpressRouteCircuitImpl, NetworkManager> +class ExpressRouteCircuitImpl extends + GroupableParentResourceWithTagsImpl implements ExpressRouteCircuit, ExpressRouteCircuit.Definition, ExpressRouteCircuit.Update { private ExpressRouteCircuitPeeringsImpl peerings; private Map expressRouteCircuitPeerings; @@ -91,8 +90,7 @@ private ExpressRouteCircuitServiceProviderProperties ensureServiceProviderProper @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCircuits() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); @@ -103,22 +101,15 @@ protected void initializeChildrenFromInner() { expressRouteCircuitPeerings = new HashMap<>(); if (innerModel().peerings() != null) { for (ExpressRouteCircuitPeeringInner peering : innerModel().peerings()) { - expressRouteCircuitPeerings - .put( - peering.name(), - new ExpressRouteCircuitPeeringImpl<>( - this, - peering, - manager().serviceClient().getExpressRouteCircuitPeerings(), - peering.peeringType())); + expressRouteCircuitPeerings.put(peering.name(), new ExpressRouteCircuitPeeringImpl<>(this, peering, + manager().serviceClient().getExpressRouteCircuitPeerings(), peering.peeringType())); } } } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCircuits() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -126,20 +117,16 @@ protected Mono getInnerAsync() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - expressRouteCircuit -> { - ExpressRouteCircuitImpl impl = (ExpressRouteCircuitImpl) expressRouteCircuit; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(expressRouteCircuit -> { + ExpressRouteCircuitImpl impl = (ExpressRouteCircuitImpl) expressRouteCircuit; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCircuits() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringImpl.java index e9de7423393b3..03c49e9dd4a12 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringImpl.java @@ -18,24 +18,16 @@ import java.util.Arrays; -class ExpressRouteCircuitPeeringImpl< - ParentModelT, - ParentInnerT, - ParentT extends GroupableResource & Refreshable> - extends CreatableUpdatableImpl< - ExpressRouteCircuitPeering, - ExpressRouteCircuitPeeringInner, - ExpressRouteCircuitPeeringImpl> +class ExpressRouteCircuitPeeringImpl & Refreshable> + extends + CreatableUpdatableImpl> implements ExpressRouteCircuitPeering, ExpressRouteCircuitPeering.Definition, ExpressRouteCircuitPeering.Update { private final ExpressRouteCircuitPeeringsClient client; private final ParentT parent; private ExpressRouteCircuitStatsImpl stats; - ExpressRouteCircuitPeeringImpl( - ParentT parent, - ExpressRouteCircuitPeeringInner innerObject, - ExpressRouteCircuitPeeringsClient client, - ExpressRoutePeeringType type) { + ExpressRouteCircuitPeeringImpl(ParentT parent, ExpressRouteCircuitPeeringInner innerObject, + ExpressRouteCircuitPeeringsClient client, ExpressRoutePeeringType type) { super(type.toString(), innerObject); this.client = client; this.parent = parent; @@ -44,8 +36,8 @@ class ExpressRouteCircuitPeeringImpl< } @Override - public ExpressRouteCircuitPeeringImpl withAdvertisedPublicPrefixes( - String publicPrefix) { + public ExpressRouteCircuitPeeringImpl + withAdvertisedPublicPrefixes(String publicPrefix) { ensureMicrosoftPeeringConfig().withAdvertisedPublicPrefixes(Arrays.asList(publicPrefix)); return this; } @@ -58,15 +50,15 @@ private ExpressRouteCircuitPeeringConfig ensureMicrosoftPeeringConfig() { } @Override - public ExpressRouteCircuitPeeringImpl withPrimaryPeerAddressPrefix( - String addressPrefix) { + public ExpressRouteCircuitPeeringImpl + withPrimaryPeerAddressPrefix(String addressPrefix) { innerModel().withPrimaryPeerAddressPrefix(addressPrefix); return this; } @Override - public ExpressRouteCircuitPeeringImpl withSecondaryPeerAddressPrefix( - String addressPrefix) { + public ExpressRouteCircuitPeeringImpl + withSecondaryPeerAddressPrefix(String addressPrefix) { innerModel().withSecondaryPeerAddressPrefix(addressPrefix); return this; } @@ -95,15 +87,12 @@ public boolean isInCreateMode() { @Override public Mono createResourceAsync() { - return this - .client - .createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), innerModel()) - .flatMap( - innerModel -> { - this.setInner(innerModel); - stats = new ExpressRouteCircuitStatsImpl(innerModel.stats()); - return parent.refreshAsync().then(Mono.just(this)); - }); + return this.client.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), innerModel()) + .flatMap(innerModel -> { + this.setInner(innerModel); + stats = new ExpressRouteCircuitStatsImpl(innerModel.stats()); + return parent.refreshAsync().then(Mono.just(this)); + }); } // Getters diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringsImpl.java index 31c1147ccc77d..9fd9da6073db4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitPeeringsImpl.java @@ -16,14 +16,8 @@ import reactor.core.publisher.Mono; /** Represents Express Route Circuit Peerings collection associated with Network Watcher. */ -class ExpressRouteCircuitPeeringsImpl - extends IndependentChildrenImpl< - ExpressRouteCircuitPeering, - ExpressRouteCircuitPeeringImpl, - ExpressRouteCircuitPeeringInner, - ExpressRouteCircuitPeeringsClient, - NetworkManager, - ExpressRouteCircuit> +class ExpressRouteCircuitPeeringsImpl extends + IndependentChildrenImpl, ExpressRouteCircuitPeeringInner, ExpressRouteCircuitPeeringsClient, NetworkManager, ExpressRouteCircuit> implements ExpressRouteCircuitPeerings { private final ExpressRouteCircuitImpl parent; @@ -51,8 +45,8 @@ public PagedFlux listAsync() { @Override protected ExpressRouteCircuitPeeringImpl wrapModel(String name) { - return new ExpressRouteCircuitPeeringImpl<>( - parent, new ExpressRouteCircuitPeeringInner(), innerModel(), ExpressRoutePeeringType.fromString(name)); + return new ExpressRouteCircuitPeeringImpl<>(parent, new ExpressRouteCircuitPeeringInner(), innerModel(), + ExpressRoutePeeringType.fromString(name)); } protected ExpressRouteCircuitPeeringImpl @@ -65,22 +59,22 @@ public PagedFlux listAsync() { @Override public ExpressRouteCircuitPeeringImpl defineAzurePrivatePeering() { - return new ExpressRouteCircuitPeeringImpl<>( - parent, new ExpressRouteCircuitPeeringInner(), innerModel(), ExpressRoutePeeringType.AZURE_PRIVATE_PEERING); + return new ExpressRouteCircuitPeeringImpl<>(parent, new ExpressRouteCircuitPeeringInner(), innerModel(), + ExpressRoutePeeringType.AZURE_PRIVATE_PEERING); } @Override public ExpressRouteCircuitPeeringImpl defineAzurePublicPeering() { - return new ExpressRouteCircuitPeeringImpl<>( - parent, new ExpressRouteCircuitPeeringInner(), innerModel(), ExpressRoutePeeringType.AZURE_PUBLIC_PEERING); + return new ExpressRouteCircuitPeeringImpl<>(parent, new ExpressRouteCircuitPeeringInner(), innerModel(), + ExpressRoutePeeringType.AZURE_PUBLIC_PEERING); } @Override public ExpressRouteCircuitPeeringImpl defineMicrosoftPeering() { - return new ExpressRouteCircuitPeeringImpl<>( - parent, new ExpressRouteCircuitPeeringInner(), innerModel(), ExpressRoutePeeringType.MICROSOFT_PEERING); + return new ExpressRouteCircuitPeeringImpl<>(parent, new ExpressRouteCircuitPeeringInner(), innerModel(), + ExpressRoutePeeringType.MICROSOFT_PEERING); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitsImpl.java index 4bcab94914951..f67b82fb45ffd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitsImpl.java @@ -9,13 +9,8 @@ import com.azure.resourcemanager.network.models.ExpressRouteCircuits; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; -public class ExpressRouteCircuitsImpl - extends TopLevelModifiableResourcesImpl< - ExpressRouteCircuit, - ExpressRouteCircuitImpl, - ExpressRouteCircuitInner, - ExpressRouteCircuitsClient, - NetworkManager> +public class ExpressRouteCircuitsImpl extends + TopLevelModifiableResourcesImpl implements ExpressRouteCircuits { public ExpressRouteCircuitsImpl(NetworkManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionImpl.java index def6a02dd9e9a..e6dcc267e2bf2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionImpl.java @@ -18,9 +18,8 @@ import reactor.core.publisher.Mono; /** Implementation for ExpressRouteCrossConnection. */ -public class ExpressRouteCrossConnectionImpl - extends GroupableParentResourceWithTagsImpl< - ExpressRouteCrossConnection, ExpressRouteCrossConnectionInner, ExpressRouteCrossConnectionImpl, NetworkManager> +public class ExpressRouteCrossConnectionImpl extends + GroupableParentResourceWithTagsImpl implements ExpressRouteCrossConnection, ExpressRouteCrossConnection.Update { private ExpressRouteCrossConnectionPeeringsImpl peerings; private Map crossConnectionPeerings; @@ -32,8 +31,7 @@ public class ExpressRouteCrossConnectionImpl @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCrossConnections() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); @@ -44,18 +42,15 @@ protected void initializeChildrenFromInner() { crossConnectionPeerings = new HashMap<>(); if (innerModel().peerings() != null) { for (ExpressRouteCrossConnectionPeeringInner peering : innerModel().peerings()) { - crossConnectionPeerings - .put( - peering.name(), - new ExpressRouteCrossConnectionPeeringImpl(this, peering, peering.peeringType())); + crossConnectionPeerings.put(peering.name(), + new ExpressRouteCrossConnectionPeeringImpl(this, peering, peering.peeringType())); } } } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCrossConnections() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -63,21 +58,16 @@ protected Mono getInnerAsync() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - expressRouteCrossConnection -> { - ExpressRouteCrossConnectionImpl impl = - (ExpressRouteCrossConnectionImpl) expressRouteCrossConnection; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(expressRouteCrossConnection -> { + ExpressRouteCrossConnectionImpl impl = (ExpressRouteCrossConnectionImpl) expressRouteCrossConnection; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getExpressRouteCrossConnections() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringImpl.java index 4cfd87668f381..17787fba58b32 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringImpl.java @@ -17,21 +17,15 @@ import java.util.Arrays; -class ExpressRouteCrossConnectionPeeringImpl - extends CreatableUpdatableImpl< - ExpressRouteCrossConnectionPeering, - ExpressRouteCrossConnectionPeeringInner, - ExpressRouteCrossConnectionPeeringImpl> - implements ExpressRouteCrossConnectionPeering, - ExpressRouteCrossConnectionPeering.Definition, - ExpressRouteCrossConnectionPeering.Update { +class ExpressRouteCrossConnectionPeeringImpl extends + CreatableUpdatableImpl + implements ExpressRouteCrossConnectionPeering, ExpressRouteCrossConnectionPeering.Definition, + ExpressRouteCrossConnectionPeering.Update { private final ExpressRouteCrossConnectionPeeringsClient client; private final ExpressRouteCrossConnection parent; - ExpressRouteCrossConnectionPeeringImpl( - ExpressRouteCrossConnectionImpl parent, - ExpressRouteCrossConnectionPeeringInner innerObject, - ExpressRoutePeeringType type) { + ExpressRouteCrossConnectionPeeringImpl(ExpressRouteCrossConnectionImpl parent, + ExpressRouteCrossConnectionPeeringInner innerObject, ExpressRoutePeeringType type) { super(type.toString(), innerObject); this.client = parent.manager().serviceClient().getExpressRouteCrossConnectionPeerings(); this.parent = parent; @@ -127,15 +121,12 @@ public boolean isInCreateMode() { @Override public Mono createResourceAsync() { - return this - .client - .createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), innerModel()) - .map( - innerModel -> { - ExpressRouteCrossConnectionPeeringImpl.this.setInner(innerModel); - parent.refresh(); - return ExpressRouteCrossConnectionPeeringImpl.this; - }); + return this.client.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), innerModel()) + .map(innerModel -> { + ExpressRouteCrossConnectionPeeringImpl.this.setInner(innerModel); + parent.refresh(); + return ExpressRouteCrossConnectionPeeringImpl.this; + }); } // Getters diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringsImpl.java index 03568f72f547e..fc08738b2f9d2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionPeeringsImpl.java @@ -15,14 +15,8 @@ import reactor.core.publisher.Mono; /** Represents Express Route Cross Connection Peerings collection associated with Network Watcher. */ -class ExpressRouteCrossConnectionPeeringsImpl - extends IndependentChildrenImpl< - ExpressRouteCrossConnectionPeering, - ExpressRouteCrossConnectionPeeringImpl, - ExpressRouteCrossConnectionPeeringInner, - ExpressRouteCrossConnectionPeeringsClient, - NetworkManager, - ExpressRouteCrossConnection> +class ExpressRouteCrossConnectionPeeringsImpl extends + IndependentChildrenImpl implements ExpressRouteCrossConnectionPeerings { private final ExpressRouteCrossConnectionImpl parent; @@ -49,8 +43,8 @@ public PagedFlux listAsync() { @Override protected ExpressRouteCrossConnectionPeeringImpl wrapModel(String name) { - return new ExpressRouteCrossConnectionPeeringImpl( - parent, new ExpressRouteCrossConnectionPeeringInner(), ExpressRoutePeeringType.fromString(name)); + return new ExpressRouteCrossConnectionPeeringImpl(parent, new ExpressRouteCrossConnectionPeeringInner(), + ExpressRoutePeeringType.fromString(name)); } protected ExpressRouteCrossConnectionPeeringImpl wrapModel(ExpressRouteCrossConnectionPeeringInner inner) { @@ -59,14 +53,14 @@ protected ExpressRouteCrossConnectionPeeringImpl wrapModel(ExpressRouteCrossConn @Override public ExpressRouteCrossConnectionPeeringImpl defineAzurePrivatePeering() { - return new ExpressRouteCrossConnectionPeeringImpl( - parent, new ExpressRouteCrossConnectionPeeringInner(), ExpressRoutePeeringType.AZURE_PRIVATE_PEERING); + return new ExpressRouteCrossConnectionPeeringImpl(parent, new ExpressRouteCrossConnectionPeeringInner(), + ExpressRoutePeeringType.AZURE_PRIVATE_PEERING); } @Override public ExpressRouteCrossConnectionPeeringImpl defineMicrosoftPeering() { - return new ExpressRouteCrossConnectionPeeringImpl( - parent, new ExpressRouteCrossConnectionPeeringInner(), ExpressRoutePeeringType.MICROSOFT_PEERING); + return new ExpressRouteCrossConnectionPeeringImpl(parent, new ExpressRouteCrossConnectionPeeringInner(), + ExpressRoutePeeringType.MICROSOFT_PEERING); } @Override @@ -96,19 +90,14 @@ public ExpressRouteCrossConnection parent() { @Override public Mono deleteByParentAsync(String groupName, String parentName, String name) { - return this - .innerModel() - .deleteAsync(groupName, parentName, name) - .doOnSuccess( - result -> { - parent.refresh(); - }) - .then(); + return this.innerModel().deleteAsync(groupName, parentName, name).doOnSuccess(result -> { + parent.refresh(); + }).then(); } @Override - public Mono getByParentAsync( - String resourceGroup, String parentName, String name) { + public Mono getByParentAsync(String resourceGroup, String parentName, + String name) { return innerModel().getAsync(resourceGroup, parentName, name).map(inner -> wrapModel(inner)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionsImpl.java index 97869d96462c6..a59b598a21e5e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCrossConnectionsImpl.java @@ -14,9 +14,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl; import reactor.core.publisher.Mono; -public class ExpressRouteCrossConnectionsImpl - extends ReadableWrappersImpl< - ExpressRouteCrossConnection, ExpressRouteCrossConnectionImpl, ExpressRouteCrossConnectionInner> +public class ExpressRouteCrossConnectionsImpl extends + ReadableWrappersImpl implements ExpressRouteCrossConnections { private final NetworkManager manager; @@ -51,12 +50,11 @@ public ExpressRouteCrossConnection getByResourceGroup(String resourceGroupName, @Override public Mono getByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } return this.inner().getByResourceGroupAsync(resourceGroupName, name).map(inner -> wrapModel(inner)); } @@ -69,8 +67,8 @@ public PagedIterable listByResourceGroup(String res @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/FlowLogSettingsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/FlowLogSettingsImpl.java index 51c659fe4b299..c962214926166 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/FlowLogSettingsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/FlowLogSettingsImpl.java @@ -41,16 +41,14 @@ public FlowLogSettings apply(Context context) { @Override public Mono applyAsync(Context context) { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .setFlowLogConfigurationAsync(parent().resourceGroupName(), parent().name(), this.innerModel()) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map( - flowLogInformationInner -> - new FlowLogSettingsImpl(FlowLogSettingsImpl.this.parent, flowLogInformationInner, nsgId)); + .map(flowLogInformationInner -> new FlowLogSettingsImpl(FlowLogSettingsImpl.this.parent, + flowLogInformationInner, nsgId)); } @Override @@ -111,8 +109,7 @@ public Update update() { @Override protected Mono getInnerAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/GroupableParentResourceWithTagsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/GroupableParentResourceWithTagsImpl.java index 952f654fbb72b..79db0e218778e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/GroupableParentResourceWithTagsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/GroupableParentResourceWithTagsImpl.java @@ -18,12 +18,7 @@ * @param the implementation type of the fluent model type * @param the service manager type */ -public abstract class GroupableParentResourceWithTagsImpl< - FluentModelT extends Resource, - InnerModelT extends com.azure.core.management.Resource, - FluentModelImplT extends - GroupableParentResourceWithTagsImpl, - ManagerT extends Manager> +public abstract class GroupableParentResourceWithTagsImpl, ManagerT extends Manager> extends GroupableParentResourceImpl implements UpdatableWithTags, AppliableWithTags { protected GroupableParentResourceWithTagsImpl(String name, InnerModelT innerObject, ManagerT manager) { @@ -47,11 +42,9 @@ public FluentModelT applyTags() { public Mono applyTagsAsync() { @SuppressWarnings("unchecked") final FluentModelT self = (FluentModelT) this; - return applyTagsToInnerAsync() - .flatMap( - inner -> { - setInner(inner); - return Mono.just(self); - }); + return applyTagsToInnerAsync().flatMap(inner -> { + setInner(inner); + return Mono.just(self); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Ipv6PeeringConfigImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Ipv6PeeringConfigImpl.java index c064cc5bd5154..d1c22d7c40ac3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Ipv6PeeringConfigImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Ipv6PeeringConfigImpl.java @@ -12,15 +12,13 @@ import java.util.List; /** Implementation for Ipv6PeeringConfig. */ -class Ipv6PeeringConfigImpl extends IndexableWrapperImpl - implements Ipv6PeeringConfig, - Ipv6PeeringConfig.Definition, - Ipv6PeeringConfig.UpdateDefinition, - Ipv6PeeringConfig.Update { +class Ipv6PeeringConfigImpl extends IndexableWrapperImpl implements + Ipv6PeeringConfig, Ipv6PeeringConfig.Definition, + Ipv6PeeringConfig.UpdateDefinition, Ipv6PeeringConfig.Update { private final ExpressRouteCrossConnectionPeeringImpl parent; - Ipv6PeeringConfigImpl( - Ipv6ExpressRouteCircuitPeeringConfig innerObject, ExpressRouteCrossConnectionPeeringImpl parent) { + Ipv6PeeringConfigImpl(Ipv6ExpressRouteCircuitPeeringConfig innerObject, + ExpressRouteCrossConnectionPeeringImpl parent) { super(innerObject); this.parent = parent; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerBackendImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerBackendImpl.java index 4610589cf8efb..52bfe763dcaf4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerBackendImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerBackendImpl.java @@ -23,10 +23,8 @@ /** Implementation for LoadBalancerBackend. */ class LoadBalancerBackendImpl extends ChildResourceImpl - implements LoadBalancerBackend, - LoadBalancerBackend.Definition, - LoadBalancerBackend.UpdateDefinition, - LoadBalancerBackend.Update { + implements LoadBalancerBackend, LoadBalancerBackend.Definition, + LoadBalancerBackend.UpdateDefinition, LoadBalancerBackend.Update { LoadBalancerBackendImpl(BackendAddressPoolInner inner, LoadBalancerImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerFrontendImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerFrontendImpl.java index 2a98b0ed75062..3914cfab0a6bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerFrontendImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerFrontendImpl.java @@ -33,15 +33,12 @@ /** Implementation for LoadBalancerPublicFrontend. */ class LoadBalancerFrontendImpl extends ChildResourceImpl - implements LoadBalancerFrontend, - LoadBalancerPrivateFrontend, - LoadBalancerPrivateFrontend.Definition, - LoadBalancerPrivateFrontend.UpdateDefinition, - LoadBalancerPrivateFrontend.Update, - LoadBalancerPublicFrontend, - LoadBalancerPublicFrontend.Definition, - LoadBalancerPublicFrontend.UpdateDefinition, - LoadBalancerPublicFrontend.Update { + implements LoadBalancerFrontend, LoadBalancerPrivateFrontend, + LoadBalancerPrivateFrontend.Definition, + LoadBalancerPrivateFrontend.UpdateDefinition, LoadBalancerPrivateFrontend.Update, + LoadBalancerPublicFrontend, + LoadBalancerPublicFrontend.Definition, + LoadBalancerPublicFrontend.UpdateDefinition, LoadBalancerPublicFrontend.Update { LoadBalancerFrontendImpl(FrontendIpConfigurationInner inner, LoadBalancerImpl parent) { super(inner, parent); @@ -169,10 +166,7 @@ public LoadBalancerFrontendImpl withExistingSubnet(Network network, String subne public LoadBalancerFrontendImpl withExistingSubnet(String parentNetworkResourceId, String subnetName) { SubnetInner subnetRef = new SubnetInner(); subnetRef.withId(parentNetworkResourceId + "/subnets/" + subnetName); - this - .innerModel() - .withSubnet(subnetRef) - .withPublicIpAddress(null); // Ensure no conflicting public and private settings + this.innerModel().withSubnet(subnetRef).withPublicIpAddress(null); // Ensure no conflicting public and private settings return this; } @@ -200,8 +194,7 @@ public LoadBalancerFrontendImpl withExistingPublicIpAddress(PublicIpAddress pip) @Override public LoadBalancerFrontendImpl withExistingPublicIpAddress(String resourceId) { PublicIpAddressInner pipRef = new PublicIpAddressInner().withId(resourceId); - this - .innerModel() + this.innerModel() .withPublicIpAddress(pipRef) // Ensure no conflicting public and private settings @@ -219,8 +212,7 @@ public LoadBalancerFrontendImpl withoutPublicIpAddress() { @Override public LoadBalancerFrontendImpl withPrivateIpAddressDynamic() { - this - .innerModel() + this.innerModel() .withPrivateIpAddress(null) .withPrivateIpAllocationMethod(IpAllocationMethod.DYNAMIC) @@ -231,8 +223,7 @@ public LoadBalancerFrontendImpl withPrivateIpAddressDynamic() { @Override public LoadBalancerFrontendImpl withPrivateIpAddressStatic(String ipAddress) { - this - .innerModel() + this.innerModel() .withPrivateIpAddress(ipAddress) .withPrivateIpAllocationMethod(IpAllocationMethod.STATIC) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerImpl.java index 5041eccf8a5fc..e01f688ee6441 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerImpl.java @@ -77,20 +77,16 @@ class LoadBalancerImpl @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - loadBalancer -> { - LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(loadBalancer -> { + LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getLoadBalancers() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -98,8 +94,7 @@ protected Mono getInnerAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getLoadBalancers() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -172,8 +167,8 @@ LoadBalancerPrivateFrontend ensurePrivateFrontendWithSubnet(String networkId, St return frontend; } else { // Create new frontend - LoadBalancerFrontendImpl fe = - this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIpAddressDynamic(); + LoadBalancerFrontendImpl fe + = this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIpAddressDynamic(); fe.attach(); return fe; } @@ -269,13 +264,11 @@ protected void beforeCreating() { // Clear deleted frontend references List refs = outboundRule.innerModel().frontendIpConfigurations(); if (refs != null && !refs.isEmpty()) { - List existingFrontendIpConfigurations = - refs.stream() - .filter(ref -> - this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id())) - ) - .collect(Collectors.toList()); - existingFrontendIpConfigurations = existingFrontendIpConfigurations.isEmpty() ? null : existingFrontendIpConfigurations; + List existingFrontendIpConfigurations = refs.stream() + .filter(ref -> this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) + .collect(Collectors.toList()); + existingFrontendIpConfigurations + = existingFrontendIpConfigurations.isEmpty() ? null : existingFrontendIpConfigurations; outboundRule.innerModel().withFrontendIpConfigurations(existingFrontendIpConfigurations); } // clear deleted backend references @@ -306,7 +299,10 @@ protected void beforeCreating() { lbRule.innerModel().withBackendAddressPool(null); } if (!CoreUtils.isNullOrEmpty(lbRule.innerModel().backendAddressPools())) { - lbRule.innerModel().backendAddressPools().removeIf(backendRef -> backendRef != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(backendRef.id()))); + lbRule.innerModel() + .backendAddressPools() + .removeIf(backendRef -> backendRef != null + && !this.backends().containsKey(ResourceUtils.nameFromResourceId(backendRef.id()))); } // Clear deleted probe references @@ -324,51 +320,35 @@ protected Mono afterCreatingAsync() { if (this.nicsInBackends != null) { List nicExceptions = new ArrayList<>(); - return Flux - .fromIterable(this.nicsInBackends.entrySet()) - .flatMap( - nicInBackend -> { - String nicId = nicInBackend.getKey(); - String backendName = nicInBackend.getValue(); - return this - .manager() - .networkInterfaces() - .getByIdAsync(nicId) - .flatMap( - nic -> { - NicIpConfiguration nicIP = nic.primaryIPConfiguration(); - return nic - .update() - .updateIPConfiguration(nicIP.name()) - .withExistingLoadBalancerBackend(this, backendName) - .parent() - .applyAsync(); - }); - }) - .onErrorResume( - t -> { - nicExceptions.add(t); - return Mono.empty(); - }) - .then( - Mono - .defer( - () -> { - if (!nicExceptions.isEmpty()) { - return Mono.error(Exceptions.multiple(nicExceptions)); - } else { - this.nicsInBackends.clear(); - return Mono.empty(); - } - })); + return Flux.fromIterable(this.nicsInBackends.entrySet()).flatMap(nicInBackend -> { + String nicId = nicInBackend.getKey(); + String backendName = nicInBackend.getValue(); + return this.manager().networkInterfaces().getByIdAsync(nicId).flatMap(nic -> { + NicIpConfiguration nicIP = nic.primaryIPConfiguration(); + return nic.update() + .updateIPConfiguration(nicIP.name()) + .withExistingLoadBalancerBackend(this, backendName) + .parent() + .applyAsync(); + }); + }).onErrorResume(t -> { + nicExceptions.add(t); + return Mono.empty(); + }).then(Mono.defer(() -> { + if (!nicExceptions.isEmpty()) { + return Mono.error(Exceptions.multiple(nicExceptions)); + } else { + this.nicsInBackends.clear(); + return Mono.empty(); + } + })); } return Mono.empty(); } @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getLoadBalancers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); @@ -377,13 +357,11 @@ protected Mono createInner() { @Override public Mono createResourceAsync() { beforeCreating(); - return createInner() - .flatMap( - inner -> { - setInner(inner); - initializeChildrenFromInner(); - return afterCreatingAsync().then(this.refreshAsync()); - }); + return createInner().flatMap(inner -> { + setInner(inner); + initializeChildrenFromInner(); + return afterCreatingAsync().then(this.refreshAsync()); + }); } private void initializeFrontendsFromInner() { @@ -471,8 +449,7 @@ private void initializeOutboundRulesFromInner() { } String futureResourceId() { - return new StringBuilder() - .append(super.resourceIdBase()) + return new StringBuilder().append(super.resourceIdBase()) .append("/providers/Microsoft.Network/loadBalancers/") .append(this.name()) .toString(); @@ -536,12 +513,12 @@ LoadBalancerImpl withBackend(LoadBalancerBackendImpl backend) { // Withers (fluent) LoadBalancerImpl withNewPublicIPAddress(String dnsLeafLabel, String frontendName) { - PublicIpAddress.DefinitionStages.WithGroup precreatablePIP = - manager().publicIpAddresses().define(dnsLeafLabel).withRegion(this.regionName()); + PublicIpAddress.DefinitionStages.WithGroup precreatablePIP + = manager().publicIpAddresses().define(dnsLeafLabel).withRegion(this.regionName()); Creatable creatablePip; if (super.creatableGroup == null) { - creatablePip = - precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); + creatablePip + = precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); } else { creatablePip = precreatablePIP.withNewResourceGroup(super.creatableGroup).withLeafDomainLabel(dnsLeafLabel); } @@ -565,8 +542,8 @@ LoadBalancerImpl withNewPublicIPAddress(Creatable creatablePip, this.creatablePIPKeys.put(this.addDependency(creatablePip), frontendName); } else if (!existingPipFrontendName.equalsIgnoreCase(frontendName)) { // Existing PIP definition already in use but under a different frontend, so error - String exceptionMessage = - "This public IP address definition is already associated with a frontend under a different name."; + String exceptionMessage + = "This public IP address definition is already associated with a frontend under a different name."; throw logger.logExceptionAsError(new IllegalArgumentException(exceptionMessage)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatPoolImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatPoolImpl.java index 6c0b6b5e326ac..bdd88f2559b5a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatPoolImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatPoolImpl.java @@ -19,9 +19,8 @@ /** Implementation for LoadBalancerInboundNatRule. */ class LoadBalancerInboundNatPoolImpl extends ChildResourceImpl implements LoadBalancerInboundNatPool, - LoadBalancerInboundNatPool.Definition, - LoadBalancerInboundNatPool.UpdateDefinition, - LoadBalancerInboundNatPool.Update { + LoadBalancerInboundNatPool.Definition, + LoadBalancerInboundNatPool.UpdateDefinition, LoadBalancerInboundNatPool.Update { LoadBalancerInboundNatPoolImpl(InboundNatPool inner, LoadBalancerImpl parent) { super(inner, parent); @@ -46,8 +45,7 @@ public int backendPort() { @Override public LoadBalancerFrontend frontend() { - return this - .parent() + return this.parent() .frontends() .get(ResourceUtils.nameFromResourceId(this.innerModel().frontendIpConfiguration().id())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatRuleImpl.java index f394331a65079..4e7e1f9cd7ef8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerInboundNatRuleImpl.java @@ -19,9 +19,8 @@ /** Implementation for LoadBalancerInboundNatRule. */ class LoadBalancerInboundNatRuleImpl extends ChildResourceImpl implements LoadBalancerInboundNatRule, - LoadBalancerInboundNatRule.Definition, - LoadBalancerInboundNatRule.UpdateDefinition, - LoadBalancerInboundNatRule.Update { + LoadBalancerInboundNatRule.Definition, + LoadBalancerInboundNatRule.UpdateDefinition, LoadBalancerInboundNatRule.Update { LoadBalancerInboundNatRuleImpl(InboundNatRuleInner inner, LoadBalancerImpl parent) { super(inner, parent); @@ -74,8 +73,7 @@ public boolean floatingIPEnabled() { @Override public LoadBalancerFrontend frontend() { - return this - .parent() + return this.parent() .frontends() .get(ResourceUtils.nameFromResourceId(this.innerModel().frontendIpConfiguration().id())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerOutboundRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerOutboundRuleImpl.java index 5c4ee49ffbb95..30885f9d2e999 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerOutboundRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerOutboundRuleImpl.java @@ -22,8 +22,7 @@ import java.util.TreeMap; public class LoadBalancerOutboundRuleImpl extends ChildResourceImpl - implements LoadBalancerOutboundRule, - LoadBalancerOutboundRule.Definition, + implements LoadBalancerOutboundRule, LoadBalancerOutboundRule.Definition, LoadBalancerOutboundRule.Update { LoadBalancerOutboundRuleImpl(OutboundRuleInner inner, LoadBalancerImpl parent) { @@ -39,11 +38,11 @@ public LoadBalancerOutboundRuleProtocol protocol() { @Override public Map frontends() { Map nameToFrontEndMap = new TreeMap<>(); - if (this.innerModel().frontendIpConfigurations() != null && !this.innerModel().frontendIpConfigurations().isEmpty()) { + if (this.innerModel().frontendIpConfigurations() != null + && !this.innerModel().frontendIpConfigurations().isEmpty()) { for (SubResource frontendIpConfiguration : this.innerModel().frontendIpConfigurations()) { - LoadBalancerFrontend frontend = this.parent() - .frontends() - .get(ResourceUtils.nameFromResourceId(frontendIpConfiguration.id())); + LoadBalancerFrontend frontend + = this.parent().frontends().get(ResourceUtils.nameFromResourceId(frontendIpConfiguration.id())); nameToFrontEndMap.put(frontend.name(), frontend); } } @@ -52,8 +51,7 @@ public Map frontends() { @Override public LoadBalancerBackend backend() { - return this - .parent() + return this.parent() .backends() .get(ResourceUtils.nameFromResourceId(this.innerModel().backendAddressPool().id())); } @@ -96,8 +94,8 @@ public LoadBalancerOutboundRuleImpl fromBackend(String name) { // Ensure existence of backend, creating one if needed this.parent().defineBackend(name).attach(); - SubResource backendRef = - new SubResource().withId(this.parent().futureResourceId() + "/backendAddressPools/" + name); + SubResource backendRef + = new SubResource().withId(this.parent().futureResourceId() + "/backendAddressPools/" + name); this.innerModel().withBackendAddressPool(backendRef); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerProbeImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerProbeImpl.java index 1ef06fd4593b9..b4a267a0ec31c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerProbeImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancerProbeImpl.java @@ -19,14 +19,10 @@ /** Implementation for LoadBalancerTcpProbe and its create and update interfaces. */ class LoadBalancerProbeImpl extends ChildResourceImpl - implements LoadBalancerTcpProbe, - LoadBalancerTcpProbe.Definition, - LoadBalancerTcpProbe.UpdateDefinition, - LoadBalancerTcpProbe.Update, - LoadBalancerHttpProbe, - LoadBalancerHttpProbe.Definition, - LoadBalancerHttpProbe.UpdateDefinition, - LoadBalancerHttpProbe.Update { + implements LoadBalancerTcpProbe, LoadBalancerTcpProbe.Definition, + LoadBalancerTcpProbe.UpdateDefinition, LoadBalancerTcpProbe.Update, LoadBalancerHttpProbe, + LoadBalancerHttpProbe.Definition, + LoadBalancerHttpProbe.UpdateDefinition, LoadBalancerHttpProbe.Update { LoadBalancerProbeImpl(ProbeInner inner, LoadBalancerImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancersImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancersImpl.java index 19890d46f9efe..67c7a0585b181 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancersImpl.java @@ -10,9 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for {@link LoadBalancers}. */ -public class LoadBalancersImpl - extends TopLevelModifiableResourcesImpl< - LoadBalancer, LoadBalancerImpl, LoadBalancerInner, LoadBalancersClient, NetworkManager> +public class LoadBalancersImpl extends + TopLevelModifiableResourcesImpl implements LoadBalancers { public LoadBalancersImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancingRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancingRuleImpl.java index f47b7822ccaa1..cce857da62e05 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancingRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LoadBalancingRuleImpl.java @@ -29,10 +29,8 @@ /** Implementation for LoadBalancingRule. */ class LoadBalancingRuleImpl extends ChildResourceImpl - implements LoadBalancingRule, - LoadBalancingRule.Definition, - LoadBalancingRule.UpdateDefinition, - LoadBalancingRule.Update { + implements LoadBalancingRule, LoadBalancingRule.Definition, + LoadBalancingRule.UpdateDefinition, LoadBalancingRule.Update { LoadBalancingRuleImpl(LoadBalancingRuleInner inner, LoadBalancerImpl parent) { super(inner, parent); @@ -268,8 +266,8 @@ public LoadBalancingRuleImpl toBackend(String backendName) { // Ensure existence of backend, creating one if needed this.parent().defineBackend(backendName).attach(); - SubResource backendRef = - new SubResource().withId(this.parent().futureResourceId() + "/backendAddressPools/" + backendName); + SubResource backendRef + = new SubResource().withId(this.parent().futureResourceId() + "/backendAddressPools/" + backendName); this.innerModel().withBackendAddressPool(backendRef); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewayImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewayImpl.java index 9babdcdfee35b..0ee9ee12d6ef1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewayImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewayImpl.java @@ -17,16 +17,13 @@ import reactor.core.publisher.Mono; /** Implementation for LocalNetworkGateway and its create and update interfaces. */ -class LocalNetworkGatewayImpl - extends GroupableResourceImpl< - LocalNetworkGateway, LocalNetworkGatewayInner, LocalNetworkGatewayImpl, NetworkManager> - implements LocalNetworkGateway, - LocalNetworkGateway.Definition, - LocalNetworkGateway.Update, - AppliableWithTags { - - LocalNetworkGatewayImpl( - String name, final LocalNetworkGatewayInner innerModel, final NetworkManager networkManager) { +class LocalNetworkGatewayImpl extends + GroupableResourceImpl + implements LocalNetworkGateway, LocalNetworkGateway.Definition, LocalNetworkGateway.Update, + AppliableWithTags { + + LocalNetworkGatewayImpl(String name, final LocalNetworkGatewayInner innerModel, + final NetworkManager networkManager) { super(name, innerModel, networkManager); } @@ -98,8 +95,7 @@ public LocalNetworkGatewayImpl withoutBgp() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getLocalNetworkGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -107,8 +103,7 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getLocalNetworkGateways() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) @@ -134,15 +129,13 @@ public LocalNetworkGateway applyTags() { @Override public Mono applyTagsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getLocalNetworkGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())) - .flatMap( - inner -> { - setInner(inner); - return Mono.just((LocalNetworkGateway) LocalNetworkGatewayImpl.this); - }); + .flatMap(inner -> { + setInner(inner); + return Mono.just((LocalNetworkGateway) LocalNetworkGatewayImpl.this); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewaysImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewaysImpl.java index 1a3e101cae60f..4fcdbb759bd2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewaysImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/LocalNetworkGatewaysImpl.java @@ -15,13 +15,8 @@ import reactor.core.publisher.Mono; /** Implementation for LocalNetworkGateways. */ -public class LocalNetworkGatewaysImpl - extends GroupableResourcesImpl< - LocalNetworkGateway, - LocalNetworkGatewayImpl, - LocalNetworkGatewayInner, - LocalNetworkGatewaysClient, - NetworkManager> +public class LocalNetworkGatewaysImpl extends + GroupableResourcesImpl implements LocalNetworkGateways { public LocalNetworkGatewaysImpl(final NetworkManager networkManager) { @@ -40,8 +35,9 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), - rg -> inner().listByResourceGroupAsync(rg.name())), this::wrapModel); + return PagedConverter + .mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), + rg -> inner().listByResourceGroupAsync(rg.name())), this::wrapModel); } @Override @@ -52,8 +48,8 @@ public PagedIterable listByResourceGroup(String groupName) @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkImpl.java index f57abb9583465..31552521fb00b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkImpl.java @@ -59,20 +59,16 @@ protected void initializeChildrenFromInner() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - network -> { - NetworkImpl impl = (NetworkImpl) network; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(network -> { + NetworkImpl impl = (NetworkImpl) network; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworks() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -80,8 +76,7 @@ protected Mono getInnerAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworks() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -107,12 +102,10 @@ private IpAddressAvailabilityResultInner checkIPAvailability(String ipAddress) { } IpAddressAvailabilityResultInner result = null; try { - result = - this - .manager() - .serviceClient() - .getVirtualNetworks() - .checkIpAddressAvailability(this.resourceGroupName(), this.name(), ipAddress); + result = this.manager() + .serviceClient() + .getVirtualNetworks() + .checkIpAddressAvailability(this.resourceGroupName(), this.name(), ipAddress); } catch (ManagementException e) { if (!e.getValue().getCode().equalsIgnoreCase("PrivateIPAddressNotInAnySubnet")) { throw logger.logExceptionAsError(e); @@ -250,20 +243,18 @@ public SubnetImpl updateSubnet(String name) { @Override protected Mono createInner() { if (ddosProtectionPlanCreatable != null && this.taskResult(ddosProtectionPlanCreatable.key()) != null) { - DdosProtectionPlan ddosProtectionPlan = - this.taskResult(ddosProtectionPlanCreatable.key()); + DdosProtectionPlan ddosProtectionPlan + = this.taskResult(ddosProtectionPlanCreatable.key()); withExistingDdosProtectionPlan(ddosProtectionPlan.id()); } - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworks() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) - .map( - virtualNetworkInner -> { - NetworkImpl.this.ddosProtectionPlanCreatable = null; - return virtualNetworkInner; - }); + .map(virtualNetworkInner -> { + NetworkImpl.this.ddosProtectionPlanCreatable = null; + return virtualNetworkInner; + }); } @Override @@ -289,11 +280,9 @@ public String ddosProtectionPlanId() { @Override public NetworkImpl withNewDdosProtectionPlan() { innerModel().withEnableDdosProtection(true); - DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = - manager() - .ddosProtectionPlans() - .define(this.manager().resourceManager().internalContext().randomResourceName(name(), 20)) - .withRegion(region()); + DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = manager().ddosProtectionPlans() + .define(this.manager().resourceManager().internalContext().randomResourceName(name(), 20)) + .withRegion(region()); if (super.creatableGroup != null && isInCreateMode()) { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withNewResourceGroup(super.creatableGroup); } else { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfaceImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfaceImpl.java index 1a8793482863c..9151f3b6bfbb5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfaceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfaceImpl.java @@ -43,9 +43,8 @@ import reactor.core.publisher.Mono; /** Implementation for NetworkInterface and its create and update interfaces. */ -class NetworkInterfaceImpl - extends GroupableParentResourceWithTagsImpl< - NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> +class NetworkInterfaceImpl extends + GroupableParentResourceWithTagsImpl implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { private final ClientLogger logger = new ClientLogger(this.getClass()); @@ -77,21 +76,17 @@ class NetworkInterfaceImpl @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - networkInterface -> { - NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; - impl.clearCachedRelatedResources(); - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(networkInterface -> { + NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; + impl.clearCachedRelatedResources(); + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -99,8 +94,7 @@ protected Mono getInnerAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkInterfaces() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -169,8 +163,8 @@ public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBal } @Override - public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( - LoadBalancer loadBalancer, String inboundNatRuleName) { + public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule(LoadBalancer loadBalancer, + String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @@ -237,8 +231,8 @@ public NetworkInterfaceImpl withoutNetworkSecurityGroup() { } @Override - public NetworkInterfaceImpl withExistingApplicationSecurityGroup( - ApplicationSecurityGroup applicationSecurityGroup) { + public NetworkInterfaceImpl + withExistingApplicationSecurityGroup(ApplicationSecurityGroup applicationSecurityGroup) { // update application security group for all ip configurations, // as nic requires same set for all ip configurations. for (NicIpConfiguration ipConfiguration : this.nicIPConfigurations.values()) { @@ -261,8 +255,8 @@ public NicIpConfigurationImpl defineSecondaryIPConfiguration(String name) { // copy application security group from primary to secondary, // as nic requires same set for all ip configurations. - List inners = - this.primaryIPConfiguration().innerModel().applicationSecurityGroups(); + List inners + = this.primaryIPConfiguration().innerModel().applicationSecurityGroups(); if (inners != null) { for (ApplicationSecurityGroupInner inner : inners) { nicIpConfiguration.withExistingApplicationSecurityGroup(inner); @@ -412,11 +406,8 @@ public String networkSecurityGroupId() { public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); - this.networkSecurityGroup = - super - .myManager - .networkSecurityGroups() - .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); + this.networkSecurityGroup = super.myManager.networkSecurityGroups() + .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } @@ -466,8 +457,8 @@ protected void initializeChildrenFromInner() { List inners = this.innerModel().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIpConfigurationInner inner : inners) { - NicIpConfigurationImpl nicIPConfiguration = - new NicIpConfigurationImpl(inner, this, super.myManager, false); + NicIpConfigurationImpl nicIPConfiguration + = new NicIpConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } @@ -481,8 +472,8 @@ protected void initializeChildrenFromInner() { * @return {@link NicIpConfiguration} */ private NicIpConfigurationImpl prepareNewNicIPConfiguration(String name) { - NicIpConfigurationImpl nicIPConfiguration = - NicIpConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); + NicIpConfigurationImpl nicIPConfiguration + = NicIpConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } @@ -509,39 +500,29 @@ Creatable newGroup() { @Override public Accepted beginCreate() { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> - this - .manager() - .serviceClient() - .getNetworkInterfaces() - .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) - .block(), - inner -> new NetworkInterfaceImpl(inner.name(), inner, this.manager()), - NetworkInterfaceInner.class, - () -> { - Flux dependencyTasksAsync = - taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); - dependencyTasksAsync.blockLast(); - - beforeCreating(); - }, - inner -> { - innerToFluentMap(this); - initializeChildrenFromInner(); - afterCreating(); - }, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.manager() + .serviceClient() + .getNetworkInterfaces() + .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) + .block(), + inner -> new NetworkInterfaceImpl(inner.name(), inner, this.manager()), NetworkInterfaceInner.class, () -> { + Flux dependencyTasksAsync + = taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); + dependencyTasksAsync.blockLast(); + + beforeCreating(); + }, inner -> { + innerToFluentMap(this); + initializeChildrenFromInner(); + afterCreating(); + }, Context.NONE); } @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); @@ -563,8 +544,7 @@ protected void beforeCreating() { // Associate an NSG if needed if (networkSecurityGroup != null) { - this - .innerModel() + this.innerModel() .withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesClientImpl.java index 51b98c8ec9b6e..22d09842150cf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesClientImpl.java @@ -3050,7 +3050,7 @@ public Mono getVirtualMachineScaleSetIpCon final String expand = null; return getVirtualMachineScaleSetIpConfigurationWithResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, expand) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesImpl.java index 4e61d70fa4f64..ded088d58c13b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkInterfacesImpl.java @@ -25,9 +25,8 @@ import java.util.function.Function; /** Implementation for {@link NetworkInterfaces}. */ -public class NetworkInterfacesImpl - extends TopLevelModifiableResourcesImpl< - NetworkInterface, NetworkInterfaceImpl, NetworkInterfaceInner, NetworkInterfacesClient, NetworkManager> +public class NetworkInterfacesImpl extends + TopLevelModifiableResourcesImpl implements NetworkInterfaces { private final ClientLogger logger = new ClientLogger(this.getClass()); @@ -37,48 +36,48 @@ public NetworkInterfacesImpl(final NetworkManager networkManager) { } @Override - public VirtualMachineScaleSetNetworkInterface getByVirtualMachineScaleSetInstanceId( - String resourceGroupName, String scaleSetName, String instanceId, String name) { - VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces = - new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); + public VirtualMachineScaleSetNetworkInterface getByVirtualMachineScaleSetInstanceId(String resourceGroupName, + String scaleSetName, String instanceId, String name) { + VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces + = new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); return scaleSetNetworkInterfaces.getByVirtualMachineInstanceId(instanceId, name); } @Override public Mono getByVirtualMachineScaleSetInstanceIdAsync( String resourceGroupName, String scaleSetName, String instanceId, String name) { - VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces = - new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); + VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces + = new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); return scaleSetNetworkInterfaces.getByVirtualMachineInstanceIdAsync(instanceId, name); } @Override - public PagedIterable listByVirtualMachineScaleSet( - String resourceGroupName, String scaleSetName) { - VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces = - new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); + public PagedIterable listByVirtualMachineScaleSet(String resourceGroupName, + String scaleSetName) { + VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces + = new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); return scaleSetNetworkInterfaces.list(); } @Override public PagedIterable listByVirtualMachineScaleSetId(String id) { - return this - .listByVirtualMachineScaleSet(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); + return this.listByVirtualMachineScaleSet(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id)); } @Override - public PagedIterable listByVirtualMachineScaleSetInstanceId( - String resourceGroupName, String scaleSetName, String instanceId) { - VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces = - new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); + public PagedIterable + listByVirtualMachineScaleSetInstanceId(String resourceGroupName, String scaleSetName, String instanceId) { + VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces + = new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); return scaleSetNetworkInterfaces.listByVirtualMachineInstanceId(instanceId); } @Override - public PagedFlux listByVirtualMachineScaleSetInstanceIdAsync( - String resourceGroupName, String scaleSetName, String instanceId) { - VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces = - new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); + public PagedFlux + listByVirtualMachineScaleSetInstanceIdAsync(String resourceGroupName, String scaleSetName, String instanceId) { + VirtualMachineScaleSetNetworkInterfacesImpl scaleSetNetworkInterfaces + = new VirtualMachineScaleSetNetworkInterfacesImpl(resourceGroupName, scaleSetName, this.manager()); return scaleSetNetworkInterfaces.listByVirtualMachineInstanceIdAsync(instanceId); } @@ -110,15 +109,9 @@ public Accepted beginDeleteById(String id) { @Override public Accepted beginDeleteByResourceGroup(String resourceGroupName, String name) { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), Function.identity(), + Void.class, null, Context.NONE); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringImpl.java index 3a775b5d11112..b2b244861b92b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringImpl.java @@ -20,20 +20,16 @@ import java.util.List; /** Implementation for network peering. */ -class NetworkPeeringImpl - extends IndependentChildImpl< - NetworkPeering, Network, VirtualNetworkPeeringInner, NetworkPeeringImpl, NetworkManager> +class NetworkPeeringImpl extends + IndependentChildImpl implements NetworkPeering, NetworkPeering.Definition, NetworkPeering.Update { private NetworkImpl parent; private Network remoteNetwork; private Boolean remoteAccess; // Controls the allowAccess setting on the remote peering (null means no change) - private Boolean - remoteForwarding; // Controls the trafficForwarding setting on the remote peering (null means no change) - private Boolean - startGatewayUseByRemoteNetwork; // Controls the UseGateway setting on the remote network (null means no change) - private Boolean - allowGatewayUseOnRemoteNetwork; // Controls the AllowGatewayTransit setting on the remote network (null means no + private Boolean remoteForwarding; // Controls the trafficForwarding setting on the remote peering (null means no change) + private Boolean startGatewayUseByRemoteNetwork; // Controls the UseGateway setting on the remote network (null means no change) + private Boolean allowGatewayUseOnRemoteNetwork; // Controls the AllowGatewayTransit setting on the remote network (null means no // change) NetworkPeeringImpl(VirtualNetworkPeeringInner inner, NetworkImpl parent) { @@ -248,191 +244,170 @@ public boolean checkAccessBetweenNetworks() { protected Mono createChildResourceAsync() { final NetworkPeeringImpl localPeering = this; final String networkName = ResourceUtils.nameFromResourceId(this.networkId()); - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkPeerings() .createOrUpdateAsync(this.parent.resourceGroupName(), networkName, this.name(), this.innerModel()) // After successful creation, update the inner - .doOnNext( - inner -> { - setInner(inner); - }) + .doOnNext(inner -> { + setInner(inner); + }) // Then get the remote network to update it if needed and in the same subscription - .flatMap( - inner -> { - SubResource networkRef = inner.remoteVirtualNetwork(); - if (localPeering.isSameSubscription()) { - // Update the remote network only if it is in the same subscription - return localPeering.manager().networks().getByIdAsync(networkRef.id()); - } else { - // Otherwise, skip this - return Mono.empty(); - } - }) + .flatMap(inner -> { + SubResource networkRef = inner.remoteVirtualNetwork(); + if (localPeering.isSameSubscription()) { + // Update the remote network only if it is in the same subscription + return localPeering.manager().networks().getByIdAsync(networkRef.id()); + } else { + // Otherwise, skip this + return Mono.empty(); + } + }) // Then update the existing remote network if needed, flatMap will skip when input is empty - .flatMap( - remoteNetwork -> { - // Check if any peering is already pointing at this network - return remoteNetwork - .peerings() - .listAsync() - .filter( - remotePeering -> - (remotePeering != null - && remotePeering.remoteNetworkId() != null - && remotePeering.remoteNetworkId().equalsIgnoreCase(localPeering.parent.id()))) - .collectList() - .flatMap( - remotePeerings -> { - if (remotePeerings.isEmpty()) { - return Mono.empty(); - } else { - return Mono.justOrEmpty(remotePeerings.get(remotePeerings.size() - 1)); - } - }) - - // Depending on the existence of a matching remote peering, create one or update existing - .flatMap( - remotePeering -> { - // Matching peering exists, so update as needed - Update remotePeeringUpdate = remotePeering.update(); - boolean isUpdateNeeded = false; - - // Update traffic forwarding on the remote peering if needed - if (localPeering.remoteForwarding != null) { - if (localPeering.remoteForwarding.booleanValue() - && !remotePeering.isTrafficForwardingFromRemoteNetworkAllowed()) { - isUpdateNeeded = true; - remotePeeringUpdate = - remotePeeringUpdate.withTrafficForwardingFromRemoteNetwork(); - } else if (!localPeering.remoteForwarding.booleanValue() - && remotePeering.isTrafficForwardingFromRemoteNetworkAllowed()) { - isUpdateNeeded = true; - remotePeeringUpdate = - remotePeeringUpdate.withoutTrafficForwardingFromRemoteNetwork(); - } - } - - // Update network access on the remote peering if needed - if (localPeering.remoteAccess != null) { - if (localPeering.remoteAccess.booleanValue() - && !((NetworkPeeringImpl) remotePeering).isAccessFromRemoteNetworkAllowed()) { - isUpdateNeeded = true; - remotePeeringUpdate = - ((NetworkPeeringImpl) remotePeeringUpdate).withAccessFromRemoteNetwork(); - } else if (!localPeering.remoteAccess.booleanValue() - && ((NetworkPeeringImpl) remotePeering).isAccessFromRemoteNetworkAllowed()) { - isUpdateNeeded = true; - remotePeeringUpdate = - ((NetworkPeeringImpl) remotePeeringUpdate).withoutAccessFromRemoteNetwork(); - } - } - - // Update gateway use permission on the remote peering if needed - if (localPeering.allowGatewayUseOnRemoteNetwork != null) { - if (localPeering.allowGatewayUseOnRemoteNetwork.booleanValue() - && remotePeering.gatewayUse() != NetworkPeeringGatewayUse.BY_REMOTE_NETWORK) { - // Allow gateway use on remote network - isUpdateNeeded = true; - remotePeeringUpdate.withGatewayUseByRemoteNetworkAllowed(); - } else if (!localPeering.allowGatewayUseOnRemoteNetwork.booleanValue() - && remotePeering.gatewayUse() == NetworkPeeringGatewayUse.BY_REMOTE_NETWORK) { - // Disallow gateway use on remote network - isUpdateNeeded = true; - remotePeeringUpdate.withoutGatewayUseByRemoteNetwork(); - } - } - - // Update gateway use start on the remote peering if needed - if (localPeering.startGatewayUseByRemoteNetwork != null) { - if (localPeering.startGatewayUseByRemoteNetwork.booleanValue() - && remotePeering.gatewayUse() != NetworkPeeringGatewayUse.ON_REMOTE_NETWORK) { - remotePeeringUpdate.withGatewayUseOnRemoteNetworkStarted(); - isUpdateNeeded = true; - } else if (!localPeering.startGatewayUseByRemoteNetwork.booleanValue() - && remotePeering.gatewayUse() == NetworkPeeringGatewayUse.ON_REMOTE_NETWORK) { - remotePeeringUpdate.withoutGatewayUseOnRemoteNetwork(); - isUpdateNeeded = true; - } - } - - if (isUpdateNeeded) { - localPeering.remoteForwarding = null; - localPeering.remoteAccess = null; - localPeering.startGatewayUseByRemoteNetwork = null; - localPeering.allowGatewayUseOnRemoteNetwork = null; - return remotePeeringUpdate.applyAsync(); - } else { - return Mono.just((Indexable) localPeering); - } - }) - .switchIfEmpty( - Mono - .defer( - () -> { - // No matching remote peering, so create one on the remote network - String peeringName = this.manager().resourceManager().internalContext() - .randomResourceName("peer", 15); - - WithCreate remotePeeringDefinition = - remoteNetwork - .peerings() - .define(peeringName) - .withRemoteNetwork(localPeering.parent.id()); - - // Process remote network's UseRemoteGateways setting - if (localPeering.startGatewayUseByRemoteNetwork != null) { - if (localPeering.startGatewayUseByRemoteNetwork.booleanValue()) { - // Start gateway use on this network by the remote network - remotePeeringDefinition.withGatewayUseOnRemoteNetworkStarted(); - } - } - - // Process remote network's AllowGatewayTransit setting - if (localPeering.allowGatewayUseOnRemoteNetwork != null) { - if (localPeering.allowGatewayUseOnRemoteNetwork.booleanValue()) { - // Allow gateway use on remote network - remotePeeringDefinition.withGatewayUseByRemoteNetworkAllowed(); - } - } - - if (localPeering.remoteAccess != null && !localPeering.remoteAccess) { - ((NetworkPeeringImpl) remotePeeringDefinition) - .withoutAccessFromRemoteNetwork(); // Assumes by default access is on - // for new peerings - } - - if (localPeering.remoteForwarding != null - && localPeering.remoteForwarding.booleanValue()) { - remotePeeringDefinition - .withTrafficForwardingFromRemoteNetwork(); // Assumes by default - // forwarding is off for new - // peerings - } - - localPeering.remoteAccess = null; - localPeering.remoteForwarding = null; - localPeering.startGatewayUseByRemoteNetwork = null; - localPeering.allowGatewayUseOnRemoteNetwork = null; - return remotePeeringDefinition.createAsync(); - })); - }) + .flatMap(remoteNetwork -> { + // Check if any peering is already pointing at this network + return remoteNetwork.peerings() + .listAsync() + .filter(remotePeering -> (remotePeering != null + && remotePeering.remoteNetworkId() != null + && remotePeering.remoteNetworkId().equalsIgnoreCase(localPeering.parent.id()))) + .collectList() + .flatMap(remotePeerings -> { + if (remotePeerings.isEmpty()) { + return Mono.empty(); + } else { + return Mono.justOrEmpty(remotePeerings.get(remotePeerings.size() - 1)); + } + }) + + // Depending on the existence of a matching remote peering, create one or update existing + .flatMap(remotePeering -> { + // Matching peering exists, so update as needed + Update remotePeeringUpdate = remotePeering.update(); + boolean isUpdateNeeded = false; + + // Update traffic forwarding on the remote peering if needed + if (localPeering.remoteForwarding != null) { + if (localPeering.remoteForwarding.booleanValue() + && !remotePeering.isTrafficForwardingFromRemoteNetworkAllowed()) { + isUpdateNeeded = true; + remotePeeringUpdate = remotePeeringUpdate.withTrafficForwardingFromRemoteNetwork(); + } else if (!localPeering.remoteForwarding.booleanValue() + && remotePeering.isTrafficForwardingFromRemoteNetworkAllowed()) { + isUpdateNeeded = true; + remotePeeringUpdate = remotePeeringUpdate.withoutTrafficForwardingFromRemoteNetwork(); + } + } + + // Update network access on the remote peering if needed + if (localPeering.remoteAccess != null) { + if (localPeering.remoteAccess.booleanValue() + && !((NetworkPeeringImpl) remotePeering).isAccessFromRemoteNetworkAllowed()) { + isUpdateNeeded = true; + remotePeeringUpdate + = ((NetworkPeeringImpl) remotePeeringUpdate).withAccessFromRemoteNetwork(); + } else if (!localPeering.remoteAccess.booleanValue() + && ((NetworkPeeringImpl) remotePeering).isAccessFromRemoteNetworkAllowed()) { + isUpdateNeeded = true; + remotePeeringUpdate + = ((NetworkPeeringImpl) remotePeeringUpdate).withoutAccessFromRemoteNetwork(); + } + } + + // Update gateway use permission on the remote peering if needed + if (localPeering.allowGatewayUseOnRemoteNetwork != null) { + if (localPeering.allowGatewayUseOnRemoteNetwork.booleanValue() + && remotePeering.gatewayUse() != NetworkPeeringGatewayUse.BY_REMOTE_NETWORK) { + // Allow gateway use on remote network + isUpdateNeeded = true; + remotePeeringUpdate.withGatewayUseByRemoteNetworkAllowed(); + } else if (!localPeering.allowGatewayUseOnRemoteNetwork.booleanValue() + && remotePeering.gatewayUse() == NetworkPeeringGatewayUse.BY_REMOTE_NETWORK) { + // Disallow gateway use on remote network + isUpdateNeeded = true; + remotePeeringUpdate.withoutGatewayUseByRemoteNetwork(); + } + } + + // Update gateway use start on the remote peering if needed + if (localPeering.startGatewayUseByRemoteNetwork != null) { + if (localPeering.startGatewayUseByRemoteNetwork.booleanValue() + && remotePeering.gatewayUse() != NetworkPeeringGatewayUse.ON_REMOTE_NETWORK) { + remotePeeringUpdate.withGatewayUseOnRemoteNetworkStarted(); + isUpdateNeeded = true; + } else if (!localPeering.startGatewayUseByRemoteNetwork.booleanValue() + && remotePeering.gatewayUse() == NetworkPeeringGatewayUse.ON_REMOTE_NETWORK) { + remotePeeringUpdate.withoutGatewayUseOnRemoteNetwork(); + isUpdateNeeded = true; + } + } + + if (isUpdateNeeded) { + localPeering.remoteForwarding = null; + localPeering.remoteAccess = null; + localPeering.startGatewayUseByRemoteNetwork = null; + localPeering.allowGatewayUseOnRemoteNetwork = null; + return remotePeeringUpdate.applyAsync(); + } else { + return Mono.just((Indexable) localPeering); + } + }) + .switchIfEmpty(Mono.defer(() -> { + // No matching remote peering, so create one on the remote network + String peeringName + = this.manager().resourceManager().internalContext().randomResourceName("peer", 15); + + WithCreate remotePeeringDefinition + = remoteNetwork.peerings().define(peeringName).withRemoteNetwork(localPeering.parent.id()); + + // Process remote network's UseRemoteGateways setting + if (localPeering.startGatewayUseByRemoteNetwork != null) { + if (localPeering.startGatewayUseByRemoteNetwork.booleanValue()) { + // Start gateway use on this network by the remote network + remotePeeringDefinition.withGatewayUseOnRemoteNetworkStarted(); + } + } + + // Process remote network's AllowGatewayTransit setting + if (localPeering.allowGatewayUseOnRemoteNetwork != null) { + if (localPeering.allowGatewayUseOnRemoteNetwork.booleanValue()) { + // Allow gateway use on remote network + remotePeeringDefinition.withGatewayUseByRemoteNetworkAllowed(); + } + } + + if (localPeering.remoteAccess != null && !localPeering.remoteAccess) { + ((NetworkPeeringImpl) remotePeeringDefinition).withoutAccessFromRemoteNetwork(); // Assumes by default access is on + // for new peerings + } + + if (localPeering.remoteForwarding != null && localPeering.remoteForwarding.booleanValue()) { + remotePeeringDefinition.withTrafficForwardingFromRemoteNetwork(); // Assumes by default + // forwarding is off for new + // peerings + } + + localPeering.remoteAccess = null; + localPeering.remoteForwarding = null; + localPeering.startGatewayUseByRemoteNetwork = null; + localPeering.allowGatewayUseOnRemoteNetwork = null; + return remotePeeringDefinition.createAsync(); + })); + }) // Then refresh the parent local network, if available .flatMap(remotePeering -> (localPeering.parent != null) ? localPeering.parent.refreshAsync() : Mono.empty()) // Then refresh the remote network, if available and in the same subscription - .flatMap( - t -> { - if (localPeering.remoteNetwork != null && localPeering.isSameSubscription()) { - return localPeering.remoteNetwork.refreshAsync(); - } else { - return Mono.empty(); - } - }) + .flatMap(t -> { + if (localPeering.remoteNetwork != null && localPeering.isSameSubscription()) { + return localPeering.remoteNetwork.refreshAsync(); + } else { + return Mono.empty(); + } + }) // Then return the created local peering .then(Mono.just(localPeering)); @@ -441,12 +416,11 @@ protected Mono createChildResourceAsync() { @Override protected Mono getInnerAsync() { this.remoteNetwork = null; - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkPeerings() - .getAsync( - this.resourceGroupName(), ResourceUtils.nameFromResourceId(this.networkId()), this.innerModel().name()); + .getAsync(this.resourceGroupName(), ResourceUtils.nameFromResourceId(this.networkId()), + this.innerModel().name()); } @Override @@ -461,14 +435,9 @@ public Mono getRemoteNetworkAsync() { return Mono.just(self.remoteNetwork); } else if (this.isSameSubscription()) { // Fetch the remote network if within the same subscription - return this - .manager() - .networks() - .getByIdAsync(this.remoteNetworkId()) - .doOnNext( - network -> { - self.remoteNetwork = network; - }); + return this.manager().networks().getByIdAsync(this.remoteNetworkId()).doOnNext(network -> { + self.remoteNetwork = network; + }); } else { // Otherwise bail out self.remoteNetwork = null; @@ -485,16 +454,13 @@ public NetworkPeering getRemotePeering() { @Override public Mono getRemotePeeringAsync() { final NetworkPeeringImpl self = this; - return this - .getRemoteNetworkAsync() - .flatMap( - remoteNetwork -> { - if (remoteNetwork == null) { - return Mono.empty(); - } else { - return remoteNetwork.peerings().getByRemoteNetworkAsync(self.networkId()); - } - }); + return this.getRemoteNetworkAsync().flatMap(remoteNetwork -> { + if (remoteNetwork == null) { + return Mono.empty(); + } else { + return remoteNetwork.peerings().getByRemoteNetworkAsync(self.networkId()); + } + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringsImpl.java index ed024305999a4..15a786f108698 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkPeeringsImpl.java @@ -15,14 +15,8 @@ import reactor.core.publisher.Mono; /** Implementation for network peerings. */ -class NetworkPeeringsImpl - extends IndependentChildrenImpl< - NetworkPeering, - NetworkPeeringImpl, - VirtualNetworkPeeringInner, - VirtualNetworkPeeringsClient, - NetworkManager, - Network> +class NetworkPeeringsImpl extends + IndependentChildrenImpl implements NetworkPeerings { private final NetworkImpl network; @@ -53,51 +47,46 @@ protected NetworkPeeringImpl wrapModel(VirtualNetworkPeeringInner inner) { @Override public Mono deleteByParentAsync(String groupName, String parentName, final String name) { - return this - .manager() + return this.manager() .networks() // Get the parent network of the peering to delete .getByResourceGroupAsync(groupName, parentName) // Then find the local peering to delete - .flatMap( - localNetwork -> { - if (localNetwork == null) { - return Mono.empty(); // Missing local network, so nothing else to do - } else { - String peeringId = localNetwork.id() + "/peerings/" + name; - return localNetwork.peerings().getByIdAsync(peeringId); - } - }) + .flatMap(localNetwork -> { + if (localNetwork == null) { + return Mono.empty(); // Missing local network, so nothing else to do + } else { + String peeringId = localNetwork.id() + "/peerings/" + name; + return localNetwork.peerings().getByIdAsync(peeringId); + } + }) .flux() // Then get the remote peering if available and possible to delete - .flatMap( - localPeering -> { - if (localPeering == null) { - return Mono.empty(); - } else if (!localPeering.isSameSubscription()) { - return Mono.just(localPeering); - } else { - return Mono.just(localPeering).concatWith(localPeering.getRemotePeeringAsync()); - } - }) + .flatMap(localPeering -> { + if (localPeering == null) { + return Mono.empty(); + } else if (!localPeering.isSameSubscription()) { + return Mono.just(localPeering); + } else { + return Mono.just(localPeering).concatWith(localPeering.getRemotePeeringAsync()); + } + }) // Then delete each peering (this will be called for each of the peerings, so at least once for the local // peering, and second time for the remote one if any - .flatMap( - peering -> { - if (peering == null) { - return Mono.empty(); - } else { - String networkName = ResourceUtils.nameFromResourceId(peering.networkId()); - return peering - .manager() - .serviceClient() - .getVirtualNetworkPeerings() - .deleteAsync(peering.resourceGroupName(), networkName, peering.name()); - } - }) + .flatMap(peering -> { + if (peering == null) { + return Mono.empty(); + } else { + String networkName = ResourceUtils.nameFromResourceId(peering.networkId()); + return peering.manager() + .serviceClient() + .getVirtualNetworkPeerings() + .deleteAsync(peering.resourceGroupName(), networkName, peering.name()); + } + }) // Then continue till the last peering is deleted .then(); @@ -154,17 +143,13 @@ public Mono getByRemoteNetworkAsync(final String remoteNetworkRe if (remoteNetworkResourceId == null) { return Mono.empty(); } else { - return this - .listAsync() - .filter( - peering -> { - if (peering == null) { - return false; - } else { - return remoteNetworkResourceId.equalsIgnoreCase(peering.remoteNetworkId()); - } - }) - .last(); + return this.listAsync().filter(peering -> { + if (peering == null) { + return false; + } else { + return remoteNetworkResourceId.equalsIgnoreCase(peering.remoteNetworkId()); + } + }).last(); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfileImpl.java index ae327e1876c62..e498cd421b9d2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfileImpl.java @@ -16,8 +16,8 @@ import java.util.Collections; import java.util.List; -final class NetworkProfileImpl extends - GroupableParentResourceWithTagsImpl +final class NetworkProfileImpl + extends GroupableParentResourceWithTagsImpl implements NetworkProfile, NetworkProfile.Definition, NetworkProfile.Update { NetworkProfileImpl(String name, NetworkProfileInner innerObject, NetworkManager manager) { @@ -26,8 +26,8 @@ final class NetworkProfileImpl extends @Override public List containerNetworkInterfaceConfigurations() { - List inner = - this.innerModel().containerNetworkInterfaceConfigurations(); + List inner + = this.innerModel().containerNetworkInterfaceConfigurations(); if (inner != null) { return Collections.unmodifiableList(inner); } else { @@ -37,8 +37,7 @@ public List containerNetworkInterfaceCon @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkProfiles() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -46,8 +45,7 @@ protected Mono applyTagsToInnerAsync() { @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkProfiles() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); @@ -59,40 +57,33 @@ protected void initializeChildrenFromInner() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkProfiles() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } - @Override - public NetworkProfileImpl withContainerNetworkInterfaceConfiguration( - String name, String ipConfigName, String virtualNetworkId, String subnetName) { + public NetworkProfileImpl withContainerNetworkInterfaceConfiguration(String name, String ipConfigName, + String virtualNetworkId, String subnetName) { String subnetId = String.format("%s/subnets/%s", virtualNetworkId, subnetName); return withContainerNetworkInterfaceConfiguration(name, ipConfigName, subnetId); } @Override - public NetworkProfileImpl withContainerNetworkInterfaceConfiguration( - String name, String ipConfigName, Subnet subnet) { + public NetworkProfileImpl withContainerNetworkInterfaceConfiguration(String name, String ipConfigName, + Subnet subnet) { return withContainerNetworkInterfaceConfiguration(name, ipConfigName, subnet.id()); } - private NetworkProfileImpl withContainerNetworkInterfaceConfiguration( - String name, String ipConfigName, String subnetId) { - this.innerModel().withContainerNetworkInterfaceConfigurations( - Collections - .singletonList( - new ContainerNetworkInterfaceConfiguration() - .withName(name) - .withIpConfigurations( - Collections - .singletonList( - new IpConfigurationProfileInner() - .withName(ipConfigName) - .withSubnet(new SubnetInner().withId(subnetId)))))); + private NetworkProfileImpl withContainerNetworkInterfaceConfiguration(String name, String ipConfigName, + String subnetId) { + this.innerModel() + .withContainerNetworkInterfaceConfigurations( + Collections.singletonList(new ContainerNetworkInterfaceConfiguration().withName(name) + .withIpConfigurations( + Collections.singletonList(new IpConfigurationProfileInner().withName(ipConfigName) + .withSubnet(new SubnetInner().withId(subnetId)))))); return this; } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfilesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfilesImpl.java index db083f2eb8c54..56353e6481444 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfilesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkProfilesImpl.java @@ -11,8 +11,7 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; public final class NetworkProfilesImpl extends - TopLevelModifiableResourcesImpl + TopLevelModifiableResourcesImpl implements NetworkProfiles { public NetworkProfilesImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupImpl.java index 9a9f56f4d5f7d..5aae0c511e72d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupImpl.java @@ -20,16 +20,15 @@ import java.util.TreeSet; /** Implementation for NetworkSecurityGroup and its create and update interfaces. */ -class NetworkSecurityGroupImpl - extends GroupableParentResourceWithTagsImpl< - NetworkSecurityGroup, NetworkSecurityGroupInner, NetworkSecurityGroupImpl, NetworkManager> +class NetworkSecurityGroupImpl extends + GroupableParentResourceWithTagsImpl implements NetworkSecurityGroup, NetworkSecurityGroup.Definition, NetworkSecurityGroup.Update { private Map rules; private Map defaultRules; - NetworkSecurityGroupImpl( - final String name, final NetworkSecurityGroupInner innerModel, final NetworkManager networkManager) { + NetworkSecurityGroupImpl(final String name, final NetworkSecurityGroupInner innerModel, + final NetworkManager networkManager) { super(name, innerModel, networkManager); } @@ -69,21 +68,17 @@ public NetworkSecurityRuleImpl defineRule(String name) { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - networkSecurityGroup -> { - NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; - - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(networkSecurityGroup -> { + NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; + + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -91,8 +86,7 @@ protected Mono getInnerAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkSecurityGroups() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -147,8 +141,7 @@ protected void beforeCreating() { @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkSecurityGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupsImpl.java index 6aa3375528b21..aac10aee75f1f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityGroupsImpl.java @@ -14,13 +14,8 @@ import reactor.core.publisher.Mono; /** Implementation for NetworkSecurityGroups. */ -public class NetworkSecurityGroupsImpl - extends TopLevelModifiableResourcesImpl< - NetworkSecurityGroup, - NetworkSecurityGroupImpl, - NetworkSecurityGroupInner, - NetworkSecurityGroupsClient, - NetworkManager> +public class NetworkSecurityGroupsImpl extends + TopLevelModifiableResourcesImpl implements NetworkSecurityGroups { public NetworkSecurityGroupsImpl(final NetworkManager networkManager) { @@ -30,12 +25,11 @@ public NetworkSecurityGroupsImpl(final NetworkManager networkManager) { @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } // Clear NIC references if any return getByResourceGroupAsync(resourceGroupName, name) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityRuleImpl.java index 5cb290542264d..9675524771352 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkSecurityRuleImpl.java @@ -25,10 +25,8 @@ /** Implementation for {@link NetworkSecurityRule} and its create and update interfaces. */ class NetworkSecurityRuleImpl extends ChildResourceImpl - implements NetworkSecurityRule, - NetworkSecurityRule.Definition, - NetworkSecurityRule.UpdateDefinition, - NetworkSecurityRule.Update { + implements NetworkSecurityRule, NetworkSecurityRule.Definition, + NetworkSecurityRule.UpdateDefinition, NetworkSecurityRule.Update { private Map sourceAsgs = new HashMap<>(); private Map destinationAsgs = new HashMap<>(); private final ClientLogger logger = new ClientLogger(getClass()); @@ -282,10 +280,8 @@ public NetworkSecurityRuleImpl toPortRanges(String... ranges) { @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { - throw logger - .logExceptionAsError( - new IllegalArgumentException( - "The priority number of a network security rule must be between 100 and 4096.")); + throw logger.logExceptionAsError(new IllegalArgumentException( + "The priority number of a network security rule must be between 100 and 4096.")); } this.innerModel().withPriority(priority); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatcherImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatcherImpl.java index 6cdc3d4ab4359..446550ba0098b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatcherImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatcherImpl.java @@ -27,8 +27,8 @@ class NetworkWatcherImpl NetworkWatcherImpl(String name, final NetworkWatcherInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.packetCaptures = new PacketCapturesImpl(networkManager.serviceClient().getPacketCaptures(), this); - this.connectionMonitors = - new ConnectionMonitorsImpl(networkManager.serviceClient().getConnectionMonitors(), this); + this.connectionMonitors + = new ConnectionMonitorsImpl(networkManager.serviceClient().getConnectionMonitors(), this); } public PacketCapturesImpl packetCaptures() { @@ -49,20 +49,17 @@ public TopologyImpl topology() { @Override public SecurityGroupView getSecurityGroupView(String vmId) { - SecurityGroupViewResultInner securityGroupViewResultInner = - this - .manager() - .serviceClient() - .getNetworkWatchers() - .getVMSecurityRules(this.resourceGroupName(), this.name(), - new SecurityGroupViewParameters().withTargetResourceId(vmId)); + SecurityGroupViewResultInner securityGroupViewResultInner = this.manager() + .serviceClient() + .getNetworkWatchers() + .getVMSecurityRules(this.resourceGroupName(), this.name(), + new SecurityGroupViewParameters().withTargetResourceId(vmId)); return new SecurityGroupViewImpl(this, securityGroupViewResultInner, vmId); } @Override public Mono getSecurityGroupViewAsync(final String vmId) { - return this - .manager() + return this.manager() .serviceClient() .getNetworkWatchers() .getVMSecurityRulesAsync(this.resourceGroupName(), this.name(), @@ -71,20 +68,17 @@ public Mono getSecurityGroupViewAsync(final String vmId) { } public FlowLogSettings getFlowLogSettings(String nsgId) { - FlowLogInformationInner flowLogInformationInner = - this - .manager() - .serviceClient() - .getNetworkWatchers() - .getFlowLogStatus(this.resourceGroupName(), this.name(), - new FlowLogStatusParameters().withTargetResourceId(nsgId)); + FlowLogInformationInner flowLogInformationInner = this.manager() + .serviceClient() + .getNetworkWatchers() + .getFlowLogStatus(this.resourceGroupName(), this.name(), + new FlowLogStatusParameters().withTargetResourceId(nsgId)); return new FlowLogSettingsImpl(this, flowLogInformationInner, nsgId); } @Override public Mono getFlowLogSettingsAsync(final String nsgId) { - return this - .manager() + return this.manager() .serviceClient() .getNetworkWatchers() .getFlowLogStatusAsync(this.resourceGroupName(), this.name(), @@ -123,8 +117,7 @@ public AzureReachabilityReportImpl azureReachabilityReport() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkWatchers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -133,8 +126,7 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkWatchers() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -152,15 +144,13 @@ public NetworkWatcher applyTags() { @Override public Mono applyTagsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkWatchers() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())) - .flatMap( - inner -> { - setInner(inner); - return Mono.just((NetworkWatcher) NetworkWatcherImpl.this); - }); + .flatMap(inner -> { + setInner(inner); + return Mono.just((NetworkWatcher) NetworkWatcherImpl.this); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatchersImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatchersImpl.java index 23708c3d98998..bb1bd581053ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatchersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworkWatchersImpl.java @@ -10,9 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for Network Watchers. */ -public class NetworkWatchersImpl - extends TopLevelModifiableResourcesImpl< - NetworkWatcher, NetworkWatcherImpl, NetworkWatcherInner, NetworkWatchersClient, NetworkManager> +public class NetworkWatchersImpl extends + TopLevelModifiableResourcesImpl implements NetworkWatchers { public NetworkWatchersImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworksImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworksImpl.java index 120133a6ee0e5..6df62c987b1de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NetworksImpl.java @@ -15,9 +15,8 @@ import java.util.ArrayList; /** Implementation for Networks. */ -public class NetworksImpl - extends TopLevelModifiableResourcesImpl< - Network, NetworkImpl, VirtualNetworkInner, VirtualNetworksClient, NetworkManager> +public class NetworksImpl extends + TopLevelModifiableResourcesImpl implements Networks { public NetworksImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NextHopImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NextHopImpl.java index 771b506b0fd24..43383b989f88e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NextHopImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NextHopImpl.java @@ -85,16 +85,14 @@ public String routeTableId() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .getNextHopAsync(parent.resourceGroupName(), parent.name(), parameters) - .map( - nextHopResultInner -> { - NextHopImpl.this.result = nextHopResultInner; - return NextHopImpl.this; - }); + .map(nextHopResultInner -> { + NextHopImpl.this.result = nextHopResultInner; + return NextHopImpl.this; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationBaseImpl.java index 8d969ee416ee1..56a70481771e4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationBaseImpl.java @@ -47,8 +47,8 @@ abstract class NicIpConfigurationBaseImpl listAssociatedApplicationGatewayBackends() { - return com - .azure - .resourcemanager - .network - .implementation - .Utils - .listAssociatedApplicationGatewayBackends( - this.parent().manager(), this.innerModel().applicationGatewayBackendAddressPools()); + return com.azure.resourcemanager.network.implementation.Utils.listAssociatedApplicationGatewayBackends( + this.parent().manager(), this.innerModel().applicationGatewayBackendAddressPools()); } @Override @@ -184,7 +178,8 @@ public List listAssociatedApplicationSecurityGroups() List applicationSecurityGroups = Flux .fromStream(this.innerModel().applicationSecurityGroups().stream().map(ApplicationSecurityGroupInner::id)) .flatMapSequential(id -> this.networkManager.applicationSecurityGroups().getByIdAsync(id)) - .collectList().block(); + .collectList() + .block(); return applicationSecurityGroups == null ? Collections.emptyList() : Collections.unmodifiableList(applicationSecurityGroups); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationImpl.java index ecca0e730cf00..7d84849938722 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/NicIpConfigurationImpl.java @@ -34,10 +34,8 @@ /** Implementation for NicIPConfiguration and its create and update interfaces. */ class NicIpConfigurationImpl extends NicIpConfigurationBaseImpl - implements NicIpConfiguration, - NicIpConfiguration.Definition, - NicIpConfiguration.UpdateDefinition, - NicIpConfiguration.Update { + implements NicIpConfiguration, NicIpConfiguration.Definition, + NicIpConfiguration.UpdateDefinition, NicIpConfiguration.Update { /** the network client. */ private final NetworkManager networkManager; /** flag indicating whether IP configuration is in create or update mode. */ @@ -57,18 +55,15 @@ class NicIpConfigurationImpl extends NicIpConfigurationBaseImpl creatable) { @Override public NicIpConfigurationImpl withNewNetwork(String name, String addressSpaceCidr) { - Network.DefinitionStages.WithGroup definitionWithGroup = - this.networkManager.networks().define(name).withRegion(this.parent().regionName()); + Network.DefinitionStages.WithGroup definitionWithGroup + = this.networkManager.networks().define(name).withRegion(this.parent().regionName()); Network.DefinitionStages.WithCreate definitionAfterGroup; if (this.parent().newGroup() != null) { @@ -203,8 +198,8 @@ public NicIpConfigurationImpl withExistingLoadBalancerBackend(LoadBalancer loadB } @Override - public NicIpConfigurationImpl withExistingApplicationGatewayBackend( - ApplicationGateway appGateway, String backendName) { + public NicIpConfigurationImpl withExistingApplicationGatewayBackend(ApplicationGateway appGateway, + String backendName) { if (appGateway != null) { for (ApplicationGatewayBackendAddressPool pool : appGateway.innerModel().backendAddressPools()) { if (pool.name().equalsIgnoreCase(backendName)) { @@ -218,8 +213,8 @@ public NicIpConfigurationImpl withExistingApplicationGatewayBackend( } @Override - public NicIpConfigurationImpl withExistingLoadBalancerInboundNatRule( - LoadBalancer loadBalancer, String inboundNatRuleName) { + public NicIpConfigurationImpl withExistingLoadBalancerInboundNatRule(LoadBalancer loadBalancer, + String inboundNatRuleName) { if (loadBalancer != null) { for (InboundNatRuleInner rule : loadBalancer.innerModel().inboundNatRules()) { if (rule.name().equalsIgnoreCase(inboundNatRuleName)) { @@ -259,18 +254,21 @@ private List ensureInboundNatRules() { return natRefs; } - protected static void ensureConfigurations(Collection nicIPConfigurations, Map specifiedIpConfigNames) { + protected static void ensureConfigurations(Collection nicIPConfigurations, + Map specifiedIpConfigNames) { for (NicIpConfiguration nicIPConfiguration : nicIPConfigurations) { NicIpConfigurationImpl config = (NicIpConfigurationImpl) nicIPConfiguration; config.innerModel().withSubnet(config.subnetToAssociate()); - config.innerModel().withPublicIpAddress(config.publicIPToAssociate(specifiedIpConfigNames.getOrDefault(config.name(), null))); + config.innerModel() + .withPublicIpAddress( + config.publicIPToAssociate(specifiedIpConfigNames.getOrDefault(config.name(), null))); } } // Creates a creatable public IP address definition with the given name and DNS label. private Creatable prepareCreatablePublicIP(String name, String leafDnsLabel) { - PublicIpAddress.DefinitionStages.WithGroup definitionWithGroup = - this.networkManager.publicIpAddresses().define(name).withRegion(this.parent().regionName()); + PublicIpAddress.DefinitionStages.WithGroup definitionWithGroup + = this.networkManager.publicIpAddresses().define(name).withRegion(this.parent().regionName()); PublicIpAddress.DefinitionStages.WithCreate definitionAfterGroup; if (this.parent().newGroup() != null) { @@ -306,14 +304,8 @@ private SubnetInner subnetToAssociate() { } } - throw logger - .logExceptionAsError( - new RuntimeException( - "A subnet with name '" - + subnetToAssociate - + "' not found under the network '" - + this.existingVirtualNetworkToAssociate.name() - + "'")); + throw logger.logExceptionAsError(new RuntimeException("A subnet with name '" + subnetToAssociate + + "' not found under the network '" + this.existingVirtualNetworkToAssociate.name() + "'")); } else { if (subnetToAssociate != null) { @@ -401,9 +393,7 @@ NicIpConfigurationImpl withExistingApplicationSecurityGroup(ApplicationSecurityG NicIpConfigurationImpl withoutApplicationSecurityGroup(String name) { if (this.innerModel().applicationSecurityGroups() != null) { this.innerModel().applicationSecurityGroups().removeIf(asg -> { - String asgName = asg.name() == null - ? ResourceUtils.nameFromResourceId(asg.id()) - : asg.name(); + String asgName = asg.name() == null ? ResourceUtils.nameFromResourceId(asg.id()) : asg.name(); return Objects.equals(name, asgName); }); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PCFilterImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PCFilterImpl.java index 312c8a1422b6a..a691ba1c35572 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PCFilterImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PCFilterImpl.java @@ -59,8 +59,8 @@ public PCFilterImpl withLocalIpAddress(String ipAddress) { } @Override - public Definition withLocalIpAddressesRange( - String startIpAddress, String endIpAddress) { + public Definition withLocalIpAddressesRange(String startIpAddress, + String endIpAddress) { this.innerModel().withLocalIpAddress(startIpAddress + RANGE_DELIMITER + endIpAddress); return this; } @@ -82,8 +82,8 @@ public PCFilterImpl withRemoteIpAddress(String ipAddress) { } @Override - public Definition withRemoteIpAddressesRange( - String startIpAddress, String endIpAddress) { + public Definition withRemoteIpAddressesRange(String startIpAddress, + String endIpAddress) { this.innerModel().withRemoteIpAddress(startIpAddress + RANGE_DELIMITER + endIpAddress); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PacketCaptureImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PacketCaptureImpl.java index 5ce1b51367e0c..53236857a3180 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PacketCaptureImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PacketCaptureImpl.java @@ -27,8 +27,8 @@ public class PacketCaptureImpl private final PacketCaptureInner createParameters; private final NetworkWatcher parent; - PacketCaptureImpl( - String name, NetworkWatcherImpl parent, PacketCaptureResultInner innerObject, PacketCapturesClient client) { + PacketCaptureImpl(String name, NetworkWatcherImpl parent, PacketCaptureResultInner innerObject, + PacketCapturesClient client) { super(name, innerObject); this.client = client; this.parent = parent; @@ -57,9 +57,7 @@ public PacketCaptureStatus getStatus() { @Override public Mono getStatusAsync() { - return this - .client - .getStatusAsync(parent.resourceGroupName(), parent.name(), name()) + return this.client.getStatusAsync(parent.resourceGroupName(), parent.name(), name()) .map(inner -> new PacketCaptureStatusImpl(inner)); } @@ -132,9 +130,7 @@ public boolean isInCreateMode() { @Override public Mono createResourceAsync() { - return this - .client - .createAsync(parent.resourceGroupName(), parent.name(), this.name(), createParameters) + return this.client.createAsync(parent.resourceGroupName(), parent.name(), this.name(), createParameters) .map(innerToFluentMap(this)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PointToSiteConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PointToSiteConfigurationImpl.java index 4685711a7200f..795d9311816ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PointToSiteConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PointToSiteConfigurationImpl.java @@ -20,9 +20,8 @@ /** Implementation for PointToSiteConfiguration and its create and update interfaces. */ class PointToSiteConfigurationImpl extends IndexableWrapperImpl - implements PointToSiteConfiguration, - PointToSiteConfiguration.Definition, - PointToSiteConfiguration.Update { + implements PointToSiteConfiguration, PointToSiteConfiguration.Definition, + PointToSiteConfiguration.Update { private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; private static final String END_CERT = "-----END CERTIFICATE-----"; @@ -52,8 +51,7 @@ public PointToSiteConfigurationImpl withAzureCertificate(String name, String cer if (innerModel().vpnClientRootCertificates() == null) { innerModel().withVpnClientRootCertificates(new ArrayList()); } - innerModel() - .vpnClientRootCertificates() + innerModel().vpnClientRootCertificates() .add(new VpnClientRootCertificate().withName(name).withPublicCertData(certificateData)); innerModel().withRadiusServerAddress(null).withRadiusServerSecret(null); return this; @@ -66,8 +64,8 @@ public PointToSiteConfigurationImpl withAzureCertificateFromFile(String name, Fi return this; } else { byte[] content = Files.readAllBytes(certificateFile.toPath()); - String certificate = - new String(content, StandardCharsets.UTF_8).replace(BEGIN_CERT, "").replace(END_CERT, ""); + String certificate + = new String(content, StandardCharsets.UTF_8).replace(BEGIN_CERT, "").replace(END_CERT, ""); return this.withAzureCertificate(name, certificate); } } @@ -98,8 +96,7 @@ public PointToSiteConfigurationImpl withRevokedCertificate(String name, String t if (innerModel().vpnClientRevokedCertificates() == null) { innerModel().withVpnClientRevokedCertificates(new ArrayList()); } - innerModel() - .vpnClientRevokedCertificates() + innerModel().vpnClientRevokedCertificates() .add(new VpnClientRevokedCertificate().withName(name).withThumbprint(thumbprint)); innerModel().withRadiusServerAddress(null).withRadiusServerSecret(null); return this; diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupImpl.java index 02b7ddb3fbed3..017b9e0560558 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupImpl.java @@ -16,8 +16,8 @@ import java.util.Collections; import java.util.List; -class PrivateDnsZoneGroupImpl extends IndependentChildImpl< - PrivateDnsZoneGroup, PrivateEndpoint, PrivateDnsZoneGroupInner, PrivateDnsZoneGroupImpl, NetworkManager> +class PrivateDnsZoneGroupImpl extends + IndependentChildImpl implements PrivateDnsZoneGroup, PrivateDnsZoneGroup.Definition, PrivateDnsZoneGroup.Update { private final PrivateEndpointImpl parent; @@ -28,15 +28,12 @@ protected PrivateDnsZoneGroupImpl(String name, PrivateDnsZoneGroupInner innerMod } @Override - public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure( - String name, String privateDnsZoneId) { + public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure(String name, String privateDnsZoneId) { if (innerModel().privateDnsZoneConfigs() == null) { innerModel().withPrivateDnsZoneConfigs(new ArrayList<>()); } - innerModel().privateDnsZoneConfigs().add( - new PrivateDnsZoneConfig() - .withName(name) - .withPrivateDnsZoneId(privateDnsZoneId)); + innerModel().privateDnsZoneConfigs() + .add(new PrivateDnsZoneConfig().withName(name).withPrivateDnsZoneId(privateDnsZoneId)); return this; } @@ -55,14 +52,18 @@ public String id() { @Override protected Mono createChildResourceAsync() { - return this.manager().serviceClient().getPrivateDnsZoneGroups() + return this.manager() + .serviceClient() + .getPrivateDnsZoneGroups() .createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getPrivateDnsZoneGroups() + return this.manager() + .serviceClient() + .getPrivateDnsZoneGroups() .getAsync(parent.resourceGroupName(), parent.name(), this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupsImpl.java index c7f1dabbc8910..d79ae963e1223 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateDnsZoneGroupsImpl.java @@ -15,14 +15,9 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; import reactor.core.publisher.Mono; -public class PrivateDnsZoneGroupsImpl - extends - IndependentChildrenImpl< - PrivateDnsZoneGroup, PrivateDnsZoneGroupImpl, - PrivateDnsZoneGroupInner, PrivateDnsZoneGroupsClient, - NetworkManager, PrivateEndpoint> - implements - PrivateDnsZoneGroups { +public class PrivateDnsZoneGroupsImpl extends + IndependentChildrenImpl + implements PrivateDnsZoneGroups { private final PrivateEndpointImpl parent; @@ -68,7 +63,7 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.innerModel(). - listAsync(parent.name(), parent.resourceGroupName()), this::wrapModel); + return PagedConverter.mapPage(this.innerModel().listAsync(parent.name(), parent.resourceGroupName()), + this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointImpl.java index 81db4705d1512..266c1a7fdf3db 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointImpl.java @@ -30,23 +30,17 @@ import java.util.function.Function; import java.util.stream.Collectors; -class PrivateEndpointImpl extends - GroupableResourceImpl - implements - PrivateEndpoint, - PrivateEndpoint.Definition, - PrivateEndpoint.Update { +class PrivateEndpointImpl + extends GroupableResourceImpl + implements PrivateEndpoint, PrivateEndpoint.Definition, PrivateEndpoint.Update { private final ClientLogger logger = new ClientLogger(PrivateEndpointImpl.class); private PrivateDnsZoneGroups privateDnsZoneGroups; static class PrivateEndpointConnectionImpl extends - ChildResourceImpl - implements - PrivateLinkServiceConnection, - PrivateLinkServiceConnection.Definition, + ChildResourceImpl + implements PrivateLinkServiceConnection, PrivateLinkServiceConnection.Definition, PrivateLinkServiceConnection.Update { private boolean manualApproval = false; @@ -56,8 +50,7 @@ static class PrivateEndpointConnectionImpl extends } PrivateEndpointConnectionImpl(com.azure.resourcemanager.network.models.PrivateLinkServiceConnection innerModel, - PrivateEndpointImpl parent, - boolean manualApproval) { + PrivateEndpointImpl parent, boolean manualApproval) { super(innerModel, parent); this.manualApproval = manualApproval; } @@ -82,7 +75,9 @@ public List subResourceNames() { if (this.innerModel().groupIds() == null) { return Collections.emptyList(); } - return this.innerModel().groupIds().stream() + return this.innerModel() + .groupIds() + .stream() .map(PrivateLinkSubResourceName::fromString) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @@ -121,8 +116,8 @@ public PrivateEndpointConnectionImpl withResourceId(String privateLinkServiceRes @Override public PrivateEndpointConnectionImpl withSubResource(PrivateLinkSubResourceName subResourceName) { - this.innerModel().withGroupIds( - Collections.singletonList(Objects.requireNonNull(subResourceName).toString())); + this.innerModel() + .withGroupIds(Collections.singletonList(Objects.requireNonNull(subResourceName).toString())); return this; } @@ -168,7 +163,9 @@ public List networkInterfaces() { if (this.innerModel().networkInterfaces() == null) { return Collections.emptyList(); } - return this.innerModel().networkInterfaces().stream() + return this.innerModel() + .networkInterfaces() + .stream() .map(ni -> new SubResource().withId(ni.id())) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @@ -182,12 +179,16 @@ public ProvisioningState provisioningState() { public Map privateLinkServiceConnections() { Map connections = new HashMap<>(); if (this.innerModel().privateLinkServiceConnections() != null) { - connections.putAll(this.innerModel().privateLinkServiceConnections().stream() + connections.putAll(this.innerModel() + .privateLinkServiceConnections() + .stream() .map(connection -> new PrivateEndpointConnectionImpl(connection, this, false)) .collect(Collectors.toMap(PrivateEndpointConnectionImpl::name, Function.identity()))); } if (this.innerModel().manualPrivateLinkServiceConnections() != null) { - connections.putAll(this.innerModel().manualPrivateLinkServiceConnections().stream() + connections.putAll(this.innerModel() + .manualPrivateLinkServiceConnections() + .stream() .map(connection -> new PrivateEndpointConnectionImpl(connection, this, true)) .collect(Collectors.toMap(PrivateEndpointConnectionImpl::name, Function.identity()))); } @@ -217,11 +218,11 @@ public PrivateEndpointImpl withSubnetId(String subnetId) { @Override public PrivateEndpointImpl withoutPrivateLinkServiceConnection(String name) { if (this.innerModel().privateLinkServiceConnections() != null) { - this.innerModel().privateLinkServiceConnections() - .removeIf(connection -> connection.name().equals(name)); + this.innerModel().privateLinkServiceConnections().removeIf(connection -> connection.name().equals(name)); } if (this.innerModel().manualPrivateLinkServiceConnections() != null) { - this.innerModel().manualPrivateLinkServiceConnections() + this.innerModel() + .manualPrivateLinkServiceConnections() .removeIf(connection -> connection.name().equals(name)); } return this; @@ -235,8 +236,10 @@ public PrivateEndpointConnectionImpl definePrivateLinkServiceConnection(String n @Override public PrivateLinkServiceConnection.Update updatePrivateLinkServiceConnection(String name) { if (this.innerModel().privateLinkServiceConnections() != null) { - Optional connection = - this.innerModel().privateLinkServiceConnections().stream() + Optional connection + = this.innerModel() + .privateLinkServiceConnections() + .stream() .filter(c -> c.name().equals(name)) .findAny(); if (connection.isPresent()) { @@ -244,8 +247,10 @@ public PrivateLinkServiceConnection.Update updatePrivateLinkServiceConnection(St } } if (this.innerModel().manualPrivateLinkServiceConnections() != null) { - Optional connection = - this.innerModel().manualPrivateLinkServiceConnections().stream() + Optional connection + = this.innerModel() + .manualPrivateLinkServiceConnections() + .stream() .filter(c -> c.name().equals(name)) .findAny(); if (connection.isPresent()) { @@ -273,14 +278,18 @@ PrivateEndpointImpl withPrivateEndpointConnection(PrivateEndpointConnectionImpl @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getPrivateEndpoints() + return this.manager() + .serviceClient() + .getPrivateEndpoints() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getPrivateEndpoints() + return this.manager() + .serviceClient() + .getPrivateEndpoints() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointsImpl.java index f88ab6a6ce642..dba30768751d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PrivateEndpointsImpl.java @@ -11,8 +11,7 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; public class PrivateEndpointsImpl extends - TopLevelModifiableResourcesImpl< - PrivateEndpoint, PrivateEndpointImpl, PrivateEndpointInner, PrivateEndpointsClient, NetworkManager> + TopLevelModifiableResourcesImpl implements PrivateEndpoints { public PrivateEndpointsImpl(NetworkManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressImpl.java index 61033859967f6..92d0003287e2b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressImpl.java @@ -52,8 +52,7 @@ class PublicIpAddressImpl @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getPublicIpAddresses() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -84,8 +83,7 @@ public PublicIpAddressImpl withLeafDomainLabel(String dnsName) { if (this.innerModel().dnsSettings() == null) { this.innerModel().withDnsSettings(new PublicIpAddressDnsSettings()); } - this - .innerModel() + this.innerModel() .dnsSettings() .withDomainNameLabel((dnsName == null) ? null : dnsName.toLowerCase(Locale.ROOT)); return this; @@ -126,8 +124,7 @@ public PublicIpAddressImpl withReverseFqdn(String reverseFqdn) { if (this.innerModel().dnsSettings() == null) { this.innerModel().withDnsSettings(new PublicIpAddressDnsSettings()); } - this - .innerModel() + this.innerModel() .dnsSettings() .withReverseFqdn(reverseFqdn != null ? reverseFqdn.toLowerCase(Locale.ROOT) : null); return this; @@ -189,29 +186,20 @@ public String leafDomainLabel() { @Override public Accepted beginCreate() { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> - this - .manager() - .serviceClient() - .getPublicIpAddresses() - .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) - .block(), - inner -> new PublicIpAddressImpl(inner.name(), inner, this.manager()), - PublicIpAddressInner.class, - () -> { - Flux dependencyTasksAsync = - taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); - dependencyTasksAsync.blockLast(); - - this.cleanupDnsSettings(); - }, - this::setInner, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.manager() + .serviceClient() + .getPublicIpAddresses() + .createOrUpdateWithResponseAsync(resourceGroupName(), name(), this.innerModel()) + .block(), + inner -> new PublicIpAddressImpl(inner.name(), inner, this.manager()), PublicIpAddressInner.class, () -> { + Flux dependencyTasksAsync + = taskGroup().invokeDependencyAsync(taskGroup().newInvocationContext()); + dependencyTasksAsync.blockLast(); + + this.cleanupDnsSettings(); + }, this::setInner, Context.NONE); } // CreateUpdateTaskGroup.ResourceCreator implementation @@ -219,8 +207,7 @@ public Accepted beginCreate() { public Mono createResourceAsync() { this.cleanupDnsSettings(); - return this - .manager() + return this.manager() .serviceClient() .getPublicIpAddresses() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) @@ -320,16 +307,14 @@ public PublicIpAddress applyTags() { @Override public Mono applyTagsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getPublicIpAddresses() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())) - .flatMap( - inner -> { - setInner(inner); - return Mono.just((PublicIpAddress) PublicIpAddressImpl.this); - }); + .flatMap(inner -> { + setInner(inner); + return Mono.just((PublicIpAddress) PublicIpAddressImpl.this); + }); } @Override @@ -369,9 +354,9 @@ public PublicIpAddressImpl withIpAddressVersion(IpVersion ipVersion) { return this; } -// @Override -// public PublicIpAddressImpl withDeleteOptions(DeleteOptions deleteOptions) { -// this.innerModel().withDeleteOption(deleteOptions); -// return this; -// } + // @Override + // public PublicIpAddressImpl withDeleteOptions(DeleteOptions deleteOptions) { + // this.innerModel().withDeleteOption(deleteOptions); + // return this; + // } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesClientImpl.java index 377e67969cdfd..30e7b9fe67119 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesClientImpl.java @@ -769,7 +769,7 @@ public Mono getCloudServicePublicIpAddressAsync(String res final String expand = null; return getCloudServicePublicIpAddressWithResponseAsync(resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, ipConfigurationName, publicIpAddressName, expand) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** @@ -2508,7 +2508,7 @@ public Mono getVirtualMachineScaleSetPublicIpAddressAsync( final String expand = null; return getVirtualMachineScaleSetPublicIpAddressWithResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, publicIpAddressName, expand) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** @@ -2533,7 +2533,7 @@ public Response getVirtualMachineScaleSetPublicIpAddressWi String ipConfigurationName, String publicIpAddressName, String expand, Context context) { return getVirtualMachineScaleSetPublicIpAddressWithResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, publicIpAddressName, expand, context) - .block(); + .block(); } /** @@ -2557,7 +2557,7 @@ public PublicIpAddressInner getVirtualMachineScaleSetPublicIpAddress(String reso final String expand = null; return getVirtualMachineScaleSetPublicIpAddressWithResponse(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, publicIpAddressName, expand, Context.NONE) - .getValue(); + .getValue(); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesImpl.java index 87324801fffa6..b557133a3ac87 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpAddressesImpl.java @@ -18,9 +18,8 @@ import java.util.function.Function; /** Implementation for {@link PublicIpAddresses}. */ -public class PublicIpAddressesImpl - extends TopLevelModifiableResourcesImpl< - PublicIpAddress, PublicIpAddressImpl, PublicIpAddressInner, PublicIpAddressesClient, NetworkManager> +public class PublicIpAddressesImpl extends + TopLevelModifiableResourcesImpl implements PublicIpAddresses { private final ClientLogger logger = new ClientLogger(this.getClass()); @@ -62,15 +61,9 @@ public Accepted beginDeleteById(String id) { @Override public Accepted beginDeleteByResourceGroup(String resourceGroupName, String name) { - return AcceptedImpl - .newAccepted( - logger, - this.manager().serviceClient().getHttpPipeline(), - this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), + this.manager().serviceClient().getDefaultPollInterval(), + () -> this.inner().deleteWithResponseAsync(resourceGroupName, name).block(), Function.identity(), + Void.class, null, Context.NONE); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixImpl.java index 2c74ecbcd08d3..ee4e4c37dd251 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixImpl.java @@ -35,16 +35,14 @@ class PublicIpPrefixImpl @Override public Mono createResourceAsync() { PublicIpPrefixesClient client = this.manager().serviceClient().getPublicIpPrefixes(); - return client - .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override public Mono updateResourceAsync() { PublicIpPrefixesClient client = this.manager().serviceClient().getPublicIpPrefixes(); - return client - .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); } @@ -66,16 +64,14 @@ public PublicIpPrefix applyTags() { @Override public Mono applyTagsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getPublicIpPrefixes() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())) - .map( - inner -> { - setInner(inner); - return PublicIpPrefixImpl.this; - }); + .map(inner -> { + setInner(inner); + return PublicIpPrefixImpl.this; + }); } @Override @@ -110,9 +106,8 @@ public ProvisioningState provisioningState() { @Override public List publicIpAddresses() { - return Collections - .unmodifiableList( - innerModel().publicIpAddresses() == null ? new ArrayList<>() : this.innerModel().publicIpAddresses()); + return Collections.unmodifiableList( + innerModel().publicIpAddresses() == null ? new ArrayList<>() : this.innerModel().publicIpAddresses()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixesImpl.java index bb92be6d6e88a..a9a4eea6fa650 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/PublicIpPrefixesImpl.java @@ -9,9 +9,8 @@ import com.azure.resourcemanager.network.models.PublicIpPrefixes; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; -public class PublicIpPrefixesImpl - extends TopLevelModifiableResourcesImpl< - PublicIpPrefix, PublicIpPrefixImpl, PublicIpPrefixInner, PublicIpPrefixesClient, NetworkManager> +public class PublicIpPrefixesImpl extends + TopLevelModifiableResourcesImpl implements PublicIpPrefixes { public PublicIpPrefixesImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterImpl.java index 6c2a05ebdafaf..87ee4a633c2e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterImpl.java @@ -36,8 +36,7 @@ class RouteFilterImpl @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getRouteFilters() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); @@ -54,21 +53,12 @@ protected void initializeChildrenFromInner() { } if (this.innerModel().peerings() != null) { - this.peerings = - this - .innerModel() - .peerings() - .stream() - .collect( - Collectors - .toMap( - ExpressRouteCircuitPeeringInner::name, - peering -> - new ExpressRouteCircuitPeeringImpl<>( - this, - peering, - manager().serviceClient().getExpressRouteCircuitPeerings(), - peering.peeringType()))); + this.peerings = this.innerModel() + .peerings() + .stream() + .collect(Collectors.toMap(ExpressRouteCircuitPeeringInner::name, + peering -> new ExpressRouteCircuitPeeringImpl<>(this, peering, + manager().serviceClient().getExpressRouteCircuitPeerings(), peering.peeringType()))); } else { this.peerings = new HashMap<>(); } @@ -81,8 +71,7 @@ protected void beforeCreating() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getRouteFilters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -90,14 +79,11 @@ protected Mono getInnerAsync() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - routeFilter -> { - RouteFilterImpl impl = (RouteFilterImpl) routeFilter; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(routeFilter -> { + RouteFilterImpl impl = (RouteFilterImpl) routeFilter; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterRuleImpl.java index 50afc6f7af254..a271b107407c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterRuleImpl.java @@ -15,10 +15,8 @@ /** Implementation for {@link RouteFilterRule} and its create and update interfaces. */ class RouteFilterRuleImpl extends ChildResourceImpl - implements RouteFilterRule, - RouteFilterRule.Definition, - RouteFilterRule.UpdateDefinition, - RouteFilterRule.Update { + implements RouteFilterRule, RouteFilterRule.Definition, + RouteFilterRule.UpdateDefinition, RouteFilterRule.Update { RouteFilterRuleImpl(RouteFilterRuleInner inner, RouteFilterImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFiltersImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFiltersImpl.java index 18847171eccec..472793474c425 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFiltersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFiltersImpl.java @@ -10,9 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for RouteFilters. */ -public class RouteFiltersImpl - extends TopLevelModifiableResourcesImpl< - RouteFilter, RouteFilterImpl, RouteFilterInner, RouteFiltersClient, NetworkManager> +public class RouteFiltersImpl extends + TopLevelModifiableResourcesImpl implements RouteFilters { public RouteFiltersImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteImpl.java index 3245b5be5c891..6894a4e225f52 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteImpl.java @@ -9,11 +9,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.ChildResourceImpl; /** Implementation of Route. */ -class RouteImpl extends ChildResourceImpl - implements Route, - Route.Definition, - Route.UpdateDefinition, - Route.Update { +class RouteImpl extends ChildResourceImpl implements Route, + Route.Definition, Route.UpdateDefinition, Route.Update { RouteImpl(RouteInner inner, RouteTableImpl parent) { super(inner, parent); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTableImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTableImpl.java index 5e3969a2a71ca..a25a11668ee9e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTableImpl.java @@ -31,8 +31,7 @@ class RouteTableImpl @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getRouteTables() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -56,20 +55,16 @@ protected void initializeChildrenFromInner() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - routeTable -> { - RouteTableImpl impl = (RouteTableImpl) routeTable; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(routeTable -> { + RouteTableImpl impl = (RouteTableImpl) routeTable; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getRouteTables() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -77,13 +72,8 @@ protected Mono getInnerAsync() { @Override public List listAssociatedSubnets() { - return com - .azure - .resourcemanager - .network - .implementation - .Utils - .listAssociatedSubnets(this.myManager, this.innerModel().subnets()); + return com.azure.resourcemanager.network.implementation.Utils.listAssociatedSubnets(this.myManager, + this.innerModel().subnets()); } // Setters (fluent) @@ -107,8 +97,7 @@ public Update withoutRoute(String name) { @Override public RouteTableImpl withRoute(String destinationAddressPrefix, RouteNextHopType nextHop) { - return this - .defineRoute("route_" + this.name() + System.currentTimeMillis()) + return this.defineRoute("route_" + this.name() + System.currentTimeMillis()) .withDestinationAddressPrefix(destinationAddressPrefix) .withNextHop(nextHop) .attach(); @@ -116,8 +105,7 @@ public RouteTableImpl withRoute(String destinationAddressPrefix, RouteNextHopTyp @Override public RouteTableImpl withRouteViaVirtualAppliance(String destinationAddressPrefix, String ipAddress) { - return this - .defineRoute("route_" + this.name() + System.currentTimeMillis()) + return this.defineRoute("route_" + this.name() + System.currentTimeMillis()) .withDestinationAddressPrefix(destinationAddressPrefix) .withNextHopToVirtualAppliance(ipAddress) .attach(); @@ -138,8 +126,7 @@ protected void beforeCreating() { @Override protected Mono createInner() { - return this - .manager() + return this.manager() .serviceClient() .getRouteTables() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTablesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTablesImpl.java index ec29bac4c0024..b1dccacc68059 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTablesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteTablesImpl.java @@ -10,9 +10,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for RouteTables. */ -public class RouteTablesImpl - extends TopLevelModifiableResourcesImpl< - RouteTable, RouteTableImpl, RouteTableInner, RouteTablesClient, NetworkManager> +public class RouteTablesImpl extends + TopLevelModifiableResourcesImpl implements RouteTables { public RouteTablesImpl(final NetworkManager networkManager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SecurityGroupViewImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SecurityGroupViewImpl.java index c8fdfa1dec6dd..d14eecfcbc096 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SecurityGroupViewImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SecurityGroupViewImpl.java @@ -55,20 +55,16 @@ public NetworkWatcher parent() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - securityGroupView -> { - SecurityGroupViewImpl impl = (SecurityGroupViewImpl) securityGroupView; - impl.initializeFromInner(); - return impl; - }); + return super.refreshAsync().map(securityGroupView -> { + SecurityGroupViewImpl impl = (SecurityGroupViewImpl) securityGroupView; + impl.initializeFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ServiceEndpointPolicyDefinitionsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ServiceEndpointPolicyDefinitionsClientImpl.java index e4593331b9852..76f40fbc352db 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ServiceEndpointPolicyDefinitionsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ServiceEndpointPolicyDefinitionsClientImpl.java @@ -727,7 +727,7 @@ public Mono createOrUpdateAsync(String res ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) { return beginCreateOrUpdateAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -750,7 +750,7 @@ private Mono createOrUpdateAsync(String re ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SubnetImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SubnetImpl.java index 703652dd5b694..8d0ceee8fa2b6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SubnetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/SubnetImpl.java @@ -39,10 +39,8 @@ /** Implementation for Subnet and its create and update interfaces. */ class SubnetImpl extends ChildResourceImpl - implements Subnet, - Subnet.Definition, - Subnet.UpdateDefinition, - Subnet.Update { + implements Subnet, Subnet.Definition, + Subnet.UpdateDefinition, Subnet.Update { SubnetImpl(SubnetInner inner, NetworkImpl parent) { super(inner, parent); @@ -192,13 +190,10 @@ public SubnetImpl withAccessFromService(ServiceEndpointType service) { } } if (!found) { - this - .innerModel() + this.innerModel() .serviceEndpoints() - .add( - new ServiceEndpointPropertiesFormat() - .withService(service.toString()) - .withLocations(new ArrayList())); + .add(new ServiceEndpointPropertiesFormat().withService(service.toString()) + .withLocations(new ArrayList())); } return this; } @@ -365,17 +360,14 @@ private Set listAvailablePrivateIPAddresses(String cidr) { } String takenIPAddress = cidr.split("/")[0]; - IpAddressAvailabilityResultInner result = - this - .parent() - .manager() - .serviceClient() - .getVirtualNetworks() - .checkIpAddressAvailability(this.parent().resourceGroupName(), this.parent().name(), takenIPAddress); + IpAddressAvailabilityResultInner result = this.parent() + .manager() + .serviceClient() + .getVirtualNetworks() + .checkIpAddressAvailability(this.parent().resourceGroupName(), this.parent().name(), takenIPAddress); if (result == null // there's a case when user doesn't have the permission to query, result.availableIpAddresses() will be null - || result.availableIpAddresses() == null - ) { + || result.availableIpAddresses() == null) { return ipAddresses; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TopologyImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TopologyImpl.java index 80e3c2f8d3afd..2744da0595da8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TopologyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TopologyImpl.java @@ -81,9 +81,8 @@ public TopologyImpl withTargetNetwork(String networkId) { @Override public TopologyImpl withTargetSubnet(String subnetName) { - parameters - .withTargetSubnet( - new SubResource().withId(parameters.targetVirtualNetwork().id() + "/subnets/" + subnetName)); + parameters.withTargetSubnet( + new SubResource().withId(parameters.targetVirtualNetwork().id() + "/subnets/" + subnetName)); return this; } @@ -94,17 +93,15 @@ public TopologyInner innerModel() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .getTopologyAsync(parent().resourceGroupName(), parent().name(), parameters) - .map( - topologyInner -> { - TopologyImpl.this.inner = topologyInner; - TopologyImpl.this.initializeResourcesFromInner(); - return TopologyImpl.this; - }); + .map(topologyInner -> { + TopologyImpl.this.inner = topologyInner; + TopologyImpl.this.initializeResourcesFromInner(); + return TopologyImpl.this; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TroubleshootingImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TroubleshootingImpl.java index 4abb1dcd1e64f..6827aa33647e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TroubleshootingImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/TroubleshootingImpl.java @@ -49,17 +49,15 @@ public NetworkWatcher parent() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .getTroubleshootingAsync(parent.resourceGroupName(), parent.name(), parameters) - .map( - troubleshootingResultInner -> { - TroubleshootingImpl.this.result = troubleshootingResultInner; - return TroubleshootingImpl.this; - }); + .map(troubleshootingResultInner -> { + TroubleshootingImpl.this.result = troubleshootingResultInner; + return TroubleshootingImpl.this; + }); } // Getters diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Utils.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Utils.java index a75b7769f5c29..89c723f81db9c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Utils.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/Utils.java @@ -71,8 +71,8 @@ static List listAssociatedSubnets(NetworkManager manager, List listAssociatedApplicationGatewayBackends( - NetworkManager manager, List backendRefs) { + static Collection listAssociatedApplicationGatewayBackends(NetworkManager manager, + List backendRefs) { final Map appGateways = new HashMap<>(); final List backends = new ArrayList<>(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VerificationIPFlowImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VerificationIPFlowImpl.java index a43182884cc46..1936f23325eb7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VerificationIPFlowImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VerificationIPFlowImpl.java @@ -107,16 +107,14 @@ public String ruleName() { @Override public Mono executeWorkAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getNetworkWatchers() .verifyIpFlowAsync(parent.resourceGroupName(), parent.name(), parameters) - .map( - verificationIPFlowResultInner -> { - VerificationIPFlowImpl.this.result = verificationIPFlowResultInner; - return VerificationIPFlowImpl.this; - }); + .map(verificationIPFlowResultInner -> { + VerificationIPFlowImpl.this.result = verificationIPFlowResultInner; + return VerificationIPFlowImpl.this; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfaceImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfaceImpl.java index 273f3540498af..cd63caa807b6b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfaceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfaceImpl.java @@ -23,9 +23,8 @@ import reactor.core.publisher.Mono; /** The implementation for VirtualMachineScaleSetNetworkInterface. */ -class VirtualMachineScaleSetNetworkInterfaceImpl - extends ResourceImpl< - VirtualMachineScaleSetNetworkInterface, NetworkInterfaceInner, VirtualMachineScaleSetNetworkInterfaceImpl> +class VirtualMachineScaleSetNetworkInterfaceImpl extends + ResourceImpl implements VirtualMachineScaleSetNetworkInterface { /** the network client. */ private final NetworkManager networkManager; @@ -36,12 +35,8 @@ class VirtualMachineScaleSetNetworkInterfaceImpl private final ClientLogger logger = new ClientLogger(getClass()); - VirtualMachineScaleSetNetworkInterfaceImpl( - String name, - String scaleSetName, - String resourceGroupName, - NetworkInterfaceInner innerObject, - NetworkManager networkManager) { + VirtualMachineScaleSetNetworkInterfaceImpl(String name, String scaleSetName, String resourceGroupName, + NetworkInterfaceInner innerObject, NetworkManager networkManager) { super(name, innerObject); this.scaleSetName = scaleSetName; this.resourceGroupName = resourceGroupName; @@ -125,8 +120,8 @@ public Map ipConfigurations() } Map nicIPConfigurations = new TreeMap<>(); for (NetworkInterfaceIpConfigurationInner inner : inners) { - VirtualMachineScaleSetNicIpConfigurationImpl nicIPConfiguration = - new VirtualMachineScaleSetNicIpConfigurationImpl(inner, this, this.networkManager); + VirtualMachineScaleSetNicIpConfigurationImpl nicIPConfiguration + = new VirtualMachineScaleSetNicIpConfigurationImpl(inner, this, this.networkManager); nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } return Collections.unmodifiableMap(nicIPConfigurations); @@ -156,8 +151,7 @@ public NetworkSecurityGroup getNetworkSecurityGroup() { if (nsgId == null) { return null; } - return this - .manager() + return this.manager() .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(nsgId), ResourceUtils.nameFromResourceId(nsgId)); } @@ -178,15 +172,11 @@ public Mono createResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getNetworkInterfaces() - .getVirtualMachineScaleSetNetworkInterfaceAsync( - this.resourceGroupName, - this.scaleSetName, - ResourceUtils.nameFromResourceId(this.virtualMachineId()), - this.name()); + .getVirtualMachineScaleSetNetworkInterfaceAsync(this.resourceGroupName, this.scaleSetName, + ResourceUtils.nameFromResourceId(this.virtualMachineId()), this.name()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfacesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfacesImpl.java index ef183f9269fe5..c137af4d7b7b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfacesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNetworkInterfacesImpl.java @@ -14,16 +14,15 @@ import reactor.core.publisher.Mono; /** Implementation for VirtualMachineScaleSetNetworkInterfaces. */ -class VirtualMachineScaleSetNetworkInterfacesImpl - extends ReadableWrappersImpl< - VirtualMachineScaleSetNetworkInterface, VirtualMachineScaleSetNetworkInterfaceImpl, NetworkInterfaceInner> +class VirtualMachineScaleSetNetworkInterfacesImpl extends + ReadableWrappersImpl implements VirtualMachineScaleSetNetworkInterfaces { private final String resourceGroupName; private final String scaleSetName; private final NetworkManager networkManager; - VirtualMachineScaleSetNetworkInterfacesImpl( - String resourceGroupName, String scaleSetName, NetworkManager networkManager) { + VirtualMachineScaleSetNetworkInterfacesImpl(String resourceGroupName, String scaleSetName, + NetworkManager networkManager) { this.resourceGroupName = resourceGroupName; this.scaleSetName = scaleSetName; this.networkManager = networkManager; @@ -43,16 +42,14 @@ protected VirtualMachineScaleSetNetworkInterfaceImpl wrapModel(NetworkInterfaceI if (inner == null) { return null; } - return new VirtualMachineScaleSetNetworkInterfaceImpl( - inner.name(), this.scaleSetName, this.resourceGroupName, inner, this.manager()); + return new VirtualMachineScaleSetNetworkInterfaceImpl(inner.name(), this.scaleSetName, this.resourceGroupName, + inner, this.manager()); } @Override public VirtualMachineScaleSetNetworkInterface getByVirtualMachineInstanceId(String instanceId, String name) { - NetworkInterfaceInner networkInterfaceInner = - this - .inner() - .getVirtualMachineScaleSetNetworkInterface(this.resourceGroupName, this.scaleSetName, instanceId, name); + NetworkInterfaceInner networkInterfaceInner = this.inner() + .getVirtualMachineScaleSetNetworkInterface(this.resourceGroupName, this.scaleSetName, instanceId, name); if (networkInterfaceInner == null) { return null; } @@ -60,8 +57,8 @@ public VirtualMachineScaleSetNetworkInterface getByVirtualMachineInstanceId(Stri } @Override - public Mono getByVirtualMachineInstanceIdAsync( - String instanceId, String name) { + public Mono getByVirtualMachineInstanceIdAsync(String instanceId, + String name) { return this.inner() .getVirtualMachineScaleSetNetworkInterfaceAsync(this.resourceGroupName, this.scaleSetName, instanceId, name) .map(this::wrapModel); @@ -69,9 +66,8 @@ public Mono getByVirtualMachineInstanceI @Override public PagedIterable list() { - return super - .wrapList( - this.inner().listVirtualMachineScaleSetNetworkInterfaces(this.resourceGroupName, this.scaleSetName)); + return super.wrapList( + this.inner().listVirtualMachineScaleSetNetworkInterfaces(this.resourceGroupName, this.scaleSetName)); } @Override @@ -81,21 +77,13 @@ public PagedFlux listAsync() { @Override public PagedIterable listByVirtualMachineInstanceId(String instanceId) { - return super - .wrapList( - this - .inner() - .listVirtualMachineScaleSetVMNetworkInterfaces( - this.resourceGroupName, this.scaleSetName, instanceId)); + return super.wrapList(this.inner() + .listVirtualMachineScaleSetVMNetworkInterfaces(this.resourceGroupName, this.scaleSetName, instanceId)); } @Override public PagedFlux listByVirtualMachineInstanceIdAsync(String instanceId) { - return super - .wrapPageAsync( - this - .inner() - .listVirtualMachineScaleSetVMNetworkInterfacesAsync( - this.resourceGroupName, this.scaleSetName, instanceId)); + return super.wrapPageAsync(this.inner() + .listVirtualMachineScaleSetVMNetworkInterfacesAsync(this.resourceGroupName, this.scaleSetName, instanceId)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNicIpConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNicIpConfigurationImpl.java index e35f9d6d79a2a..9263cc418eab4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNicIpConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualMachineScaleSetNicIpConfigurationImpl.java @@ -9,14 +9,11 @@ import com.azure.resourcemanager.network.fluent.models.NetworkInterfaceIpConfigurationInner; /** Implementation for NicIPConfiguration for network interfaces associated with virtual machine scale set. */ -class VirtualMachineScaleSetNicIpConfigurationImpl - extends NicIpConfigurationBaseImpl< - VirtualMachineScaleSetNetworkInterfaceImpl, VirtualMachineScaleSetNetworkInterface> +class VirtualMachineScaleSetNicIpConfigurationImpl extends + NicIpConfigurationBaseImpl implements VirtualMachineScaleSetNicIpConfiguration { - VirtualMachineScaleSetNicIpConfigurationImpl( - NetworkInterfaceIpConfigurationInner inner, - VirtualMachineScaleSetNetworkInterfaceImpl parent, - NetworkManager networkManager) { + VirtualMachineScaleSetNicIpConfigurationImpl(NetworkInterfaceIpConfigurationInner inner, + VirtualMachineScaleSetNetworkInterfaceImpl parent, NetworkManager networkManager) { super(inner, parent, networkManager); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionImpl.java index fb26c01c3dd0d..5ae685000bd8d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionImpl.java @@ -24,21 +24,15 @@ import reactor.core.publisher.Mono; /** Implementation for VirtualNetworkGatewayConnection and its create and update interfaces. */ -public class VirtualNetworkGatewayConnectionImpl - extends GroupableResourceImpl< - VirtualNetworkGatewayConnection, - VirtualNetworkGatewayConnectionInner, - VirtualNetworkGatewayConnectionImpl, - NetworkManager> - implements VirtualNetworkGatewayConnection, - VirtualNetworkGatewayConnection.Definition, - VirtualNetworkGatewayConnection.Update, - AppliableWithTags { +public class VirtualNetworkGatewayConnectionImpl extends + GroupableResourceImpl + implements VirtualNetworkGatewayConnection, VirtualNetworkGatewayConnection.Definition, + VirtualNetworkGatewayConnection.Update, AppliableWithTags { private final VirtualNetworkGateway parent; private String updateSharedKey; - VirtualNetworkGatewayConnectionImpl( - String name, VirtualNetworkGatewayImpl parent, VirtualNetworkGatewayConnectionInner inner) { + VirtualNetworkGatewayConnectionImpl(String name, VirtualNetworkGatewayImpl parent, + VirtualNetworkGatewayConnectionInner inner) { super(name, inner, parent.manager()); this.parent = parent; } @@ -168,8 +162,8 @@ public VirtualNetworkGatewayConnectionImpl withLocalNetworkGateway(LocalNetworkG } @Override - public VirtualNetworkGatewayConnectionImpl withSecondVirtualNetworkGateway( - VirtualNetworkGateway virtualNetworkGateway2) { + public VirtualNetworkGatewayConnectionImpl + withSecondVirtualNetworkGateway(VirtualNetworkGateway virtualNetworkGateway2) { innerModel().withVirtualNetworkGateway2(virtualNetworkGateway2.innerModel()); return this; } @@ -204,8 +198,7 @@ public VirtualNetworkGatewayConnectionImpl withAuthorization(String authorizatio @Override protected Mono getInnerAsync() { - return myManager - .serviceClient() + return myManager.serviceClient() .getVirtualNetworkGatewayConnections() .getByResourceGroupAsync(resourceGroupName(), name()); } @@ -213,8 +206,7 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { beforeCreating(); - return myManager - .serviceClient() + return myManager.serviceClient() .getVirtualNetworkGatewayConnections() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)) @@ -222,15 +214,15 @@ public Mono createResourceAsync() { if (updateSharedKey == null) { return Mono.just(virtualNetworkGatewayConnection); } - return myManager.serviceClient().getVirtualNetworkGatewayConnections() - .setSharedKeyAsync( - this.resourceGroupName(), - this.name(), + return myManager.serviceClient() + .getVirtualNetworkGatewayConnections() + .setSharedKeyAsync(this.resourceGroupName(), this.name(), new ConnectionSharedKeyInner().withValue(updateSharedKey)) .doOnSuccess(inner -> { updateSharedKey = null; }) - .then(myManager.serviceClient().getVirtualNetworkGatewayConnections() + .then(myManager.serviceClient() + .getVirtualNetworkGatewayConnections() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(innerToFluentMap(this))); }); @@ -252,8 +244,7 @@ public VirtualNetworkGatewayConnection applyTags() { @Override public Mono applyTagsAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGatewayConnections() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionsImpl.java index 93b21bbd9f532..2f4ae8a73c456 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayConnectionsImpl.java @@ -18,13 +18,8 @@ import reactor.core.publisher.Mono; /** The implementation of VirtualNetworkGatewayConnections. */ -class VirtualNetworkGatewayConnectionsImpl - extends GroupableResourcesImpl< - VirtualNetworkGatewayConnection, - VirtualNetworkGatewayConnectionImpl, - VirtualNetworkGatewayConnectionInner, - VirtualNetworkGatewayConnectionsClient, - NetworkManager> +class VirtualNetworkGatewayConnectionsImpl extends + GroupableResourcesImpl implements VirtualNetworkGatewayConnections { private final VirtualNetworkGatewayImpl parent; @@ -71,12 +66,10 @@ public PagedIterable list() { @Override public VirtualNetworkGatewayConnection getByName(String name) { - VirtualNetworkGatewayConnectionInner inner = - this - .manager() - .serviceClient() - .getVirtualNetworkGatewayConnections() - .getByResourceGroup(this.parent().resourceGroupName(), name); + VirtualNetworkGatewayConnectionInner inner = this.manager() + .serviceClient() + .getVirtualNetworkGatewayConnections() + .getByResourceGroup(this.parent().resourceGroupName(), name); return new VirtualNetworkGatewayConnectionImpl(name, parent, inner); } @@ -87,8 +80,9 @@ public VirtualNetworkGateway parent() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), rg -> - inner().listByResourceGroupAsync(rg.name())), this::wrapModel); + return PagedConverter + .mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), + rg -> inner().listByResourceGroupAsync(rg.name())), this::wrapModel); } @Override @@ -134,8 +128,9 @@ public String setSharedKeyByName(String name, String sharedKey) { @Override public Mono setSharedKeyByNameAsync(String name, String sharedKey) { - return inner().setSharedKeyAsync( - this.parent().resourceGroupName(), name, new ConnectionSharedKeyInner().withValue(sharedKey)) + return inner() + .setSharedKeyAsync(this.parent().resourceGroupName(), name, + new ConnectionSharedKeyInner().withValue(sharedKey)) .map(ConnectionSharedKeyInner::value); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayImpl.java index 8d1e7dd6e53d6..7e2ed33fbe178 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayImpl.java @@ -39,9 +39,8 @@ import java.util.TreeMap; /** Implementation for VirtualNetworkGateway and its create and update interfaces. */ -class VirtualNetworkGatewayImpl - extends GroupableParentResourceWithTagsImpl< - VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> +class VirtualNetworkGatewayImpl extends + GroupableParentResourceWithTagsImpl implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "GatewaySubnet"; private final ClientLogger logger = new ClientLogger(getClass()); @@ -51,8 +50,8 @@ class VirtualNetworkGatewayImpl private Creatable creatableNetwork; private Creatable creatablePip; - VirtualNetworkGatewayImpl( - String name, final VirtualNetworkGatewayInner innerModel, final NetworkManager networkManager) { + VirtualNetworkGatewayImpl(String name, final VirtualNetworkGatewayInner innerModel, + final NetworkManager networkManager) { super(name, innerModel, networkManager); } @@ -78,11 +77,9 @@ public VirtualNetworkGatewayImpl withPolicyBasedVpn() { @Override public VirtualNetworkGatewayImpl withSku(VirtualNetworkGatewaySkuName skuName) { - VirtualNetworkGatewaySku sku = - new VirtualNetworkGatewaySku() - .withName(skuName) - // same sku tier as sku name - .withTier(VirtualNetworkGatewaySkuTier.fromString(skuName.toString())); + VirtualNetworkGatewaySku sku = new VirtualNetworkGatewaySku().withName(skuName) + // same sku tier as sku name + .withTier(VirtualNetworkGatewaySkuTier.fromString(skuName.toString())); this.innerModel().withSku(sku); return this; } @@ -95,8 +92,8 @@ public VirtualNetworkGatewayImpl withNewNetwork(Creatable creatable) { @Override public VirtualNetworkGatewayImpl withNewNetwork(String name, String addressSpace, String subnetAddressSpaceCidr) { - Network.DefinitionStages.WithGroup definitionWithGroup = - this.manager().networks().define(name).withRegion(this.regionName()); + Network.DefinitionStages.WithGroup definitionWithGroup + = this.manager().networks().define(name).withRegion(this.regionName()); Network.DefinitionStages.WithCreate definitionAfterGroup; if (this.newGroup() != null) { @@ -104,17 +101,15 @@ public VirtualNetworkGatewayImpl withNewNetwork(String name, String addressSpace } else { definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName()); } - Creatable network = - definitionAfterGroup.withAddressSpace(addressSpace).withSubnet(GATEWAY_SUBNET, subnetAddressSpaceCidr); + Creatable network + = definitionAfterGroup.withAddressSpace(addressSpace).withSubnet(GATEWAY_SUBNET, subnetAddressSpaceCidr); return withNewNetwork(network); } @Override public VirtualNetworkGatewayImpl withNewNetwork(String addressSpaceCidr, String subnetAddressSpaceCidr) { - withNewNetwork( - this.manager().resourceManager().internalContext().randomResourceName("vnet", 8), - addressSpaceCidr, - subnetAddressSpaceCidr); + withNewNetwork(this.manager().resourceManager().internalContext().randomResourceName("vnet", 8), + addressSpaceCidr, subnetAddressSpaceCidr); return this; } @@ -145,13 +140,11 @@ public VirtualNetworkGatewayImpl withNewPublicIpAddress(Creatable resetAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGateways() .resetAsync(resourceGroupName(), name()) - .map( - inner -> { - VirtualNetworkGatewayImpl.this.setInner(inner); - return Mono.empty(); - }) + .map(inner -> { + VirtualNetworkGatewayImpl.this.setInner(inner); + return Mono.empty(); + }) .then(); } @@ -200,20 +191,17 @@ public PagedIterable listConnections() { @Override public PagedFlux listConnectionsAsync() { - PagedFlux connectionInners = - this - .manager() - .serviceClient() - .getVirtualNetworkGateways() - .listConnectionsAsync(this.resourceGroupName(), this.name()); - return PagedConverter - .flatMapPage(connectionInners, connectionInner -> connections().getByIdAsync(connectionInner.id())); + PagedFlux connectionInners = this.manager() + .serviceClient() + .getVirtualNetworkGateways() + .listConnectionsAsync(this.resourceGroupName(), this.name()); + return PagedConverter.flatMapPage(connectionInners, + connectionInner -> connections().getByIdAsync(connectionInner.id())); } @Override public String generateVpnProfile() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGateways() .generateVpnProfile(resourceGroupName(), name(), new VpnClientParameters()); @@ -221,8 +209,7 @@ public String generateVpnProfile() { @Override public Mono generateVpnProfileAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGateways() .generateVpnProfileAsync(resourceGroupName(), name(), new VpnClientParameters()); @@ -230,8 +217,7 @@ public Mono generateVpnProfileAsync() { @Override protected Mono applyTagsToInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); @@ -300,20 +286,16 @@ protected void initializeChildrenFromInner() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - virtualNetworkGateway -> { - VirtualNetworkGatewayImpl impl = (VirtualNetworkGatewayImpl) virtualNetworkGateway; - impl.initializeChildrenFromInner(); - return impl; - }); + return super.refreshAsync().map(virtualNetworkGateway -> { + VirtualNetworkGatewayImpl impl = (VirtualNetworkGatewayImpl) virtualNetworkGateway; + impl.initializeChildrenFromInner(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getVirtualNetworkGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -329,8 +311,8 @@ VirtualNetworkGatewayImpl withConfig(VirtualNetworkGatewayIpConfigurationImpl co private VirtualNetworkGatewayIpConfigurationImpl defineIPConfiguration(String name) { VirtualNetworkGatewayIpConfiguration ipConfig = this.ipConfigs.get(name); if (ipConfig == null) { - VirtualNetworkGatewayIpConfigurationInner inner = - new VirtualNetworkGatewayIpConfigurationInner().withName(name); + VirtualNetworkGatewayIpConfigurationInner inner + = new VirtualNetworkGatewayIpConfigurationInner().withName(name); return new VirtualNetworkGatewayIpConfigurationImpl(inner, this); } else { return (VirtualNetworkGatewayIpConfigurationImpl) ipConfig; @@ -342,8 +324,8 @@ private void initializeIPConfigsFromInner() { List inners = this.innerModel().ipConfigurations(); if (inners != null) { for (VirtualNetworkGatewayIpConfigurationInner inner : inners) { - VirtualNetworkGatewayIpConfigurationImpl config = - new VirtualNetworkGatewayIpConfigurationImpl(inner, this); + VirtualNetworkGatewayIpConfigurationImpl config + = new VirtualNetworkGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } @@ -364,8 +346,8 @@ private BgpSettings ensureBgpSettings() { } private VirtualNetworkGatewayIpConfigurationImpl ensureDefaultIPConfig() { - VirtualNetworkGatewayIpConfigurationImpl ipConfig = - (VirtualNetworkGatewayIpConfigurationImpl) defaultIPConfiguration(); + VirtualNetworkGatewayIpConfigurationImpl ipConfig + = (VirtualNetworkGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); @@ -377,13 +359,11 @@ private VirtualNetworkGatewayIpConfigurationImpl ensureDefaultIPConfig() { private Creatable ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); - this.creatablePip = - this - .manager() - .publicIpAddresses() - .define(pipName) - .withRegion(this.regionName()) - .withExistingResourceGroup(this.resourceGroupName()); + this.creatablePip = this.manager() + .publicIpAddresses() + .define(pipName) + .withRegion(this.regionName()) + .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } @@ -404,14 +384,10 @@ protected Mono createInner() { final Mono pipObservable; if (defaultIPConfig.publicIpAddressId() == null) { // If public ip not specified, then create a default PIP - pipObservable = - ensureDefaultPipDefinition() - .createAsync() - .map( - publicIPAddress -> { - defaultIPConfig.withExistingPublicIpAddress(publicIPAddress); - return publicIPAddress; - }); + pipObservable = ensureDefaultPipDefinition().createAsync().map(publicIPAddress -> { + defaultIPConfig.withExistingPublicIpAddress(publicIPAddress); + return publicIPAddress; + }); } else { // If existing public ip address specified, skip creating the PIP pipObservable = Mono.empty(); @@ -424,30 +400,21 @@ protected Mono createInner() { networkObservable = Mono.empty(); // ...and don't create another VNet } else if (creatableNetwork != null) { // But if default IP config does not have a subnet specified, then create a VNet - networkObservable = - creatableNetwork - .createAsync() - .map( - network -> { - // ... and assign the created VNet to the default IP config - defaultIPConfig.withExistingSubnet(network, GATEWAY_SUBNET); - return network; - }); + networkObservable = creatableNetwork.createAsync().map(network -> { + // ... and assign the created VNet to the default IP config + defaultIPConfig.withExistingSubnet(network, GATEWAY_SUBNET); + return network; + }); } else { throw logger.logExceptionAsError(new IllegalStateException("Creatable Network should not be null")); } - return Flux - .merge(networkObservable, pipObservable) + return Flux.merge(networkObservable, pipObservable) .last(Resource.DUMMY) - .flatMap( - resource -> - VirtualNetworkGatewayImpl - .this - .manager() - .serviceClient() - .getVirtualNetworkGateways() - .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); + .flatMap(resource -> VirtualNetworkGatewayImpl.this.manager() + .serviceClient() + .getVirtualNetworkGateways() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayIpConfigurationImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayIpConfigurationImpl.java index 1a324f36fc375..0a34f5fef5227 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayIpConfigurationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewayIpConfigurationImpl.java @@ -14,16 +14,15 @@ import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.ChildResourceImpl; /** Implementation for VirtualNetworkGatewayIpConfiguration. */ -class VirtualNetworkGatewayIpConfigurationImpl - extends ChildResourceImpl< - VirtualNetworkGatewayIpConfigurationInner, VirtualNetworkGatewayImpl, VirtualNetworkGateway> +class VirtualNetworkGatewayIpConfigurationImpl extends + ChildResourceImpl implements VirtualNetworkGatewayIpConfiguration, - VirtualNetworkGatewayIpConfiguration.Definition, - VirtualNetworkGatewayIpConfiguration.UpdateDefinition, - VirtualNetworkGatewayIpConfiguration.Update { + VirtualNetworkGatewayIpConfiguration.Definition, + VirtualNetworkGatewayIpConfiguration.UpdateDefinition, + VirtualNetworkGatewayIpConfiguration.Update { - VirtualNetworkGatewayIpConfigurationImpl( - VirtualNetworkGatewayIpConfigurationInner inner, VirtualNetworkGatewayImpl parent) { + VirtualNetworkGatewayIpConfigurationImpl(VirtualNetworkGatewayIpConfigurationInner inner, + VirtualNetworkGatewayImpl parent) { super(inner, parent); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewaysImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewaysImpl.java index 618a36c4007b6..e504ecc08a0e8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewaysImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkGatewaysImpl.java @@ -15,13 +15,8 @@ import reactor.core.publisher.Mono; /** Implementation for VirtualNetworkGateways. */ -public class VirtualNetworkGatewaysImpl - extends GroupableResourcesImpl< - VirtualNetworkGateway, - VirtualNetworkGatewayImpl, - VirtualNetworkGatewayInner, - VirtualNetworkGatewaysClient, - NetworkManager> +public class VirtualNetworkGatewaysImpl extends + GroupableResourcesImpl implements VirtualNetworkGateways { public VirtualNetworkGatewaysImpl(final NetworkManager networkManager) { @@ -41,8 +36,9 @@ public PagedIterable list() { // TODO: Test this @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), - rg -> inner().listByResourceGroupAsync(rg.name())), this::wrapModel); + return PagedConverter + .mapPage(PagedConverter.mergePagedFlux(this.manager().resourceManager().resourceGroups().listAsync(), + rg -> inner().listByResourceGroupAsync(rg.name())), this::wrapModel); } @Override @@ -53,8 +49,8 @@ public PagedIterable listByResourceGroup(String groupName @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkPeeringsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkPeeringsClientImpl.java index 5388325e169e1..da9f8e4d8f0c0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkPeeringsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/VirtualNetworkPeeringsClientImpl.java @@ -757,7 +757,7 @@ public Mono createOrUpdateAsync(String resourceGroup SyncRemoteAddressSpace syncRemoteAddressSpace) { return beginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -779,7 +779,7 @@ public Mono createOrUpdateAsync(String resourceGroup final SyncRemoteAddressSpace syncRemoteAddressSpace = null; return beginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -804,7 +804,7 @@ private Mono createOrUpdateAsync(String resourceGrou SyncRemoteAddressSpace syncRemoteAddressSpace, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPoliciesImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPoliciesImpl.java index 9539f3e0cd850..f1377c475f2ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPoliciesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPoliciesImpl.java @@ -11,11 +11,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for {@link WebApplicationFirewallPolicies}. */ -public class WebApplicationFirewallPoliciesImpl - extends - TopLevelModifiableResourcesImpl< - WebApplicationFirewallPolicy, WebApplicationFirewallPolicyImpl, WebApplicationFirewallPolicyInner, - WebApplicationFirewallPoliciesClient, NetworkManager> +public class WebApplicationFirewallPoliciesImpl extends + TopLevelModifiableResourcesImpl implements WebApplicationFirewallPolicies { public WebApplicationFirewallPoliciesImpl(NetworkManager manager) { diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPolicyImpl.java index bf6e853bbf0fd..9a7ec3d1be2f5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/WebApplicationFirewallPolicyImpl.java @@ -32,16 +32,15 @@ /** * Implementation of the {@link WebApplicationFirewallPolicy} interface. */ -public class WebApplicationFirewallPolicyImpl extends GroupableResourceImpl< - WebApplicationFirewallPolicy, WebApplicationFirewallPolicyInner, WebApplicationFirewallPolicyImpl, NetworkManager> - implements WebApplicationFirewallPolicy, - WebApplicationFirewallPolicy.Definition, - WebApplicationFirewallPolicy.Update, - WebApplicationFirewallPolicy.UpdateStages.WithRequestBodyOrUpdate { +public class WebApplicationFirewallPolicyImpl extends + GroupableResourceImpl + implements WebApplicationFirewallPolicy, WebApplicationFirewallPolicy.Definition, + WebApplicationFirewallPolicy.Update, WebApplicationFirewallPolicy.UpdateStages.WithRequestBodyOrUpdate { private static final String BOT_DETECTION_RULE_SET_TYPE = "Microsoft_BotManagerRuleSet"; private static final String BOT_DETECTION_RULE_SET_VERSION_DEFAULT = "0.1"; - protected WebApplicationFirewallPolicyImpl(String name, WebApplicationFirewallPolicyInner innerObject, NetworkManager manager) { + protected WebApplicationFirewallPolicyImpl(String name, WebApplicationFirewallPolicyInner innerObject, + NetworkManager manager) { super(name, innerObject, manager); } @@ -88,7 +87,8 @@ public List getAssociatedApplicationGatewayIds() { if (CoreUtils.isNullOrEmpty(this.innerModel().applicationGateways())) { return Collections.emptyList(); } - return Collections.unmodifiableList(this.innerModel().applicationGateways() + return Collections.unmodifiableList(this.innerModel() + .applicationGateways() .stream() .map(ApplicationGatewayInner::id) .collect(Collectors.toList())); @@ -152,8 +152,7 @@ public WebApplicationFirewallPolicyImpl withoutBotProtection() { @Override public WebApplicationFirewallPolicyImpl withBotProtection(String version) { String versionOrDefault = CoreUtils.isNullOrEmpty(version) ? BOT_DETECTION_RULE_SET_VERSION_DEFAULT : version; - Optional ruleSetOptional = ensureManagedRules() - .managedRuleSets() + Optional ruleSetOptional = ensureManagedRules().managedRuleSets() .stream() .filter(ruleSet -> BOT_DETECTION_RULE_SET_TYPE.equals(ruleSet.ruleSetType())) .findFirst(); @@ -165,9 +164,8 @@ public WebApplicationFirewallPolicyImpl withBotProtection(String version) { ruleSet.withRuleSetVersion(version); } } else { - ensureManagedRules().managedRuleSets().add( - new ManagedRuleSet() - .withRuleSetType(BOT_DETECTION_RULE_SET_TYPE) + ensureManagedRules().managedRuleSets() + .add(new ManagedRuleSet().withRuleSetType(BOT_DETECTION_RULE_SET_TYPE) .withRuleSetVersion(versionOrDefault)); } return this; @@ -187,39 +185,39 @@ public WebApplicationFirewallPolicyImpl disableRequestBodyInspection() { @Override public WebApplicationFirewallPolicyImpl withRequestBodySizeLimitInKb(int limitInKb) { - ensurePolicySettings() - .withRequestBodyInspectLimitInKB(limitInKb) - .withMaxRequestBodySizeInKb(limitInKb); + ensurePolicySettings().withRequestBodyInspectLimitInKB(limitInKb).withMaxRequestBodySizeInKb(limitInKb); return this; } @Override public WebApplicationFirewallPolicyImpl withFileUploadSizeLimitInMb(int limitInMb) { - ensurePolicySettings() - .withFileUploadLimitInMb(limitInMb); + ensurePolicySettings().withFileUploadLimitInMb(limitInMb); return this; } @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getWebApplicationFirewallPolicies() + return this.manager() + .serviceClient() + .getWebApplicationFirewallPolicies() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override public WebApplicationFirewallPolicyImpl withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSet, - ManagedRuleGroupOverride... managedRuleGroupOverrides) { + ManagedRuleGroupOverride... managedRuleGroupOverrides) { Objects.requireNonNull(managedRuleSet); return withManagedRuleSet(managedRuleSet.type(), managedRuleSet.version(), managedRuleGroupOverrides); } @Override public WebApplicationFirewallPolicyImpl withManagedRuleSet(String type, String version, - ManagedRuleGroupOverride... managedRuleGroupOverrides) { + ManagedRuleGroupOverride... managedRuleGroupOverrides) { ManagedRuleSet managedRuleSet = new ManagedRuleSet().withRuleSetType(type).withRuleSetVersion(version); if (managedRuleGroupOverrides != null) { - managedRuleSet.withRuleGroupOverrides(Arrays.stream(managedRuleGroupOverrides).collect(Collectors.toList())); + managedRuleSet + .withRuleGroupOverrides(Arrays.stream(managedRuleGroupOverrides).collect(Collectors.toList())); } return withManagedRuleSet(managedRuleSet); } @@ -237,7 +235,8 @@ public WebApplicationFirewallPolicyImpl withManagedRuleSet(ManagedRuleSet manage } @Override - public WebApplicationFirewallPolicyImpl withoutManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSet) { + public WebApplicationFirewallPolicyImpl + withoutManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSet) { Objects.requireNonNull(managedRuleSet); return withoutManagedRuleSet(managedRuleSet.type(), managedRuleSet.version()); } @@ -245,15 +244,20 @@ public WebApplicationFirewallPolicyImpl withoutManagedRuleSet(KnownWebApplicatio @Override public WebApplicationFirewallPolicyImpl withoutManagedRuleSet(String type, String version) { if (this.innerModel().managedRules() != null && this.innerModel().managedRules().managedRuleSets() != null) { - this.innerModel().managedRules().managedRuleSets().removeIf(ruleSet -> Objects.equals(type, ruleSet.ruleSetType()) - && Objects.equals(version, ruleSet.ruleSetVersion())); + this.innerModel() + .managedRules() + .managedRuleSets() + .removeIf(ruleSet -> Objects.equals(type, ruleSet.ruleSetType()) + && Objects.equals(version, ruleSet.ruleSetVersion())); } return this; } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getWebApplicationFirewallPolicies() + return this.manager() + .serviceClient() + .getWebApplicationFirewallPolicies() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateway.java index 08df6aac06766..736dc87cb84b2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateway.java @@ -21,12 +21,8 @@ /** Entry point for application gateway management API in Azure. */ public interface ApplicationGateway - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags, - HasSubnet, - HasPrivateIpAddress { + extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags, HasSubnet, HasPrivateIpAddress { // Actions @@ -289,8 +285,8 @@ interface WithRedirectConfiguration { * @param name a unique name for the redirect configuration * @return the first stage of the redirect configuration definition */ - ApplicationGatewayRedirectConfiguration.DefinitionStages.Blank defineRedirectConfiguration( - String name); + ApplicationGatewayRedirectConfiguration.DefinitionStages.Blank + defineRedirectConfiguration(String name); } /** The stage of an application gateway definition allowing to add a probe. */ @@ -683,7 +679,7 @@ interface WithSslPolicy { * @return the next stage of the definition */ WithCreate withCustomV2SslPolicy(ApplicationGatewaySslProtocol minProtocolVersion, - List cipherSuites); + List cipherSuites); /** * Configures to use the provided TLS/SSL policy for the application gateway. @@ -698,41 +694,18 @@ WithCreate withCustomV2SslPolicy(ApplicationGatewaySslProtocol minProtocolVersio * The stage of an application gateway definition containing all the required inputs for the resource to be * created, but also allowing for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithSku, - WithInstanceCount, - WithWebApplicationFirewall, - WithSslCert, - WithFrontendPort, - WithListener, - WithBackendHttpConfig, - WithBackend, - WithExistingSubnet, - WithPrivateIPAddress, - WithPrivateFrontend, - WithPublicFrontend, - WithPublicIPAddress, - WithProbe, - WithDisabledSslProtocol, - WithAuthenticationCertificate, - WithRedirectConfiguration, - WithAvailabilityZone, - WithManagedServiceIdentity, - WithHttp2, - WithWebApplicationFirewallPolicy, - WithSslPolicy { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, WithSku, + WithInstanceCount, WithWebApplicationFirewall, WithSslCert, WithFrontendPort, WithListener, + WithBackendHttpConfig, WithBackend, WithExistingSubnet, WithPrivateIPAddress, WithPrivateFrontend, + WithPublicFrontend, WithPublicIPAddress, WithProbe, WithDisabledSslProtocol, WithAuthenticationCertificate, + WithRedirectConfiguration, WithAvailabilityZone, WithManagedServiceIdentity, WithHttp2, + WithWebApplicationFirewallPolicy, WithSslPolicy { } } /** The entirety of the application gateway definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.WithRequestRoutingRule, - DefinitionStages.WithRequestRoutingRuleOrCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.WithRequestRoutingRule, DefinitionStages.WithRequestRoutingRuleOrCreate { } /** Grouping of application gateway update stages. */ @@ -1182,8 +1155,8 @@ interface WithRedirectConfiguration { * @param name a unique name for the redirect configuration * @return the first stage of the redirect configuration definition */ - ApplicationGatewayRedirectConfiguration.UpdateDefinitionStages.Blank defineRedirectConfiguration( - String name); + ApplicationGatewayRedirectConfiguration.UpdateDefinitionStages.Blank + defineRedirectConfiguration(String name); /** * Removes a redirect configuration from the application gateway. @@ -1266,8 +1239,8 @@ interface WithRequestRoutingRule { * @param name a unique name for the request routing rule * @return the first stage of the request routing rule */ - ApplicationGatewayRequestRoutingRule.UpdateDefinitionStages.Blank defineRequestRoutingRule( - String name); + ApplicationGatewayRequestRoutingRule.UpdateDefinitionStages.Blank + defineRequestRoutingRule(String name); /** * Removes a request routing rule from the application gateway. @@ -1454,7 +1427,7 @@ interface WithSslPolicy { * @return the next stage of the update */ Update withCustomV2SslPolicy(ApplicationGatewaySslProtocol minProtocolVersion, - List cipherSuites); + List cipherSuites); /** * Configures to use the provided TLS/SSL policy for the application gateway. @@ -1467,30 +1440,13 @@ Update withCustomV2SslPolicy(ApplicationGatewaySslProtocol minProtocolVersion, } /** The template for an application gateway update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithInstanceCount, - UpdateStages.WithWebApplicationFirewall, - UpdateStages.WithBackend, - UpdateStages.WithBackendHttpConfig, - UpdateStages.WithIPConfig, - UpdateStages.WithFrontend, - UpdateStages.WithPublicIPAddress, - UpdateStages.WithFrontendPort, - UpdateStages.WithSslCert, - UpdateStages.WithListener, - UpdateStages.WithRequestRoutingRule, - UpdateStages.WithExistingSubnet, - UpdateStages.WithProbe, - UpdateStages.WithDisabledSslProtocol, - UpdateStages.WithAuthenticationCertificate, - UpdateStages.WithRedirectConfiguration, - UpdateStages.WithUrlPathMap, - UpdateStages.WithManagedServiceIdentity, - UpdateStages.WithHttp2, - UpdateStages.WithWebApplicationFirewallPolicy, - UpdateStages.WithSslPolicy { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithInstanceCount, UpdateStages.WithWebApplicationFirewall, UpdateStages.WithBackend, + UpdateStages.WithBackendHttpConfig, UpdateStages.WithIPConfig, UpdateStages.WithFrontend, + UpdateStages.WithPublicIPAddress, UpdateStages.WithFrontendPort, UpdateStages.WithSslCert, + UpdateStages.WithListener, UpdateStages.WithRequestRoutingRule, UpdateStages.WithExistingSubnet, + UpdateStages.WithProbe, UpdateStages.WithDisabledSslProtocol, UpdateStages.WithAuthenticationCertificate, + UpdateStages.WithRedirectConfiguration, UpdateStages.WithUrlPathMap, UpdateStages.WithManagedServiceIdentity, + UpdateStages.WithHttp2, UpdateStages.WithWebApplicationFirewallPolicy, UpdateStages.WithSslPolicy { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayAuthenticationCertificate.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayAuthenticationCertificate.java index 087b958da7263..0ade61e5be3fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayAuthenticationCertificate.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayAuthenticationCertificate.java @@ -83,10 +83,8 @@ interface WithAttach extends Attachable.InDefinition { * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithData { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithData { } /** Grouping of application gateway authentication certificate update stages. */ @@ -168,9 +166,7 @@ interface WithAttach extends Attachable.InUpdate { * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithData { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithData { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHealthStatus.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHealthStatus.java index cb26e8aab3684..05a29ef76adf0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHealthStatus.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHealthStatus.java @@ -8,24 +8,24 @@ /** Application gateway backend health status. */ public class ApplicationGatewayBackendHealthStatus extends ExpandableStringEnum { /** Unknown health status. */ - public static final ApplicationGatewayBackendHealthStatus UNKNOWN = - fromString(ApplicationGatewayBackendHealthServerHealth.UNKNOWN.toString()); + public static final ApplicationGatewayBackendHealthStatus UNKNOWN + = fromString(ApplicationGatewayBackendHealthServerHealth.UNKNOWN.toString()); /** The server is up. */ - public static final ApplicationGatewayBackendHealthStatus UP = - fromString(ApplicationGatewayBackendHealthServerHealth.UP.toString()); + public static final ApplicationGatewayBackendHealthStatus UP + = fromString(ApplicationGatewayBackendHealthServerHealth.UP.toString()); /** The server is down. */ - public static final ApplicationGatewayBackendHealthStatus DOWN = - fromString(ApplicationGatewayBackendHealthServerHealth.DOWN.toString()); + public static final ApplicationGatewayBackendHealthStatus DOWN + = fromString(ApplicationGatewayBackendHealthServerHealth.DOWN.toString()); /** Partial health status. */ - public static final ApplicationGatewayBackendHealthStatus PARTIAL = - fromString(ApplicationGatewayBackendHealthServerHealth.PARTIAL.toString()); + public static final ApplicationGatewayBackendHealthStatus PARTIAL + = fromString(ApplicationGatewayBackendHealthServerHealth.PARTIAL.toString()); /** The server is draining. */ - public static final ApplicationGatewayBackendHealthStatus DRAINING = - fromString(ApplicationGatewayBackendHealthServerHealth.DRAINING.toString()); + public static final ApplicationGatewayBackendHealthStatus DRAINING + = fromString(ApplicationGatewayBackendHealthServerHealth.DRAINING.toString()); /** The server is unhealthy. */ public static final ApplicationGatewayBackendHealthStatus UNHEALTHY = fromString("Unhealthy"); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfiguration.java index f63c45ad0f0cb..36479ecd4ca5d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfiguration.java @@ -14,10 +14,8 @@ /** A client-side representation of an application gateway's backend HTTP configuration. */ @Fluent() public interface ApplicationGatewayBackendHttpConfiguration - extends HasInnerModel, - ChildResource, - HasProtocol, - HasPort { + extends HasInnerModel, ChildResource, + HasProtocol, HasPort { /** @return authentication certificates associated with this backend HTTPS configuration */ Map authenticationCertificates(); @@ -284,17 +282,9 @@ interface WithAttachAndAuthCert extends WithAttach, WithAuthen * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface WithAttach - extends Attachable.InDefinition, - WithPort, - WithAffinity, - WithProtocol, - WithRequestTimeout, - WithProbe, - WithHostHeader, - WithConnectionDraining, - WithCookieName, - WithPath { + interface WithAttach extends Attachable.InDefinition, WithPort, + WithAffinity, WithProtocol, WithRequestTimeout, WithProbe, + WithHostHeader, WithConnectionDraining, WithCookieName, WithPath { } } @@ -304,10 +294,8 @@ interface WithAttach * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithAttachAndAuthCert { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithAttachAndAuthCert { } /** Grouping of application gateway backend HTTPS configuration update stages. */ @@ -528,18 +516,10 @@ interface WithAuthenticationCertificate { * The entirety of an application gateway backend HTTPS configuration update as part of an application gateway * update. */ - interface Update - extends Settable, - UpdateStages.WithPort, - UpdateStages.WithAffinity, - UpdateStages.WithProtocol, - UpdateStages.WithRequestTimeout, - UpdateStages.WithProbe, - UpdateStages.WithHostHeader, - UpdateStages.WithConnectionDraining, - UpdateStages.WithCookieName, - UpdateStages.WithPath, - UpdateStages.WithAuthenticationCertificate { + interface Update extends Settable, UpdateStages.WithPort, UpdateStages.WithAffinity, + UpdateStages.WithProtocol, UpdateStages.WithRequestTimeout, UpdateStages.WithProbe, UpdateStages.WithHostHeader, + UpdateStages.WithConnectionDraining, UpdateStages.WithCookieName, UpdateStages.WithPath, + UpdateStages.WithAuthenticationCertificate { } /** @@ -576,16 +556,9 @@ interface WithAttachAndAuthCert extends WithAttach, WithAuthen * definition */ interface WithAttach - extends Attachable.InUpdate, - WithPort, - WithAffinity, - WithProtocol, - WithRequestTimeout, - WithHostHeader, - WithConnectionDraining, - WithCookieName, - WithPath, - WithAuthenticationCertificate { + extends Attachable.InUpdate, WithPort, WithAffinity, WithProtocol, + WithRequestTimeout, WithHostHeader, WithConnectionDraining, + WithCookieName, WithPath, WithAuthenticationCertificate { } /** @@ -804,9 +777,7 @@ interface WithConnectionDraining { * * @param the stage of the parent application gateway update to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithAttachAndAuthCert { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithAttachAndAuthCert { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfigurationHealth.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfigurationHealth.java index 5c69cde4a6c7b..8fd418e02451c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfigurationHealth.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendHttpConfigurationHealth.java @@ -12,10 +12,8 @@ * A client-side representation of the health information of an application gateway backend HTTP settings configuration. */ @Fluent -public interface ApplicationGatewayBackendHttpConfigurationHealth - extends HasInnerModel, - HasParent, - HasName { +public interface ApplicationGatewayBackendHttpConfigurationHealth extends + HasInnerModel, HasParent, HasName { /** * @return the associated application gateway backend HTTP configuration settings this health information pertains diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendServerHealth.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendServerHealth.java index 632326285fbe1..7b3b4fcfeec17 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendServerHealth.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayBackendServerHealth.java @@ -11,7 +11,7 @@ @Fluent public interface ApplicationGatewayBackendServerHealth extends HasInnerModel, - HasParent { + HasParent { /** @return IP address of the server this health information pertains to */ String ipAddress(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayFrontend.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayFrontend.java index 8551ebe6116b5..8f78da38ad37a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayFrontend.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayFrontend.java @@ -11,12 +11,8 @@ /** A client-side representation of an application gateway frontend. */ @Fluent() -public interface ApplicationGatewayFrontend - extends HasInnerModel, - ChildResource, - HasPrivateIpAddress, - HasSubnet, - HasPublicIpAddress { +public interface ApplicationGatewayFrontend extends HasInnerModel, + ChildResource, HasPrivateIpAddress, HasSubnet, HasPublicIpAddress { /** @return true if the frontend is accessible via a public IP address, else false */ boolean isPublic(); @@ -98,10 +94,8 @@ interface WithAttach * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithPublicIPAddress { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithPublicIPAddress { } /** Grouping of application gateway frontend update stages. */ @@ -179,11 +173,8 @@ interface WithPrivateIP * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface WithAttach - extends Attachable.InUpdateAlt, - WithPublicIPAddress, - WithSubnet, - WithPrivateIP { + interface WithAttach extends Attachable.InUpdateAlt, WithPublicIPAddress, + WithSubnet, WithPrivateIP { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayIpConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayIpConfiguration.java index e43de9eae546f..fdd4d5e55b33e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayIpConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayIpConfiguration.java @@ -83,10 +83,8 @@ interface WithAttach extends Attachable.InDefinition { * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithSubnet, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithSubnet, + DefinitionStages.WithAttach { } /** Grouping of application gateway IP configuration update stages. */ @@ -179,9 +177,7 @@ interface WithAttach extends Attachable.InUpdate { * * @param the parent type */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithSubnet, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithSubnet, UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayListener.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayListener.java index 43b02fa6c3d0a..ea6701e69258d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayListener.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayListener.java @@ -11,15 +11,9 @@ /** A client-side representation of an application gateway's HTTP listener. */ @Fluent() -public interface ApplicationGatewayListener - extends HasInnerModel, - ChildResource, - HasSslCertificate, - HasPublicIpAddress, - HasProtocol, - HasHostname, - HasServerNameIndication, - HasSubnet { +public interface ApplicationGatewayListener extends HasInnerModel, + ChildResource, HasSslCertificate, HasPublicIpAddress, + HasProtocol, HasHostname, HasServerNameIndication, HasSubnet { /** @return the frontend IP configuration this listener is associated with. */ ApplicationGatewayFrontend frontend(); @@ -50,11 +44,8 @@ interface Blank extends WithFrontend { * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface WithAttach - extends Attachable.InDefinition, - WithProtocol, - WithHostname, - WithServerNameIndication { + interface WithAttach extends Attachable.InDefinition, WithProtocol, + WithHostname, WithServerNameIndication { } /** @@ -186,14 +177,10 @@ interface WithServerNameIndication * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithFrontend, - DefinitionStages.WithFrontendPort, - DefinitionStages.WithSslCertificate, - DefinitionStages.WithSslPassword, - DefinitionStages.WithHostname { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithFrontend, DefinitionStages.WithFrontendPort, + DefinitionStages.WithSslCertificate, DefinitionStages.WithSslPassword, + DefinitionStages.WithHostname { } /** Grouping of application gateway HTTP listener update stages. */ @@ -297,15 +284,9 @@ interface WithHostname extends HasHostname.UpdateStages.WithHostname { } /** The entirety of an application gateway HTTP listener update as part of an application gateway update. */ - interface Update - extends Settable, - UpdateStages.WithServerNameIndication, - UpdateStages.WithHostname, - UpdateStages.WithProtocol, - UpdateStages.WithSslCertificate, - UpdateStages.WithSslPassword, - UpdateStages.WithFrontendPort, - UpdateStages.WithFrontend { + interface Update extends Settable, UpdateStages.WithServerNameIndication, + UpdateStages.WithHostname, UpdateStages.WithProtocol, UpdateStages.WithSslCertificate, + UpdateStages.WithSslPassword, UpdateStages.WithFrontendPort, UpdateStages.WithFrontend { } /** @@ -454,10 +435,8 @@ interface WithServerNameIndication * definition */ interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithServerNameIndication, - UpdateDefinitionStages.WithHostname, - UpdateDefinitionStages.WithProtocol { + extends Attachable.InUpdate, UpdateDefinitionStages.WithServerNameIndication, + UpdateDefinitionStages.WithHostname, UpdateDefinitionStages.WithProtocol { } } @@ -468,11 +447,8 @@ interface WithAttach * definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithFrontend, - UpdateDefinitionStages.WithFrontendPort, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithSslCertificate, - UpdateDefinitionStages.WithSslPassword { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithFrontend, + UpdateDefinitionStages.WithFrontendPort, UpdateDefinitionStages.WithAttach, + UpdateDefinitionStages.WithSslCertificate, UpdateDefinitionStages.WithSslPassword { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayPathRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayPathRule.java index be8afe6a91bf1..5174e8674dfd8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayPathRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayPathRule.java @@ -134,10 +134,8 @@ interface WithAttach * definition */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithBackendHttpConfiguration, - DefinitionStages.WithBackend, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithBackendHttpConfiguration, + DefinitionStages.WithBackend, DefinitionStages.WithAttach { } /** The entirety of path rule of URL path map update as part of an application gateway update. */ @@ -250,11 +248,8 @@ interface WithAttach * @param the stage of the parent application gateway URL path map definition to return to after attaching * this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithBackendHttpConfiguration, - UpdateDefinitionStages.WithBackend, - UpdateDefinitionStages.WithPath, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithBackendHttpConfiguration, UpdateDefinitionStages.WithBackend, + UpdateDefinitionStages.WithPath, UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayProbe.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayProbe.java index 5087c41f11371..6cd2cb63ae1f6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayProbe.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayProbe.java @@ -12,10 +12,8 @@ /** A client-side representation of an application gateway probe. */ @Fluent() -public interface ApplicationGatewayProbe - extends HasInnerModel, - ChildResource, - HasProtocol { +public interface ApplicationGatewayProbe extends HasInnerModel, + ChildResource, HasProtocol { /** @return the number of seconds between probe retries */ int timeBetweenProbesInSeconds(); @@ -247,11 +245,8 @@ interface WithHealthyHttpResponseBodyContents { * definition */ interface WithAttach - extends Attachable.InDefinitionAlt, - WithInterval, - WithRetries, - WithHealthyHttpResponseStatusCodeRanges, - WithHealthyHttpResponseBodyContents { + extends Attachable.InDefinitionAlt, WithInterval, WithRetries, + WithHealthyHttpResponseStatusCodeRanges, WithHealthyHttpResponseBodyContents { } } @@ -261,13 +256,9 @@ interface WithAttach * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithProtocol, - DefinitionStages.WithPath, - DefinitionStages.WithHost, - DefinitionStages.WithTimeout { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithProtocol, DefinitionStages.WithPath, DefinitionStages.WithHost, + DefinitionStages.WithTimeout { } /** Grouping of application gateway probe update stages. */ @@ -426,16 +417,9 @@ interface WithHealthyHttpResponseBodyContents { } /** The entirety of an application gateway probe update as part of an application gateway update. */ - interface Update - extends Settable, - UpdateStages.WithProtocol, - UpdateStages.WithPath, - UpdateStages.WithHost, - UpdateStages.WithTimeout, - UpdateStages.WithInterval, - UpdateStages.WithRetries, - UpdateStages.WithHealthyHttpResponseStatusCodeRanges, - UpdateStages.WithHealthyHttpResponseBodyContents { + interface Update extends Settable, UpdateStages.WithProtocol, UpdateStages.WithPath, + UpdateStages.WithHost, UpdateStages.WithTimeout, UpdateStages.WithInterval, UpdateStages.WithRetries, + UpdateStages.WithHealthyHttpResponseStatusCodeRanges, UpdateStages.WithHealthyHttpResponseBodyContents { } /** Grouping of application gateway probe definition stages applicable as part of an application gateway update. */ @@ -628,11 +612,8 @@ interface WithHealthyHttpResponseBodyContents { * definition */ interface WithAttach - extends Attachable.InUpdateAlt, - WithInterval, - WithRetries, - WithHealthyHttpResponseStatusCodeRanges, - WithHealthyHttpResponseBodyContents { + extends Attachable.InUpdateAlt, WithInterval, WithRetries, + WithHealthyHttpResponseStatusCodeRanges, WithHealthyHttpResponseBodyContents { } } @@ -642,13 +623,9 @@ interface WithAttach * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithProtocol, - UpdateDefinitionStages.WithPath, - UpdateDefinitionStages.WithHost, - UpdateDefinitionStages.WithTimeout, - UpdateDefinitionStages.WithInterval { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithProtocol, + UpdateDefinitionStages.WithPath, UpdateDefinitionStages.WithHost, + UpdateDefinitionStages.WithTimeout, UpdateDefinitionStages.WithInterval { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRedirectConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRedirectConfiguration.java index 0433236b0aa3b..f34009c97316d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRedirectConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRedirectConfiguration.java @@ -148,12 +148,9 @@ interface WithAttach extends Attachable.InDefinition, WithQuer * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithAttachAndPath, - DefinitionStages.WithTarget, - DefinitionStages.WithType { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithAttachAndPath, DefinitionStages.WithTarget, + DefinitionStages.WithType { } /** Grouping of application gateway redirect configuration update stages. */ @@ -253,12 +250,8 @@ interface WithQueryStringIncluded { /** * The entirety of an application gateway redirect configuration update as part of an application gateway update. */ - interface Update - extends Settable, - UpdateStages.WithTarget, - UpdateStages.WithType, - UpdateStages.WithPathIncluded, - UpdateStages.WithQueryStringIncluded { + interface Update extends Settable, UpdateStages.WithTarget, UpdateStages.WithType, + UpdateStages.WithPathIncluded, UpdateStages.WithQueryStringIncluded { } /** @@ -380,11 +373,8 @@ interface WithAttach extends Attachable.InUpdate, WithQueryStr * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithAttachAndPath, - UpdateDefinitionStages.WithTarget, - UpdateDefinitionStages.WithType { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithAttachAndPath, + UpdateDefinitionStages.WithTarget, UpdateDefinitionStages.WithType { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRequestRoutingRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRequestRoutingRule.java index 885b7ea88fb8f..8bd55ae6510d7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRequestRoutingRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRequestRoutingRule.java @@ -13,16 +13,9 @@ /** A client-side representation of an application gateway request routing rule. */ @Fluent() -public interface ApplicationGatewayRequestRoutingRule - extends HasInnerModel, - ChildResource, - HasPublicIpAddress, - HasSslCertificate, - HasFrontendPort, - HasBackendPort, - HasHostname, - HasCookieBasedAffinity, - HasServerNameIndication { +public interface ApplicationGatewayRequestRoutingRule extends HasInnerModel, + ChildResource, HasPublicIpAddress, HasSslCertificate, + HasFrontendPort, HasBackendPort, HasHostname, HasCookieBasedAffinity, HasServerNameIndication { /** @return the redirect configuration associated with this request routing rule, if any */ ApplicationGatewayRedirectConfiguration redirectConfiguration(); @@ -70,12 +63,8 @@ interface Blank extends WithListenerOrFrontend { * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - WithHostname, - WithCookieBasedAffinity, - WithUrlPathMap, - WithPriority { + interface WithAttach extends Attachable.InDefinition, WithHostname, + WithCookieBasedAffinity, WithUrlPathMap, WithPriority { } /** @@ -176,9 +165,8 @@ interface WithFrontendPort { * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface WithSslCertificate - extends HasSslCertificate.DefinitionStages.WithSslCertificate< - WithBackendHttpConfigOrSniOrRedirect> { + interface WithSslCertificate extends + HasSslCertificate.DefinitionStages.WithSslCertificate> { } /** @@ -296,10 +284,8 @@ interface WithBackendOrAddress extends WithBackend, WithBacken * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface WithBackendHttpConfigurationOrSni - extends WithBackendHttpConfiguration, - HasServerNameIndication.DefinitionStages.WithServerNameIndication< - WithBackendHttpConfiguration> { + interface WithBackendHttpConfigurationOrSni extends WithBackendHttpConfiguration, + HasServerNameIndication.DefinitionStages.WithServerNameIndication> { } /** @@ -421,24 +407,17 @@ interface WithPriority { * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithFrontend, - DefinitionStages.WithListener, - DefinitionStages.WithFrontendPort, - DefinitionStages.WithListenerOrFrontend, - DefinitionStages.WithBackend, - DefinitionStages.WithBackendAddress, - DefinitionStages.WithBackendOrAddress, - DefinitionStages.WithBackendAddressOrAttach, - DefinitionStages.WithBackendHttpConfigOrRedirect, - DefinitionStages.WithBackendHttpConfiguration, - DefinitionStages.WithBackendHttpConfigurationOrSni, - DefinitionStages.WithSslCertificate, - DefinitionStages.WithBackendHttpConfigOrSniOrRedirect, - DefinitionStages.WithSslPassword>, - DefinitionStages.WithUrlPathMap { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithFrontend, DefinitionStages.WithListener, + DefinitionStages.WithFrontendPort, DefinitionStages.WithListenerOrFrontend, + DefinitionStages.WithBackend, DefinitionStages.WithBackendAddress, + DefinitionStages.WithBackendOrAddress, DefinitionStages.WithBackendAddressOrAttach, + DefinitionStages.WithBackendHttpConfigOrRedirect, + DefinitionStages.WithBackendHttpConfiguration, + DefinitionStages.WithBackendHttpConfigurationOrSni, DefinitionStages.WithSslCertificate, + DefinitionStages.WithBackendHttpConfigOrSniOrRedirect, + DefinitionStages.WithSslPassword>, + DefinitionStages.WithUrlPathMap { } /** Grouping of application gateway request routing rule update stages. */ @@ -543,15 +522,9 @@ interface WithPriority { } /** The entirety of an application gateway request routing rule update as part of an application gateway update. */ - interface Update - extends Settable, - UpdateStages.WithListener, - UpdateStages.WithBackend, - UpdateStages.WithBackendHttpConfiguration, - UpdateStages.WithSslCertificate, - UpdateStages.WithSslPassword, - UpdateStages.WithRedirectConfig, - UpdateStages.WithPriority { + interface Update extends Settable, UpdateStages.WithListener, UpdateStages.WithBackend, + UpdateStages.WithBackendHttpConfiguration, UpdateStages.WithSslCertificate, UpdateStages.WithSslPassword, + UpdateStages.WithRedirectConfig, UpdateStages.WithPriority { } /** @@ -575,12 +548,8 @@ interface Blank extends WithListenerOrFrontend { * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - WithHostname, - WithCookieBasedAffinity, - WithRedirectConfig, - WithPriority { + interface WithAttach extends Attachable.InUpdate, WithHostname, + WithCookieBasedAffinity, WithRedirectConfig, WithPriority { } /** @@ -727,9 +696,8 @@ interface WithFrontendPort { * * @param the next stage of the definition */ - interface WithSslCertificate - extends HasSslCertificate.UpdateDefinitionStages.WithSslCertificate< - WithBackendHttpConfigOrSniOrRedirect> { + interface WithSslCertificate extends + HasSslCertificate.UpdateDefinitionStages.WithSslCertificate> { } /** @@ -837,10 +805,8 @@ interface WithBackendOrAddress extends WithBackend, WithBacken * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface WithBackendHttpConfigurationOrSni - extends WithBackendHttpConfiguration, - HasServerNameIndication.UpdateDefinitionStages.WithServerNameIndication< - WithBackendHttpConfiguration> { + interface WithBackendHttpConfigurationOrSni extends WithBackendHttpConfiguration, + HasServerNameIndication.UpdateDefinitionStages.WithServerNameIndication> { } /** @@ -910,23 +876,17 @@ interface WithServerNameIndication * * @param the stage of the application gateway definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithFrontend, - UpdateDefinitionStages.WithListener, - UpdateDefinitionStages.WithFrontendPort, - UpdateDefinitionStages.WithListenerOrFrontend, - UpdateDefinitionStages.WithBackend, - UpdateDefinitionStages.WithBackendAddress, - UpdateDefinitionStages.WithBackendOrAddress, - UpdateDefinitionStages.WithBackendAddressOrAttach, - UpdateDefinitionStages.WithBackendHttpConfiguration, - UpdateDefinitionStages.WithBackendHttpConfigOrRedirect, - UpdateDefinitionStages.WithBackendHttpConfigurationOrSni, - UpdateDefinitionStages.WithBackendHttpConfigOrSniOrRedirect, - UpdateDefinitionStages.WithSslCertificate, - UpdateDefinitionStages.WithSslPassword< - UpdateDefinitionStages.WithBackendHttpConfigOrSniOrRedirect> { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithFrontend, + UpdateDefinitionStages.WithListener, UpdateDefinitionStages.WithFrontendPort, + UpdateDefinitionStages.WithListenerOrFrontend, UpdateDefinitionStages.WithBackend, + UpdateDefinitionStages.WithBackendAddress, UpdateDefinitionStages.WithBackendOrAddress, + UpdateDefinitionStages.WithBackendAddressOrAttach, + UpdateDefinitionStages.WithBackendHttpConfiguration, + UpdateDefinitionStages.WithBackendHttpConfigOrRedirect, + UpdateDefinitionStages.WithBackendHttpConfigurationOrSni, + UpdateDefinitionStages.WithBackendHttpConfigOrSniOrRedirect, + UpdateDefinitionStages.WithSslCertificate, + UpdateDefinitionStages.WithSslPassword> { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewaySslCertificate.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewaySslCertificate.java index 7455f73319c10..0c4075a34ca4a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewaySslCertificate.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewaySslCertificate.java @@ -101,11 +101,8 @@ interface WithPassword { * * @param the stage of the parent application gateway definition to return to after attaching */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithData, - DefinitionStages.WithPassword { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithData, DefinitionStages.WithPassword { } /** Grouping of application gateway SSL certificate update stages. */ @@ -195,9 +192,7 @@ interface WithPassword { * @param the stage of the parent application gateway definition to return to after attaching */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithData, - UpdateDefinitionStages.WithPassword, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithData, + UpdateDefinitionStages.WithPassword, UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayUrlPathMap.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayUrlPathMap.java index 58874ec67254b..f59fe7dead956 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayUrlPathMap.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayUrlPathMap.java @@ -159,12 +159,9 @@ interface WithAttach * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithBackendHttpConfiguration, - DefinitionStages.WithBackend, - DefinitionStages.WithPathRule, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, + DefinitionStages.WithBackendHttpConfiguration, DefinitionStages.WithBackend, + DefinitionStages.WithPathRule, DefinitionStages.WithAttach { } /** The entirety of an application gateway URL path map update as part of an application gateway update. */ @@ -371,11 +368,9 @@ interface WithAttach * definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithBackendOrAddress, - UpdateDefinitionStages.WithBackendHttpConfiguration, - UpdateDefinitionStages.WithBackendAddressOrPath, - UpdateDefinitionStages.WithPathRule, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithBackendOrAddress, + UpdateDefinitionStages.WithBackendHttpConfiguration, + UpdateDefinitionStages.WithBackendAddressOrPath, UpdateDefinitionStages.WithPathRule, + UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateways.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateways.java index 792a2189e3ab2..2347197d6c360 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateways.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGateways.java @@ -21,16 +21,10 @@ /** Entry point to application gateway management API in Azure. */ @Fluent() public interface ApplicationGateways - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Starts the specified application gateways. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroup.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroup.java index 2e98ee0fcb7c2..63686b1fb423e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroup.java @@ -14,10 +14,8 @@ /** Application security group. */ @Fluent -public interface ApplicationSecurityGroup - extends GroupableResource, - Refreshable, - Updatable { +public interface ApplicationSecurityGroup extends GroupableResource, + Refreshable, Updatable { /** * @return the resource GUID property of the application security group resource. It uniquely identifies a resource, * even if the user changes its name or migrate the resource across subscriptions or resource groups. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroups.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroups.java index 5722a6dc58ec3..67a02ceabefbd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationSecurityGroups.java @@ -17,15 +17,9 @@ /** Entry point to application security group management. */ @Fluent -public interface ApplicationSecurityGroups - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface ApplicationSecurityGroups extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AvailableProviders.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AvailableProviders.java index dc45bbcac3a9f..3a4565fc3354b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AvailableProviders.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AvailableProviders.java @@ -20,10 +20,8 @@ public interface AvailableProviders Map providersByCountry(); /** The entirety of available providers parameters definition. */ - interface Definition - extends DefinitionStages.WithExecuteAndCountry, - DefinitionStages.WithExecuteAndState, - DefinitionStages.WithExecuteAndCity { + interface Definition extends DefinitionStages.WithExecuteAndCountry, DefinitionStages.WithExecuteAndState, + DefinitionStages.WithExecuteAndCity { } /** Grouping of available providers parameters definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AzureReachabilityReport.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AzureReachabilityReport.java index 77e06ea91db77..dbe6b9bf30af5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AzureReachabilityReport.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/AzureReachabilityReport.java @@ -12,10 +12,8 @@ /** An immutable client-side representation of Azure reachability report details. */ @Fluent -public interface AzureReachabilityReport - extends Executable, - HasInnerModel, - HasParent { +public interface AzureReachabilityReport extends Executable, + HasInnerModel, HasParent { /** @return the aggregation level of Azure reachability report. Can be Country, State or City. */ String aggregationLevel(); @@ -24,15 +22,13 @@ public interface AzureReachabilityReport /** @return list of Azure reachability report items. */ List reachabilityReport(); + /** @return parameters used to query available internet providers */ AzureReachabilityReportParameters azureReachabilityReportParameters(); /** The entirety of Azure reachability report parameters definition. */ - interface Definition - extends DefinitionStages.WithProviderLocation, - DefinitionStages.WithStartTime, - DefinitionStages.WithEndTime, - DefinitionStages.WithExecute { + interface Definition extends DefinitionStages.WithProviderLocation, DefinitionStages.WithStartTime, + DefinitionStages.WithEndTime, DefinitionStages.WithExecute { } /** Grouping of Azure reachability report definition stages. */ @@ -44,12 +40,14 @@ interface WithProviderLocation { * @return the AzureReachabilityReport object itself */ WithStartTime withProviderLocation(String country); + /** * @param country the name of the country * @param state the name of the state * @return the AzureReachabilityReport object itself */ WithStartTime withProviderLocation(String country, String state); + /** * @param country the name of the country * @param state the name of the state @@ -105,10 +103,8 @@ interface WithProviders { * The stage of the definition which contains all the minimum required inputs for execution, but also allows for * any other optional settings to be specified. */ - interface WithExecute - extends Executable, - DefinitionStages.WithAzureLocations, - DefinitionStages.WithProviders { + interface WithExecute extends Executable, DefinitionStages.WithAzureLocations, + DefinitionStages.WithProviders { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitor.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitor.java index 6278e5a78e121..4e7de8b72ea30 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitor.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitor.java @@ -82,11 +82,8 @@ public interface ConnectionMonitor extends HasInnerModel queryAsync(); /** The entirety of the connection monitor definition. */ - interface Definition - extends DefinitionStages.WithSource, - DefinitionStages.WithDestination, - DefinitionStages.WithDestinationPort, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.WithSource, DefinitionStages.WithDestination, + DefinitionStages.WithDestinationPort, DefinitionStages.WithCreate { } /** Grouping of connection monitor definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitors.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitors.java index 30db728d2fb7b..a68d58934aec2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitors.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectionMonitors.java @@ -10,9 +10,6 @@ /** Entry point to connection monitors management API in Azure. */ @Fluent -public interface ConnectionMonitors - extends SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName { +public interface ConnectionMonitors extends SupportsCreating, + SupportsListing, SupportsGettingByName, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectivityCheck.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectivityCheck.java index 6b2783c9143e4..7795b546e998a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectivityCheck.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ConnectivityCheck.java @@ -35,11 +35,8 @@ public interface ConnectivityCheck extends Executable, HasPar int probesFailed(); /** The entirety of connectivity check parameters definition. */ - interface Definition - extends DefinitionStages.ToDestination, - DefinitionStages.ToDestinationPort, - DefinitionStages.FromSourceVirtualMachine, - DefinitionStages.WithExecute { + interface Definition extends DefinitionStages.ToDestination, DefinitionStages.ToDestinationPort, + DefinitionStages.FromSourceVirtualMachine, DefinitionStages.WithExecute { } /** Grouping of connectivity check parameters definition stages. */ @@ -51,6 +48,7 @@ interface FromSourceVirtualMachine { * @return next definition stage */ WithExecute fromSourceVirtualMachine(String resourceId); + /** * @param vm virtual machine from which a connectivity check will be initiated * @return next definition stage @@ -95,10 +93,8 @@ interface FromSourcePort { * The stage of the definition which contains all the minimum required inputs for execution, but also allows for * any other optional settings to be specified. */ - interface WithExecute - extends Executable, - FromSourcePort, - HasProtocol.DefinitionStages.WithProtocol { + interface WithExecute extends Executable, FromSourcePort, + HasProtocol.DefinitionStages.WithProtocol { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlan.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlan.java index 82c0126a014c8..46e563770ccf9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlan.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlan.java @@ -16,10 +16,8 @@ /** DDoS protection plan. */ @Fluent -public interface DdosProtectionPlan - extends GroupableResource, - Refreshable, - Updatable { +public interface DdosProtectionPlan extends GroupableResource, + Refreshable, Updatable { /** * @return the resource GUID property of the DDoS protection plan resource. It uniquely identifies a resource, even * if the user changes its name or migrate the resource across subscriptions or resource groups. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlans.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlans.java index dced3184b0e18..e574a623f9484 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlans.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/DdosProtectionPlans.java @@ -18,14 +18,8 @@ /** Entry point to DDoS protection plans management. */ @Fluent public interface DdosProtectionPlans - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuit.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuit.java index 56c9ab7a34a56..2fc3decccd290 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuit.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuit.java @@ -15,11 +15,8 @@ /** Entry point for Express Route Circuit management API in Azure. */ @Fluent -public interface ExpressRouteCircuit - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface ExpressRouteCircuit extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { // Actions @@ -64,14 +61,9 @@ public interface ExpressRouteCircuit String provisioningState(); /** The entirety of the express route circuit definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithServiceProvider, - DefinitionStages.WithPeeringLocation, - DefinitionStages.WithBandwidth, - DefinitionStages.WithSku, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, + DefinitionStages.WithServiceProvider, DefinitionStages.WithPeeringLocation, DefinitionStages.WithBandwidth, + DefinitionStages.WithSku, DefinitionStages.WithCreate { } /** Grouping of express route circuit definition stages. */ @@ -153,11 +145,8 @@ interface WithAuthorization { * The stage of the express route circuit definition which contains all the minimum required inputs for the * resource to be created, but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithAllowClassicOperations, - WithAuthorization { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + WithAllowClassicOperations, WithAuthorization { } } @@ -216,11 +205,7 @@ interface WithAuthorization { /** The template for a express route circuit update operation, containing all the settings that can be modified. */ interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithBandwidth, - UpdateStages.WithSku, - UpdateStages.WithAllowClassicOperations, - UpdateStages.WithAuthorization { + extends Appliable, Resource.UpdateWithTags, UpdateStages.WithBandwidth, + UpdateStages.WithSku, UpdateStages.WithAllowClassicOperations, UpdateStages.WithAuthorization { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeering.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeering.java index 0b514e1e5a1c6..8302f1df06842 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeering.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeering.java @@ -15,10 +15,8 @@ /** Client-side representation of express route circuit peering object, associated with express route circuit. */ @Fluent public interface ExpressRouteCircuitPeering - extends IndependentChild, - HasInnerModel, - Refreshable, - Updatable { + extends IndependentChild, HasInnerModel, + Refreshable, Updatable { // Getters @@ -76,14 +74,9 @@ public interface ExpressRouteCircuitPeering Ipv6ExpressRouteCircuitPeeringConfig ipv6PeeringConfig(); /** The entirety of the express route circuit peering definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAdvertisedPublicPrefixes, - DefinitionStages.WithPrimaryPeerAddressPrefix, - DefinitionStages.WithSecondaryPeerAddressPrefix, - DefinitionStages.WithVlanId, - DefinitionStages.WithPeerAsn, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAdvertisedPublicPrefixes, + DefinitionStages.WithPrimaryPeerAddressPrefix, DefinitionStages.WithSecondaryPeerAddressPrefix, + DefinitionStages.WithVlanId, DefinitionStages.WithPeerAsn, DefinitionStages.WithCreate { } /** Grouping of express route circuit peering definition stages. */ @@ -157,13 +150,9 @@ interface WithCreate extends Creatable { } /** Grouping of express route circuit peering update stages. */ - interface Update - extends Appliable, - UpdateStages.WithAdvertisedPublicPrefixes, - UpdateStages.WithPrimaryPeerAddressPrefix, - UpdateStages.WithSecondaryPeerAddressPrefix, - UpdateStages.WithVlanId, - UpdateStages.WithPeerAsn { + interface Update extends Appliable, UpdateStages.WithAdvertisedPublicPrefixes, + UpdateStages.WithPrimaryPeerAddressPrefix, UpdateStages.WithSecondaryPeerAddressPrefix, UpdateStages.WithVlanId, + UpdateStages.WithPeerAsn { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeerings.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeerings.java index 11a45324718f2..f1b09713193d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeerings.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitPeerings.java @@ -12,13 +12,9 @@ /** Entry point for express route circuit peerings management API in Azure. */ @Fluent -public interface ExpressRouteCircuitPeerings - extends SupportsListing, - SupportsGettingByName, - SupportsGettingById, - SupportsDeletingByName, - SupportsDeletingById, - HasParent { +public interface ExpressRouteCircuitPeerings extends SupportsListing, + SupportsGettingByName, SupportsGettingById, + SupportsDeletingByName, SupportsDeletingById, HasParent { /** * Begins definition of Azure private peering. * diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitSkuType.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitSkuType.java index 4c5762f67aa7c..b9ba3594f3d71 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitSkuType.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuitSkuType.java @@ -12,18 +12,17 @@ public class ExpressRouteCircuitSkuType { private static final Map VALUES_BY_NAME = new HashMap<>(); /** Static value for Standard sku tier and MeteredData sku family. */ - public static final ExpressRouteCircuitSkuType STANDARD_METEREDDATA = - new ExpressRouteCircuitSkuType(ExpressRouteCircuitSkuTier.STANDARD, ExpressRouteCircuitSkuFamily.METERED_DATA); + public static final ExpressRouteCircuitSkuType STANDARD_METEREDDATA = new ExpressRouteCircuitSkuType( + ExpressRouteCircuitSkuTier.STANDARD, ExpressRouteCircuitSkuFamily.METERED_DATA); /** Static value for Standard sku tier and UnlimitedData sku family. */ - public static final ExpressRouteCircuitSkuType STANDARD_UNLIMITEDDATA = - new ExpressRouteCircuitSkuType( - ExpressRouteCircuitSkuTier.STANDARD, ExpressRouteCircuitSkuFamily.UNLIMITED_DATA); + public static final ExpressRouteCircuitSkuType STANDARD_UNLIMITEDDATA = new ExpressRouteCircuitSkuType( + ExpressRouteCircuitSkuTier.STANDARD, ExpressRouteCircuitSkuFamily.UNLIMITED_DATA); /** Static value for Premium sku tier and MeteredData sku family. */ - public static final ExpressRouteCircuitSkuType PREMIUM_METEREDDATA = - new ExpressRouteCircuitSkuType(ExpressRouteCircuitSkuTier.PREMIUM, ExpressRouteCircuitSkuFamily.METERED_DATA); + public static final ExpressRouteCircuitSkuType PREMIUM_METEREDDATA + = new ExpressRouteCircuitSkuType(ExpressRouteCircuitSkuTier.PREMIUM, ExpressRouteCircuitSkuFamily.METERED_DATA); /** Static value for Premium sku tier and UnlimitedData sku family. */ - public static final ExpressRouteCircuitSkuType PREMIUM_UNLIMITEDDATA = - new ExpressRouteCircuitSkuType(ExpressRouteCircuitSkuTier.PREMIUM, ExpressRouteCircuitSkuFamily.UNLIMITED_DATA); + public static final ExpressRouteCircuitSkuType PREMIUM_UNLIMITEDDATA = new ExpressRouteCircuitSkuType( + ExpressRouteCircuitSkuTier.PREMIUM, ExpressRouteCircuitSkuFamily.UNLIMITED_DATA); /** the SKU corresponding to this type. */ private final ExpressRouteCircuitSku sku; @@ -44,12 +43,11 @@ public static ExpressRouteCircuitSkuType[] values() { * @param skuFamily an SKU family */ public ExpressRouteCircuitSkuType(ExpressRouteCircuitSkuTier skuTier, ExpressRouteCircuitSkuFamily skuFamily) { - this( - new ExpressRouteCircuitSku() - .withName( - (skuTier == null ? "" : skuTier.toString()) + "_" + (skuFamily == null ? "" : skuFamily.toString())) - .withTier(skuTier) - .withFamily(skuFamily)); + this(new ExpressRouteCircuitSku() + .withName( + (skuTier == null ? "" : skuTier.toString()) + "_" + (skuFamily == null ? "" : skuFamily.toString())) + .withTier(skuTier) + .withFamily(skuFamily)); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuits.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuits.java index 0295f5940f1a6..1594b0697aecc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuits.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCircuits.java @@ -16,14 +16,8 @@ /** Entry point to express route circuits management API in Azure. */ @Fluent -public interface ExpressRouteCircuits - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - HasManager { +public interface ExpressRouteCircuits extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsBatchCreation, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnection.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnection.java index fa2319270ddf6..78046f1ea299e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnection.java @@ -14,11 +14,9 @@ /** Entry point for Express Route Cross Connection management API in Azure. */ @Fluent -public interface ExpressRouteCrossConnection - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface ExpressRouteCrossConnection extends + GroupableResource, Refreshable, + Updatable, UpdatableWithTags { /** @return entry point to manage express route peerings associated with express route circuit */ ExpressRouteCrossConnectionPeerings peerings(); @@ -84,10 +82,7 @@ interface WithServiceProviderNotes { * The template for a express route cross connection update operation, containing all the settings that can be * modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithServiceProviderProviosioningState, - UpdateStages.WithServiceProviderNotes { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithServiceProviderProviosioningState, UpdateStages.WithServiceProviderNotes { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeering.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeering.java index f7bb4d89884da..4b80aee5dcae3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeering.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeering.java @@ -18,10 +18,8 @@ */ @Fluent public interface ExpressRouteCrossConnectionPeering - extends IndependentChild, - HasInnerModel, - Refreshable, - Updatable { + extends IndependentChild, HasInnerModel, + Refreshable, Updatable { /** @return the peering type */ ExpressRoutePeeringType peeringType(); @@ -68,16 +66,10 @@ public interface ExpressRouteCrossConnectionPeering Ipv6ExpressRouteCircuitPeeringConfig ipv6PeeringConfig(); /** The entirety of the express route Cross Connection peering definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAdvertisedPublicPrefixes, - DefinitionStages.WithCustomerASN, - DefinitionStages.WithRoutingRegistryName, - DefinitionStages.WithPrimaryPeerAddressPrefix, - DefinitionStages.WithSecondaryPeerAddressPrefix, - DefinitionStages.WithVlanId, - DefinitionStages.WithPeerASN, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAdvertisedPublicPrefixes, + DefinitionStages.WithCustomerASN, DefinitionStages.WithRoutingRegistryName, + DefinitionStages.WithPrimaryPeerAddressPrefix, DefinitionStages.WithSecondaryPeerAddressPrefix, + DefinitionStages.WithVlanId, DefinitionStages.WithPeerASN, DefinitionStages.WithCreate { } /** Grouping of express route Cross Connection peering definition stages. */ @@ -214,26 +206,16 @@ interface WithState { * The stage of the Express Route Cross Connection Peering definition which contains all the minimum required * inputs for the resource to be created, but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithSharedKey, - DefinitionStages.WithIpv6PeeringConfig, - DefinitionStages.WithState { + interface WithCreate extends Creatable, DefinitionStages.WithSharedKey, + DefinitionStages.WithIpv6PeeringConfig, DefinitionStages.WithState { } } /** Grouping of express route cross connection peering update stages. */ - interface Update - extends Appliable, - UpdateStages.WithAdvertisedPublicPrefixes, - UpdateStages.WithCustomerASN, - UpdateStages.WithRoutingRegistryName, - UpdateStages.WithPrimaryPeerAddressPrefix, - UpdateStages.WithSecondaryPeerAddressPrefix, - UpdateStages.WithVlanId, - UpdateStages.WithPeerASN, - UpdateStages.WithIpv6PeeringConfig, - UpdateStages.WithState { + interface Update extends Appliable, UpdateStages.WithAdvertisedPublicPrefixes, + UpdateStages.WithCustomerASN, UpdateStages.WithRoutingRegistryName, UpdateStages.WithPrimaryPeerAddressPrefix, + UpdateStages.WithSecondaryPeerAddressPrefix, UpdateStages.WithVlanId, UpdateStages.WithPeerASN, + UpdateStages.WithIpv6PeeringConfig, UpdateStages.WithState { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeerings.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeerings.java index 21963ba6b3054..7af26cabd30cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeerings.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnectionPeerings.java @@ -12,13 +12,9 @@ /** Entry point for express route cross connection peerings management API in Azure. */ @Fluent -public interface ExpressRouteCrossConnectionPeerings - extends SupportsListing, - SupportsGettingByName, - SupportsGettingById, - SupportsDeletingByName, - SupportsDeletingById, - HasParent { +public interface ExpressRouteCrossConnectionPeerings extends SupportsListing, + SupportsGettingByName, SupportsGettingById, + SupportsDeletingByName, SupportsDeletingById, HasParent { /** * Begins definition of Azure private peering. * diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnections.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnections.java index cab0f2c88b0ec..15c7708c16be3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnections.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ExpressRouteCrossConnections.java @@ -13,9 +13,7 @@ /** Entry point to express route crosss connections management API in Azure. */ @Fluent public interface ExpressRouteCrossConnections - extends SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - HasManager { + extends SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/FlowLogSettings.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/FlowLogSettings.java index 8e00e21352750..0cfbae9b84341 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/FlowLogSettings.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/FlowLogSettings.java @@ -14,11 +14,8 @@ * Client-side representation of the configuration of flow log, associated with network watcher and an Azure resource. */ @Fluent -public interface FlowLogSettings - extends HasParent, - HasInnerModel, - Updatable, - Refreshable { +public interface FlowLogSettings extends HasParent, HasInnerModel, + Updatable, Refreshable { /** * Get the ID of the resource to configure for flow logging. * @@ -102,10 +99,7 @@ interface WithRetentionPolicy { * *

Call {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - UpdateStages.WithEnabled, - UpdateStages.WithStorageAccount, - UpdateStages.WithRetentionPolicy { + interface Update extends Appliable, UpdateStages.WithEnabled, UpdateStages.WithStorageAccount, + UpdateStages.WithRetentionPolicy { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Ipv6PeeringConfig.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Ipv6PeeringConfig.java index 70215c7c7de16..869c6f17d90db 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Ipv6PeeringConfig.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Ipv6PeeringConfig.java @@ -132,13 +132,10 @@ interface WithAttach extends Attachable.InDefinition, WithRout * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithPrimaryPeerAddressPrefix, - DefinitionStages.WithSecondaryPeerAddressPrefix, - DefinitionStages.WithCustomerASN, - DefinitionStages.WithRoutingRegistryName { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithPrimaryPeerAddressPrefix, + DefinitionStages.WithSecondaryPeerAddressPrefix, DefinitionStages.WithCustomerASN, + DefinitionStages.WithRoutingRegistryName { } /** Grouping of public frontend update stages. */ @@ -235,13 +232,9 @@ interface WithRouteFilter { /** The entirety of a public frontend update as part of an Internet-facing load balancer update. */ interface Update - extends Settable, - UpdateStages.WithAdvertisedPublicPrefixes, - UpdateStages.WithPrimaryPeerAddressPrefix, - UpdateStages.WithSecondaryPeerAddressPrefix, - UpdateStages.WithCustomerASN, - UpdateStages.WithRoutingRegistryName, - UpdateStages.WithRouteFilter { + extends Settable, UpdateStages.WithAdvertisedPublicPrefixes, + UpdateStages.WithPrimaryPeerAddressPrefix, UpdateStages.WithSecondaryPeerAddressPrefix, + UpdateStages.WithCustomerASN, UpdateStages.WithRoutingRegistryName, UpdateStages.WithRouteFilter { } /** Grouping of public frontend definition stages applicable as part of an Internet-facing load balancer update. */ @@ -370,13 +363,10 @@ interface WithAttach extends Attachable.InUpdate, WithRouteFil * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithAdvertisedPublicPrefixes, - UpdateDefinitionStages.WithPrimaryPeerAddressPrefix, - UpdateDefinitionStages.WithSecondaryPeerAddressPrefix, - UpdateDefinitionStages.WithCustomerASN, - UpdateDefinitionStages.WithRoutingRegistryName { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithAdvertisedPublicPrefixes, + UpdateDefinitionStages.WithPrimaryPeerAddressPrefix, + UpdateDefinitionStages.WithSecondaryPeerAddressPrefix, UpdateDefinitionStages.WithCustomerASN, + UpdateDefinitionStages.WithRoutingRegistryName { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancer.java index a4fcb890d6fe2..ca846769a8458 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancer.java @@ -16,12 +16,8 @@ /** Entry point for load balancer management API in Azure. */ @Fluent -public interface LoadBalancer - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags, - HasLoadBalancingRules { +public interface LoadBalancer extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags, HasLoadBalancingRules { // Getters @@ -78,18 +74,11 @@ public interface LoadBalancer Map outboundRules(); /** The entirety of the load balancer definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.WithBackend, - DefinitionStages.WithLoadBalancingRule, - DefinitionStages.WithLBRuleOrNat, - DefinitionStages.WithLBRuleOrNatOrCreate, - DefinitionStages.WithCreateAndInboundNatPool, - DefinitionStages.WithCreateAndInboundNatRule, - DefinitionStages.WithCreateAndOutboundRule, - DefinitionStages.WithCreateAndNatChoice { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.WithBackend, DefinitionStages.WithLoadBalancingRule, DefinitionStages.WithLBRuleOrNat, + DefinitionStages.WithLBRuleOrNatOrCreate, DefinitionStages.WithCreateAndInboundNatPool, + DefinitionStages.WithCreateAndInboundNatRule, DefinitionStages.WithCreateAndOutboundRule, + DefinitionStages.WithCreateAndNatChoice { } /** Grouping of load balancer definition stages. */ @@ -134,7 +123,8 @@ interface WithPublicFrontend { * @param name the name for the frontend * @return the first stage of a new frontend definition */ - LoadBalancerPublicFrontend.DefinitionStages.Blank definePublicFrontend(String name); + LoadBalancerPublicFrontend.DefinitionStages.Blank + definePublicFrontend(String name); } /** The stage of a load balancer definition allowing to add a backend. */ @@ -214,13 +204,8 @@ interface WithSku { * The stage of a load balancer definition containing all the required inputs for the resource to be created, * but also allowing for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithBackend, - WithFrontend, - WithProbe, - WithSku { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, WithBackend, + WithFrontend, WithProbe, WithSku { } /** @@ -241,7 +226,7 @@ interface WithCreateAndInboundNatRule extends WithCreate, WithInboundNatRule { /** * The stage of a load balancer definition allowing to create the load balancer or add an outbound rule */ - interface WithCreateAndOutboundRule extends WithCreate, WithOutboundRule { + interface WithCreateAndOutboundRule extends WithCreate, WithOutboundRule { } /** The stage of a load balancer definition allowing to create a new inbound NAT rule. */ @@ -252,8 +237,8 @@ interface WithInboundNatRule { * @param name the name of the inbound NAT rule * @return the first stage of the new inbound NAT rule definition */ - LoadBalancerInboundNatRule.DefinitionStages.Blank defineInboundNatRule( - String name); + LoadBalancerInboundNatRule.DefinitionStages.Blank + defineInboundNatRule(String name); } /** @@ -266,7 +251,8 @@ interface WithOutboundRule { * @param name the name of the outbound rule * @return the first stage of the new outbound rule definition */ - LoadBalancerOutboundRule.DefinitionStages.Blank defineOutboundRule(String name); + LoadBalancerOutboundRule.DefinitionStages.Blank + defineOutboundRule(String name); } /** @@ -283,8 +269,8 @@ interface WithInboundNatPool { * @param name the name of the inbound NAT pool * @return the first stage of the new inbound NAT pool definition */ - LoadBalancerInboundNatPool.DefinitionStages.Blank defineInboundNatPool( - String name); + LoadBalancerInboundNatPool.DefinitionStages.Blank + defineInboundNatPool(String name); } } @@ -553,16 +539,9 @@ interface WithOutboundRule { } /** The template for a load balancer update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithProbe, - UpdateStages.WithBackend, - UpdateStages.WithLoadBalancingRule, - UpdateStages.WithPublicFrontend, - UpdateStages.WithPrivateFrontend, - UpdateStages.WithOutboundRule, - UpdateStages.WithInboundNatRule, - UpdateStages.WithInboundNatPool { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithProbe, + UpdateStages.WithBackend, UpdateStages.WithLoadBalancingRule, UpdateStages.WithPublicFrontend, + UpdateStages.WithPrivateFrontend, UpdateStages.WithOutboundRule, UpdateStages.WithInboundNatRule, + UpdateStages.WithInboundNatPool { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerHttpProbe.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerHttpProbe.java index ac8bce7f9fdef..99e9a91555ea3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerHttpProbe.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerHttpProbe.java @@ -31,11 +31,8 @@ interface Blank extends WithRequestPath { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - WithPort, - WithIntervalInSeconds, - WithNumberOfProbes { + interface WithAttach extends Attachable.InDefinition, WithPort, + WithIntervalInSeconds, WithNumberOfProbes { } /** @@ -105,10 +102,8 @@ interface WithNumberOfProbes { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithRequestPath { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithRequestPath { } /** Grouping of probe update stages. */ @@ -162,12 +157,8 @@ interface WithRequestPath { } /** The entirety of a probe update as part of a load balancer update. */ - interface Update - extends Settable, - UpdateStages.WithIntervalInSeconds, - UpdateStages.WithNumberOfProbes, - UpdateStages.WithPort, - UpdateStages.WithRequestPath { + interface Update extends Settable, UpdateStages.WithIntervalInSeconds, + UpdateStages.WithNumberOfProbes, UpdateStages.WithPort, UpdateStages.WithRequestPath { } /** Grouping of probe definition stages applicable as part of a load balancer update. */ @@ -188,11 +179,8 @@ interface Blank extends WithRequestPath { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - WithPort, - WithIntervalInSeconds, - WithNumberOfProbes { + interface WithAttach extends Attachable.InUpdate, WithPort, + WithIntervalInSeconds, WithNumberOfProbes { } /** @@ -262,9 +250,7 @@ interface WithNumberOfProbes { * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithRequestPath { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithRequestPath { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatPool.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatPool.java index 8ac39b0fb3325..e717f554a1523 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatPool.java @@ -10,12 +10,8 @@ /** A client-side representation of an inbound NAT pool. */ @Fluent() -public interface LoadBalancerInboundNatPool - extends HasFrontend, - HasBackendPort, - HasProtocol, - HasInnerModel, - ChildResource { +public interface LoadBalancerInboundNatPool extends HasFrontend, HasBackendPort, HasProtocol, + HasInnerModel, ChildResource { /** @return the starting frontend port number */ int frontendPortRangeStart(); @@ -95,13 +91,9 @@ interface WithBackendPort * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithProtocol, - DefinitionStages.WithFrontend, - DefinitionStages.WithFrontendPortRange, - DefinitionStages.WithBackendPort { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithProtocol, DefinitionStages.WithFrontend, + DefinitionStages.WithFrontendPortRange, DefinitionStages.WithBackendPort { } /** Grouping of inbound NAT pool update stages. */ @@ -137,12 +129,8 @@ interface WithBackendPort extends HasBackendPort.UpdateStages.WithBackendPort, - UpdateStages.WithProtocol, - UpdateStages.WithFrontend, - UpdateStages.WithBackendPort, - UpdateStages.WithFrontendPortRange { + interface Update extends Settable, UpdateStages.WithProtocol, UpdateStages.WithFrontend, + UpdateStages.WithBackendPort, UpdateStages.WithFrontendPortRange { } /** Grouping of inbound NAT pool definition stages applicable as part of a load balancer update. */ @@ -217,11 +205,8 @@ interface WithBackendPort * @param the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithProtocol, - UpdateDefinitionStages.WithFrontend, - UpdateDefinitionStages.WithFrontendPortRange, - UpdateDefinitionStages.WithBackendPort { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAttach, + UpdateDefinitionStages.WithProtocol, UpdateDefinitionStages.WithFrontend, + UpdateDefinitionStages.WithFrontendPortRange, UpdateDefinitionStages.WithBackendPort { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatRule.java index ac0407a67874f..cccf0bf1edf59 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerInboundNatRule.java @@ -11,14 +11,8 @@ /** An immutable client-side representation of an inbound NAT rule. */ @Fluent() -public interface LoadBalancerInboundNatRule - extends HasFrontend, - HasBackendPort, - HasProtocol, - HasFloatingIP, - HasFrontendPort, - HasInnerModel, - ChildResource { +public interface LoadBalancerInboundNatRule extends HasFrontend, HasBackendPort, HasProtocol, + HasFloatingIP, HasFrontendPort, HasInnerModel, ChildResource { /** @return the name of the IP configuration within the network interface associated with this NAT rule */ String backendNicIpConfigurationName(); @@ -48,10 +42,8 @@ interface Blank extends WithProtocol { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithBackendPort, - DefinitionStages.WithFloatingIP, - DefinitionStages.WithIdleTimeout { + extends Attachable.InDefinition, DefinitionStages.WithBackendPort, + DefinitionStages.WithFloatingIP, DefinitionStages.WithIdleTimeout { } /** @@ -119,12 +111,9 @@ interface WithIdleTimeout { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithProtocol, - DefinitionStages.WithFrontend, - DefinitionStages.WithFrontendPort, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithProtocol, + DefinitionStages.WithFrontend, DefinitionStages.WithFrontendPort, + DefinitionStages.WithAttach { } /** Grouping of inbound NAT rule update stages. */ @@ -167,14 +156,9 @@ interface WithIdleTimeout { } /** The entirety of an inbound NAT rule update as part of a load balancer update. */ - interface Update - extends Settable, - UpdateStages.WithBackendPort, - UpdateStages.WithFloatingIP, - UpdateStages.WithFrontend, - UpdateStages.WithFrontendPort, - UpdateStages.WithIdleTimeout, - UpdateStages.WithProtocol { + interface Update extends Settable, UpdateStages.WithBackendPort, UpdateStages.WithFloatingIP, + UpdateStages.WithFrontend, UpdateStages.WithFrontendPort, UpdateStages.WithIdleTimeout, + UpdateStages.WithProtocol { } /** Grouping of inbound NAT rule definition stages as part of a load balancer update. */ @@ -196,10 +180,8 @@ interface Blank extends WithProtocol { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithBackendPort, - UpdateDefinitionStages.WithFloatingIP, - UpdateDefinitionStages.WithIdleTimeout { + extends Attachable.InUpdate, UpdateDefinitionStages.WithBackendPort, + UpdateDefinitionStages.WithFloatingIP, UpdateDefinitionStages.WithIdleTimeout { } /** @@ -269,11 +251,8 @@ interface WithIdleTimeout { * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithProtocol, - UpdateDefinitionStages.WithFrontend, - UpdateDefinitionStages.WithFrontendPort, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithProtocol, UpdateDefinitionStages.WithFrontend, + UpdateDefinitionStages.WithFrontendPort, UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerOutboundRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerOutboundRule.java index 5694e9bed5f35..a94dece7b26d2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerOutboundRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerOutboundRule.java @@ -13,10 +13,8 @@ import java.util.Map; /** An immutable client-side representation of an outbound rule. */ -public interface LoadBalancerOutboundRule - extends HasInnerModel, - HasProtocol, - ChildResource { +public interface LoadBalancerOutboundRule extends HasInnerModel, + HasProtocol, ChildResource { /** @return the associated frontends */ Map frontends(); @@ -57,8 +55,7 @@ interface Blank extends LoadBalancerOutboundRule.DefinitionStages.WithP * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, + interface WithAttach extends Attachable.InDefinition, LoadBalancerOutboundRule.DefinitionStages.WithEnableTcpReset, LoadBalancerOutboundRule.DefinitionStages.WithIdleTimeout { } @@ -68,8 +65,8 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithProtocol - extends HasProtocol.DefinitionStages.WithProtocol, LoadBalancerOutboundRuleProtocol> { + interface WithProtocol extends + HasProtocol.DefinitionStages.WithProtocol, LoadBalancerOutboundRuleProtocol> { } /** @@ -77,7 +74,7 @@ interface WithProtocol * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithBackend { + interface WithBackend { /** * Specifies a backend for outbound rule to apply to * @param name the backend name @@ -144,8 +141,7 @@ interface WithEnableTcpReset { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends LoadBalancerOutboundRule.DefinitionStages.Blank, + interface Definition extends LoadBalancerOutboundRule.DefinitionStages.Blank, LoadBalancerOutboundRule.DefinitionStages.WithProtocol, LoadBalancerOutboundRule.DefinitionStages.WithBackend, LoadBalancerOutboundRule.DefinitionStages.WithFrontend, @@ -185,7 +181,8 @@ interface WithFrontend { /** * The stage of an outbound rule update allowing to specify the transport protocol for the rule to apply to. */ - interface WithProtocol extends HasProtocol.UpdateStages.WithProtocol, LoadBalancerOutboundRuleProtocol> { + interface WithProtocol + extends HasProtocol.UpdateStages.WithProtocol, LoadBalancerOutboundRuleProtocol> { } /** @@ -219,9 +216,7 @@ interface WithIdleTimeout { } /** The entirety of an inbound NAT rule update as part of a load balancer update. */ - interface Update - extends Settable, - LoadBalancerOutboundRule.UpdateStages.WithProtocol, + interface Update extends Settable, LoadBalancerOutboundRule.UpdateStages.WithProtocol, LoadBalancerOutboundRule.UpdateStages.WithBackend, LoadBalancerOutboundRule.UpdateStages.WithFrontend, LoadBalancerOutboundRule.UpdateStages.WithEnableTcpReset, diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPrivateFrontend.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPrivateFrontend.java index 44c3f7f154969..fbe9ad9a9838d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPrivateFrontend.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPrivateFrontend.java @@ -71,10 +71,9 @@ interface WithAvailabilityZone { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinitionAlt, - HasPrivateIpAddress.DefinitionStages.WithPrivateIPAddress>, - DefinitionStages.WithAvailabilityZone { + interface WithAttach extends Attachable.InDefinitionAlt, + HasPrivateIpAddress.DefinitionStages.WithPrivateIPAddress>, + DefinitionStages.WithAvailabilityZone { } } @@ -83,10 +82,8 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithSubnet { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithSubnet { } /** Grouping of private frontend update stages. */ @@ -105,10 +102,8 @@ interface WithSubnet { } /** The entirety of a private frontend update as part of a load balancer update. */ - interface Update - extends Settable, - UpdateStages.WithSubnet, - HasPrivateIpAddress.UpdateStages.WithPrivateIPAddress { + interface Update extends Settable, UpdateStages.WithSubnet, + HasPrivateIpAddress.UpdateStages.WithPrivateIPAddress { } /** Grouping of private frontend definition stages applicable as part of a load balancer update. */ @@ -160,10 +155,9 @@ interface WithAvailabilityZone { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdateAlt, - HasPrivateIpAddress.UpdateDefinitionStages.WithPrivateIPAddress>, - WithAvailabilityZone { + interface WithAttach extends Attachable.InUpdateAlt, + HasPrivateIpAddress.UpdateDefinitionStages.WithPrivateIPAddress>, + WithAvailabilityZone { } } @@ -172,9 +166,7 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithSubnet { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithSubnet { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerProbe.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerProbe.java index 5dd964bd81459..b90ce9bff5c2b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerProbe.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerProbe.java @@ -9,12 +9,8 @@ /** A client-side representation of a load balancing probe. */ @Fluent() -public interface LoadBalancerProbe - extends HasInnerModel, - ChildResource, - HasLoadBalancingRules, - HasProtocol, - HasPort { +public interface LoadBalancerProbe extends HasInnerModel, ChildResource, + HasLoadBalancingRules, HasProtocol, HasPort { /** @return number of seconds between probes */ int intervalInSeconds(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPublicFrontend.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPublicFrontend.java index 7c6ebbae3a347..843cbd31372a9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPublicFrontend.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerPublicFrontend.java @@ -46,10 +46,8 @@ interface WithAttach extends Attachable.InDefinition { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithPublicIPAddress { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithPublicIPAddress { } /** Grouping of public frontend update stages. */ @@ -99,9 +97,7 @@ interface WithAttach extends Attachable.InUpdate { * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithPublicIPAddress { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithPublicIPAddress { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerTcpProbe.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerTcpProbe.java index ecf0cd81c2a56..5e36588541f41 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerTcpProbe.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancerTcpProbe.java @@ -84,10 +84,8 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithPort { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithPort { } /** Grouping of probe update stages. */ @@ -130,11 +128,8 @@ interface WithNumberOfProbes { } /** The entirety of a probe update as part of a load balancer update. */ - interface Update - extends Settable, - UpdateStages.WithPort, - UpdateStages.WithIntervalInSeconds, - UpdateStages.WithNumberOfProbes { + interface Update extends Settable, UpdateStages.WithPort, UpdateStages.WithIntervalInSeconds, + UpdateStages.WithNumberOfProbes { } /** Grouping of probe definition stages applicable as part of a load balancer update. */ @@ -211,9 +206,7 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithPort { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithPort { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancers.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancers.java index 07b912a76432a..8c4024699d111 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancers.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancers.java @@ -18,14 +18,8 @@ /** Entry point to load balancer management API in Azure. */ @Fluent() public interface LoadBalancers - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancingRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancingRule.java index 2e5053fab0084..25c034c181817 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancingRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LoadBalancingRule.java @@ -13,14 +13,8 @@ /** A client-side representation of an HTTP load balancing rule. */ @Fluent() -public interface LoadBalancingRule - extends HasInnerModel, - ChildResource, - HasBackendPort, - HasFrontend, - HasFloatingIP, - HasProtocol, - HasFrontendPort { +public interface LoadBalancingRule extends HasInnerModel, ChildResource, + HasBackendPort, HasFrontend, HasFloatingIP, HasProtocol, HasFrontendPort { /** @return the method of load distribution */ LoadDistribution loadDistribution(); @@ -180,12 +174,9 @@ interface WithBackendPort * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithFloatingIP, - DefinitionStages.WithIdleTimeoutInMinutes, - DefinitionStages.WithLoadDistribution, - DefinitionStages.WithProbe { + interface WithAttach extends Attachable.InDefinition, + DefinitionStages.WithFloatingIP, DefinitionStages.WithIdleTimeoutInMinutes, + DefinitionStages.WithLoadDistribution, DefinitionStages.WithProbe { } /** @@ -233,14 +224,10 @@ interface WithLoadDistribution { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithProtocol, - DefinitionStages.WithFrontendPort, - DefinitionStages.WithFrontend, - DefinitionStages.WithBackend, - DefinitionStages.WithBackendPort { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithProtocol, DefinitionStages.WithFrontendPort, + DefinitionStages.WithFrontend, DefinitionStages.WithBackend, + DefinitionStages.WithBackendPort { } /** Grouping of load balancing rule update stages. */ @@ -307,16 +294,9 @@ interface WithLoadDistribution { } /** The entirety of a load balancing rule update as part of a load balancer update. */ - interface Update - extends Settable, - UpdateStages.WithFrontendPort, - UpdateStages.WithFrontend, - UpdateStages.WithProtocol, - UpdateStages.WithBackendPort, - UpdateStages.WithFloatingIP, - UpdateStages.WithIdleTimeoutInMinutes, - UpdateStages.WithLoadDistribution, - UpdateStages.WithProbe { + interface Update extends Settable, UpdateStages.WithFrontendPort, UpdateStages.WithFrontend, + UpdateStages.WithProtocol, UpdateStages.WithBackendPort, UpdateStages.WithFloatingIP, + UpdateStages.WithIdleTimeoutInMinutes, UpdateStages.WithLoadDistribution, UpdateStages.WithProbe { } /** Grouping of load balancing rule definition stages applicable as part of a load balancer update. */ @@ -491,12 +471,9 @@ interface WithLoadDistribution { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithFloatingIP, - UpdateDefinitionStages.WithIdleTimeoutInMinutes, - UpdateDefinitionStages.WithLoadDistribution, - UpdateDefinitionStages.WithProbe { + interface WithAttach extends Attachable.InUpdate, + UpdateDefinitionStages.WithFloatingIP, UpdateDefinitionStages.WithIdleTimeoutInMinutes, + UpdateDefinitionStages.WithLoadDistribution, UpdateDefinitionStages.WithProbe { } } @@ -505,13 +482,9 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithProtocol, - UpdateDefinitionStages.WithFrontendPort, - UpdateDefinitionStages.WithFrontend, - UpdateDefinitionStages.WithBackend, - UpdateDefinitionStages.WithBackendPort { + interface UpdateDefinition extends UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach, UpdateDefinitionStages.WithProtocol, + UpdateDefinitionStages.WithFrontendPort, UpdateDefinitionStages.WithFrontend, + UpdateDefinitionStages.WithBackend, UpdateDefinitionStages.WithBackendPort { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateway.java index 8ead6c3c9d6f0..de88fcbc259de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateway.java @@ -15,11 +15,8 @@ /** Entry point for Local Network Gateway management API in Azure. */ @Fluent -public interface LocalNetworkGateway - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface LocalNetworkGateway extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { // Getters @@ -36,11 +33,8 @@ public interface LocalNetworkGateway String provisioningState(); /** The entirety of the local network gateway definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithIPAddress, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithIPAddress, + DefinitionStages.WithCreate { } /** Grouping of local network gateway definition stages. */ @@ -94,11 +88,8 @@ interface WithBgp { * The stage of the local network gateway definition which contains all the minimum required inputs for the * resource to be created (via {@link WithCreate#create()}). */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithAddressSpace, - DefinitionStages.WithBgp { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithAddressSpace, DefinitionStages.WithBgp { } } @@ -156,11 +147,7 @@ interface WithBgp { } /** The template for a local network gateway update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithIPAddress, - UpdateStages.WithAddressSpace, - UpdateStages.WithBgp { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithIPAddress, UpdateStages.WithAddressSpace, UpdateStages.WithBgp { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateways.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateways.java index 063f0e5c75968..c442dc37337ee 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateways.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/LocalNetworkGateways.java @@ -15,13 +15,8 @@ /** Entry point to local network gateways management API in Azure. */ @Fluent -public interface LocalNetworkGateways - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface LocalNetworkGateways extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Network.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Network.java index 7e2274a163004..9f142e8150b5d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Network.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Network.java @@ -16,11 +16,8 @@ /** Entry point for Virtual Network management API in Azure. */ @Fluent() -public interface Network - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface Network extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags { /** * Checks if the specified private IP address is available in this network. @@ -71,12 +68,8 @@ public interface Network String ddosProtectionPlanId(); /** The entirety of the virtual network definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSubnet, - DefinitionStages.WithCreate, - DefinitionStages.WithCreateAndSubnet { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSubnet, + DefinitionStages.WithCreate, DefinitionStages.WithCreateAndSubnet { } /** Grouping of virtual network definition stages. */ @@ -167,11 +160,8 @@ interface WithVmProtection { * *

Subnets can be added only right after the address space is explicitly specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithDdosProtectionPlan, - DefinitionStages.WithVmProtection { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithDdosProtectionPlan, DefinitionStages.WithVmProtection { /** * Specifies the IP address of an existing DNS server to associate with the virtual network. @@ -356,13 +346,8 @@ interface WithVmProtection { } /** The template for a virtual network update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSubnet, - UpdateStages.WithDnsServer, - UpdateStages.WithAddressSpace, - UpdateStages.WithDdosProtectionPlan, - UpdateStages.WithVmProtection { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSubnet, + UpdateStages.WithDnsServer, UpdateStages.WithAddressSpace, UpdateStages.WithDdosProtectionPlan, + UpdateStages.WithVmProtection { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterface.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterface.java index e080c4b56b1b7..312462400f8fd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterface.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterface.java @@ -18,11 +18,8 @@ /** Network interface. */ @Fluent public interface NetworkInterface - extends NetworkInterfaceBase, - GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { + extends NetworkInterfaceBase, GroupableResource, + Refreshable, Updatable, UpdatableWithTags { /** @return the IP configurations of this network interface, indexed by their names. */ Map ipConfigurations(); @@ -31,12 +28,8 @@ public interface NetworkInterface /** The entirety of the network interface definition. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithPrimaryNetwork, - DefinitionStages.WithPrimaryNetworkSubnet, - DefinitionStages.WithPrimaryPrivateIP, - DefinitionStages.WithCreate { + extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithPrimaryNetwork, + DefinitionStages.WithPrimaryNetworkSubnet, DefinitionStages.WithPrimaryPrivateIP, DefinitionStages.WithCreate { } /** Grouping of network interface definition stages. */ @@ -272,15 +265,9 @@ interface WithPublicIPAddressDeleteOptions { * to be created, but also allows for any other optional settings to be specified. */ interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithPrimaryPublicIPAddress, - WithNetworkSecurityGroup, - WithSecondaryIPConfiguration, - WithAcceleratedNetworking, - WithLoadBalancer, - WithApplicationSecurityGroup, - WithPublicIPAddressDeleteOptions { + extends Creatable, Resource.DefinitionWithTags, WithPrimaryPublicIPAddress, + WithNetworkSecurityGroup, WithSecondaryIPConfiguration, WithAcceleratedNetworking, WithLoadBalancer, + WithApplicationSecurityGroup, WithPublicIPAddressDeleteOptions { /** * Enables IP forwarding in the network interface. * @@ -512,8 +499,8 @@ interface WithIPConfiguration { * @param name name for the IP configuration * @return the first stage of the update */ - NicIpConfiguration.UpdateDefinitionStages.Blank defineSecondaryIPConfiguration( - String name); + NicIpConfiguration.UpdateDefinitionStages.Blank + defineSecondaryIPConfiguration(String name); /** * Starts update of an IP configuration. @@ -604,18 +591,10 @@ interface WithPublicIPAddressDeleteOptions { /** The template for an update operation, containing all the settings that can be modified. */ interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithPrimaryNetworkSubnet, - UpdateStages.WithPrimaryPrivateIP, - UpdateStages.WithPrimaryPublicIPAddress, - UpdateStages.WithNetworkSecurityGroup, - UpdateStages.WithIPForwarding, - UpdateStages.WithDnsServer, - UpdateStages.WithIPConfiguration, - UpdateStages.WithLoadBalancer, - UpdateStages.WithAcceleratedNetworking, - UpdateStages.WithApplicationSecurityGroup, - UpdateStages.WithPublicIPAddressDeleteOptions { + extends Appliable, Resource.UpdateWithTags, UpdateStages.WithPrimaryNetworkSubnet, + UpdateStages.WithPrimaryPrivateIP, UpdateStages.WithPrimaryPublicIPAddress, + UpdateStages.WithNetworkSecurityGroup, UpdateStages.WithIPForwarding, UpdateStages.WithDnsServer, + UpdateStages.WithIPConfiguration, UpdateStages.WithLoadBalancer, UpdateStages.WithAcceleratedNetworking, + UpdateStages.WithApplicationSecurityGroup, UpdateStages.WithPublicIPAddressDeleteOptions { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterfaces.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterfaces.java index 4c7ee09ea7990..872241e37e4f5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterfaces.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkInterfaces.java @@ -23,16 +23,10 @@ /** Entry point to network interface management. */ @Fluent public interface NetworkInterfaces - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Gets a network interface associated with a virtual machine scale set instance. @@ -43,8 +37,8 @@ public interface NetworkInterfaces * @param name the network interface name * @return network interface */ - VirtualMachineScaleSetNetworkInterface getByVirtualMachineScaleSetInstanceId( - String resourceGroupName, String scaleSetName, String instanceId, String name); + VirtualMachineScaleSetNetworkInterface getByVirtualMachineScaleSetInstanceId(String resourceGroupName, + String scaleSetName, String instanceId, String name); /** * Gets a network interface associated with a virtual machine scale set instance. @@ -55,8 +49,8 @@ VirtualMachineScaleSetNetworkInterface getByVirtualMachineScaleSetInstanceId( * @param name the network interface name * @return network interface */ - Mono getByVirtualMachineScaleSetInstanceIdAsync( - String resourceGroupName, String scaleSetName, String instanceId, String name); + Mono getByVirtualMachineScaleSetInstanceIdAsync(String resourceGroupName, + String scaleSetName, String instanceId, String name); /** * List the network interfaces associated with a virtual machine scale set. @@ -65,8 +59,8 @@ Mono getByVirtualMachineScaleSetInstance * @param scaleSetName scale set name * @return list of network interfaces */ - PagedIterable listByVirtualMachineScaleSet( - String resourceGroupName, String scaleSetName); + PagedIterable listByVirtualMachineScaleSet(String resourceGroupName, + String scaleSetName); /** * List the network interfaces associated with a virtual machine scale set. @@ -84,8 +78,8 @@ PagedIterable listByVirtualMachineScaleS * @param instanceId the virtual machine scale set vm instance id * @return list of network interfaces */ - PagedIterable listByVirtualMachineScaleSetInstanceId( - String resourceGroupName, String scaleSetName, String instanceId); + PagedIterable + listByVirtualMachineScaleSetInstanceId(String resourceGroupName, String scaleSetName, String instanceId); /** * List the network interfaces associated with a specific virtual machine instance in a scale set asynchronously. @@ -95,8 +89,8 @@ PagedIterable listByVirtualMachineScaleS * @param instanceId the virtual machine scale set vm instance id * @return list of network interfaces */ - PagedFlux listByVirtualMachineScaleSetInstanceIdAsync( - String resourceGroupName, String scaleSetName, String instanceId); + PagedFlux + listByVirtualMachineScaleSetInstanceIdAsync(String resourceGroupName, String scaleSetName, String instanceId); /** * Begins deleting a virtual machine from Azure, identifying it by its resource ID. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeering.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeering.java index 484213606caae..8c813d161d3fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeering.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeering.java @@ -16,11 +16,8 @@ /** An client-side representation of a network peering. */ @Fluent() -public interface NetworkPeering - extends IndependentChild, - HasInnerModel, - Refreshable, - Updatable { +public interface NetworkPeering extends IndependentChild, HasInnerModel, + Refreshable, Updatable { /** @return the local virtual network's ID */ String networkId(); @@ -226,11 +223,8 @@ interface Definition } /** The template for a network peering update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithTrafficForwarding, - UpdateStages.WithAccess, - UpdateStages.WithGatewayUse { + interface Update extends Appliable, UpdateStages.WithTrafficForwarding, UpdateStages.WithAccess, + UpdateStages.WithGatewayUse { } /** Grouping of all the network peering update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeerings.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeerings.java index 5dda8634ed642..c1ce5168e57e0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeerings.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkPeerings.java @@ -16,14 +16,9 @@ /** Entry point to network peering management API. */ @Fluent -public interface NetworkPeerings - extends SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - SupportsBatchCreation, - SupportsDeletingByParent, - SupportsListing, - HasManager { +public interface NetworkPeerings extends SupportsCreating, SupportsDeletingById, + SupportsGettingById, SupportsBatchCreation, SupportsDeletingByParent, + SupportsListing, HasManager { /** * Finds the peering, if any, that is associated with the specified network. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfile.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfile.java index 9800e818db9c9..e7a777d3fffbb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfile.java @@ -15,11 +15,8 @@ import java.util.List; /** An immutable client-side representation of NetworkProfile. */ -public interface NetworkProfile extends - GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface NetworkProfile extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { /** * Gets the containerNetworkInterfaceConfigurations property: List of chid container network interface @@ -30,27 +27,23 @@ public interface NetworkProfile extends List containerNetworkInterfaceConfigurations(); /** The entirety of the NetworkProfile definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithContainerNetworkInterfaceConfigurations, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, + DefinitionStages.WithContainerNetworkInterfaceConfigurations, DefinitionStages.WithCreate { } + /** The NetworkProfile definition stages. */ interface DefinitionStages { /** * The first stage of the NetworkProfile definition. */ - interface Blank extends - GroupableResource.DefinitionWithRegion { + interface Blank extends GroupableResource.DefinitionWithRegion { } /** * The stage of the NetworkProfile definition allowing to specify parent resource. */ interface WithGroup extends - GroupableResource.DefinitionStages.WithGroup - { + GroupableResource.DefinitionStages.WithGroup { } /** @@ -58,8 +51,7 @@ interface WithGroup extends * resource to be created, but also allows for any other optional properties to be specified. */ interface WithCreate - extends Creatable, - Resource.DefinitionWithTags { + extends Creatable, Resource.DefinitionWithTags { } /** @@ -76,8 +68,8 @@ interface WithContainerNetworkInterfaceConfigurations { * @param subnetName the name of the subnet * @return the next stage */ - WithCreate withContainerNetworkInterfaceConfiguration( - String name, String ipConfigName, String virtualNetworkId, String subnetName); + WithCreate withContainerNetworkInterfaceConfiguration(String name, String ipConfigName, + String virtualNetworkId, String subnetName); /** * Specifies the network interface configuration for container. @@ -87,14 +79,11 @@ WithCreate withContainerNetworkInterfaceConfiguration( * @param subnet the Subnet resource * @return the next stage */ - WithCreate withContainerNetworkInterfaceConfiguration( - String name, String ipConfigName, Subnet subnet); + WithCreate withContainerNetworkInterfaceConfiguration(String name, String ipConfigName, Subnet subnet); } } /** The template for NetworkProfile update. */ - interface Update extends - Appliable, - Resource.UpdateWithTags { + interface Update extends Appliable, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfiles.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfiles.java index f2ea4341c4da3..9d59b9ac9e80b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfiles.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkProfiles.java @@ -14,13 +14,8 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; /** Resource collection API of NetworkProfiles. */ -public interface NetworkProfiles extends - SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface NetworkProfiles extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroup.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroup.java index b83e4472506d4..bd8803ffd400d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroup.java @@ -18,11 +18,8 @@ /** Network security group. */ @Fluent() public interface NetworkSecurityGroup - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags, - HasAssociatedSubnets { + extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags, HasAssociatedSubnets { // Getters @@ -71,10 +68,8 @@ interface WithRule { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithRule { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithRule { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroups.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroups.java index d56aa9fd4dd9b..90d64f226afcf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityGroups.java @@ -18,14 +18,8 @@ /** Entry point to network security group management. */ @Fluent() public interface NetworkSecurityGroups - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityRule.java index 67da7b0688ea9..86578ad1997d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkSecurityRule.java @@ -81,15 +81,10 @@ public interface NetworkSecurityRule extends HasInnerModel, C * * @param the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithDirectionAccess, - DefinitionStages.WithSourceAddressOrSecurityGroup, - DefinitionStages.WithSourcePort, - DefinitionStages.WithDestinationAddressOrSecurityGroup, - DefinitionStages.WithDestinationPort, - DefinitionStages.WithProtocol { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithDirectionAccess, DefinitionStages.WithSourceAddressOrSecurityGroup, + DefinitionStages.WithSourcePort, DefinitionStages.WithDestinationAddressOrSecurityGroup, + DefinitionStages.WithDestinationPort, DefinitionStages.WithProtocol { } /** Grouping of security rule definition stages applicable as part of a network security group creation. */ @@ -384,14 +379,12 @@ interface WithAttach * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithDirectionAccess, - UpdateDefinitionStages.WithSourceAddressOrSecurityGroup, - UpdateDefinitionStages.WithSourcePort, - UpdateDefinitionStages.WithDestinationAddressOrSecurityGroup, - UpdateDefinitionStages.WithDestinationPort, - UpdateDefinitionStages.WithProtocol, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithDirectionAccess, + UpdateDefinitionStages.WithSourceAddressOrSecurityGroup, + UpdateDefinitionStages.WithSourcePort, + UpdateDefinitionStages.WithDestinationAddressOrSecurityGroup, + UpdateDefinitionStages.WithDestinationPort, UpdateDefinitionStages.WithProtocol, + UpdateDefinitionStages.WithAttach { } /** Grouping of security rule definition stages applicable as part of a network security group update. */ @@ -666,14 +659,9 @@ interface WithAttach extends Attachable.InUpdate { } /** The entirety of a security rule update as part of a network security group update. */ - interface Update - extends UpdateStages.WithDirectionAccess, - UpdateStages.WithSourceAddressOrSecurityGroup, - UpdateStages.WithSourcePort, - UpdateStages.WithDestinationAddressOrSecurityGroup, - UpdateStages.WithDestinationPort, - UpdateStages.WithProtocol, - Settable { + interface Update extends UpdateStages.WithDirectionAccess, UpdateStages.WithSourceAddressOrSecurityGroup, + UpdateStages.WithSourcePort, UpdateStages.WithDestinationAddressOrSecurityGroup, + UpdateStages.WithDestinationPort, UpdateStages.WithProtocol, Settable { /** * Specifies the priority to assign to this security rule. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatcher.java index 5dee5568241da..25e852acf9199 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatcher.java @@ -15,11 +15,8 @@ /** Entry point for Network Watcher API in Azure. */ @Fluent -public interface NetworkWatcher - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface NetworkWatcher extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { /** @return entry point to manage packet captures associated with network watcher */ PacketCaptures packetCaptures(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatchers.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatchers.java index 8583ec5597c0e..e567c1d2745b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatchers.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkWatchers.java @@ -17,15 +17,9 @@ /** Entry point for Network Watcher API in Azure. */ @Fluent -public interface NetworkWatchers - extends SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface NetworkWatchers extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Networks.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Networks.java index 737b114a25bc8..563225ae296c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Networks.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Networks.java @@ -17,15 +17,8 @@ /** Entry point to virtual network management API in Azure. */ @Fluent() -public interface Networks - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface Networks extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, + HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NextHop.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NextHop.java index 45a2a92c246df..e373a622cc550 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NextHop.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NextHop.java @@ -40,11 +40,8 @@ public interface NextHop extends Executable, HasParent String routeTableId(); /** The entirety of next hop parameters definition. */ - interface Definition - extends DefinitionStages.WithTargetResource, - DefinitionStages.WithSourceIP, - DefinitionStages.WithDestinationIP, - DefinitionStages.WithExecute { + interface Definition extends DefinitionStages.WithTargetResource, DefinitionStages.WithSourceIP, + DefinitionStages.WithDestinationIP, DefinitionStages.WithExecute { } /** Grouping of next hop definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NicIpConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NicIpConfiguration.java index fb6dcb288b463..e27f3c7830a3b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NicIpConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NicIpConfiguration.java @@ -13,11 +13,8 @@ /** An IP configuration in a network interface. */ @Fluent() -public interface NicIpConfiguration - extends NicIpConfigurationBase, - HasInnerModel, - ChildResource, - HasPublicIpAddress { +public interface NicIpConfiguration extends NicIpConfigurationBase, HasInnerModel, + ChildResource, HasPublicIpAddress { /** * The entirety of the network interface IP configuration definition. @@ -25,12 +22,9 @@ public interface NicIpConfiguration * @param the stage of the parent network interface definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithNetwork, - DefinitionStages.WithSubnet, - DefinitionStages.WithPrivateIP { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithNetwork, DefinitionStages.WithSubnet, + DefinitionStages.WithPrivateIP { } /** @@ -165,8 +159,8 @@ interface WithLoadBalancer { * @param inboundNatRuleName the name of an existing inbound NAT rule on the selected load balancer * @return the next stage of the definition */ - WithAttach withExistingLoadBalancerInboundNatRule( - LoadBalancer loadBalancer, String inboundNatRuleName); + WithAttach withExistingLoadBalancerInboundNatRule(LoadBalancer loadBalancer, + String inboundNatRuleName); } /** @@ -184,11 +178,10 @@ interface WithApplicationGateway { * @param backendName the name of an existing backend on the application gateway * @return the next stage of the definition */ - WithAttach withExistingApplicationGatewayBackend( - ApplicationGateway appGateway, String backendName); + WithAttach withExistingApplicationGatewayBackend(ApplicationGateway appGateway, + String backendName); } - /** The stage of the definition allowing to specify delete options for the public ip address. * * @param the stage of the parent network interface definition to return to after attaching this @@ -213,12 +206,8 @@ interface WithPublicIPAddressDeleteOptions { * @param the stage of the parent network interface definition to return to after attaching this * definition */ - interface WithAttach - extends Attachable.InDefinition, - WithPublicIPAddress, - WithLoadBalancer, - WithApplicationGateway, - WithPublicIPAddressDeleteOptions { + interface WithAttach extends Attachable.InDefinition, WithPublicIPAddress, + WithLoadBalancer, WithApplicationGateway, WithPublicIPAddressDeleteOptions { } } @@ -228,12 +217,9 @@ interface WithAttach * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithNetwork, - UpdateDefinitionStages.WithPrivateIP, - UpdateDefinitionStages.WithSubnet, - UpdateDefinitionStages.WithPublicIPAddress { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAttach, + UpdateDefinitionStages.WithNetwork, UpdateDefinitionStages.WithPrivateIP, + UpdateDefinitionStages.WithSubnet, UpdateDefinitionStages.WithPublicIPAddress { } /** Grouping of network interface IP configuration definition stages. */ @@ -366,8 +352,8 @@ interface WithLoadBalancer { * @param inboundNatRuleName the name of an existing inbound NAT rule on the selected load balancer * @return the next stage of the update */ - WithAttach withExistingLoadBalancerInboundNatRule( - LoadBalancer loadBalancer, String inboundNatRuleName); + WithAttach withExistingLoadBalancerInboundNatRule(LoadBalancer loadBalancer, + String inboundNatRuleName); } /** @@ -385,8 +371,8 @@ interface WithApplicationGateway { * @param backendName the name of an existing backend on the application gateway * @return the next stage of the definition */ - WithAttach withExistingApplicationGatewayBackend( - ApplicationGateway appGateway, String backendName); + WithAttach withExistingApplicationGatewayBackend(ApplicationGateway appGateway, + String backendName); } /** @@ -395,7 +381,7 @@ WithAttach withExistingApplicationGatewayBackend( * @param the stage of the parent network interface update to return to after attaching this * definition * */ - interface WithPublicIPAddressDeleteOptions { + interface WithPublicIPAddressDeleteOptions { /** * Sets delete options for public ip address. * @@ -414,24 +400,15 @@ interface WithPublicIPAddressDeleteOptions { * @param the stage of the parent network interface update to return to after attaching this * definition */ - interface WithAttach - extends Attachable.InUpdate, - WithPublicIPAddress, - WithLoadBalancer, - WithApplicationGateway, - WithPublicIPAddressDeleteOptions { + interface WithAttach extends Attachable.InUpdate, WithPublicIPAddress, + WithLoadBalancer, WithApplicationGateway, WithPublicIPAddressDeleteOptions { } } /** The entirety of a network interface IP configuration update as part of a network interface update. */ - interface Update - extends Settable, - UpdateStages.WithSubnet, - UpdateStages.WithPrivateIP, - UpdateStages.WithPublicIPAddress, - UpdateStages.WithLoadBalancer, - UpdateStages.WithApplicationGateway, - UpdateStages.WithPublicIPAddressDeleteOptions { + interface Update extends Settable, UpdateStages.WithSubnet, UpdateStages.WithPrivateIP, + UpdateStages.WithPublicIPAddress, UpdateStages.WithLoadBalancer, UpdateStages.WithApplicationGateway, + UpdateStages.WithPublicIPAddressDeleteOptions { } /** Grouping of network interface IP configuration update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PCFilter.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PCFilter.java index 2181c1482eb7a..698f6454ce353 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PCFilter.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PCFilter.java @@ -67,13 +67,9 @@ interface WithAttach extends Attachable.InDefinition, Blank the stage of the parent definition to return to after attaching this definition */ - interface Blank - extends HasProtocol.DefinitionStages.WithProtocol< - WithAttach, PcProtocol>, - WithLocalIP, - WithRemoteIpAddress, - WithLocalPort, - WithRemotePort { + interface Blank extends + HasProtocol.DefinitionStages.WithProtocol, PcProtocol>, + WithLocalIP, WithRemoteIpAddress, WithLocalPort, WithRemotePort { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCapture.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCapture.java index 99e39c39107b7..ba5704ba95b08 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCapture.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCapture.java @@ -65,10 +65,8 @@ public interface PacketCapture extends HasInnerModel, Mono getStatusAsync(); /** The entirety of the packet capture definition. */ - interface Definition - extends PacketCapture.DefinitionStages.WithTarget, - PacketCapture.DefinitionStages.WithStorageLocation, - PacketCapture.DefinitionStages.WithCreateAndStoragePath { + interface Definition extends PacketCapture.DefinitionStages.WithTarget, + PacketCapture.DefinitionStages.WithStorageLocation, PacketCapture.DefinitionStages.WithCreateAndStoragePath { } /** Grouping of Packet Capture definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCaptures.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCaptures.java index 6040e638d1f81..e03791bd1876d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCaptures.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PacketCaptures.java @@ -10,9 +10,6 @@ /** Entry point to packet captures management API in Azure. */ @Fluent -public interface PacketCaptures - extends SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName { +public interface PacketCaptures extends SupportsCreating, + SupportsListing, SupportsGettingByName, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PointToSiteConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PointToSiteConfiguration.java index 9de2f22a9dafb..afc8f0747da92 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PointToSiteConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PointToSiteConfiguration.java @@ -111,6 +111,7 @@ interface WithTunnelType { * @return the next stage of the definition */ WithAttach withSstpOnly(); + /** * Specifies that only IKEv2 VPN tunnel type will be used. * @@ -138,11 +139,8 @@ interface WithAttach extends Attachable.InDefinition, WithTunn * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttachAndAzureCertificate - extends WithAttach, - WithTunnelType, - WithAzureCertificate, - WithRevokedCertificate { + interface WithAttachAndAzureCertificate extends WithAttach, WithTunnelType, + WithAzureCertificate, WithRevokedCertificate { } } @@ -152,10 +150,8 @@ interface WithAttachAndAzureCertificate * @param the stage of the parent definition to return to after attaching this definition */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAuthenticationType, - DefinitionStages.WithAddressPool, - DefinitionStages.WithAttachAndAzureCertificate { + extends DefinitionStages.Blank, DefinitionStages.WithAuthenticationType, + DefinitionStages.WithAddressPool, DefinitionStages.WithAttachAndAzureCertificate { } /** Grouping of point-to-site configuration update stages. */ @@ -246,11 +242,7 @@ interface WithTunnelType { } /** The entirety of a subnet update as part of a network update. */ - interface Update - extends UpdateStages.WithAddressPool, - UpdateStages.WithAuthenticationType, - UpdateStages.WithRevokedCertificate, - UpdateStages.WithTunnelType, - Settable { + interface Update extends UpdateStages.WithAddressPool, UpdateStages.WithAuthenticationType, + UpdateStages.WithRevokedCertificate, UpdateStages.WithTunnelType, Settable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroup.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroup.java index edaf722810dff..a746fd91a3689 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroup.java @@ -15,11 +15,8 @@ import java.util.List; /** An immutable client-side representation of an Azure private DNS zone group. */ -public interface PrivateDnsZoneGroup extends - IndependentChild, - HasInnerModel, - Refreshable, - Updatable { +public interface PrivateDnsZoneGroup extends IndependentChild, HasInnerModel, + Refreshable, Updatable { /** * @return the provisioning state. @@ -34,10 +31,8 @@ public interface PrivateDnsZoneGroup extends /** * Container interface for all the definitions that need to be implemented. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithZoneConfigure, - DefinitionStages.WithCreate { + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithZoneConfigure, DefinitionStages.WithCreate { } /** @@ -68,16 +63,12 @@ interface WithZoneConfigure { * A definition with sufficient inputs to create a new private dns zone group in the cloud, but * exposing additional optional inputs to specify. */ - interface WithCreate extends - WithZoneConfigure, - Creatable { + interface WithCreate extends WithZoneConfigure, Creatable { } } /** The template for update operation, containing all the settings that can be modified. */ - interface Update extends - UpdateStages.WithZoneConfigure, - Appliable { + interface Update extends UpdateStages.WithZoneConfigure, Appliable { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroups.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroups.java index 2d63ba781181b..c63b33b9a7fe0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateDnsZoneGroups.java @@ -12,11 +12,7 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; /** Entry point for private dns zone groups management API. */ -public interface PrivateDnsZoneGroups extends - SupportsCreating, - SupportsDeletingById, - SupportsGettingById, - SupportsDeletingByParent, - SupportsListing, - HasManager { +public interface PrivateDnsZoneGroups extends SupportsCreating, + SupportsDeletingById, SupportsGettingById, SupportsDeletingByParent, + SupportsListing, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoint.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoint.java index ce7b00c5416cf..a9ecf27b13108 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoint.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoint.java @@ -21,14 +21,12 @@ import java.util.Map; /** An immutable client-side representation of an Azure private endpoint. */ -public interface PrivateEndpoint extends - GroupableResource, - Refreshable, - Updatable { +public interface PrivateEndpoint extends GroupableResource, + Refreshable, Updatable { /** A client-side representation of a private link service connection. */ - interface PrivateLinkServiceConnection extends - HasInnerModel, + interface PrivateLinkServiceConnection + extends HasInnerModel, ChildResource { /** @@ -84,8 +82,8 @@ interface WithPrivateLinkServiceResource { * @param privateLinkServiceResource the resource of the private link service * @return the next stage of the definition */ - PrivateLinkServiceConnection.DefinitionStages.WithSubResource withResource( - Resource privateLinkServiceResource); + PrivateLinkServiceConnection.DefinitionStages.WithSubResource + withResource(Resource privateLinkServiceResource); /** * Specifies the resource of the private link service. @@ -93,8 +91,8 @@ PrivateLinkServiceConnection.DefinitionStages.WithSubResource withResou * @param privateLinkServiceResourceId the resource ID of the private link service * @return the next stage of the definition */ - PrivateLinkServiceConnection.DefinitionStages.WithSubResource withResourceId( - String privateLinkServiceResourceId); + PrivateLinkServiceConnection.DefinitionStages.WithSubResource + withResourceId(String privateLinkServiceResourceId); } /** @@ -110,8 +108,8 @@ interface WithSubResource { * @param subResourceName the name of the sub resource * @return the next stage of the definition */ - PrivateLinkServiceConnection.DefinitionStages.WithAttach withSubResource( - PrivateLinkSubResourceName subResourceName); + PrivateLinkServiceConnection.DefinitionStages.WithAttach + withSubResource(PrivateLinkSubResourceName subResourceName); /** * Specifies no sub resource, used for Private Link service. @@ -133,8 +131,8 @@ interface WithApprovalMethod { * @param requestMessage the request message for manual approval * @return the next stage of the definition */ - PrivateLinkServiceConnection.DefinitionStages.WithAttach withManualApproval( - String requestMessage); + PrivateLinkServiceConnection.DefinitionStages.WithAttach + withManualApproval(String requestMessage); } /** @@ -145,9 +143,7 @@ PrivateLinkServiceConnection.DefinitionStages.WithAttach withManualAppr * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach extends - Attachable.InDefinition, - WithApprovalMethod { + interface WithAttach extends Attachable.InDefinition, WithApprovalMethod { } } @@ -156,8 +152,7 @@ interface WithAttach extends * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition extends - PrivateLinkServiceConnection.DefinitionStages.Blank, + interface Definition extends PrivateLinkServiceConnection.DefinitionStages.Blank, PrivateLinkServiceConnection.DefinitionStages.WithPrivateLinkServiceResource, PrivateLinkServiceConnection.DefinitionStages.WithSubResource, PrivateLinkServiceConnection.DefinitionStages.WithApprovalMethod, @@ -181,9 +176,8 @@ interface WithApprovalMethod { } /** The entirety of a private link service update. */ - interface Update extends - PrivateLinkServiceConnection.UpdateStages.WithApprovalMethod, - Settable { + interface Update + extends PrivateLinkServiceConnection.UpdateStages.WithApprovalMethod, Settable { } } @@ -220,12 +214,8 @@ interface Update extends /** * Container interface for all the definitions that need to be implemented. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSubnet, - DefinitionStages.WithPrivateLinkServiceConnection, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSubnet, + DefinitionStages.WithPrivateLinkServiceConnection, DefinitionStages.WithCreate { } /** @@ -288,9 +278,7 @@ interface WithCreate extends Creatable { } /** The template for a private endpoint update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithPrivateLinkServiceConnection, + interface Update extends Appliable, UpdateStages.WithPrivateLinkServiceConnection, Resource.UpdateWithTags { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoints.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoints.java index fc2df30352de3..8947593d4c63c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoints.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PrivateEndpoints.java @@ -16,15 +16,9 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; /** Entry point for private endpoints management API. */ -public interface PrivateEndpoints extends - SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface PrivateEndpoints extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddress.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddress.java index 07616efad2485..2838638b9ed0f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddress.java @@ -18,11 +18,8 @@ /** Public IP address. */ @Fluent() -public interface PublicIpAddress - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface PublicIpAddress extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { // Getters @@ -208,32 +205,25 @@ interface WithIpAddressVersion { WithCreate withIpAddressVersion(IpVersion ipVersion); } -// /** The stage of the definition allowing to specify delete options to the IP address. */ -// interface WithDeleteOptions { -// /** -// * Sets IP address delete options. -// * -// * @param deleteOptions the delete options to the IP address -// * @return the next stage of the definition -// */ -// WithCreate withDeleteOptions(DeleteOptions deleteOptions); -// } + // /** The stage of the definition allowing to specify delete options to the IP address. */ + // interface WithDeleteOptions { + // /** + // * Sets IP address delete options. + // * + // * @param deleteOptions the delete options to the IP address + // * @return the next stage of the definition + // */ + // WithCreate withDeleteOptions(DeleteOptions deleteOptions); + // } /** * The stage of the public IP definition which contains all the minimum required inputs for the resource to be * created (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithLeafDomainLabel, - DefinitionStages.WithIPAddress, - DefinitionStages.WithReverseFQDN, - DefinitionStages.WithIdleTimeout, - DefinitionStages.WithAvailabilityZone, - DefinitionStages.WithSku, - DefinitionStages.WithIpTag, - DefinitionStages.WithIpAddressVersion, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, DefinitionStages.WithLeafDomainLabel, + DefinitionStages.WithIPAddress, DefinitionStages.WithReverseFQDN, DefinitionStages.WithIdleTimeout, + DefinitionStages.WithAvailabilityZone, DefinitionStages.WithSku, DefinitionStages.WithIpTag, + DefinitionStages.WithIpAddressVersion, Resource.DefinitionWithTags { /** * Begins creating the public IP address resource. @@ -249,15 +239,9 @@ interface WithCreate * *

Use {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - UpdateStages.WithIPAddress, - UpdateStages.WithLeafDomainLabel, - UpdateStages.WithReverseFQDN, - UpdateStages.WithIdleTimout, - UpdateStages.WithIpTag, - UpdateStages.WithIpAddressVersion, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithIPAddress, UpdateStages.WithLeafDomainLabel, + UpdateStages.WithReverseFQDN, UpdateStages.WithIdleTimout, UpdateStages.WithIpTag, + UpdateStages.WithIpAddressVersion, Resource.UpdateWithTags { } /** Grouping of public IP address update stages. */ @@ -374,15 +358,15 @@ interface WithIpAddressVersion { Update withIpAddressVersion(IpVersion ipVersion); } -// /** The stage of the update allowing to specify delete options to the IP address. */ -// interface WithDeleteOptions { -// /** -// * Sets IP address delete options. -// * -// * @param deleteOptions the delete options to the IP address -// * @return the next stage of the update -// */ -// Update withDeleteOptions(DeleteOptions deleteOptions); -// } + // /** The stage of the update allowing to specify delete options to the IP address. */ + // interface WithDeleteOptions { + // /** + // * Sets IP address delete options. + // * + // * @param deleteOptions the delete options to the IP address + // * @return the next stage of the update + // */ + // Update withDeleteOptions(DeleteOptions deleteOptions); + // } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddresses.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddresses.java index 2cb586572e8ad..9de31409cc876 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddresses.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpAddresses.java @@ -18,17 +18,11 @@ /** Entry point to public IP address management. */ @Fluent() -public interface PublicIpAddresses - extends SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface PublicIpAddresses extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { /** * Begins deleting a public IP address from Azure, identifying it by its resource ID. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefix.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefix.java index 5ce00ca6d90ed..c934b12eabdf6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefix.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefix.java @@ -17,11 +17,8 @@ import java.util.Set; /** Type representing PublicIpPrefix. */ -public interface PublicIpPrefix - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { +public interface PublicIpPrefix extends GroupableResource, + Refreshable, Updatable, UpdatableWithTags { /** @return the ipPrefix value. */ String ipPrefix(); @@ -125,14 +122,9 @@ interface WithAvailabilityZone { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithIpTags, - DefinitionStages.WithPrefixLength, - DefinitionStages.WithPublicIpAddressVersion, - DefinitionStages.WithSku, - DefinitionStages.WithAvailabilityZone { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithIpTags, DefinitionStages.WithPrefixLength, DefinitionStages.WithPublicIpAddressVersion, + DefinitionStages.WithSku, DefinitionStages.WithAvailabilityZone { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefixes.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefixes.java index 1188b4e275e37..5d023fb29fc74 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefixes.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/PublicIpPrefixes.java @@ -15,15 +15,9 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; /** Type representing PublicIpPrefixes. */ -public interface PublicIpPrefixes - extends SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface PublicIpPrefixes extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Route.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Route.java index 727de3deb6c7b..07a174aee4a88 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Route.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Route.java @@ -92,11 +92,8 @@ interface WithNextHopType { * * @param the return type of the final {@link DefinitionStages.WithAttach#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithNextHopType, - DefinitionStages.WithDestinationAddressPrefix { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithNextHopType, DefinitionStages.WithDestinationAddressPrefix { } /** Grouping of route update stages. */ @@ -209,9 +206,7 @@ interface WithNextHopType { * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach, - UpdateDefinitionStages.WithNextHopType, - UpdateDefinitionStages.WithDestinationAddressPrefix { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAttach, + UpdateDefinitionStages.WithNextHopType, UpdateDefinitionStages.WithDestinationAddressPrefix { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilter.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilter.java index d7272df5c057e..05af5ee39f140 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilter.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilter.java @@ -15,10 +15,8 @@ /** Route filter. */ @Fluent -public interface RouteFilter - extends GroupableResource, - Refreshable, - Updatable { +public interface RouteFilter extends GroupableResource, Refreshable, + Updatable { /** @return rules associated with this route filter, indexed by their names */ Map rules(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilterRule.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilterRule.java index 1087eb52f9ba0..bc14e9d7b7ce2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilterRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilterRule.java @@ -38,10 +38,8 @@ public interface RouteFilterRule extends HasInnerModel, Ch * * @param the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithBgpCommunities, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithBgpCommunities, + DefinitionStages.WithAttach { } /** Grouping of route filter rule definition stages applicable as part of a route filter group creation. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilters.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilters.java index ae59e68a0580b..ac4a349ee173c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilters.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteFilters.java @@ -18,14 +18,8 @@ /** Entry point to application security group management. */ @Fluent public interface RouteFilters - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTable.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTable.java index 23e4607e51641..dc1484ee05434 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTable.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTable.java @@ -15,12 +15,8 @@ /** Entry point for route table management. */ @Fluent() -public interface RouteTable - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags, - HasAssociatedSubnets { +public interface RouteTable extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags, HasAssociatedSubnets { /** @return the routes of this route table */ Map routes(); @@ -94,11 +90,8 @@ interface WithBgpRoutePropagation { * The stage of a route table definition which contains all the minimum required inputs for the resource to be * created (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithRoute, - DefinitionStages.WithBgpRoutePropagation { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithRoute, DefinitionStages.WithBgpRoutePropagation { } } @@ -167,6 +160,7 @@ interface WithBgpRoutePropagation { * @return the next stage of the update */ Update withDisableBgpRoutePropagation(); + /** * Enable the routes learned by BGP on that route table. * @@ -181,10 +175,7 @@ interface WithBgpRoutePropagation { * *

Call {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithRoute, - UpdateStages.WithBgpRoutePropagation { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithRoute, + UpdateStages.WithBgpRoutePropagation { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTables.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTables.java index fbc78a4a5bf12..6f16265e492e1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTables.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/RouteTables.java @@ -17,15 +17,8 @@ /** Entry point to route table management. */ @Fluent() -public interface RouteTables - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface RouteTables extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Subnet.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Subnet.java index c1cc6a4af6e36..acc7105313c54 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Subnet.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Subnet.java @@ -245,14 +245,9 @@ interface WithNatGateway { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends Attachable.InDefinition, - WithNetworkSecurityGroup, - WithRouteTable, - WithDelegation, - WithServiceEndpoint, - WithPrivateEndpointNetworkPolicies, - WithPrivateLinkServiceNetworkPolicies, - WithNatGateway { + extends Attachable.InDefinition, WithNetworkSecurityGroup, WithRouteTable, + WithDelegation, WithServiceEndpoint, WithPrivateEndpointNetworkPolicies, + WithPrivateLinkServiceNetworkPolicies, WithNatGateway { } } @@ -261,10 +256,8 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAddressPrefix, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAddressPrefix, + DefinitionStages.WithAttach { } /** Grouping of subnet update stages. */ @@ -439,15 +432,9 @@ interface WithNatGateway { /** The entirety of a subnet update as part of a network update. */ interface Update - extends UpdateStages.WithAddressPrefix, - UpdateStages.WithNetworkSecurityGroup, - UpdateStages.WithRouteTable, - UpdateStages.WithDelegation, - UpdateStages.WithServiceEndpoint, - UpdateStages.WithPrivateEndpointNetworkPolicies, - UpdateStages.WithPrivateLinkServiceNetworkPolicies, - UpdateStages.WithNatGateway, - Settable { + extends UpdateStages.WithAddressPrefix, UpdateStages.WithNetworkSecurityGroup, UpdateStages.WithRouteTable, + UpdateStages.WithDelegation, UpdateStages.WithServiceEndpoint, UpdateStages.WithPrivateEndpointNetworkPolicies, + UpdateStages.WithPrivateLinkServiceNetworkPolicies, UpdateStages.WithNatGateway, Settable { } /** Grouping of subnet definition stages applicable as part of a virtual network update. */ @@ -597,14 +584,9 @@ interface WithNatGateway { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - WithNetworkSecurityGroup, - WithRouteTable, - WithDelegation, - WithServiceEndpoint, - WithPrivateEndpointNetworkPolicies, - WithNatGateway { + interface WithAttach extends Attachable.InUpdate, WithNetworkSecurityGroup, + WithRouteTable, WithDelegation, WithServiceEndpoint, + WithPrivateEndpointNetworkPolicies, WithNatGateway { } } @@ -614,9 +596,7 @@ interface WithAttach * @param the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAddressPrefix, - UpdateDefinitionStages.WithNetworkSecurityGroup, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAddressPrefix, + UpdateDefinitionStages.WithNetworkSecurityGroup, UpdateDefinitionStages.WithAttach { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Topology.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Topology.java index 1b80132e14036..9e5517f3001b4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Topology.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Topology.java @@ -29,10 +29,8 @@ public interface Topology extends Executable, HasInnerModel resources(); /** The entirety of topology parameters definition. */ - interface Definition - extends DefinitionStages.WithTargetResourceGroup, - DefinitionStages.WithExecute, - DefinitionStages.WithExecuteAndSubnet { + interface Definition extends DefinitionStages.WithTargetResourceGroup, DefinitionStages.WithExecute, + DefinitionStages.WithExecuteAndSubnet { } /** Grouping of topology definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Troubleshooting.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Troubleshooting.java index ac176c2c3a30d..797febbe552e0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Troubleshooting.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/Troubleshooting.java @@ -40,11 +40,8 @@ public interface Troubleshooting extends Executable, HasParent< List results(); /** The entirety of troubleshooting parameters definition. */ - interface Definition - extends DefinitionStages.WithTargetResource, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithStoragePath, - DefinitionStages.WithExecute { + interface Definition extends DefinitionStages.WithTargetResource, DefinitionStages.WithStorageAccount, + DefinitionStages.WithStoragePath, DefinitionStages.WithExecute { } /** Grouping of troubleshooting definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VerificationIPFlow.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VerificationIPFlow.java index dd38ee6954cf9..9b79fa7446720 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VerificationIPFlow.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VerificationIPFlow.java @@ -27,15 +27,9 @@ public interface VerificationIPFlow extends Executable, HasP String ruleName(); /** The entirety of verification ip flow parameters definition. */ - interface Definition - extends DefinitionStages.WithTargetResource, - DefinitionStages.WithDirection, - DefinitionStages.WithProtocol, - DefinitionStages.WithLocalIP, - DefinitionStages.WithRemoteIP, - DefinitionStages.WithLocalPort, - DefinitionStages.WithRemotePort, - DefinitionStages.WithExecute { + interface Definition extends DefinitionStages.WithTargetResource, DefinitionStages.WithDirection, + DefinitionStages.WithProtocol, DefinitionStages.WithLocalIP, DefinitionStages.WithRemoteIP, + DefinitionStages.WithLocalPort, DefinitionStages.WithRemotePort, DefinitionStages.WithExecute { } /** Grouping of verification ip flow parameters. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualMachineScaleSetNicIpConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualMachineScaleSetNicIpConfiguration.java index f79912e221188..ce694d8fcd8bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualMachineScaleSetNicIpConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualMachineScaleSetNicIpConfiguration.java @@ -11,9 +11,6 @@ /** An IP configuration in a network interface associated with a virtual machine scale set. */ @Fluent public interface VirtualMachineScaleSetNicIpConfiguration - extends NicIpConfigurationBase, - HasInnerModel, - ChildResource, - HasPrivateIpAddress, - HasSubnet { + extends NicIpConfigurationBase, HasInnerModel, + ChildResource, HasPrivateIpAddress, HasSubnet { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateway.java index 9662c761ce2f9..434568de4aaa0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateway.java @@ -19,10 +19,8 @@ /** Entry point for Virtual Network Gateway management API in Azure. */ @Fluent public interface VirtualNetworkGateway - extends GroupableResource, - Refreshable, - Updatable, - UpdatableWithTags { + extends GroupableResource, Refreshable, + Updatable, UpdatableWithTags { // Actions @@ -102,14 +100,8 @@ public interface VirtualNetworkGateway Collection ipConfigurations(); /** The entirety of the virtual network gateway definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithGatewayType, - DefinitionStages.WithSku, - DefinitionStages.WithNetwork, - DefinitionStages.WithBgp, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithGatewayType, + DefinitionStages.WithSku, DefinitionStages.WithNetwork, DefinitionStages.WithBgp, DefinitionStages.WithCreate { } /** Grouping of virtual network gateway definition stages. */ @@ -224,11 +216,8 @@ interface WithBgp { * The stage of the virtual network gateway definition which contains all the minimum required inputs for the * resource to be created, but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithPublicIPAddress, - DefinitionStages.WithBgp { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithPublicIPAddress, DefinitionStages.WithBgp { } } @@ -288,11 +277,7 @@ interface WithPointToSiteConfiguration { /** * The template for a virtual network gateway update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithBgp, - UpdateStages.WithPointToSiteConfiguration { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithBgp, UpdateStages.WithPointToSiteConfiguration { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnection.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnection.java index c12e9da211f85..a1c015be34637 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnection.java @@ -18,10 +18,8 @@ @Fluent public interface VirtualNetworkGatewayConnection extends IndependentChildResource, - Refreshable, - Updatable, - UpdatableWithTags, - HasParent { + Refreshable, Updatable, + UpdatableWithTags, HasParent { /** * Get the authorizationKey value. @@ -88,14 +86,9 @@ public interface VirtualNetworkGatewayConnection String provisioningState(); /** The entirety of the virtual network gateway connection definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithConnectionType, - DefinitionStages.WithLocalNetworkGateway, - DefinitionStages.WithSecondVirtualNetworkGateway, - DefinitionStages.WithSharedKey, - DefinitionStages.WithAuthorization, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithConnectionType, + DefinitionStages.WithLocalNetworkGateway, DefinitionStages.WithSecondVirtualNetworkGateway, + DefinitionStages.WithSharedKey, DefinitionStages.WithAuthorization, DefinitionStages.WithCreate { } /** Grouping of virtual network gateway connection definition stages. */ @@ -192,21 +185,14 @@ interface WithAuthorization { * The stage of a virtual network gateway connection definition with sufficient inputs to create a new * connection in the cloud, but exposing additional optional settings to specify. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithBgp, - WithAuthorization { + interface WithCreate extends Creatable, + Resource.DefinitionWithTags, WithBgp, WithAuthorization { } } /** Grouping of virtual network gateway connection update stages. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithBgp, - UpdateStages.WithSharedKey, - UpdateStages.WithAuthorization { + interface Update extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithBgp, UpdateStages.WithSharedKey, UpdateStages.WithAuthorization { } /** Grouping of virtual network gateway connection update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnections.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnections.java index 0078cb540d40a..33fe3ebaab43d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnections.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayConnections.java @@ -16,12 +16,9 @@ @Fluent public interface VirtualNetworkGatewayConnections extends SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsGettingById, - SupportsDeletingByName, - SupportsDeletingById, - HasParent { + SupportsListing, SupportsGettingByName, + SupportsGettingById, SupportsDeletingByName, SupportsDeletingById, + HasParent { /** * Gets the shared key of the virtual network gateway connection by resource ID. diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayIpConfiguration.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayIpConfiguration.java index 28d001fade3a1..c23b9d646c7f2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayIpConfiguration.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGatewayIpConfiguration.java @@ -97,10 +97,8 @@ interface WithAttach extends Attachable.InDefinition { * @param the stage of the parent application gateway definition to return to after attaching this * definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach, - DefinitionStages.WithPublicIPAddress { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach, + DefinitionStages.WithPublicIPAddress { } /** Grouping of application gateway IP configuration update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateways.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateways.java index ddbf34852cbf9..9da0a35685d63 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateways.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/VirtualNetworkGateways.java @@ -17,13 +17,8 @@ /** Entry point to virtual network gateways management API in Azure. */ @Fluent public interface VirtualNetworkGateways - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicies.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicies.java index 2ca993a2399f9..4c5e5ca10b37c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicies.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicies.java @@ -20,13 +20,8 @@ @Fluent public interface WebApplicationFirewallPolicies extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, + SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicy.java b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicy.java index 6d3f71ef798cf..0e6b2fb85358a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/WebApplicationFirewallPolicy.java @@ -18,8 +18,7 @@ /** Entry point for Web Application Firewall Policy. */ public interface WebApplicationFirewallPolicy extends GroupableResource, - Updatable, - Refreshable { + Updatable, Refreshable { /** @return mode of the Web Application Firewall Policy */ WebApplicationFirewallMode mode(); @@ -70,12 +69,8 @@ public interface WebApplicationFirewallPolicy /** * The entirety of the Web Application Firewall Policy definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.WithRequestBodyOrCreate, - DefinitionStages.WithManagedRulesOrCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.WithRequestBodyOrCreate, DefinitionStages.WithManagedRulesOrCreate { } /** Grouping of Web Application Gateway stages. */ @@ -85,7 +80,7 @@ interface Blank extends DefinitionWithRegion { } /** The stage of a Web Application Firewall Policy definition allowing to specify the resource group. */ - interface WithGroup extends GroupableResource.DefinitionStages.WithGroup{ + interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { } /** The stage of a Web Application Firewall Policy definition allowing to specify the managed rules. */ @@ -100,7 +95,7 @@ interface WithManagedRules { * @return the next stage of the definition */ WithManagedRulesOrCreate withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSet, - ManagedRuleGroupOverride... managedRuleGroupOverrides); + ManagedRuleGroupOverride... managedRuleGroupOverrides); /** * Specifies a managed rule set to be added to the Web Application Firewall, with optional rule group override @@ -112,7 +107,7 @@ WithManagedRulesOrCreate withManagedRuleSet(KnownWebApplicationGatewayManagedRul * @return the next stage of the definition */ WithManagedRulesOrCreate withManagedRuleSet(String type, String version, - ManagedRuleGroupOverride... managedRuleGroupOverrides); + ManagedRuleGroupOverride... managedRuleGroupOverrides); /** * Specifies a managed rule set to be added to the Web Application Firewall, with full configuration. @@ -222,8 +217,7 @@ interface WithInspectRequestBody { /** * The stage of a Web Application Firewall Policy definition allowing to specify request body configuration. */ - interface WithRequestBodyOrCreate - extends WithRequestBody, WithCreate { + interface WithRequestBodyOrCreate extends WithRequestBody, WithCreate { } /** @@ -268,14 +262,8 @@ interface WithRequestBody { * The stage of a Web Application Firewall Gateway definition containing all the required inputs for the resource to be * created, but also allowing for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - WithManagedRules, - WithMode, - WithState, - WithBotProtection, - WithInspectRequestBody { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + WithManagedRules, WithMode, WithState, WithBotProtection, WithInspectRequestBody { } } @@ -294,7 +282,7 @@ interface WithManagedRuleSet { * @return the next stage of the update */ Update withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSet, - ManagedRuleGroupOverride... managedRuleGroupOverrides); + ManagedRuleGroupOverride... managedRuleGroupOverrides); /** * Specifies a managed rule set to be added to the Web Application Firewall, with optional rule group override @@ -306,7 +294,7 @@ Update withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet managedRuleSe * @return the next stage of the update */ Update withManagedRuleSet(String type, String version, - ManagedRuleGroupOverride... managedRuleGroupOverrides); + ManagedRuleGroupOverride... managedRuleGroupOverrides); /** * Specifies a managed rule set to be added to the Web Application Firewall, with full configuration. @@ -488,13 +476,8 @@ interface WithRequestBody { /** The template for a Web Application Firewall Policy update operation, * containing all the settings that can be modified. */ interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithMode, - UpdateStages.WithState, - UpdateStages.WithBotProtection, - UpdateStages.WithInspectRequestBody, - UpdateStages.WithRequestBody, - UpdateStages.WithManagedRuleSet { + extends Appliable, Resource.UpdateWithTags, + UpdateStages.WithMode, UpdateStages.WithState, UpdateStages.WithBotProtection, + UpdateStages.WithInspectRequestBody, UpdateStages.WithRequestBody, UpdateStages.WithManagedRuleSet { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationGatewayTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationGatewayTests.java index 326574362985c..9bf2286693b30 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationGatewayTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationGatewayTests.java @@ -60,26 +60,24 @@ public void canCRUDApplicationGatewayWithWAF() throws Exception { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withAutoScale(2, 5) - .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withAutoScale(2, 5) + .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) + .create(); Assertions.assertNotNull(appGateway); Assertions.assertEquals(ApplicationGatewayTier.WAF_V2, appGateway.tier()); @@ -89,22 +87,14 @@ public void canCRUDApplicationGatewayWithWAF() throws Exception { ApplicationGatewayWebApplicationFirewallConfiguration config = appGateway.webApplicationFirewallConfiguration(); config.withFileUploadLimitInMb(200); - config - .withDisabledRuleGroups( - Arrays - .asList( - new ApplicationGatewayFirewallDisabledRuleGroup() - .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); + config.withDisabledRuleGroups(Arrays.asList(new ApplicationGatewayFirewallDisabledRuleGroup() + .withRuleGroupName("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION"))); config.withRequestBodyCheck(true); config.withMaxRequestBodySizeInKb(64); - config - .withExclusions( - Arrays - .asList( - new ApplicationGatewayFirewallExclusion() - .withMatchVariable("RequestHeaderNames") - .withSelectorMatchOperator("StartsWith") - .withSelector("User-Agent"))); + config.withExclusions( + Arrays.asList(new ApplicationGatewayFirewallExclusion().withMatchVariable("RequestHeaderNames") + .withSelectorMatchOperator("StartsWith") + .withSelector("User-Agent"))); appGateway.update().withWebApplicationFirewall(config).apply(); appGateway.refresh(); @@ -116,19 +106,15 @@ public void canCRUDApplicationGatewayWithWAF() throws Exception { Assertions.assertEquals(1, appGateway.webApplicationFirewallConfiguration().exclusions().size()); - Assertions.assertEquals( - "RequestHeaderNames", + Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().get(0).matchVariable()); - Assertions.assertEquals( - "StartsWith", + Assertions.assertEquals("StartsWith", appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selectorMatchOperator()); - Assertions.assertEquals( - "User-Agent", + Assertions.assertEquals("User-Agent", appGateway.webApplicationFirewallConfiguration().exclusions().get(0).selector()); Assertions.assertEquals(1, appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().size()); - Assertions.assertEquals( - "REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION", + Assertions.assertEquals("REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION", appGateway.webApplicationFirewallConfiguration().disabledRuleGroups().get(0).ruleGroupName()); } @@ -174,11 +160,7 @@ public void canSpecifyWildcardListeners() { // wildcard hostname String hostname2 = "*.contoso.com"; - gateway.update() - .updateListener(listener1) - .withHostname(hostname2) - .parent() - .apply(); + gateway.update().updateListener(listener1).withHostname(hostname2).parent().apply(); Assertions.assertEquals(hostname2, gateway.listeners().get(listener1).hostname()); @@ -187,11 +169,7 @@ public void canSpecifyWildcardListeners() { hostnames.add(hostname1); hostnames.add(hostname2); - gateway.update() - .updateListener(listener1) - .withHostnames(hostnames) - .parent() - .apply(); + gateway.update().updateListener(listener1).withHostnames(hostnames).parent().apply(); Assertions.assertEquals(hostnames, gateway.listeners().get(listener1).hostnames()); } @@ -204,57 +182,50 @@ public void canCreateApplicationGatewayWithSecret() throws Exception { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - Identity identity = - msiManager - .identities() - .define(identityName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .create(); + Identity identity = msiManager.identities() + .define(identityName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); - Secret secret1 = createKeyVaultSecret(azureCliSignedInUser().userPrincipalName(), - identity.principalId()); - Secret secret2 = createKeyVaultSecret(azureCliSignedInUser().userPrincipalName(), - identity.principalId()); + Secret secret1 = createKeyVaultSecret(azureCliSignedInUser().userPrincipalName(), identity.principalId()); + Secret secret2 = createKeyVaultSecret(azureCliSignedInUser().userPrincipalName(), identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpsPort(443) - .withSslCertificate("ssl1") - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withIdentity(serviceIdentity) - .defineSslCertificate("ssl1") - .withKeyVaultSecretId(secret1.id()) - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withAutoScale(2, 5) - .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpsPort(443) + .withSslCertificate("ssl1") + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withIdentity(serviceIdentity) + .defineSslCertificate("ssl1") + .withKeyVaultSecretId(secret1.id()) + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withAutoScale(2, 5) + .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) + .create(); Assertions.assertEquals(secret1.id(), appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); - Assertions - .assertEquals( - secret1.id(), appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); + Assertions.assertEquals(secret1.id(), + appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); - appGateway = - appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); + appGateway + = appGateway.update().defineSslCertificate("ssl2").withKeyVaultSecretId(secret2.id()).attach().apply(); Assertions.assertEquals(secret2.id(), appGateway.sslCertificates().get("ssl2").keyVaultSecretId()); } @@ -267,51 +238,46 @@ public void canCreateApplicationGatewayWithSslCertificate() throws Exception { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - Identity identity = - msiManager - .identities() - .define(identityName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .create(); + Identity identity = msiManager.identities() + .define(identityName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .create(); Assertions.assertNotNull(identity.name()); Assertions.assertNotNull(identity.principalId()); ManagedServiceIdentity serviceIdentity = createManagedServiceIdentityFromIdentity(identity); - String secretId = createKeyVaultCertificate( - azureCliSignedInUser().userPrincipalName(), - identity.principalId()); + String secretId = createKeyVaultCertificate(azureCliSignedInUser().userPrincipalName(), identity.principalId()); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpsPort(443) - .withSslCertificate("ssl1") - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withIdentity(serviceIdentity) - .defineSslCertificate("ssl1") - .withKeyVaultSecretId(secretId) - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withAutoScale(2, 5) - .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpsPort(443) + .withSslCertificate("ssl1") + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withIdentity(serviceIdentity) + .defineSslCertificate("ssl1") + .withKeyVaultSecretId(secretId) + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withAutoScale(2, 5) + .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) + .create(); Assertions.assertEquals(secretId, appGateway.sslCertificates().get("ssl1").keyVaultSecretId()); - Assertions.assertEquals(secretId, appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); + Assertions.assertEquals(secretId, + appGateway.requestRoutingRules().get("rule1").sslCertificate().keyVaultSecretId()); } @Test @@ -321,50 +287,48 @@ public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - // Request routing rules - // rule1 with no priority - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - // rule2 with no priority - .defineRequestRoutingRule("rule2") - .fromPublicFrontend() - .fromFrontendHttpPort(81) - .toBackendHttpPort(8181) - .toBackendIPAddress("11.1.1.3") - .attach() - // rule3 with priority 1 - .defineRequestRoutingRule("rule3") - .fromPublicFrontend() - .fromFrontendHttpPort(83) - .toBackendHttpPort(8383) - .toBackendIPAddress("11.1.1.4") - .withPriority(1) - .attach() - // rule4 with priority 20000 - .defineRequestRoutingRule("rule4") - .fromPublicFrontend() - .fromFrontendHttpPort(84) - .toBackendHttpPort(8384) - .toBackendIPAddress("11.1.1.5") - .withPriority(20000) - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withAutoScale(2, 5) - .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + // Request routing rules + // rule1 with no priority + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + // rule2 with no priority + .defineRequestRoutingRule("rule2") + .fromPublicFrontend() + .fromFrontendHttpPort(81) + .toBackendHttpPort(8181) + .toBackendIPAddress("11.1.1.3") + .attach() + // rule3 with priority 1 + .defineRequestRoutingRule("rule3") + .fromPublicFrontend() + .fromFrontendHttpPort(83) + .toBackendHttpPort(8383) + .toBackendIPAddress("11.1.1.4") + .withPriority(1) + .attach() + // rule4 with priority 20000 + .defineRequestRoutingRule("rule4") + .fromPublicFrontend() + .fromFrontendHttpPort(84) + .toBackendHttpPort(8384) + .toBackendIPAddress("11.1.1.5") + .withPriority(20000) + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withAutoScale(2, 5) + .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) + .create(); // add a rule5 with no priority appGateway.update() .defineRequestRoutingRule("rule5") @@ -402,11 +366,7 @@ public void canAutoAssignPriorityForRequestRoutingRulesWithWAF() { Assertions.assertEquals(10050, appGateway.requestRoutingRules().get("rule6").priority()); // update rule3's priority from 1 to 2 - appGateway.update() - .updateRequestRoutingRule("rule3") - .withPriority(2) - .parent() - .apply(); + appGateway.update().updateRequestRoutingRule("rule3").withPriority(2).parent().apply(); Assertions.assertEquals(2, appGateway.requestRoutingRules().get("rule3").priority()); } @@ -416,49 +376,41 @@ public void testAddRemoveIpAddressFromWafV2WithExclusionsEqualsAny() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withNewResourceGroup(rgName) - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withAutoScale(2, 5) - .withWebApplicationFirewall( - new ApplicationGatewayWebApplicationFirewallConfiguration() - .withEnabled(true) - .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) - .withRuleSetType("OWASP") - .withRuleSetVersion("3.0") - .withExclusions(Collections.singletonList( - new ApplicationGatewayFirewallExclusion() - .withMatchVariable("RequestHeaderNames") - .withSelectorMatchOperator(null) // Equals any - .withSelector(null) // * - )) - ) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withNewResourceGroup(rgName) + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withAutoScale(2, 5) + .withWebApplicationFirewall(new ApplicationGatewayWebApplicationFirewallConfiguration().withEnabled(true) + .withFirewallMode(ApplicationGatewayFirewallMode.PREVENTION) + .withRuleSetType("OWASP") + .withRuleSetVersion("3.0") + .withExclusions(Collections + .singletonList(new ApplicationGatewayFirewallExclusion().withMatchVariable("RequestHeaderNames") + .withSelectorMatchOperator(null) // Equals any + .withSelector(null) // * + ))) + .create(); - Assertions.assertEquals("RequestHeaderNames", appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); - Assertions.assertNull(appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); + Assertions.assertEquals("RequestHeaderNames", + appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().matchVariable()); + Assertions.assertNull( + appGateway.webApplicationFirewallConfiguration().exclusions().iterator().next().selectorMatchOperator()); Map backends = appGateway.backends(); - backends.forEach((name, backend) -> - backend.addresses().forEach(addr -> - appGateway.update() - .updateBackend(name) - .withoutIPAddress(addr.ipAddress()) - .parent() - .apply())); + backends.forEach((name, backend) -> backend.addresses() + .forEach( + addr -> appGateway.update().updateBackend(name).withoutIPAddress(addr.ipAddress()).parent().apply())); } @Test @@ -468,33 +420,29 @@ public void canAssociateWafPolicy() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - WebApplicationFirewallPolicy wafPolicy = - networkManager - .webApplicationFirewallPolicies() - .define(wafPolicyName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) - .create(); + WebApplicationFirewallPolicy wafPolicy = networkManager.webApplicationFirewallPolicies() + .define(wafPolicyName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2) + .create(); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withExistingWebApplicationFirewallPolicy(wafPolicy) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withExistingWebApplicationFirewallPolicy(wafPolicy) + .create(); Assertions.assertNotNull(appGateway.getWebApplicationFirewallPolicy()); Assertions.assertNull(appGateway.webApplicationFirewallConfiguration()); @@ -504,9 +452,7 @@ public void canAssociateWafPolicy() { Assertions.assertEquals(appGateway.id(), wafPolicy.getAssociatedApplicationGateways().iterator().next().id()); Assertions.assertEquals(wafPolicy.id(), appGateway.getWebApplicationFirewallPolicy().id()); - appGateway.update() - .withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION) - .apply(); + appGateway.update().withNewWebApplicationFirewallPolicy(WebApplicationFirewallMode.PREVENTION).apply(); WebApplicationFirewallPolicy newPolicy = appGateway.getWebApplicationFirewallPolicy(); @@ -537,24 +483,20 @@ public void canAssociateWafPolicy() { .withTier(ApplicationGatewayTier.WAF_V2) .withSize(ApplicationGatewaySkuName.WAF_V2) // mixed legacy WAF configuration and WAF policy - .withNewWebApplicationFirewallPolicy( - networkManager - .webApplicationFirewallPolicies() - .define(invalidPolicyName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) + .withNewWebApplicationFirewallPolicy(networkManager.webApplicationFirewallPolicies() + .define(invalidPolicyName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2)) .withWebApplicationFirewall(true, ApplicationGatewayFirewallMode.PREVENTION) .create(); }); // assert no policy is created - Assertions.assertTrue( - networkManager - .webApplicationFirewallPolicies() - .listByResourceGroup(rgName) - .stream() - .noneMatch(policy -> policy.name().equals(invalidPolicyName))); + Assertions.assertTrue(networkManager.webApplicationFirewallPolicies() + .listByResourceGroup(rgName) + .stream() + .noneMatch(policy -> policy.name().equals(invalidPolicyName))); } @Test @@ -564,24 +506,22 @@ public void canSetSslPolicy() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); // create with predefined ssl policy - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withPredefinedSslPolicy(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) + .create(); ApplicationGatewaySslPolicy sslPolicy = appGateway.sslPolicy(); Assertions.assertNotNull(sslPolicy); @@ -590,7 +530,8 @@ public void canSetSslPolicy() { // update with custom ssl policy appGateway.update() - .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) + .withCustomV2SslPolicy(ApplicationGatewaySslProtocol.TLSV1_2, + Collections.singletonList(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)) .apply(); sslPolicy = appGateway.sslPolicy(); @@ -598,15 +539,16 @@ public void canSetSslPolicy() { Assertions.assertEquals(ApplicationGatewaySslPolicyType.CUSTOM_V2, sslPolicy.policyType()); Assertions.assertNull(sslPolicy.policyName()); Assertions.assertEquals(ApplicationGatewaySslProtocol.TLSV1_2, sslPolicy.minProtocolVersion()); - Assertions.assertTrue(sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); + Assertions.assertTrue( + sslPolicy.cipherSuites().contains(ApplicationGatewaySslCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)); // predefined policy doesn't not support minProtocolVersion Assertions.assertThrows(ManagementException.class, () -> { appGateway.update() - .withSslPolicy(new ApplicationGatewaySslPolicy() - .withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) - .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) - .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) + .withSslPolicy( + new ApplicationGatewaySslPolicy().withPolicyType(ApplicationGatewaySslPolicyType.PREDEFINED) + .withPolicyName(ApplicationGatewaySslPolicyName.APP_GW_SSL_POLICY20150501) + .withMinProtocolVersion(ApplicationGatewaySslProtocol.TLSV1_1)) .apply(); }); } @@ -617,24 +559,22 @@ public void canCreateApplicationGatewayWithDefaultSku() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - ApplicationGateway appGateway = - networkManager - .applicationGateways() - .define(appGatewayName) - .withRegion(REGION) - .withNewResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - // BASIC still needs a public frontend. With private only, it'll report error: - // "Application Gateway does not support Application Gateway without Public IP for the selected SKU tier Basic. - // Supported SKU tiers are Standard,WAF." - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .attach() - .withExistingPublicIpAddress(pip) - .create(); + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) + .withRegion(REGION) + .withNewResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + // BASIC still needs a public frontend. With private only, it'll report error: + // "Application Gateway does not support Application Gateway without Public IP for the selected SKU tier Basic. + // Supported SKU tiers are Standard,WAF." + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .attach() + .withExistingPublicIpAddress(pip) + .create(); Assertions.assertEquals(ApplicationGatewayTier.BASIC, appGateway.tier()); // BASIC still supports request routing rule priority. @@ -648,28 +588,29 @@ public void canCRUDProbes() { PublicIpAddress pip = createResourceGroupAndPublicIpAddress(); - ApplicationGateway appGateway = networkManager.applicationGateways().define(appGatewayName) + ApplicationGateway appGateway = networkManager.applicationGateways() + .define(appGatewayName) .withRegion(REGION) .withNewResourceGroup(rgName) // Request routing rules .defineRequestRoutingRule("rule1") - // BASIC still needs a public frontend. With private only, it'll report error: - // "Application Gateway does not support Application Gateway without Public IP for the selected SKU tier Basic. - // Supported SKU tiers are Standard,WAF." - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .attach() + // BASIC still needs a public frontend. With private only, it'll report error: + // "Application Gateway does not support Application Gateway without Public IP for the selected SKU tier Basic. + // Supported SKU tiers are Standard,WAF." + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .attach() .defineProbe(probeName) - .withHostNameFromBackendHttpSettings() - .withPath("/") - .withHttp() - .withTimeoutInSeconds(10) - .withTimeBetweenProbesInSeconds(9) - .withRetriesBeforeUnhealthy(5) - .withHealthyHttpResponseStatusCodeRange(200, 249) - .attach() + .withHostNameFromBackendHttpSettings() + .withPath("/") + .withHttp() + .withTimeoutInSeconds(10) + .withTimeBetweenProbesInSeconds(9) + .withRetriesBeforeUnhealthy(5) + .withHealthyHttpResponseStatusCodeRange(200, 249) + .attach() .withExistingPublicIpAddress(pip) .create(); @@ -679,18 +620,16 @@ public void canCRUDProbes() { appGateway.update() .updateProbe(probeName) - .withoutHostNameFromBackendHttpSettings() - .withHost("microsoft.com") - .parent() + .withoutHostNameFromBackendHttpSettings() + .withHost("microsoft.com") + .parent() .apply(); Assertions.assertEquals(1, appGateway.probes().size()); Assertions.assertNotNull(appGateway.probes().get(probeName).host()); Assertions.assertFalse(appGateway.probes().get(probeName).isHostNameFromBackendHttpSettings()); - appGateway.update() - .withoutProbe(probeName) - .apply(); + appGateway.update().withoutProbe(probeName).apply(); Assertions.assertTrue(appGateway.probes().isEmpty()); } @@ -699,34 +638,32 @@ private String createKeyVaultCertificate(String signedInUser, String identityPri String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .defineAccessPolicy() - .forUser(signedInUser) - .allowSecretAllPermissions() - .allowCertificateAllPermissions() - .attach() - .defineAccessPolicy() - .forObjectId(identityPrincipal) - .allowSecretAllPermissions() - .attach() - .withAccessFromAzureServices() - .withDeploymentEnabled() -// // Important!! Only soft delete enabled key vault can be assigned to application gateway -// // See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382 -// .withSoftDeleteEnabled() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forUser(signedInUser) + .allowSecretAllPermissions() + .allowCertificateAllPermissions() + .attach() + .defineAccessPolicy() + .forObjectId(identityPrincipal) + .allowSecretAllPermissions() + .attach() + .withAccessFromAzureServices() + .withDeploymentEnabled() + // // Important!! Only soft delete enabled key vault can be assigned to application gateway + // // See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382 + // .withSoftDeleteEnabled() + .create(); // create certificate - CertificateClient certificateClient = new CertificateClientBuilder() - .vaultUrl(vault.vaultUri()) + CertificateClient certificateClient = new CertificateClientBuilder().vaultUrl(vault.vaultUri()) .pipeline(vault.vaultHttpPipeline()) .buildClient(); - KeyVaultCertificateWithPolicy certificate = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); + KeyVaultCertificateWithPolicy certificate + = certificateClient.beginCreateCertificate(secretName, CertificatePolicy.getDefault()).getFinalResult(); // take secret ID of the certificate return certificate.getSecretId(); @@ -735,30 +672,28 @@ private String createKeyVaultCertificate(String signedInUser, String identityPri private Secret createKeyVaultSecret(String signedInUser, String identityPrincipal) throws Exception { String vaultName = generateRandomResourceName("vlt", 10); String secretName = generateRandomResourceName("srt", 10); - BufferedReader buff = new BufferedReader(new FileReader(new File(getClass().getClassLoader() - .getResource("test.certificate").getFile()))); + BufferedReader buff = new BufferedReader( + new FileReader(new File(getClass().getClassLoader().getResource("test.certificate").getFile()))); String secretValue = buff.readLine(); - Vault vault = - keyVaultManager - .vaults() - .define(vaultName) - .withRegion(REGION) - .withExistingResourceGroup(rgName) - .defineAccessPolicy() - .forUser(signedInUser) - .allowSecretAllPermissions() - .attach() - .defineAccessPolicy() - .forObjectId(identityPrincipal) - .allowSecretAllPermissions() - .attach() - .withAccessFromAzureServices() - .withDeploymentEnabled() -// // Important!! Only soft delete enabled key vault can be assigned to application gateway -// // See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382 -// .withSoftDeleteEnabled() - .create(); + Vault vault = keyVaultManager.vaults() + .define(vaultName) + .withRegion(REGION) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forUser(signedInUser) + .allowSecretAllPermissions() + .attach() + .defineAccessPolicy() + .forObjectId(identityPrincipal) + .allowSecretAllPermissions() + .attach() + .withAccessFromAzureServices() + .withDeploymentEnabled() + // // Important!! Only soft delete enabled key vault can be assigned to application gateway + // // See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382 + // .withSoftDeleteEnabled() + .create(); return vault.secrets().define(secretName).withValue(secretValue).create(); } @@ -768,12 +703,9 @@ private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(I Map userAssignedIdentitiesValueObject = new HashMap<>(); userAssignedIdentitiesValueObject.put("principalId", identity.principalId()); userAssignedIdentitiesValueObject.put("clientId", identity.clientId()); - ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = - serializerAdapter - .deserialize( - serializerAdapter.serialize(userAssignedIdentitiesValueObject, SerializerEncoding.JSON), - ManagedServiceIdentityUserAssignedIdentities.class, - SerializerEncoding.JSON); + ManagedServiceIdentityUserAssignedIdentities userAssignedIdentitiesValue = serializerAdapter.deserialize( + serializerAdapter.serialize(userAssignedIdentitiesValueObject, SerializerEncoding.JSON), + ManagedServiceIdentityUserAssignedIdentities.class, SerializerEncoding.JSON); Map userAssignedIdentities = new HashMap<>(); userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue); @@ -785,8 +717,7 @@ private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(I private PublicIpAddress createResourceGroupAndPublicIpAddress() { String appPublicIp = generateRandomResourceName("pip", 15); - return networkManager - .publicIpAddresses() + return networkManager.publicIpAddresses() .define(appPublicIp) .withRegion(REGION) .withNewResourceGroup(rgName) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationSecurityGroupTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationSecurityGroupTests.java index 123eff7748663..e55175d13460b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationSecurityGroupTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/ApplicationSecurityGroupTests.java @@ -16,14 +16,12 @@ public class ApplicationSecurityGroupTests extends NetworkManagementTest { public void canCRUDApplicationSecurityGroup() throws Exception { String asgName = generateRandomResourceName("asg", 15); - ApplicationSecurityGroup applicationSecurityGroup = - networkManager - .applicationSecurityGroups() - .define(asgName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .withTag("tag1", "value1") - .create(); + ApplicationSecurityGroup applicationSecurityGroup = networkManager.applicationSecurityGroups() + .define(asgName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals("value1", applicationSecurityGroup.tags().get("tag1")); PagedIterable asgList = networkManager.applicationSecurityGroups().list(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java index 1fa445a31705f..f92ad7af89d98 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java @@ -15,14 +15,12 @@ public class DdosProtectionPlanTests extends NetworkManagementTest { public void canCRUDDdosProtectionPlan() throws Exception { String ppName = generateRandomResourceName("ddosplan", 15); - DdosProtectionPlan pPlan = - networkManager - .ddosProtectionPlans() - .define(ppName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .withTag("tag1", "value1") - .create(); + DdosProtectionPlan pPlan = networkManager.ddosProtectionPlans() + .define(ppName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals("value1", pPlan.tags().get("tag1")); PagedIterable ppList = networkManager.ddosProtectionPlans().list(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/LoadBalancerTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/LoadBalancerTests.java index 40a8dae269380..bad4fbfd27bd5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/LoadBalancerTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/LoadBalancerTests.java @@ -35,20 +35,19 @@ public void canCRUDProbe() throws Exception { String vmName = generateRandomResourceName("vm", 8); String lbName = generateRandomResourceName("lb", 8); - ResourceGroup resourceGroup = - resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - Network network = - networkManager - .networks() - .define(vmName) - .withRegion(resourceGroup.region()) - .withExistingResourceGroup(resourceGroup.name()) - .withAddressSpace("172.18.0.0/28") - .withSubnet(SUBNET_NAME, "172.18.0.0/28") - .create(); + Network network = networkManager.networks() + .define(vmName) + .withRegion(resourceGroup.region()) + .withExistingResourceGroup(resourceGroup.name()) + .withAddressSpace("172.18.0.0/28") + .withSubnet(SUBNET_NAME, "172.18.0.0/28") + .create(); - LoadBalancer loadBalancer = createLoadBalancerWithPrivateFrontend(networkManager, resourceGroup, network, lbName); + LoadBalancer loadBalancer + = createLoadBalancerWithPrivateFrontend(networkManager, resourceGroup, network, lbName); // verify created probes Assertions.assertEquals(2, loadBalancer.loadBalancingRules().size()); @@ -66,8 +65,7 @@ public void canCRUDProbe() throws Exception { Assertions.assertEquals("/", httpsProbe.requestPath()); // update probe - loadBalancer - .update() + loadBalancer.update() .updateHttpsProbe(PROBE_NAME_2) .withIntervalInSeconds(60) .withRequestPath("/health") @@ -115,10 +113,11 @@ public void canCreateOutboundRule() { String publicIpName2 = generateRandomResourceName("pip", 15); String outboundRuleName = lbName + "-OutboundRule1"; - ResourceGroup resourceGroup = - resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - LoadBalancer loadBalancer = createLoadBalancerWithPublicFrontendAndOutboundRule(networkManager, resourceGroup, lbName, frontendName1, frontendName2, backendPoolName, publicIpName1, publicIpName2, outboundRuleName); + LoadBalancer loadBalancer = createLoadBalancerWithPublicFrontendAndOutboundRule(networkManager, resourceGroup, + lbName, frontendName1, frontendName2, backendPoolName, publicIpName1, publicIpName2, outboundRuleName); // assertions for loadbalancer properties Assertions.assertEquals(lbName, loadBalancer.name()); @@ -178,19 +177,13 @@ public void canUpdateOutboundRule() { String outboundRuleName1 = lbName + "-OutboundRule1"; String outboundRuleName2 = lbName + "-OutboundRule2"; - ResourceGroup resourceGroup = - resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - - - LoadBalancer loadBalancer = createLoadBalancerWithPublicFrontendAndOutboundRule(networkManager, resourceGroup, lbName, frontendName1, frontendName2, backendPoolName, publicIpName1, publicIpName2, outboundRuleName1); + LoadBalancer loadBalancer = createLoadBalancerWithPublicFrontendAndOutboundRule(networkManager, resourceGroup, + lbName, frontendName1, frontendName2, backendPoolName, publicIpName1, publicIpName2, outboundRuleName1); // 1. update loadbalancer, update outbound rule - loadBalancer - .update() - .updateOutboundRule(outboundRuleName1) - .withIdleTimeoutInMinutes(50) - .parent() - .apply(); + loadBalancer.update().updateOutboundRule(outboundRuleName1).withIdleTimeoutInMinutes(50).parent().apply(); Map outboundRules = loadBalancer.outboundRules(); Assertions.assertEquals(1, outboundRules.size()); @@ -214,16 +207,12 @@ public void canUpdateOutboundRule() { Assertions.assertEquals(false, outboundRule.tcpResetEnabled()); // 2. update loadbalancer, remove outbound rule - loadBalancer - .update() - .withoutOutboundRule(outboundRuleName1) - .apply(); + loadBalancer.update().withoutOutboundRule(outboundRuleName1).apply(); Assertions.assertEquals(0, loadBalancer.outboundRules().size()); // 3. update loadbalancer, define a new outbound rule - loadBalancer - .update() + loadBalancer.update() .defineOutboundRule(outboundRuleName2) .withProtocol(LoadBalancerOutboundRuleProtocol.TCP) .fromBackend(backendPoolName) @@ -240,13 +229,16 @@ public void canUpdateOutboundRule() { Assertions.assertEquals(1024, outboundRuleOnUpdateDefine.allocatedOutboundPorts()); Assertions.assertEquals(backendPoolName, outboundRuleOnUpdateDefine.backend().name()); - List outboundRuleFrontendsOnUpdateDefine = new ArrayList<>(outboundRuleOnUpdateDefine.frontends().values()); + List outboundRuleFrontendsOnUpdateDefine + = new ArrayList<>(outboundRuleOnUpdateDefine.frontends().values()); Assertions.assertEquals(1, outboundRuleFrontendsOnUpdateDefine.size()); Assertions.assertEquals(frontendName2, outboundRuleFrontendsOnUpdateDefine.get(0).name()); Assertions.assertEquals(1, outboundRuleFrontendsOnUpdateDefine.get(0).outboundRules().size()); - Assertions.assertTrue(outboundRuleFrontendsOnUpdateDefine.get(0).outboundRules().containsKey(outboundRuleName2)); + Assertions + .assertTrue(outboundRuleFrontendsOnUpdateDefine.get(0).outboundRules().containsKey(outboundRuleName2)); Assertions.assertEquals(true, outboundRuleFrontendsOnUpdateDefine.get(0).isPublic()); - LoadBalancerPublicFrontend publicFrontendOnUpdateDefine = (LoadBalancerPublicFrontend) outboundRuleFrontendsOnUpdateDefine.get(0); + LoadBalancerPublicFrontend publicFrontendOnUpdateDefine + = (LoadBalancerPublicFrontend) outboundRuleFrontendsOnUpdateDefine.get(0); Assertions.assertNotNull(publicFrontendOnUpdateDefine.getPublicIpAddress()); Assertions.assertEquals(publicIpName2, publicFrontendOnUpdateDefine.getPublicIpAddress().name()); @@ -255,124 +247,117 @@ public void canUpdateOutboundRule() { } - private static LoadBalancer createLoadBalancerWithPrivateFrontend( - NetworkManager networkManager, ResourceGroup resourceGroup, Network network, String lbName) { + private static LoadBalancer createLoadBalancerWithPrivateFrontend(NetworkManager networkManager, + ResourceGroup resourceGroup, Network network, String lbName) { final String frontendName = lbName + "-FE1"; final String backendPoolName1 = lbName + "-BAP1"; final String backendPoolName2 = lbName + "-BAP2"; final String natPool50XXto22 = lbName + "natPool50XXto22"; final String natPool60XXto23 = lbName + "natPool60XXto23"; - LoadBalancer loadBalancer1 = - networkManager - .loadBalancers() - .define(lbName) - .withRegion(resourceGroup.region()) - .withExistingResourceGroup(resourceGroup.name()) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(RULE_NAME_1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(PROBE_NAME_1) - .attach() - .defineLoadBalancingRule(RULE_NAME_2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(PROBE_NAME_2) - .attach() - // Add nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatPool(natPool50XXto22) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPool60XXto23) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - // Explicitly define the frontend - .definePrivateFrontend(frontendName) - .withExistingSubnet(network, SUBNET_NAME) - .attach() - // Add two probes one per rule - .defineHttpProbe(PROBE_NAME_1) - .withRequestPath("/") - .attach() - .defineHttpsProbe(PROBE_NAME_2) - .withRequestPath("/") - .attach() - .withSku(LoadBalancerSkuType.STANDARD) - .create(); + LoadBalancer loadBalancer1 = networkManager.loadBalancers() + .define(lbName) + .withRegion(resourceGroup.region()) + .withExistingResourceGroup(resourceGroup.name()) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(RULE_NAME_1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(PROBE_NAME_1) + .attach() + .defineLoadBalancingRule(RULE_NAME_2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(PROBE_NAME_2) + .attach() + // Add nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatPool(natPool50XXto22) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPool60XXto23) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + // Explicitly define the frontend + .definePrivateFrontend(frontendName) + .withExistingSubnet(network, SUBNET_NAME) + .attach() + // Add two probes one per rule + .defineHttpProbe(PROBE_NAME_1) + .withRequestPath("/") + .attach() + .defineHttpsProbe(PROBE_NAME_2) + .withRequestPath("/") + .attach() + .withSku(LoadBalancerSkuType.STANDARD) + .create(); return loadBalancer1; } - private static LoadBalancer createLoadBalancerWithPublicFrontendAndOutboundRule( - NetworkManager networkManager, ResourceGroup resourceGroup, String lbName, String frontendName1, String frontendName2, String backendPoolName, String publicIpName1, String publicIpName2, String outboundRuleName) { - - PublicIpAddress pip1 = - networkManager - .publicIpAddresses() - .define(publicIpName1) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP() - .create(); - - PublicIpAddress pip2 = - networkManager - .publicIpAddresses() - .define(publicIpName2) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP() - .create(); - - LoadBalancer loadBalancer1 = - networkManager - .loadBalancers() - .define(lbName) - .withRegion(resourceGroup.region()) - .withExistingResourceGroup(resourceGroup) - // Add rule that uses above backend and probe - .defineLoadBalancingRule(RULE_NAME_1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName1) - .fromFrontendPort(80) - .toBackend(backendPoolName) - .withProbe(PROBE_NAME_1) - .attach() - // Explicitly define the frontend - .definePublicFrontend(frontendName1) - .withExistingPublicIpAddress(pip1) - .attach() - .definePublicFrontend(frontendName2) - .withExistingPublicIpAddress(pip2) - .attach() - // add outbound rule - .defineOutboundRule(outboundRuleName) - .withProtocol(LoadBalancerOutboundRuleProtocol.TCP) - .fromBackend(backendPoolName) - .toFrontend(frontendName2) - .withEnableTcpReset(false) - .withIdleTimeoutInMinutes(5) - .attach() - // Add one probe - .defineHttpProbe(PROBE_NAME_1) - .withRequestPath("/") - .attach() - .withSku(LoadBalancerSkuType.STANDARD) - .create(); + private static LoadBalancer createLoadBalancerWithPublicFrontendAndOutboundRule(NetworkManager networkManager, + ResourceGroup resourceGroup, String lbName, String frontendName1, String frontendName2, String backendPoolName, + String publicIpName1, String publicIpName2, String outboundRuleName) { + + PublicIpAddress pip1 = networkManager.publicIpAddresses() + .define(publicIpName1) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP() + .create(); + + PublicIpAddress pip2 = networkManager.publicIpAddresses() + .define(publicIpName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP() + .create(); + + LoadBalancer loadBalancer1 = networkManager.loadBalancers() + .define(lbName) + .withRegion(resourceGroup.region()) + .withExistingResourceGroup(resourceGroup) + // Add rule that uses above backend and probe + .defineLoadBalancingRule(RULE_NAME_1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName1) + .fromFrontendPort(80) + .toBackend(backendPoolName) + .withProbe(PROBE_NAME_1) + .attach() + // Explicitly define the frontend + .definePublicFrontend(frontendName1) + .withExistingPublicIpAddress(pip1) + .attach() + .definePublicFrontend(frontendName2) + .withExistingPublicIpAddress(pip2) + .attach() + // add outbound rule + .defineOutboundRule(outboundRuleName) + .withProtocol(LoadBalancerOutboundRuleProtocol.TCP) + .fromBackend(backendPoolName) + .toFrontend(frontendName2) + .withEnableTcpReset(false) + .withIdleTimeoutInMinutes(5) + .attach() + // Add one probe + .defineHttpProbe(PROBE_NAME_1) + .withRequestPath("/") + .attach() + .withSku(LoadBalancerSkuType.STANDARD) + .create(); return loadBalancer1; } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkInterfaceOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkInterfaceOperationsTests.java index 2511b0f1c1c86..6e6e994db2827 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkInterfaceOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkInterfaceOperationsTests.java @@ -41,7 +41,7 @@ public class NetworkInterfaceOperationsTests extends NetworkManagementTest { @Test - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void canUseMultipleIPConfigs() throws Exception { String networkName = generateRandomResourceName("net", 15); String[] nicNames = new String[3]; @@ -49,60 +49,52 @@ public void canUseMultipleIPConfigs() throws Exception { nicNames[i] = generateRandomResourceName("nic", 15); } - Network network = - networkManager - .networks() - .define(networkName) + Network network = networkManager.networks() + .define(networkName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/27") + .withSubnet("subnet1", "10.0.0.0/28") + .withSubnet("subnet2", "10.0.0.16/28") + .create(); + + List> nicDefinitions = Arrays.asList( + // 0 - NIC that starts with one IP config and ends with two + (Creatable) (networkManager.networkInterfaces() + .define(nicNames[0]) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/27") - .withSubnet("subnet1", "10.0.0.0/28") - .withSubnet("subnet2", "10.0.0.16/28") - .create(); + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") + .withPrimaryPrivateIPAddressDynamic()), + + // 1 - NIC that starts with two IP configs and ends with one + networkManager.networkInterfaces() + .define(nicNames[1]) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") + .withPrimaryPrivateIPAddressDynamic() + .defineSecondaryIPConfiguration("nicip2") + .withExistingNetwork(network) + .withSubnet("subnet1") + .withPrivateIpAddressDynamic() + .attach(), - List> nicDefinitions = - Arrays - .asList( - // 0 - NIC that starts with one IP config and ends with two - (Creatable) - (networkManager - .networkInterfaces() - .define(nicNames[0]) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") - .withPrimaryPrivateIPAddressDynamic()), - - // 1 - NIC that starts with two IP configs and ends with one - networkManager - .networkInterfaces() - .define(nicNames[1]) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") - .withPrimaryPrivateIPAddressDynamic() - .defineSecondaryIPConfiguration("nicip2") - .withExistingNetwork(network) - .withSubnet("subnet1") - .withPrivateIpAddressDynamic() - .attach(), - - // 2 - NIC that starts with two IP configs and ends with two - networkManager - .networkInterfaces() - .define(nicNames[2]) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") - .withPrimaryPrivateIPAddressDynamic() - .defineSecondaryIPConfiguration("nicip2") - .withExistingNetwork(network) - .withSubnet("subnet1") - .withPrivateIpAddressDynamic() - .attach()); + // 2 - NIC that starts with two IP configs and ends with two + networkManager.networkInterfaces() + .define(nicNames[2]) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") + .withPrimaryPrivateIPAddressDynamic() + .defineSecondaryIPConfiguration("nicip2") + .withExistingNetwork(network) + .withSubnet("subnet1") + .withPrivateIpAddressDynamic() + .attach()); // Create the NICs in parallel CreatedResources createdNics = networkManager.networkInterfaces().create(nicDefinitions); @@ -155,42 +147,36 @@ public void canUseMultipleIPConfigs() throws Exception { nic = null; - List> nicUpdates = - Arrays - .asList( - // Update NIC0 - nics[0] - .update() - .defineSecondaryIPConfiguration("nicip2") - .withExistingNetwork(network) - .withSubnet("subnet1") - .withPrivateIpAddressDynamic() - .attach() - .applyAsync(), - - // Update NIC2 - nics[1] - .update() - .withoutIPConfiguration("nicip2") - .updateIPConfiguration("primary") - .withSubnet("subnet2") - .parent() - .applyAsync(), - - // Update NIC3 - nics[2] - .update() - .withoutIPConfiguration("nicip2") - .defineSecondaryIPConfiguration("nicip3") - .withExistingNetwork(network) - .withSubnet("subnet1") - .withPrivateIpAddressDynamic() - .attach() - .applyAsync()); - - List updatedNics = - Flux - .mergeDelayError(32, (Mono[]) nicUpdates.toArray(new Mono[0])) + List> nicUpdates = Arrays.asList( + // Update NIC0 + nics[0].update() + .defineSecondaryIPConfiguration("nicip2") + .withExistingNetwork(network) + .withSubnet("subnet1") + .withPrivateIpAddressDynamic() + .attach() + .applyAsync(), + + // Update NIC2 + nics[1].update() + .withoutIPConfiguration("nicip2") + .updateIPConfiguration("primary") + .withSubnet("subnet2") + .parent() + .applyAsync(), + + // Update NIC3 + nics[2].update() + .withoutIPConfiguration("nicip2") + .defineSecondaryIPConfiguration("nicip3") + .withExistingNetwork(network) + .withSubnet("subnet1") + .withPrivateIpAddressDynamic() + .attach() + .applyAsync()); + + List updatedNics + = Flux.mergeDelayError(32, (Mono[]) nicUpdates.toArray(new Mono[0])) .collectList() .block(); @@ -250,58 +236,45 @@ public void canCreateBatchOfNetworkInterfaces() throws Exception { Creatable resourceGroupCreatable = resourceGroups.define(rgName).withRegion(Region.US_EAST); final String vnetName = "vnet1212"; - Creatable networkCreatable = - networks - .define(vnetName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(resourceGroupCreatable) - .withAddressSpace("10.0.0.0/28"); + Creatable networkCreatable = networks.define(vnetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(resourceGroupCreatable) + .withAddressSpace("10.0.0.0/28"); // Prepare a batch of nics // final String nic1Name = "nic1"; - Creatable networkInterface1Creatable = - networkInterfaces - .define(nic1Name) - .withRegion(Region.US_EAST) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.5"); + Creatable networkInterface1Creatable = networkInterfaces.define(nic1Name) + .withRegion(Region.US_EAST) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.5"); final String nic2Name = "nic2"; - Creatable networkInterface2Creatable = - networkInterfaces - .define(nic2Name) - .withRegion(Region.US_EAST) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.6"); + Creatable networkInterface2Creatable = networkInterfaces.define(nic2Name) + .withRegion(Region.US_EAST) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.6"); final String nic3Name = "nic3"; - Creatable networkInterface3Creatable = - networkInterfaces - .define(nic3Name) - .withRegion(Region.US_EAST) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.7"); + Creatable networkInterface3Creatable = networkInterfaces.define(nic3Name) + .withRegion(Region.US_EAST) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.7"); final String nic4Name = "nic4"; - Creatable networkInterface4Creatable = - networkInterfaces - .define(nic4Name) - .withRegion(Region.US_EAST) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.8"); + Creatable networkInterface4Creatable = networkInterfaces.define(nic4Name) + .withRegion(Region.US_EAST) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.8"); @SuppressWarnings("unchecked") - Collection batchNics = - networkInterfaces - .create( - networkInterface1Creatable, - networkInterface2Creatable, - networkInterface3Creatable, + Collection batchNics + = networkInterfaces + .create(networkInterface1Creatable, networkInterface2Creatable, networkInterface3Creatable, networkInterface4Creatable) .values(); @@ -326,23 +299,23 @@ public void canCreateBatchOfNetworkInterfaces() throws Exception { @Test public void canCreateNicWithApplicationSecurityGroup() { - Network network = - networkManager - .networks() - .define("vnet1") - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/27") - .withSubnet("subnet1", "10.0.0.0/28") - .withSubnet("subnet2", "10.0.0.16/28") - .create(); + Network network = networkManager.networks() + .define("vnet1") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/27") + .withSubnet("subnet1", "10.0.0.0/28") + .withSubnet("subnet2", "10.0.0.16/28") + .create(); - ApplicationSecurityGroup asg1 = networkManager.applicationSecurityGroups().define("asg1") + ApplicationSecurityGroup asg1 = networkManager.applicationSecurityGroups() + .define("asg1") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); - NetworkInterface nic = networkManager.networkInterfaces().define("nic1") + NetworkInterface nic = networkManager.networkInterfaces() + .define("nic1") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) @@ -351,11 +324,13 @@ public void canCreateNicWithApplicationSecurityGroup() { .withExistingApplicationSecurityGroup(asg1) .create(); - List applicationSecurityGroups = nic.primaryIPConfiguration().listAssociatedApplicationSecurityGroups(); + List applicationSecurityGroups + = nic.primaryIPConfiguration().listAssociatedApplicationSecurityGroups(); Assertions.assertEquals(1, applicationSecurityGroups.size()); Assertions.assertEquals("asg1", applicationSecurityGroups.iterator().next().name()); - ApplicationSecurityGroup asg2 = networkManager.applicationSecurityGroups().define("asg2") + ApplicationSecurityGroup asg2 = networkManager.applicationSecurityGroups() + .define("asg2") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); @@ -364,31 +339,33 @@ public void canCreateNicWithApplicationSecurityGroup() { .withoutApplicationSecurityGroup(asg1.name()) .withExistingApplicationSecurityGroup(asg2) .defineSecondaryIPConfiguration("nicip2") - .withExistingNetwork(network) - .withSubnet("subnet1") - .withPrivateIpAddressDynamic() - .attach() + .withExistingNetwork(network) + .withSubnet("subnet1") + .withPrivateIpAddressDynamic() + .attach() .apply(); applicationSecurityGroups = nic.primaryIPConfiguration().listAssociatedApplicationSecurityGroups(); Assertions.assertEquals(1, applicationSecurityGroups.size()); Assertions.assertEquals("asg2", applicationSecurityGroups.iterator().next().name()); - nic.update() - .withoutApplicationSecurityGroup(asg1.name()) - .withExistingApplicationSecurityGroup(asg1) - .apply(); - - Assertions.assertEquals(2, nic.ipConfigurations().get("nicip2").innerModel().applicationSecurityGroups().size()); - Assertions.assertEquals( - new HashSet<>(Arrays.asList("asg1", "asg2")), - nic.ipConfigurations().get("nicip2").innerModel().applicationSecurityGroups().stream().map(inner -> ResourceUtils.nameFromResourceId(inner.id())).collect(Collectors.toSet())); + nic.update().withoutApplicationSecurityGroup(asg1.name()).withExistingApplicationSecurityGroup(asg1).apply(); + + Assertions.assertEquals(2, + nic.ipConfigurations().get("nicip2").innerModel().applicationSecurityGroups().size()); + Assertions.assertEquals(new HashSet<>(Arrays.asList("asg1", "asg2")), + nic.ipConfigurations() + .get("nicip2") + .innerModel() + .applicationSecurityGroups() + .stream() + .map(inner -> ResourceUtils.nameFromResourceId(inner.id())) + .collect(Collectors.toSet())); if (!isPlaybackMode()) { // avoid concurrent request in playback applicationSecurityGroups = nic.ipConfigurations().get("nicip2").listAssociatedApplicationSecurityGroups(); Assertions.assertEquals(2, applicationSecurityGroups.size()); - Assertions.assertEquals( - new HashSet<>(Arrays.asList("asg1", "asg2")), + Assertions.assertEquals(new HashSet<>(Arrays.asList("asg1", "asg2")), applicationSecurityGroups.stream().map(ApplicationSecurityGroup::name).collect(Collectors.toSet())); } } @@ -397,8 +374,7 @@ public void canCreateNicWithApplicationSecurityGroup() { @Disabled("Deadlock from CountDownLatch") public void canDeleteNetworkWithServiceCallBack() { String vnetName = generateRandomResourceName("vnet", 15); - networkManager - .networks() + networkManager.networks() .define(vnetName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) @@ -414,15 +390,10 @@ public void canDeleteNetworkWithServiceCallBack() { // TODO: Fix deadlock final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counter = new AtomicInteger(0); - networkManager - .networks() - .deleteByResourceGroupAsync(rgName, vnetName) - .doOnSuccess( - aVoid -> { - counter.incrementAndGet(); - latch.countDown(); - }) - .doOnError(throwable -> latch.countDown()); + networkManager.networks().deleteByResourceGroupAsync(rgName, vnetName).doOnSuccess(aVoid -> { + counter.incrementAndGet(); + latch.countDown(); + }).doOnError(throwable -> latch.countDown()); try { latch.await(); @@ -450,7 +421,8 @@ public void canSetSubnetAddressPrefixes() { Assertions.assertTrue(CoreUtils.isNullOrEmpty(subnet.addressPrefixes())); // update withAddressPrefixes - network.update().updateSubnet(subnetName) + network.update() + .updateSubnet(subnetName) .withAddressPrefixes(Arrays.asList("10.0.0.8/29", "10.0.0.16/29")) .parent() .apply(); @@ -463,10 +435,7 @@ public void canSetSubnetAddressPrefixes() { Assertions.assertNull(subnet.addressPrefix()); // update withAddressPrefix - network.update().updateSubnet(subnetName) - .withAddressPrefix("10.0.0.0/29") - .parent() - .apply(); + network.update().updateSubnet(subnetName).withAddressPrefix("10.0.0.0/29").parent().apply(); network.refresh(); subnet = network.subnets().get(subnetName); @@ -509,7 +478,8 @@ public void canListSubnetAvailableIpAddresses() { Assertions.assertTrue(availableIps.isEmpty()); // define a new subnet with address prefixes - network.update().defineSubnet(subnet2Name) + network.update() + .defineSubnet(subnet2Name) .withAddressPrefixes(Arrays.asList("10.0.0.8/29", "10.0.0.16/29")) .attach() .apply(); @@ -546,9 +516,8 @@ public void canAssociateNatGateway() { String subnetName = "subnet1"; String subnet2Name = "subnet2"; - ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST) - .create(); + ResourceGroup resourceGroup + = resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); NatGatewayInner gateway1 = createNatGateway(); @@ -558,9 +527,9 @@ public void canAssociateNatGateway() { .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/16") .defineSubnet(subnetName) - .withAddressPrefix("10.0.0.0/24") - .withExistingNatGateway(gateway1.id()) - .attach() + .withAddressPrefix("10.0.0.0/24") + .withExistingNatGateway(gateway1.id()) + .attach() .create(); Subnet subnet = network.subnets().get(subnetName); @@ -570,12 +539,12 @@ public void canAssociateNatGateway() { network.update() .updateSubnet(subnetName) - .withExistingNatGateway(gateway2.id()) - .parent() + .withExistingNatGateway(gateway2.id()) + .parent() .defineSubnet(subnet2Name) - .withAddressPrefix("10.0.1.0/24") - .withExistingNatGateway(gateway2.id()) - .attach() + .withAddressPrefix("10.0.1.0/24") + .withExistingNatGateway(gateway2.id()) + .attach() .apply(); subnet = network.subnets().get(subnetName); @@ -607,31 +576,39 @@ public void canCreateAndUpdateNicWithMultipleDeleteOptions() { .withNewPrimaryPublicIPAddress() .withPrimaryPublicIPAddressDeleteOptions(DeleteOptions.DELETE) .defineSecondaryIPConfiguration("secondary1") - .withExistingNetwork(vnet) - .withSubnet(subnetName) - .withPrivateIpAddressDynamic() - .withNewPublicIpAddress() - .withPublicIPAddressDeleteOptions(DeleteOptions.DETACH) - .attach() + .withExistingNetwork(vnet) + .withSubnet(subnetName) + .withPrivateIpAddressDynamic() + .withNewPublicIpAddress() + .withPublicIPAddressDeleteOptions(DeleteOptions.DETACH) + .attach() .defineSecondaryIPConfiguration("secondary2") - .withExistingNetwork(vnet) - .withSubnet(subnetName) - .withPrivateIpAddressDynamic() - .withNewPublicIpAddress() - .withPublicIPAddressDeleteOptions(DeleteOptions.DETACH) - .attach() + .withExistingNetwork(vnet) + .withSubnet(subnetName) + .withPrivateIpAddressDynamic() + .withNewPublicIpAddress() + .withPublicIPAddressDeleteOptions(DeleteOptions.DETACH) + .attach() .create(); nic.refresh(); - Assertions.assertEquals(DeleteOptions.DELETE, nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); - Assertions.assertEquals(DeleteOptions.DETACH, nic.ipConfigurations().get("secondary1").innerModel().publicIpAddress().deleteOption()); - Assertions.assertEquals(DeleteOptions.DETACH, nic.ipConfigurations().get("secondary2").innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DELETE, + nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DETACH, + nic.ipConfigurations().get("secondary1").innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DETACH, + nic.ipConfigurations().get("secondary2").innerModel().publicIpAddress().deleteOption()); String existingPrimaryIpAddressId = nic.primaryIPConfiguration().publicIpAddressId(); - nic.update().withNewPrimaryPublicIPAddress().withPrimaryPublicIPAddressDeleteOptions(DeleteOptions.DETACH).apply(); + nic.update() + .withNewPrimaryPublicIPAddress() + .withPrimaryPublicIPAddressDeleteOptions(DeleteOptions.DETACH) + .apply(); nic.refresh(); - Assertions.assertFalse(existingPrimaryIpAddressId.equalsIgnoreCase(nic.primaryIPConfiguration().publicIpAddressId())); - Assertions.assertEquals(DeleteOptions.DETACH, nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); + Assertions + .assertFalse(existingPrimaryIpAddressId.equalsIgnoreCase(nic.primaryIPConfiguration().publicIpAddressId())); + Assertions.assertEquals(DeleteOptions.DETACH, + nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); String existingSecondary1IpAddressId = nic.ipConfigurations().get("secondary1").publicIpAddressId(); nic.update() @@ -652,23 +629,23 @@ public void canCreateAndUpdateNicWithMultipleDeleteOptions() { .attach() .apply(); nic.refresh(); - Assertions.assertFalse(existingSecondary1IpAddressId.equalsIgnoreCase(nic.ipConfigurations().get("secondary1").publicIpAddressId())); - Assertions.assertEquals(DeleteOptions.DELETE, nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); - Assertions.assertEquals(DeleteOptions.DELETE, nic.ipConfigurations().get("secondary1").innerModel().publicIpAddress().deleteOption()); - Assertions.assertEquals(DeleteOptions.DELETE, nic.ipConfigurations().get("secondary2").innerModel().publicIpAddress().deleteOption()); - Assertions.assertEquals(DeleteOptions.DELETE, nic.ipConfigurations().get("secondary3").innerModel().publicIpAddress().deleteOption()); + Assertions.assertFalse(existingSecondary1IpAddressId + .equalsIgnoreCase(nic.ipConfigurations().get("secondary1").publicIpAddressId())); + Assertions.assertEquals(DeleteOptions.DELETE, + nic.primaryIPConfiguration().innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DELETE, + nic.ipConfigurations().get("secondary1").innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DELETE, + nic.ipConfigurations().get("secondary2").innerModel().publicIpAddress().deleteOption()); + Assertions.assertEquals(DeleteOptions.DELETE, + nic.ipConfigurations().get("secondary3").innerModel().publicIpAddress().deleteOption()); } private NatGatewayInner createNatGateway() { String natGatewayName = generateRandomResourceName("natgw", 10); return networkManager.serviceClient() .getNatGateways() - .createOrUpdate( - rgName, - natGatewayName, - new NatGatewayInner() - .withLocation(Region.US_EAST.toString()) - .withSku(new NatGatewaySku().withName(NatGatewaySkuName.STANDARD)) - ); + .createOrUpdate(rgName, natGatewayName, new NatGatewayInner().withLocation(Region.US_EAST.toString()) + .withSku(new NatGatewaySku().withName(NatGatewaySkuName.STANDARD))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkManagementTest.java index d4c14e1b5748b..aa426c75480b7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkManagementTest.java @@ -30,21 +30,10 @@ public class NetworkManagementTest extends ResourceManagerTestProxyTestBase { protected String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkProfileTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkProfileTests.java index 06c9dd7228b7b..8dd9aee9a02df 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkProfileTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkProfileTests.java @@ -14,14 +14,16 @@ public class NetworkProfileTests extends NetworkManagementTest { @Test public void canCRUDNetworkProfile() { - Network network = networkManager.networks().define("vnet1") + Network network = networkManager.networks() + .define("vnet1") .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/24") .withSubnet("default", "10.0.0.0/24") .create(); - NetworkProfile networkProfile = networkManager.networkProfiles().define("profile1") + NetworkProfile networkProfile = networkManager.networkProfiles() + .define("profile1") .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withContainerNetworkInterfaceConfiguration("eth1", "ipconfig1", network.id(), "default") @@ -29,17 +31,18 @@ public void canCRUDNetworkProfile() { .create(); Assertions.assertEquals(1, networkProfile.containerNetworkInterfaceConfigurations().size()); - ContainerNetworkInterfaceConfiguration configuration = networkProfile.containerNetworkInterfaceConfigurations().iterator().next(); + ContainerNetworkInterfaceConfiguration configuration + = networkProfile.containerNetworkInterfaceConfigurations().iterator().next(); Assertions.assertEquals("eth1", configuration.name()); Assertions.assertEquals("ipconfig1", configuration.ipConfigurations().iterator().next().name()); - Assertions.assertEquals(network.subnets().get("default").id(), configuration.ipConfigurations().iterator().next().subnet().id()); + Assertions.assertEquals(network.subnets().get("default").id(), + configuration.ipConfigurations().iterator().next().subnet().id()); Assertions.assertEquals(1, networkManager.networkProfiles().listByResourceGroup(rgName).stream().count()); - Assertions.assertEquals(networkProfile.name(), networkManager.networkProfiles().getById(networkProfile.id()).name()); + Assertions.assertEquals(networkProfile.name(), + networkManager.networkProfiles().getById(networkProfile.id()).name()); - networkProfile.update() - .withTag("tag.2", "value.2") - .apply(); + networkProfile.update().withTag("tag.2", "value.2").apply(); Assertions.assertEquals(1, networkProfile.containerNetworkInterfaceConfigurations().size()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkSecurityGroupTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkSecurityGroupTests.java index f1cd7b0a123f1..a9bff36509875 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkSecurityGroupTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkSecurityGroupTests.java @@ -17,7 +17,7 @@ public class NetworkSecurityGroupTests extends NetworkManagementTest { @Test - public void canCRUDNetworkSecurityGroup() { + public void canCRUDNetworkSecurityGroup() { final String asgName = generateRandomResourceName("asg", 8); final String asgName2 = generateRandomResourceName("asg", 8); @@ -29,96 +29,107 @@ public void canCRUDNetworkSecurityGroup() { final Region region = Region.US_SOUTH_CENTRAL; - ApplicationSecurityGroup asg = networkManager.applicationSecurityGroups().define(asgName) + ApplicationSecurityGroup asg = networkManager.applicationSecurityGroups() + .define(asgName) .withRegion(region) .withNewResourceGroup(rgName) .create(); - ApplicationSecurityGroup asg2 = networkManager.applicationSecurityGroups().define(asgName2) + ApplicationSecurityGroup asg2 = networkManager.applicationSecurityGroups() + .define(asgName2) .withRegion(region) .withExistingResourceGroup(rgName) .create(); - ApplicationSecurityGroup asg3 = networkManager.applicationSecurityGroups().define(asgName3) + ApplicationSecurityGroup asg3 = networkManager.applicationSecurityGroups() + .define(asgName3) .withRegion(region) .withExistingResourceGroup(rgName) .create(); - ApplicationSecurityGroup asg4 = networkManager.applicationSecurityGroups().define(asgName4) + ApplicationSecurityGroup asg4 = networkManager.applicationSecurityGroups() + .define(asgName4) .withRegion(region) .withExistingResourceGroup(rgName) .create(); - NetworkSecurityGroup nsg = networkManager.networkSecurityGroups().define(nsgName) + NetworkSecurityGroup nsg = networkManager.networkSecurityGroups() + .define(nsgName) .withRegion(region) .withExistingResourceGroup(rgName) .defineRule("rule1") - .allowOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() + .allowOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() .defineRule("rule2") - .allowInbound() - .withSourceApplicationSecurityGroup(asg.id(), asg2.id()) - .fromAnyPort() - .toAnyAddress() - .toPortRange(22, 25) - .withAnyProtocol() - .withPriority(200) - .withDescription("foo!!") - .attach() + .allowInbound() + .withSourceApplicationSecurityGroup(asg.id(), asg2.id()) + .fromAnyPort() + .toAnyAddress() + .toPortRange(22, 25) + .withAnyProtocol() + .withPriority(200) + .withDescription("foo!!") + .attach() .defineRule("rule3") - .denyInbound() - .fromAnyAddress() - .fromAnyPort() - .withDestinationApplicationSecurityGroup(asg3.id(), asg4.id()) - .toPort(22) - .withAnyProtocol() - .withPriority(300) - .attach() + .denyInbound() + .fromAnyAddress() + .fromAnyPort() + .withDestinationApplicationSecurityGroup(asg3.id(), asg4.id()) + .toPort(22) + .withAnyProtocol() + .withPriority(300) + .attach() .create(); Assertions.assertEquals(2, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size()); Assertions.assertEquals(2, nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds().size()); - Assertions.assertEquals(new HashSet<>(Arrays.asList(asg.id(), asg2.id())), nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds()); - Assertions.assertEquals(new HashSet<>(Arrays.asList(asg3.id(), asg4.id())), nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds()); + Assertions.assertEquals(new HashSet<>(Arrays.asList(asg.id(), asg2.id())), + nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds()); + Assertions.assertEquals(new HashSet<>(Arrays.asList(asg3.id(), asg4.id())), + nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds()); - ApplicationSecurityGroup asg5 = networkManager.applicationSecurityGroups().define(asgName5) + ApplicationSecurityGroup asg5 = networkManager.applicationSecurityGroups() + .define(asgName5) .withRegion(region) .withExistingResourceGroup(rgName) .create(); - ApplicationSecurityGroup asg6 = networkManager.applicationSecurityGroups().define(asgName6) + ApplicationSecurityGroup asg6 = networkManager.applicationSecurityGroups() + .define(asgName6) .withRegion(region) .withExistingResourceGroup(rgName) .create(); nsg.update() .updateRule("rule2") - .withoutSourceApplicationSecurityGroup(asg2.id()) - .withSourceApplicationSecurityGroup(asg5.id()) - .parent() + .withoutSourceApplicationSecurityGroup(asg2.id()) + .withSourceApplicationSecurityGroup(asg5.id()) + .parent() .updateRule("rule3") - .withoutDestinationApplicationSecurityGroup(asg4.id()) - .withDestinationApplicationSecurityGroup(asg6.id()) - .parent() + .withoutDestinationApplicationSecurityGroup(asg4.id()) + .withDestinationApplicationSecurityGroup(asg6.id()) + .parent() .apply(); Assertions.assertEquals(2, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size()); Assertions.assertEquals(2, nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds().size()); - Assertions.assertEquals(new HashSet<>(Arrays.asList(asg.id(), asg5.id())), nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds()); - Assertions.assertEquals(new HashSet<>(Arrays.asList(asg3.id(), asg6.id())), nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds()); + Assertions.assertEquals(new HashSet<>(Arrays.asList(asg.id(), asg5.id())), + nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds()); + Assertions.assertEquals(new HashSet<>(Arrays.asList(asg3.id(), asg6.id())), + nsg.securityRules().get("rule3").destinationApplicationSecurityGroupIds()); nsg.update() .updateRule("rule2") - .fromAddress("Internet") - .parent() + .fromAddress("Internet") + .parent() .updateRule("rule3") - .toAddress("Storage.WestUS") - .parent() + .toAddress("Storage.WestUS") + .parent() .apply(); Assertions.assertEquals(0, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size()); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkWatcherTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkWatcherTests.java index 8a2bf5fca52d6..5ee75195b0828 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkWatcherTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/NetworkWatcherTests.java @@ -27,36 +27,31 @@ public void canListProvidersAndGetReachabilityReport() throws Exception { } } // create Network Watcher - NetworkWatcher nw = - networkManager.networkWatchers().define(nwName).withRegion(region).withNewResourceGroup(rgName).create(); + NetworkWatcher nw + = networkManager.networkWatchers().define(nwName).withRegion(region).withNewResourceGroup(rgName).create(); AvailableProviders providers = nw.availableProviders().execute(); Assertions.assertTrue(providers.providersByCountry().size() > 1); Assertions.assertNotNull(providers.providersByCountry().get("United States")); - providers = - nw - .availableProviders() - .withAzureLocation("West US") - .withCountry("United States") - .withState("washington") - .execute(); + providers = nw.availableProviders() + .withAzureLocation("West US") + .withCountry("United States") + .withState("washington") + .execute(); Assertions.assertEquals(1, providers.providersByCountry().size()); - Assertions - .assertEquals( - "washington", providers.providersByCountry().get("United States").states().get(0).stateName()); + Assertions.assertEquals("washington", + providers.providersByCountry().get("United States").states().get(0).stateName()); Assertions .assertTrue(providers.providersByCountry().get("United States").states().get(0).providers().size() > 0); String localProvider = providers.providersByCountry().get("United States").states().get(0).providers().get(0); - AzureReachabilityReport report = - nw - .azureReachabilityReport() - .withProviderLocation("United States", "washington") - .withStartTime(OffsetDateTime.parse("2018-04-10")) - .withEndTime(OffsetDateTime.parse("2018-04-12")) - .withProviders(localProvider) - .withAzureLocations("West US") - .execute(); + AzureReachabilityReport report = nw.azureReachabilityReport() + .withProviderLocation("United States", "washington") + .withStartTime(OffsetDateTime.parse("2018-04-10")) + .withEndTime(OffsetDateTime.parse("2018-04-12")) + .withProviders(localProvider) + .withAzureLocations("West US") + .execute(); Assertions.assertEquals("State", report.aggregationLevel()); Assertions.assertTrue(report.reachabilityReport().size() > 0); } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/RouteFilterTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/RouteFilterTests.java index 660d7f4b51871..e4c00a72bdd00 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/RouteFilterTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/RouteFilterTests.java @@ -17,14 +17,12 @@ public class RouteFilterTests extends NetworkManagementTest { public void canCRUDRouteFilter() throws Exception { String rfName = generateRandomResourceName("rf", 15); - RouteFilter routeFilter = - networkManager - .routeFilters() - .define(rfName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .withTag("tag1", "value1") - .create(); + RouteFilter routeFilter = networkManager.routeFilters() + .define(rfName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals("value1", routeFilter.tags().get("tag1")); PagedIterable rfList = networkManager.routeFilters().list(); @@ -42,21 +40,18 @@ public void canCRUDRouteFilter() throws Exception { public void canCreateRouteFilterRule() throws Exception { String rfName = generateRandomResourceName("rf", 15); String ruleName = "mynewrule"; - RouteFilter routeFilter = - networkManager - .routeFilters() - .define(rfName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .create(); + RouteFilter routeFilter = networkManager.routeFilters() + .define(rfName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .create(); routeFilter.update().defineRule(ruleName).withBgpCommunity("12076:51004").attach().apply(); Assertions.assertEquals(1, routeFilter.rules().size()); Assertions.assertEquals(1, routeFilter.rules().get(ruleName).communities().size()); Assertions.assertEquals("12076:51004", routeFilter.rules().get(ruleName).communities().get(0)); - routeFilter - .update() + routeFilter.update() .updateRule(ruleName) .withBgpCommunities("12076:51005", "12076:51026") .denyAccess() diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/WebApplicationFirewallPolicyTests.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/WebApplicationFirewallPolicyTests.java index 076e3fee85bb1..83c6dd4b90ab1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/WebApplicationFirewallPolicyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/WebApplicationFirewallPolicyTests.java @@ -23,17 +23,17 @@ public void canCrudWafPolicy() { Region region = Region.US_WEST; // waf policy with default settings - WebApplicationFirewallPolicy defaultPolicy = - networkManager.webApplicationFirewallPolicies() - .define(policyDefaultName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1) - .create(); + WebApplicationFirewallPolicy defaultPolicy = networkManager.webApplicationFirewallPolicies() + .define(policyDefaultName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1) + .create(); defaultPolicy.refresh(); - Assertions.assertTrue(defaultPolicy.getManagedRules().managedRuleSets() + Assertions.assertTrue(defaultPolicy.getManagedRules() + .managedRuleSets() .stream() .anyMatch(managedRuleSet -> managedRuleSet.ruleSetType() .equals(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1.type()))); @@ -45,24 +45,20 @@ public void canCrudWafPolicy() { Assertions.assertTrue(defaultPolicy.isEnabled()); // custom waf policy - WebApplicationFirewallPolicy policy = - networkManager.webApplicationFirewallPolicies() - .define(policyName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2, - new ManagedRuleGroupOverride() - .withRuleGroupName("REQUEST-911-METHOD-ENFORCEMENT") - .withRules(Arrays.asList( - new ManagedRuleOverride() - .withRuleId("911012") - .withState(ManagedRuleEnabledState.DISABLED)))) - .withDetectionMode() - .withBotProtection() - .enableRequestBodyInspection() - .withRequestBodySizeLimitInKb(128) - .withFileUploadSizeLimitInMb(100) - .create(); + WebApplicationFirewallPolicy policy = networkManager.webApplicationFirewallPolicies() + .define(policyName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2, + new ManagedRuleGroupOverride().withRuleGroupName("REQUEST-911-METHOD-ENFORCEMENT") + .withRules(Arrays.asList( + new ManagedRuleOverride().withRuleId("911012").withState(ManagedRuleEnabledState.DISABLED)))) + .withDetectionMode() + .withBotProtection() + .enableRequestBodyInspection() + .withRequestBodySizeLimitInKb(128) + .withFileUploadSizeLimitInMb(100) + .create(); policy.refresh(); @@ -72,13 +68,18 @@ public void canCrudWafPolicy() { Assertions.assertEquals(100, policy.fileUploadSizeLimitInMb()); Assertions.assertTrue(policy.isEnabled()); Assertions.assertEquals("0.1", - policy.getManagedRules().managedRuleSets() + policy.getManagedRules() + .managedRuleSets() .stream() .filter(managedRuleSet -> managedRuleSet.ruleSetType().equals("Microsoft_BotManagerRuleSet")) - .findFirst().get().ruleSetVersion()); - Assertions.assertTrue(policy.getManagedRules().managedRuleSets() + .findFirst() + .get() + .ruleSetVersion()); + Assertions.assertTrue(policy.getManagedRules() + .managedRuleSets() .stream() - .anyMatch(managedRuleSet -> managedRuleSet.ruleSetType().equals(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2.type()))); + .anyMatch(managedRuleSet -> managedRuleSet.ruleSetType() + .equals(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2.type()))); policy.update() .withPreventionMode() @@ -96,23 +97,26 @@ public void canCrudWafPolicy() { Assertions.assertFalse(policy.isRequestBodyInspectionEnabled()); Assertions.assertFalse(policy.isEnabled()); Assertions.assertEquals("1.0", - policy.getManagedRules().managedRuleSets() + policy.getManagedRules() + .managedRuleSets() .stream() .filter(managedRuleSet -> managedRuleSet.ruleSetType().equals("Microsoft_BotManagerRuleSet")) - .findFirst().get().ruleSetVersion()); - Assertions.assertTrue((policy.getManagedRules().managedRuleSets() + .findFirst() + .get() + .ruleSetVersion()); + Assertions.assertTrue((policy.getManagedRules() + .managedRuleSets() .stream() - .noneMatch(managedRuleSet -> managedRuleSet.ruleSetType().equals(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2.type())))); - Assertions.assertTrue(policy.getManagedRules().managedRuleSets() + .noneMatch(managedRuleSet -> managedRuleSet.ruleSetType() + .equals(KnownWebApplicationGatewayManagedRuleSet.OWASP_3_2.type())))); + Assertions.assertTrue(policy.getManagedRules() + .managedRuleSets() .stream() - .anyMatch( - managedRuleSet -> - managedRuleSet.ruleSetType().equals(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1.type()) - && managedRuleSet.ruleGroupOverrides() - .stream() - .anyMatch(ruleGroupOverride -> - "PROTOCOL-ENFORCEMENT".equals(ruleGroupOverride.ruleGroupName())) - )); + .anyMatch(managedRuleSet -> managedRuleSet.ruleSetType() + .equals(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1.type()) + && managedRuleSet.ruleGroupOverrides() + .stream() + .anyMatch(ruleGroupOverride -> "PROTOCOL-ENFORCEMENT".equals(ruleGroupOverride.ruleGroupName())))); // test deduplication policy.update() @@ -120,15 +124,13 @@ public void canCrudWafPolicy() { .withManagedRuleSet(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1) .apply(); - Assertions.assertTrue(policy.getManagedRules().managedRuleSets() + Assertions.assertTrue(policy.getManagedRules() + .managedRuleSets() .stream() - .anyMatch( - managedRuleSet -> - managedRuleSet.ruleSetType().equals(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1.type()) - && managedRuleSet.ruleGroupOverrides() - .stream() - .noneMatch(ruleGroupOverride -> - "PROTOCOL-ENFORCEMENT".equals(ruleGroupOverride.ruleGroupName())) - )); + .anyMatch(managedRuleSet -> managedRuleSet.ruleSetType() + .equals(KnownWebApplicationGatewayManagedRuleSet.MICROSOFT_DEFAULT_RULESET_2_1.type()) + && managedRuleSet.ruleGroupOverrides() + .stream() + .noneMatch(ruleGroupOverride -> "PROTOCOL-ENFORCEMENT".equals(ruleGroupOverride.ruleGroupName())))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/utils/DeprecateApplicationGatewaySku.java b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/utils/DeprecateApplicationGatewaySku.java index 0c8f087618eee..cb5d607e0184d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/utils/DeprecateApplicationGatewaySku.java +++ b/sdk/resourcemanager/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/utils/DeprecateApplicationGatewaySku.java @@ -21,91 +21,59 @@ public class DeprecateApplicationGatewaySku { @Test public void deprecateApplicationGatewaySku() throws Exception { - Path modulePath = Paths.get(this.getClass().getResource("/junit-platform.properties").toURI()).getParent().getParent().getParent(); + Path modulePath = Paths.get(this.getClass().getResource("/junit-platform.properties").toURI()) + .getParent() + .getParent() + .getParent(); Path modelsPath = Paths.get(modulePath.toString(), "src/main/java/com/azure/resourcemanager/network/models"); Path skuNameFile = Paths.get(modelsPath.toString(), "ApplicationGatewaySkuName.java"); Path tierFile = Paths.get(modelsPath.toString(), "ApplicationGatewayTier.java"); Map skuReplacementMap = new HashMap<>(); - skuReplacementMap.put( - " /** Static value Standard_Small for ApplicationGatewaySkuName. */", - " /**\n" - + " * Static value Standard_Small for ApplicationGatewaySkuName.\n" - + " *\n" + skuReplacementMap.put(" /** Static value Standard_Small for ApplicationGatewaySkuName. */", " /**\n" + + " * Static value Standard_Small for ApplicationGatewaySkuName.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); - skuReplacementMap.put( - " /** Static value Standard_Medium for ApplicationGatewaySkuName. */", - " /**\n" - + " * Static value Standard_Medium for ApplicationGatewaySkuName.\n" - + " *\n" + + " */\n" + " @Deprecated"); + skuReplacementMap.put(" /** Static value Standard_Medium for ApplicationGatewaySkuName. */", " /**\n" + + " * Static value Standard_Medium for ApplicationGatewaySkuName.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); - skuReplacementMap.put( - " /** Static value Standard_Large for ApplicationGatewaySkuName. */", - " /**\n" - + " * Static value Standard_Large for ApplicationGatewaySkuName.\n" - + " *\n" + + " */\n" + " @Deprecated"); + skuReplacementMap.put(" /** Static value Standard_Large for ApplicationGatewaySkuName. */", " /**\n" + + " * Static value Standard_Large for ApplicationGatewaySkuName.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); - skuReplacementMap.put( - " /** Static value WAF_Medium for ApplicationGatewaySkuName. */", - " /**\n" - + " * Static value WAF_Medium for ApplicationGatewaySkuName.\n" - + " *\n" + + " */\n" + " @Deprecated"); + skuReplacementMap.put(" /** Static value WAF_Medium for ApplicationGatewaySkuName. */", " /**\n" + + " * Static value WAF_Medium for ApplicationGatewaySkuName.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); - skuReplacementMap.put( - " /** Static value WAF_Large for ApplicationGatewaySkuName. */", - " /**\n" - + " * Static value WAF_Large for ApplicationGatewaySkuName.\n" - + " *\n" + + " */\n" + " @Deprecated"); + skuReplacementMap.put(" /** Static value WAF_Large for ApplicationGatewaySkuName. */", " /**\n" + + " * Static value WAF_Large for ApplicationGatewaySkuName.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); + + " */\n" + " @Deprecated"); Map tierReplacementMap = new HashMap<>(); - tierReplacementMap.put( - " /** Static value Standard for ApplicationGatewayTier. */", - " /**\n" - + " * Static value Standard for ApplicationGatewayTier.\n" - + " *\n" + tierReplacementMap.put(" /** Static value Standard for ApplicationGatewayTier. */", " /**\n" + + " * Static value Standard for ApplicationGatewayTier.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); - tierReplacementMap.put( - " /** Static value WAF for ApplicationGatewayTier. */", - " /**\n" - + " * Static value WAF for ApplicationGatewayTier.\n" - + " *\n" + + " */\n" + " @Deprecated"); + tierReplacementMap.put(" /** Static value WAF for ApplicationGatewayTier. */", " /**\n" + + " * Static value WAF for ApplicationGatewayTier.\n" + " *\n" + " * @deprecated Application Gateway V1 is officially deprecated on April 28, 2023.\n" + " * See v1-retirement-timeline\n" + " * for V1 retirement timeline and start planning your migration to Application Gateway V2 today.\n" - + " */\n" - + " @Deprecated" - ); + + " */\n" + " @Deprecated"); replaceInFile(skuNameFile, skuReplacementMap); replaceInFile(tierFile, tierReplacementMap); diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml index 351c7fe932179..9c3e3a85cd07b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml @@ -19,6 +19,7 @@ com.azure.resourcemanager.perf.App + false diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/App.java b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/App.java index 65d344a025af3..efb4111e48151 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/App.java +++ b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/App.java @@ -21,12 +21,11 @@ */ public class App { public static void main(String[] args) { - PerfStressProgram.run(new Class[]{ + PerfStressProgram.run(new Class[] { CreateDnsZonesTest.class, CreateStorageAccountsTest.class, ListResourceGroupsTest.class, ListSubscriptionsTest.class, - ListTenantsTest.class - }, args); + ListTenantsTest.class }, args); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/AzureResourceManagerTest.java b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/AzureResourceManagerTest.java index f906815f235d4..2ce83d99483af 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/AzureResourceManagerTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/AzureResourceManagerTest.java @@ -15,20 +15,18 @@ public abstract class AzureResourceManagerTest extends PerfStressTest { protected final AzureResourceManager azureResourceManager; + public AzureResourceManagerTest(TOptions options) { super(options); Configuration configuration = Configuration.getGlobalConfiguration(); - String tenantId = Objects.requireNonNull( - configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), + String tenantId = Objects.requireNonNull(configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), "'AZURE_TENANT_ID' environment variable cannot be null."); - String subscriptionId = Objects.requireNonNull( - configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID), + String subscriptionId = Objects.requireNonNull(configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID), "'AZURE_SUBSCRIPTION_ID' environment variable cannot be null."); AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); - azureResourceManager = AzureResourceManager - .authenticate(new DefaultAzureCredentialBuilder().build(), profile) + azureResourceManager = AzureResourceManager.authenticate(new DefaultAzureCredentialBuilder().build(), profile) .withDefaultSubscription(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/ResourceGroupTestBase.java b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/ResourceGroupTestBase.java index 68e5dfb8026f3..82ce68246b72d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/ResourceGroupTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/core/ResourceGroupTestBase.java @@ -11,7 +11,8 @@ import java.io.IOException; import java.util.UUID; -public abstract class ResourceGroupTestBase extends AzureResourceManagerTest { +public abstract class ResourceGroupTestBase + extends AzureResourceManagerTest { protected final String RESOURCE_GROUP_NAME; protected final ResourceNamer RESOURCE_NAMER; @@ -23,17 +24,15 @@ public ResourceGroupTestBase(TOptions options) throws IOException { @Override public Mono setupAsync() { - return super.setupAsync() - .then(azureResourceManager.resourceGroups() - .define(RESOURCE_GROUP_NAME) - .withRegion(Region.US_WEST) - .createAsync().then() - ); + return super.setupAsync().then(azureResourceManager.resourceGroups() + .define(RESOURCE_GROUP_NAME) + .withRegion(Region.US_WEST) + .createAsync() + .then()); } @Override public Mono cleanupAsync() { - return azureResourceManager.resourceGroups().deleteByNameAsync(RESOURCE_GROUP_NAME) - .then(super.cleanupAsync()); + return azureResourceManager.resourceGroups().deleteByNameAsync(RESOURCE_GROUP_NAME).then(super.cleanupAsync()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/dns/CreateDnsZonesTest.java b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/dns/CreateDnsZonesTest.java index 6733e3521bd20..cfa81fb34f659 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/dns/CreateDnsZonesTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/dns/CreateDnsZonesTest.java @@ -16,7 +16,8 @@ public CreateDnsZonesTest(PerfStressOptions options) throws IOException { @Override public void run() { - azureResourceManager.dnsZones().define(RESOURCE_NAMER.randomName("dnsstress", 24) + ".com") + azureResourceManager.dnsZones() + .define(RESOURCE_NAMER.randomName("dnsstress", 24) + ".com") .withExistingResourceGroup(RESOURCE_GROUP_NAME) .withETagCheck() .create(); @@ -24,7 +25,8 @@ public void run() { @Override public Mono runAsync() { - return azureResourceManager.dnsZones().define(RESOURCE_NAMER.randomName("dnsstress", 24) + ".com") + return azureResourceManager.dnsZones() + .define(RESOURCE_NAMER.randomName("dnsstress", 24) + ".com") .withExistingResourceGroup(RESOURCE_GROUP_NAME) .withETagCheck() .createAsync() diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/storage/CreateStorageAccountsTest.java b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/storage/CreateStorageAccountsTest.java index 6edbd7281661e..3f697f6198087 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/storage/CreateStorageAccountsTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-perf/src/main/java/com/azure/resourcemanager/perf/storage/CreateStorageAccountsTest.java @@ -17,7 +17,8 @@ public CreateStorageAccountsTest(PerfStressOptions options) throws IOException { @Override public void run() { - azureResourceManager.storageAccounts().define(RESOURCE_NAMER.randomName("sastress", 24)) + azureResourceManager.storageAccounts() + .define(RESOURCE_NAMER.randomName("sastress", 24)) .withRegion(Region.US_WEST) .withExistingResourceGroup(RESOURCE_GROUP_NAME) .create(); @@ -25,7 +26,8 @@ public void run() { @Override public Mono runAsync() { - return azureResourceManager.storageAccounts().define(RESOURCE_NAMER.randomName("sastress", 24)) + return azureResourceManager.storageAccounts() + .define(RESOURCE_NAMER.randomName("sastress", 24)) .withRegion(Region.US_WEST) .withExistingResourceGroup(RESOURCE_GROUP_NAME) .createAsync() diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml index 64cdc2cd057ad..a8a534a7c69d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml @@ -49,6 +49,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneManager.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneManager.java index 4905d67423798..290553b4b28f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneManager.java @@ -76,11 +76,8 @@ public PrivateDnsZoneManager authenticate(TokenCredential credential, AzureProfi } private PrivateDnsZoneManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new PrivateDnsManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new PrivateDnsManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/AaaaRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/AaaaRecordSetsImpl.java index 3ba31c7ffafce..623eb9ba61dad 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/AaaaRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/AaaaRecordSetsImpl.java @@ -8,8 +8,7 @@ import com.azure.resourcemanager.privatedns.models.RecordType; /** Implementation of {@link AaaaRecordSets}. */ -class AaaaRecordSetsImpl - extends PrivateDnsRecordSetsBaseImpl +class AaaaRecordSetsImpl extends PrivateDnsRecordSetsBaseImpl implements AaaaRecordSets { AaaaRecordSetsImpl(PrivateDnsZoneImpl privateDnsZone) { diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/CnameRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/CnameRecordSetsImpl.java index 6c48e1ce2ccb8..29908707db04c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/CnameRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/CnameRecordSetsImpl.java @@ -8,8 +8,7 @@ import com.azure.resourcemanager.privatedns.models.RecordType; /** Implementation of {@link CnameRecordSets}. */ -class CnameRecordSetsImpl - extends PrivateDnsRecordSetsBaseImpl +class CnameRecordSetsImpl extends PrivateDnsRecordSetsBaseImpl implements CnameRecordSets { CnameRecordSetsImpl(PrivateDnsZoneImpl privateDnsZone) { diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetImpl.java index 8a482ff9eceb3..c7bff8577d5e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetImpl.java @@ -25,21 +25,18 @@ /** Implementation of {@link PrivateDnsRecordSet}. */ class PrivateDnsRecordSetImpl extends ExternalChildResourceImpl - implements PrivateDnsRecordSet, - PrivateDnsRecordSet.Definition, - PrivateDnsRecordSet.UpdateDefinition, - PrivateDnsRecordSet.UpdateCombined { + implements PrivateDnsRecordSet, PrivateDnsRecordSet.Definition, + PrivateDnsRecordSet.UpdateDefinition, PrivateDnsRecordSet.UpdateCombined { protected final RecordSetInner recordSetRemoveInfo; protected final String type; private final ETagState etagState = new ETagState(); - protected PrivateDnsRecordSetImpl( - String name, String type, final PrivateDnsZoneImpl parent, final RecordSetInner innerModel) { + protected PrivateDnsRecordSetImpl(String name, String type, final PrivateDnsZoneImpl parent, + final RecordSetInner innerModel) { super(name, parent, innerModel); this.type = type; - this.recordSetRemoveInfo = new RecordSetInner() - .withAaaaRecords(new ArrayList<>()) + this.recordSetRemoveInfo = new RecordSetInner().withAaaaRecords(new ArrayList<>()) .withARecords(new ArrayList<>()) .withCnameRecord(new CnameRecord()) .withMxRecords(new ArrayList<>()) @@ -106,15 +103,13 @@ public PrivateDnsRecordSetImpl withAlias(String alias) { @Override public PrivateDnsRecordSetImpl withMailExchange(String mailExchangeHostName, int priority) { - innerModel().mxRecords().add( - new MxRecord().withExchange(mailExchangeHostName).withPreference(priority)); + innerModel().mxRecords().add(new MxRecord().withExchange(mailExchangeHostName).withPreference(priority)); return this; } @Override public PrivateDnsRecordSetImpl withoutMailExchange(String mailExchangeHostName, int priority) { - recordSetRemoveInfo.mxRecords().add( - new MxRecord().withExchange(mailExchangeHostName).withPreference(priority)); + recordSetRemoveInfo.mxRecords().add(new MxRecord().withExchange(mailExchangeHostName).withPreference(priority)); return this; } @@ -174,15 +169,15 @@ public PrivateDnsRecordSetImpl withNegativeResponseCachingTimeToLiveInSeconds(lo @Override public PrivateDnsRecordSetImpl withRecord(String target, int port, int priority, int weight) { - innerModel().srvRecords().add( - new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); + innerModel().srvRecords() + .add(new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); return this; } @Override public PrivateDnsRecordSetImpl withoutRecord(String target, int port, int priority, int weight) { - recordSetRemoveInfo.srvRecords().add( - new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); + recordSetRemoveInfo.srvRecords() + .add(new SrvRecord().withTarget(target).withPort(port).withPriority(priority).withWeight(weight)); return this; } @@ -255,7 +250,9 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return parent().manager().serviceClient().getRecordSets() + return parent().manager() + .serviceClient() + .getRecordSets() .getAsync(parent().resourceGroupName(), parent().name(), recordType(), name()) .map(recordSetInner -> prepare(recordSetInner)) .flatMap(recordSetInner -> createOrUpdateAsync(recordSetInner)); @@ -263,18 +260,19 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return parent().manager().serviceClient().getRecordSets() - .deleteWithResponseAsync( - parent().resourceGroupName(), - parent().name(), - recordType(), - name(), - etagState.ifMatchValueOnDelete()).then(); + return parent().manager() + .serviceClient() + .getRecordSets() + .deleteWithResponseAsync(parent().resourceGroupName(), parent().name(), recordType(), name(), + etagState.ifMatchValueOnDelete()) + .then(); } @Override protected Mono getInnerAsync() { - return parent().manager().serviceClient().getRecordSets() + return parent().manager() + .serviceClient() + .getRecordSets() .getAsync(parent().resourceGroupName(), parent().name(), recordType(), name()); } @@ -302,15 +300,11 @@ public String childResourceKey() { private Mono createOrUpdateAsync(RecordSetInner resource) { final PrivateDnsRecordSetImpl self = this; - return parent().manager().serviceClient().getRecordSets() - .createOrUpdateWithResponseAsync( - parent().resourceGroupName(), - parent().name(), - recordType(), - name(), - resource, - etagState.ifMatchValueOnUpdate(resource.etag()), - etagState.ifNonMatchValueOnCreate()) + return parent().manager() + .serviceClient() + .getRecordSets() + .createOrUpdateWithResponseAsync(parent().resourceGroupName(), parent().name(), recordType(), name(), + resource, etagState.ifMatchValueOnUpdate(resource.etag()), etagState.ifNonMatchValueOnCreate()) .map(recordSetInner -> { setInner(recordSetInner.getValue()); self.etagState.clear(); diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsBaseImpl.java index 662a8056d811a..b6116f2e25ac5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsBaseImpl.java @@ -69,7 +69,9 @@ public PrivateRecordSetT getByName(String name) { @Override public Mono getByNameAsync(String name) { - return parent().manager().serviceClient().getRecordSets() + return parent().manager() + .serviceClient() + .getRecordSets() .getAsync(parent().resourceGroupName(), parent().name(), recordType, name) .map(this::wrapModel); } @@ -84,12 +86,9 @@ protected PagedIterable listIntern(String recordSetNameSuffix } protected PagedFlux listInternAsync(String recordSetNameSuffix, Integer pageSize) { - return wrapPageAsync( - parent().manager().serviceClient().getRecordSets().listByTypeAsync( - parent().resourceGroupName(), - parent().name(), - recordType, - pageSize, - recordSetNameSuffix)); + return wrapPageAsync(parent().manager() + .serviceClient() + .getRecordSets() + .listByTypeAsync(parent().resourceGroupName(), parent().name(), recordType, pageSize, recordSetNameSuffix)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsImpl.java index 9bb63e99f9380..b3574c5443a1c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsRecordSetsImpl.java @@ -8,13 +8,8 @@ import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.ExternalChildResourcesNonCachedImpl; /** Represents an record set collection associated with a private DNS zone. */ -class PrivateDnsRecordSetsImpl - extends ExternalChildResourcesNonCachedImpl< - PrivateDnsRecordSetImpl, - PrivateDnsRecordSet, - RecordSetInner, - PrivateDnsZoneImpl, - PrivateDnsZone> { +class PrivateDnsRecordSetsImpl extends + ExternalChildResourcesNonCachedImpl { /** The default record set ttl in seconds. */ private static final long DEFAULT_TTL_IN_SECONDS = 3600; diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZoneImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZoneImpl.java index a4d90fd91fb34..bef17f7f1e795 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZoneImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZoneImpl.java @@ -172,8 +172,8 @@ public PtrRecordSets ptrRecordSets() { @Override public SoaRecordSet getSoaRecordSet() { - RecordSetInner inner = manager().serviceClient().getRecordSets() - .get(resourceGroupName(), name(), RecordType.SOA, "@"); + RecordSetInner inner + = manager().serviceClient().getRecordSets().get(resourceGroupName(), name(), RecordType.SOA, "@"); return inner == null ? null : new SoaRecordSetImpl(inner.name(), this, inner); } @@ -392,21 +392,16 @@ public Update withETagCheck(String etagValue) { public Mono createResourceAsync() { Mono mono; if (isInCreateMode()) { - mono = manager().serviceClient().getPrivateZones() - .createOrUpdateAsync( - resourceGroupName(), - name(), - innerModel(), - etagState.ifMatchValueOnUpdate(innerModel().etag()), - etagState.ifNonMatchValueOnCreate()) + mono = manager().serviceClient() + .getPrivateZones() + .createOrUpdateAsync(resourceGroupName(), name(), innerModel(), + etagState.ifMatchValueOnUpdate(innerModel().etag()), etagState.ifNonMatchValueOnCreate()) .map(innerToFluentMap(this)); } else { if (!Objects.equals(resourceTagsSnapshotOnUpdate, innerModel().tags())) { - mono = manager().serviceClient().getPrivateZones() - .updateAsync( - resourceGroupName(), - name(), - innerModel(), + mono = manager().serviceClient() + .getPrivateZones() + .updateAsync(resourceGroupName(), name(), innerModel(), etagState.ifMatchValueOnUpdate(innerModel().etag())) .map(innerToFluentMap(this)); } else { @@ -415,11 +410,10 @@ public Mono createResourceAsync() { } } - return mono - .map(privateDnsZone -> { - etagState.clear(); - return privateDnsZone; - }); + return mono.map(privateDnsZone -> { + etagState.clear(); + return privateDnsZone; + }); } @Override @@ -461,28 +455,36 @@ private PagedIterable listRecordSetsIntern(String recordSet private PagedFlux listRecordSetsInternAsync(String recordSetSuffix, Integer pageSize) { final PrivateDnsZoneImpl self = this; - return PagedConverter.mapPage(manager().serviceClient().getRecordSets() - .listAsync(resourceGroupName(), name(), pageSize, recordSetSuffix), + return PagedConverter.mapPage( + manager().serviceClient().getRecordSets().listAsync(resourceGroupName(), name(), pageSize, recordSetSuffix), recordSetInner -> { - PrivateDnsRecordSet recordSet = new PrivateDnsRecordSetImpl( - recordSetInner.name(), recordSetInner.type(), self, recordSetInner); + PrivateDnsRecordSet recordSet + = new PrivateDnsRecordSetImpl(recordSetInner.name(), recordSetInner.type(), self, recordSetInner); switch (recordSet.recordType()) { case AAAA: return new AaaaRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case A: return new ARecordSetImpl(recordSetInner.name(), self, recordSetInner); + case CNAME: return new CnameRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case MX: return new MxRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case PTR: return new PtrRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case SOA: return new SoaRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case SRV: return new SrvRecordSetImpl(recordSetInner.name(), self, recordSetInner); + case TXT: return new TxtRecordSetImpl(recordSetInner.name(), self, recordSetInner); + default: return recordSet; } diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZonesImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZonesImpl.java index 79ce1eb782efb..f9728ad8c331d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZonesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/PrivateDnsZonesImpl.java @@ -12,13 +12,8 @@ import reactor.core.publisher.Mono; /** Implementation of {@link PrivateDnsZones}. */ -public final class PrivateDnsZonesImpl - extends TopLevelModifiableResourcesImpl< - PrivateDnsZone, - PrivateDnsZoneImpl, - PrivateZoneInner, - PrivateZonesClient, - PrivateDnsZoneManager> +public final class PrivateDnsZonesImpl extends + TopLevelModifiableResourcesImpl implements PrivateDnsZones { public PrivateDnsZonesImpl(final PrivateDnsZoneManager manager) { @@ -42,8 +37,8 @@ public void deleteById(String id, String etagValue) { @Override public Mono deleteByIdAsync(String id, String etagValue) { - return deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), etagValue); + return deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id), etagValue); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinkImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinkImpl.java index 0066d5d5fd809..2a1b3d9f425a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinkImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinkImpl.java @@ -19,10 +19,8 @@ /** Implementation of {@link VirtualNetworkLink}. */ class VirtualNetworkLinkImpl extends ExternalChildResourceImpl - implements VirtualNetworkLink, - VirtualNetworkLink.Definition, - VirtualNetworkLink.UpdateDefinition, - VirtualNetworkLink.Update { + implements VirtualNetworkLink, VirtualNetworkLink.Definition, + VirtualNetworkLink.UpdateDefinition, VirtualNetworkLink.Update { private final ETagState etagState = new ETagState(); private VirtualNetworkLinkInner linkToRemove; @@ -134,7 +132,9 @@ public Mono createResourceAsync() { @Override public Mono updateResourceAsync() { - return parent().manager().serviceClient().getVirtualNetworkLinks() + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() .getAsync(parent().resourceGroupName(), parent().name(), name()) .map(virtualNetworkLinkInner -> prepareForUpdate(virtualNetworkLinkInner)) .flatMap(virtualNetworkLinkInner -> createOrUpdateAsync(virtualNetworkLinkInner)); @@ -142,13 +142,17 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return parent().manager().serviceClient().getVirtualNetworkLinks() + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() .deleteAsync(parent().resourceGroupName(), parent().name(), name(), etagState.ifMatchValueOnDelete()); } @Override protected Mono getInnerAsync() { - return parent().manager().serviceClient().getVirtualNetworkLinks() + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() .getAsync(parent().resourceGroupName(), parent().name(), name()); } @@ -164,14 +168,11 @@ public PrivateDnsZoneImpl attach() { private Mono createOrUpdateAsync(VirtualNetworkLinkInner resource) { final VirtualNetworkLinkImpl self = this; - return parent().manager().serviceClient().getVirtualNetworkLinks() - .createOrUpdateAsync( - parent().resourceGroupName(), - parent().name(), - name(), - resource, - etagState.ifMatchValueOnUpdate(resource.etag()), - etagState.ifNonMatchValueOnCreate()) + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() + .createOrUpdateAsync(parent().resourceGroupName(), parent().name(), name(), resource, + etagState.ifMatchValueOnUpdate(resource.etag()), etagState.ifNonMatchValueOnCreate()) .map(virtualNetworkLinkInner -> { setInner(virtualNetworkLinkInner); self.etagState.clear(); diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinksImpl.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinksImpl.java index 026b314c030de..fce63301570be 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/implementation/VirtualNetworkLinksImpl.java @@ -15,12 +15,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** Implementation of {@link VirtualNetworkLinks}. */ -class VirtualNetworkLinksImpl - extends ExternalChildResourcesNonCachedImpl +class VirtualNetworkLinksImpl extends + ExternalChildResourcesNonCachedImpl implements VirtualNetworkLinks { VirtualNetworkLinksImpl(PrivateDnsZoneImpl parent) { @@ -34,9 +30,10 @@ public PagedIterable list(int pageSize) { @Override public PagedFlux listAsync(int pageSize) { - return PagedConverter.mapPage(parent().manager().serviceClient().getVirtualNetworkLinks() - .listAsync(parent().resourceGroupName(), parent().name(), pageSize), - this::wrapModel); + return PagedConverter.mapPage(parent().manager() + .serviceClient() + .getVirtualNetworkLinks() + .listAsync(parent().resourceGroupName(), parent().name(), pageSize), this::wrapModel); } @Override @@ -46,20 +43,20 @@ public void deleteById(String id) { @Override public Mono deleteByIdAsync(String id) { - return deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), null); + return deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id), null); } @Override public void deleteById(String id, String etagValue) { - deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), etagValue).block(); + deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), + etagValue).block(); } @Override public Mono deleteByIdAsync(String id, String etagValue) { - return deleteByResourceGroupNameAsync( - ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id), etagValue); + return deleteByResourceGroupNameAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(id), etagValue); } @Override @@ -79,7 +76,9 @@ public void deleteByResourceGroupName(String resourceGroupName, String name, Str @Override public Mono deleteByResourceGroupNameAsync(String resourceGroupName, String name, String etagValue) { - return parent().manager().serviceClient().getVirtualNetworkLinks() + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() .deleteAsync(resourceGroupName, name, etagValue); } @@ -100,7 +99,9 @@ public VirtualNetworkLink getByName(String name) { @Override public Mono getByNameAsync(String name) { - return parent().manager().serviceClient().getVirtualNetworkLinks() + return parent().manager() + .serviceClient() + .getVirtualNetworkLinks() .getAsync(parent().resourceGroupName(), parent().name(), name) .map(this::wrapModel); } @@ -117,9 +118,10 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(parent().manager().serviceClient().getVirtualNetworkLinks() - .listAsync(parent().resourceGroupName(), parent().name()), - this::wrapModel); + return PagedConverter.mapPage(parent().manager() + .serviceClient() + .getVirtualNetworkLinks() + .listAsync(parent().resourceGroupName(), parent().name()), this::wrapModel); } public VirtualNetworkLinksClient inner() { diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSet.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSet.java index 533eda7371cd5..0206a1574cd72 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSet.java @@ -15,12 +15,12 @@ /** An immutable client-side representation of a record set in Azure Private DNS Zone. */ @Fluent public interface PrivateDnsRecordSet - extends ExternalChildResource, - HasInnerModel { + extends ExternalChildResource, HasInnerModel { /** * @return the type of the record set. */ RecordType recordType(); + /** * @return the ETag of the record set. */ @@ -53,31 +53,20 @@ public interface PrivateDnsRecordSet * @param the stage of the parent definition to return to after attaching this definition */ interface Definition - extends DefinitionStages.AaaaRecordSetBlank, - DefinitionStages.WithAaaaRecordIPv6Address, - DefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, - DefinitionStages.ARecordSetBlank, - DefinitionStages.WithARecordIPv4Address, - DefinitionStages.WithARecordIPv4AddressOrAttachable, - DefinitionStages.CNameRecordSetBlank, - DefinitionStages.WithCNameRecordAlias, - DefinitionStages.WithCNameRecordSetAttachable, - DefinitionStages.MXRecordSetBlank, - DefinitionStages.WithMXRecordMailExchange, - DefinitionStages.WithMXRecordMailExchangeOrAttachable, - DefinitionStages.PtrRecordSetBlank, - DefinitionStages.WithPtrRecordTargetDomainName, - DefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, - DefinitionStages.SoaRecordSetBlank, - DefinitionStages.WithSoaRecordAttributes, - DefinitionStages.WithSoaRecordAttributesOrAttachable, - DefinitionStages.SrvRecordSetBlank, - DefinitionStages.WithSrvRecordEntry, - DefinitionStages.WithSrvRecordEntryOrAttachable, - DefinitionStages.TxtRecordSetBlank, - DefinitionStages.WithTxtRecordTextValue, - DefinitionStages.WithTxtRecordTextValueOrAttachable, - DefinitionStages.WithAttach { + extends DefinitionStages.AaaaRecordSetBlank, DefinitionStages.WithAaaaRecordIPv6Address, + DefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, DefinitionStages.ARecordSetBlank, + DefinitionStages.WithARecordIPv4Address, DefinitionStages.WithARecordIPv4AddressOrAttachable, + DefinitionStages.CNameRecordSetBlank, DefinitionStages.WithCNameRecordAlias, + DefinitionStages.WithCNameRecordSetAttachable, DefinitionStages.MXRecordSetBlank, + DefinitionStages.WithMXRecordMailExchange, + DefinitionStages.WithMXRecordMailExchangeOrAttachable, DefinitionStages.PtrRecordSetBlank, + DefinitionStages.WithPtrRecordTargetDomainName, + DefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, + DefinitionStages.SoaRecordSetBlank, DefinitionStages.WithSoaRecordAttributes, + DefinitionStages.WithSoaRecordAttributesOrAttachable, DefinitionStages.SrvRecordSetBlank, + DefinitionStages.WithSrvRecordEntry, DefinitionStages.WithSrvRecordEntryOrAttachable, + DefinitionStages.TxtRecordSetBlank, DefinitionStages.WithTxtRecordTextValue, + DefinitionStages.WithTxtRecordTextValueOrAttachable, DefinitionStages.WithAttach { } /** Grouping of DNS zone record set definition stages as a part of parent DNS zone definition. */ @@ -314,8 +303,8 @@ interface WithSoaRecordAttributes { * @param negativeCachingTimeToLive the time-to-live for cached negative response * @return the next stage of the definition */ - WithSoaRecordAttributesOrAttachable withNegativeResponseCachingTimeToLiveInSeconds( - long negativeCachingTimeToLive); + WithSoaRecordAttributesOrAttachable + withNegativeResponseCachingTimeToLiveInSeconds(long negativeCachingTimeToLive); } /** @@ -452,11 +441,8 @@ interface WithETagCheck { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithTtl, - DefinitionStages.WithMetadata, - DefinitionStages.WithETagCheck { + interface WithAttach extends Attachable.InDefinition, DefinitionStages.WithTtl, + DefinitionStages.WithMetadata, DefinitionStages.WithETagCheck { } } @@ -465,32 +451,24 @@ interface WithAttach * * @param the stage of the parent definition to return to after attaching this definition */ - interface UpdateDefinition - extends UpdateDefinitionStages.AaaaRecordSetBlank, - UpdateDefinitionStages.WithAaaaRecordIPv6Address, - UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, - UpdateDefinitionStages.ARecordSetBlank, - UpdateDefinitionStages.WithARecordIPv4Address, - UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable, - UpdateDefinitionStages.CNameRecordSetBlank, - UpdateDefinitionStages.WithCNameRecordAlias, - UpdateDefinitionStages.WithCNameRecordSetAttachable, - UpdateDefinitionStages.MXRecordSetBlank, - UpdateDefinitionStages.WithMXRecordMailExchange, - UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable, - UpdateDefinitionStages.PtrRecordSetBlank, - UpdateDefinitionStages.WithPtrRecordTargetDomainName, - UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, - UpdateDefinitionStages.SoaRecordSetBlank, - UpdateDefinitionStages.WithSoaRecordAttributes, - UpdateDefinitionStages.WithSoaRecordAttributesOrAttachable, - UpdateDefinitionStages.SrvRecordSetBlank, - UpdateDefinitionStages.WithSrvRecordEntry, - UpdateDefinitionStages.WithSrvRecordEntryOrAttachable, - UpdateDefinitionStages.TxtRecordSetBlank, - UpdateDefinitionStages.WithTxtRecordTextValue, - UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.AaaaRecordSetBlank, + UpdateDefinitionStages.WithAaaaRecordIPv6Address, + UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable, + UpdateDefinitionStages.ARecordSetBlank, UpdateDefinitionStages.WithARecordIPv4Address, + UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable, + UpdateDefinitionStages.CNameRecordSetBlank, UpdateDefinitionStages.WithCNameRecordAlias, + UpdateDefinitionStages.WithCNameRecordSetAttachable, UpdateDefinitionStages.MXRecordSetBlank, + UpdateDefinitionStages.WithMXRecordMailExchange, + UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable, + UpdateDefinitionStages.PtrRecordSetBlank, + UpdateDefinitionStages.WithPtrRecordTargetDomainName, + UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable, + UpdateDefinitionStages.SoaRecordSetBlank, UpdateDefinitionStages.WithSoaRecordAttributes, + UpdateDefinitionStages.WithSoaRecordAttributesOrAttachable, + UpdateDefinitionStages.SrvRecordSetBlank, UpdateDefinitionStages.WithSrvRecordEntry, + UpdateDefinitionStages.WithSrvRecordEntryOrAttachable, + UpdateDefinitionStages.TxtRecordSetBlank, UpdateDefinitionStages.WithTxtRecordTextValue, + UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable, UpdateDefinitionStages.WithAttach { } /** Grouping of DNS zone record set definition stages as a part of parent DNS zone update. */ @@ -727,8 +705,8 @@ interface WithSoaRecordAttributes { * @param negativeCachingTimeToLive the time-to-live for cached negative response * @return the next stage of the definition */ - WithSoaRecordAttributesOrAttachable withNegativeResponseCachingTimeToLiveInSeconds( - long negativeCachingTimeToLive); + WithSoaRecordAttributesOrAttachable + withNegativeResponseCachingTimeToLiveInSeconds(long negativeCachingTimeToLive); } /** @@ -865,25 +843,14 @@ interface WithETagCheck { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithTtl, - UpdateDefinitionStages.WithMetadata, - UpdateDefinitionStages.WithETagCheck { + interface WithAttach extends Attachable.InUpdate, UpdateDefinitionStages.WithTtl, + UpdateDefinitionStages.WithMetadata, UpdateDefinitionStages.WithETagCheck { } } /** The entirety of a record sets update as a part of parent DNS zone update. */ - interface UpdateCombined - extends UpdateAaaaRecordSet, - UpdateARecordSet, - UpdateCNameRecordSet, - UpdateMXRecordSet, - UpdatePtrRecordSet, - UpdateSoaRecord, - UpdateSrvRecordSet, - UpdateTxtRecordSet, - Update { + interface UpdateCombined extends UpdateAaaaRecordSet, UpdateARecordSet, UpdateCNameRecordSet, UpdateMXRecordSet, + UpdatePtrRecordSet, UpdateSoaRecord, UpdateSrvRecordSet, UpdateTxtRecordSet, Update { } /** The entirety of an AAAA record set update as a part of parent DNS zone update. */ @@ -921,11 +888,8 @@ interface UpdateTxtRecordSet extends UpdateStages.WithTxtRecordTextValue, Update /** * the set of configurations that can be updated for DNS record set irrespective of their type {@link RecordType}. */ - interface Update - extends Settable, - UpdateStages.WithTtl, - UpdateStages.WithMetadata, - UpdateStages.WithETagCheck { + interface Update extends Settable, UpdateStages.WithTtl, UpdateStages.WithMetadata, + UpdateStages.WithETagCheck { } /** Grouping of DNS zone record set update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSets.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSets.java index 01a693cb5f487..26b366fe828c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSets.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsRecordSets.java @@ -16,9 +16,7 @@ */ @Fluent public interface PrivateDnsRecordSets - extends SupportsListing, - SupportsGettingByName, - HasParent { + extends SupportsListing, SupportsGettingByName, HasParent { /** * Lists all the record sets with the given suffix. * diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZone.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZone.java index 93d6a6cbaf72e..7d319a114878a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZone.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZone.java @@ -16,10 +16,8 @@ /** An immutable client-side representation of an Azure Private DNS Zone. */ @Fluent -public interface PrivateDnsZone - extends GroupableResource, - Refreshable, - Updatable { +public interface PrivateDnsZone extends GroupableResource, + Refreshable, Updatable { /** * @return the ETag of the zone. @@ -259,11 +257,8 @@ interface WithETagCheck { * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ interface WithCreate - extends Creatable, - DefinitionStages.WithRecordSet, - DefinitionStages.WithVirtualNetworkLink, - DefinitionStages.WithETagCheck, - Resource.DefinitionWithTags { + extends Creatable, DefinitionStages.WithRecordSet, DefinitionStages.WithVirtualNetworkLink, + DefinitionStages.WithETagCheck, Resource.DefinitionWithTags { } } @@ -586,11 +581,7 @@ interface WithETagCheck { * *

Call {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - UpdateStages.WithRecordSet, - UpdateStages.WithVirtualNetworkLink, - UpdateStages.WithETagCheck, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithRecordSet, UpdateStages.WithVirtualNetworkLink, + UpdateStages.WithETagCheck, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZones.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZones.java index a9aaa060bc97c..ded32814b889a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZones.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/PrivateDnsZones.java @@ -19,16 +19,10 @@ /** Entry point to private DNS zone management API in Azure. */ @Fluent public interface PrivateDnsZones - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsGettingByResourceGroup, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingById, + SupportsGettingByResourceGroup, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Deletes a resource from Azure, identifying it by its resource ID. * diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLink.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLink.java index 13e24274e304b..bda4aa924296f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLink.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLink.java @@ -45,9 +45,7 @@ public interface VirtualNetworkLink * * @param the stage of the parent definition to return to after attaching this definition */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAttach { } /** Grouping of virtual network link definition stages as a part of parent DNS zone definition. */ @@ -120,12 +118,9 @@ interface WithReferencedVirtualNetwork { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithAutoRegistration, - DefinitionStages.WithReferencedVirtualNetwork, - DefinitionStages.WithETagCheck, - Resource.DefinitionWithRegion>, - Resource.DefinitionWithTags> { + extends Attachable.InDefinition, DefinitionStages.WithAutoRegistration, + DefinitionStages.WithReferencedVirtualNetwork, DefinitionStages.WithETagCheck, + Resource.DefinitionWithRegion>, Resource.DefinitionWithTags> { } } @@ -135,8 +130,7 @@ interface WithAttach * @param the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition - extends UpdateDefinitionStages.Blank, - UpdateDefinitionStages.WithAttach { + extends UpdateDefinitionStages.Blank, UpdateDefinitionStages.WithAttach { } /** Grouping of DNS zone record set definition stages as a part of parent DNS zone update. */ @@ -209,8 +203,7 @@ interface WithReferencedVirtualNetwork { * @param the stage of the parent definition to return to after attaching this definition */ interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithAutoRegistration, + extends Attachable.InUpdate, UpdateDefinitionStages.WithAutoRegistration, UpdateDefinitionStages.WithReferencedVirtualNetwork, UpdateDefinitionStages.WithETagCheck { } @@ -219,11 +212,8 @@ interface WithAttach /** * the set of configurations that can be updated for virtual network link. */ - interface Update - extends Settable, - UpdateStages.WithAutoRegistration, - UpdateStages.WithETagCheck, - Resource.UpdateWithTags { + interface Update extends Settable, UpdateStages.WithAutoRegistration, + UpdateStages.WithETagCheck, Resource.UpdateWithTags { } /** Grouping of virtual network link update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLinks.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLinks.java index 0f18ec0956375..cc017a8054baa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLinks.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/main/java/com/azure/resourcemanager/privatedns/models/VirtualNetworkLinks.java @@ -13,11 +13,8 @@ /** Entry point to virtual network link management API in Azure. */ @Fluent -public interface VirtualNetworkLinks - extends SupportsGettingById, - SupportsGettingByName, - SupportsListing, - HasParent { +public interface VirtualNetworkLinks extends SupportsGettingById, + SupportsGettingByName, SupportsListing, HasParent { /** * Lists all the virtual network links, with number of entries in each page limited to given size. * diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneCnameRecordSetTests.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneCnameRecordSetTests.java index 6428800f0fd74..a4fc32907e3a0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneCnameRecordSetTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneCnameRecordSetTests.java @@ -32,25 +32,12 @@ public class PrivateDnsZoneCnameRecordSetTests extends ResourceManagerTestProxyT protected PrivateDnsZoneManager privateZoneManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } - - @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); @@ -69,16 +56,14 @@ public void canUpdateCname() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone dnsZone = - privateZoneManager - .privateZones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineCnameRecordSet("www") - .withAlias("cname.contoso.com") - .withTimeToLive(7200) - .attach() - .create(); + PrivateDnsZone dnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineCnameRecordSet("www") + .withAlias("cname.contoso.com") + .withTimeToLive(7200) + .attach() + .create(); // Check CNAME records dnsZone.refresh(); @@ -90,13 +75,7 @@ public void canUpdateCname() { Assertions.assertEquals("cname.contoso.com", cnameRecordSet.canonicalName()); // Update alias and ttl: - dnsZone - .update() - .updateCnameRecordSet("www") - .withAlias("new.contoso.com") - .withTimeToLive(1234) - .parent() - .apply(); + dnsZone.update().updateCnameRecordSet("www").withAlias("new.contoso.com").withTimeToLive(1234).parent().apply(); // Check CNAME records dnsZone.refresh(); diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneRecordSetETagTests.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneRecordSetETagTests.java index 1449c7caf0615..48b17ed01bc53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneRecordSetETagTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/PrivateDnsZoneRecordSetETagTests.java @@ -39,21 +39,10 @@ public class PrivateDnsZoneRecordSetETagTests extends ResourceManagerTestProxyTe protected PrivateDnsZoneManager privateZoneManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -74,17 +63,13 @@ public void canUpdateZone() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone privateDnsZone = - privateZoneManager.privateZones().define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .withTag("key1", "value1") - .create(); + PrivateDnsZone privateDnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withTag("key1", "value1") + .create(); - privateDnsZone.update() - .withoutTag("key1") - .withTag("key2", "value2") - .withTag("key3", "value3") - .apply(); + privateDnsZone.update().withoutTag("key1").withTag("key2", "value2").withTag("key3", "value3").apply(); privateDnsZone.refresh(); Assertions.assertEquals(2, privateDnsZone.tags().size()); @@ -93,11 +78,11 @@ public void canUpdateZone() { privateDnsZone.update() .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() .apply(); Assertions.assertEquals(1, TestUtilities.getSize(privateDnsZone.aRecordSets().list())); } @@ -107,18 +92,18 @@ public void canCreateZoneWithDefaultETag() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone privateDnsZone = - privateZoneManager.privateZones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + PrivateDnsZone privateDnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withETagCheck() + .create(); Assertions.assertNotNull(privateDnsZone.etag()); - Runnable runnable = - () -> - privateZoneManager - .privateZones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .withETagCheck() - .create(); + Runnable runnable = () -> privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withETagCheck() + .create(); ensureETagExceptionIsThrown(runnable); } @@ -127,14 +112,15 @@ public void canUpdateZoneWithExplicitETag() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - final PrivateDnsZone privateDnsZone = - privateZoneManager.privateZones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + final PrivateDnsZone privateDnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withETagCheck() + .create(); Assertions.assertNotNull(privateDnsZone.etag()); - Runnable runnable = () -> privateDnsZone.update() - .withTag("k1", "v1") - .withETagCheck(privateDnsZone.etag() + "-foo") - .apply(); + Runnable runnable + = () -> privateDnsZone.update().withTag("k1", "v1").withETagCheck(privateDnsZone.etag() + "-foo").apply(); ensureETagExceptionIsThrown(runnable); privateDnsZone.update().withETagCheck(privateDnsZone.etag()).apply(); } @@ -144,8 +130,11 @@ public void canDeleteZoneWithExplicitETag() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - final PrivateDnsZone dnsZone = - privateZoneManager.privateZones().define(topLevelDomain).withNewResourceGroup(rgName, region).withETagCheck().create(); + final PrivateDnsZone dnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .withETagCheck() + .create(); Assertions.assertNotNull(dnsZone.etag()); Runnable runnable = () -> privateZoneManager.privateZones().deleteById(dnsZone.id(), dnsZone.etag() + "-foo"); @@ -158,31 +147,29 @@ public void canCreateRecordSetsWithDefaultETag() { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone dnsZone = - privateZoneManager - .privateZones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .defineCnameRecordSet("documents") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .defineCnameRecordSet("userguide") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .create(); + PrivateDnsZone dnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .defineCnameRecordSet("documents") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .defineCnameRecordSet("userguide") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -203,30 +190,29 @@ public void canCreateRecordSetsWithDefaultETag() { Exception compositeException = null; try { - privateZoneManager - .privateZones() + privateZoneManager.privateZones() .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .defineCnameRecordSet("documents") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .defineCnameRecordSet("userguide") - .withAlias("doc.contoso.com") - .withETagCheck() - .attach() - .create(); + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .defineCnameRecordSet("documents") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .defineCnameRecordSet("userguide") + .withAlias("doc.contoso.com") + .withETagCheck() + .attach() + .create(); } catch (ManagementException exception) { compositeException = exception; } @@ -249,23 +235,21 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone dnsZone = - privateZoneManager - .privateZones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .create(); + PrivateDnsZone dnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -283,8 +267,7 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { // Exception compositeException = null; try { - dnsZone - .update() + dnsZone.update() .updateARecordSet("www") .withETagCheck(aRecordSet.etag() + "-foo") .parent() @@ -307,15 +290,14 @@ public void canUpdateRecordSetWithExplicitETag() throws Exception { } } // Try update with correct etags - dnsZone - .update() + dnsZone.update() .updateARecordSet("www") - .withIPv4Address("24.97.105.45") - .withETagCheck(aRecordSet.etag()) - .parent() + .withIPv4Address("24.97.105.45") + .withETagCheck(aRecordSet.etag()) + .parent() .updateAaaaRecordSet("www") - .withETagCheck(aaaaRecordSet.etag()) - .parent() + .withETagCheck(aaaaRecordSet.etag()) + .parent() .apply(); // Check A records @@ -337,23 +319,21 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { final Region region = Region.US_EAST; final String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; - PrivateDnsZone dnsZone = - privateZoneManager - .privateZones() - .define(topLevelDomain) - .withNewResourceGroup(rgName, region) - .defineARecordSet("www") - .withIPv4Address("23.96.104.40") - .withIPv4Address("24.97.105.41") - .withTimeToLive(7200) - .withETagCheck() - .attach() - .defineAaaaRecordSet("www") - .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") - .withETagCheck() - .attach() - .create(); + PrivateDnsZone dnsZone = privateZoneManager.privateZones() + .define(topLevelDomain) + .withNewResourceGroup(rgName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) + .withETagCheck() + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .withETagCheck() + .attach() + .create(); // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); @@ -371,8 +351,7 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { // Exception compositeException = null; try { - dnsZone - .update() + dnsZone.update() .withoutARecordSet("www", aRecordSet.etag() + "-foo") .withoutAaaaRecordSet("www", aaaaRecordSet.etag() + "-foo") .apply(); @@ -391,8 +370,7 @@ public void canDeleteRecordSetWithExplicitETag() throws Exception { } } // Try delete with correct etags - dnsZone - .update() + dnsZone.update() .withoutARecordSet("www", aRecordSet.etag()) .withoutAaaaRecordSet("www", aaaaRecordSet.etag()) .apply(); @@ -428,9 +406,7 @@ private void ensureETagExceptionIsThrown(final Runnable runnable) { } Assertions.assertTrue(isManagementExceptionThrown, "Expected ManagementException is not thrown"); Assertions.assertTrue(isCloudErrorSet, "Expected CloudError property is not set in ManagementException"); - Assertions - .assertTrue( - isPreconditionFailedCodeSet, - "Expected PreconditionFailed code is not set indicating ETag concurrency check failure"); + Assertions.assertTrue(isPreconditionFailedCodeSet, + "Expected PreconditionFailed code is not set indicating ETag concurrency check failure"); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/VirtualNetworkLinkETagTests.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/VirtualNetworkLinkETagTests.java index 7f76f0271da4d..9a5fcfacf82a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/VirtualNetworkLinkETagTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/test/java/com/azure/resourcemanager/privatedns/VirtualNetworkLinkETagTests.java @@ -44,21 +44,10 @@ public class VirtualNetworkLinkETagTests extends ResourceManagerTestProxyTestBas protected NetworkManager networkManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -118,9 +107,9 @@ public void canUpdateVirtualNetworkLinkWithExplicitETag() { try { privateDnsZone.update() .updateVirtualNetworkLink(vnetLinkName) - .enableAutoRegistration() - .withETagCheck(virtualNetworkLink.etag() + "-foo") - .parent() + .enableAutoRegistration() + .withETagCheck(virtualNetworkLink.etag() + "-foo") + .parent() .apply(); } catch (Exception exception) { compositeException = exception; @@ -129,9 +118,9 @@ public void canUpdateVirtualNetworkLinkWithExplicitETag() { privateDnsZone.update() .updateVirtualNetworkLink(vnetLinkName) - .enableAutoRegistration() - .withETagCheck(virtualNetworkLink.etag()) - .parent() + .enableAutoRegistration() + .withETagCheck(virtualNetworkLink.etag()) + .parent() .apply(); virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); @@ -155,31 +144,29 @@ public void canDeleteVirtualNetworkLinkWithExplicitETag() { Exception compositeException = null; try { - privateDnsZone.update() - .withoutVirtualNetworkLink(vnetLinkName, virtualNetworkLink.etag() + "-foo") - .apply(); + privateDnsZone.update().withoutVirtualNetworkLink(vnetLinkName, virtualNetworkLink.etag() + "-foo").apply(); } catch (Exception exception) { compositeException = exception; } validateAggregateException(compositeException); - privateDnsZone.update() - .withoutVirtualNetworkLink(vnetLinkName, virtualNetworkLink.etag()) - .apply(); + privateDnsZone.update().withoutVirtualNetworkLink(vnetLinkName, virtualNetworkLink.etag()).apply(); virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); Assertions.assertTrue(TestUtilities.getSize(virtualNetworkLinks) == 0); } private NetworkSecurityGroup createNetworkSecurityGroup() { - return networkManager.networkSecurityGroups().define(nsgName) + return networkManager.networkSecurityGroups() + .define(nsgName) .withRegion(region) .withNewResourceGroup(rgName) .create(); } private Network createNetwork(NetworkSecurityGroup nsg) { - return networkManager.networks().define(vnetName) + return networkManager.networks() + .define(vnetName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") @@ -193,7 +180,8 @@ private Network createNetwork(NetworkSecurityGroup nsg) { } private PrivateDnsZone createPrivateDnsZone(Network network) { - return privateZoneManager.privateZones().define(topLevelDomain) + return privateZoneManager.privateZones() + .define(topLevelDomain) .withExistingResourceGroup(rgName) .defineVirtualNetworkLink(vnetLinkName) .disableAutoRegistration() diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml index 388d8cd9743d7..60cd235dee0cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml @@ -49,6 +49,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/RedisManager.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/RedisManager.java index 986948b5f3794..221ff38b3b3fa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/RedisManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/RedisManager.java @@ -78,11 +78,8 @@ public RedisManager authenticate(TokenCredential credential, AzureProfile profil } private RedisManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new RedisManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new RedisManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/ConfigurationUtils.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/ConfigurationUtils.java index 3f02e0d8d38d0..2fba5c19d7330 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/ConfigurationUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/ConfigurationUtils.java @@ -85,8 +85,7 @@ static Map toMap(RedisConfiguration configuration) { return map; } - static void putConfiguration(RedisConfiguration configuration, - String key, String value) { + static void putConfiguration(RedisConfiguration configuration, String key, String value) { if (configuration == null) { return; } @@ -94,51 +93,67 @@ static void putConfiguration(RedisConfiguration configuration, case "maxmemory-policy": configuration.withMaxmemoryPolicy(value); break; + case "storage-subscription-id": configuration.withStorageSubscriptionId(value); break; + case "aad-enabled": configuration.withAadEnabled(value); break; + case "rdb-backup-enabled": configuration.withRdbBackupEnabled(value); break; + case "preferred-data-persistence-auth-method": configuration.withPreferredDataPersistenceAuthMethod(value); break; + case "rdb-backup-max-snapshot-count": configuration.withRdbBackupMaxSnapshotCount(value); break; + case "aof-storage-connection-string-0": configuration.withAofStorageConnectionString0(value); break; + case "aof-storage-connection-string-1": configuration.withAofStorageConnectionString1(value); break; + case "authnotrequired": configuration.withAuthnotrequired(value); break; + case "rdb-storage-connection-string": configuration.withRdbStorageConnectionString(value); break; + case "aof-backup-enabled": configuration.withAofBackupEnabled(value); break; + case "maxmemory-delta": configuration.withMaxmemoryDelta(value); break; + case "notify-keyspace-events": configuration.withNotifyKeyspaceEvents(value); break; + case "maxfragmentationmemory-reserved": configuration.withMaxfragmentationmemoryReserved(value); break; + case "maxmemory-reserved": configuration.withMaxmemoryReserved(value); break; + case "rdb-backup-frequency": configuration.withRdbBackupFrequency(value); break; + default: if (configuration.additionalProperties() == null) { configuration.withAdditionalProperties(new HashMap<>()); @@ -159,51 +174,67 @@ static void removeConfiguration(RedisConfiguration configuration, String key) { case "maxmemory-policy": configuration.withMaxmemoryPolicy(null); break; + case "storage-subscription-id": configuration.withStorageSubscriptionId(null); break; + case "aad-enabled": configuration.withAadEnabled(null); break; + case "rdb-backup-enabled": configuration.withRdbBackupEnabled(null); break; + case "preferred-data-persistence-auth-method": configuration.withPreferredDataPersistenceAuthMethod(null); break; + case "rdb-backup-max-snapshot-count": configuration.withRdbBackupMaxSnapshotCount(null); break; + case "aof-storage-connection-string-0": configuration.withAofStorageConnectionString0(null); break; + case "aof-storage-connection-string-1": configuration.withAofStorageConnectionString1(null); break; + case "authnotrequired": configuration.withAuthnotrequired(null); break; + case "rdb-storage-connection-string": configuration.withRdbStorageConnectionString(null); break; + case "aof-backup-enabled": configuration.withAofBackupEnabled(null); break; + case "maxmemory-delta": configuration.withMaxmemoryDelta(null); break; + case "notify-keyspace-events": configuration.withNotifyKeyspaceEvents(null); break; + case "maxfragmentationmemory-reserved": configuration.withMaxfragmentationmemoryReserved(null); break; + case "maxmemory-reserved": configuration.withMaxmemoryReserved(null); break; + case "rdb-backup-frequency": configuration.withRdbBackupFrequency(null); break; + default: break; } diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisCacheImpl.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisCacheImpl.java index ef77728d300a0..5fcbb1f737a9e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisCacheImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisCacheImpl.java @@ -156,8 +156,7 @@ public TlsVersion minimumTlsVersion() { @Override public Map redisConfiguration() { - return Collections.unmodifiableMap( - ConfigurationUtils.toMap(this.innerModel().redisConfiguration())); + return Collections.unmodifiableMap(ConfigurationUtils.toMap(this.innerModel().redisConfiguration())); } @Override @@ -183,16 +182,19 @@ public RedisAccessKeys keys() { @Override public RedisAccessKeys refreshKeys() { - RedisAccessKeysInner response = - this.manager().serviceClient().getRedis().listKeys(this.resourceGroupName(), this.name()); + RedisAccessKeysInner response + = this.manager().serviceClient().getRedis().listKeys(this.resourceGroupName(), this.name()); cachedAccessKeys = new RedisAccessKeysImpl(response); return cachedAccessKeys; } @Override public RedisAccessKeys regenerateKey(RedisKeyType keyType) { - RedisAccessKeysInner response = - this.manager().serviceClient().getRedis().regenerateKey(this.resourceGroupName(), this.name(), new RedisRegenerateKeyParameters().withKeyType(keyType)); + RedisAccessKeysInner response = this.manager() + .serviceClient() + .getRedis() + .regenerateKey(this.resourceGroupName(), this.name(), + new RedisRegenerateKeyParameters().withKeyType(keyType)); cachedAccessKeys = new RedisAccessKeysImpl(response); return cachedAccessKeys; } @@ -234,8 +236,8 @@ public void exportData(String containerSASUrl, String prefix) { @Override public void exportData(String containerSASUrl, String prefix, String fileFormat) { - ExportRdbParameters parameters = - new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat); + ExportRdbParameters parameters + = new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat); this.manager().serviceClient().getRedis().exportData(this.resourceGroupName(), this.name(), parameters); } @@ -360,9 +362,8 @@ public RedisCacheImpl withSubnet(String subnetId) { if (isInCreateMode()) { createParameters.withSubnetId(subnetId); } else { - throw logger - .logExceptionAsError( - new UnsupportedOperationException("Subnet cannot be modified during update operation.")); + throw logger.logExceptionAsError( + new UnsupportedOperationException("Subnet cannot be modified during update operation.")); } } return this; @@ -373,9 +374,8 @@ public RedisCacheImpl withStaticIp(String staticIp) { if (isInCreateMode()) { createParameters.withStaticIp(staticIp); } else { - throw logger - .logExceptionAsError( - new UnsupportedOperationException("Static IP cannot be modified during update operation.")); + throw logger.logExceptionAsError( + new UnsupportedOperationException("Static IP cannot be modified during update operation.")); } return this; } @@ -461,12 +461,9 @@ public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) { @Override public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) { - return this - .withPatchSchedule( - new ScheduleEntry() - .withDayOfWeek(dayOfWeek) - .withStartHourUtc(startHourUtc) - .withMaintenanceWindow(maintenanceWindow)); + return this.withPatchSchedule(new ScheduleEntry().withDayOfWeek(dayOfWeek) + .withStartHourUtc(startHourUtc) + .withMaintenanceWindow(maintenanceWindow)); } @Override @@ -525,9 +522,7 @@ public void deletePatchSchedule() { @Override public Mono refreshAsync() { - return super - .refreshAsync() - .then(this.firewallRules.refreshAsync()) + return super.refreshAsync().then(this.firewallRules.refreshAsync()) .then(this.patchSchedules.refreshAsync()) .then(Mono.just(this)); } @@ -561,29 +556,22 @@ public RedisCacheImpl update() { public Mono updateResourceAsync() { updateParameters.withTags(this.innerModel().tags()); this.patchScheduleAdded = false; - return this - .manager() + return this.manager() .serviceClient() .getRedis() .updateAsync(resourceGroupName(), name(), updateParameters) .map(innerToFluentMap(this)) .filter( redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString())) - .flatMapMany( - redisCache -> - Mono - .delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( - manager().serviceClient().getDefaultPollInterval())) - .flatMap(o -> - manager().serviceClient().getRedis().getByResourceGroupAsync(resourceGroupName(), name())) - .doOnNext(this::setInner) - .repeat() - .takeUntil( - redisResourceInner -> - redisResourceInner - .provisioningState() - .toString() - .equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))) + .flatMapMany(redisCache -> Mono + .delay(ResourceManagerUtils.InternalRuntimeContext + .getDelayDuration(manager().serviceClient().getDefaultPollInterval())) + .flatMap(o -> manager().serviceClient().getRedis().getByResourceGroupAsync(resourceGroupName(), name())) + .doOnNext(this::setInner) + .repeat() + .takeUntil(redisResourceInner -> redisResourceInner.provisioningState() + .toString() + .equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))) .then(this.patchSchedules.commitAndGetAllAsync()) .then(this.firewallRules.commitAndGetAllAsync()) .then(Mono.just(this)); @@ -597,8 +585,7 @@ public Mono createResourceAsync() { withRedisVersion(RedisVersion.V6); } this.patchScheduleAdded = false; - return this - .manager() + return this.manager() .serviceClient() .getRedis() .createAsync(this.resourceGroupName(), this.name(), createParameters) @@ -608,26 +595,27 @@ public Mono createResourceAsync() { @Override public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) { String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId); - RedisLinkedServerCreateParameters params = - new RedisLinkedServerCreateParameters() - .withLinkedRedisCacheId(linkedRedisCacheId) + RedisLinkedServerCreateParameters params + = new RedisLinkedServerCreateParameters().withLinkedRedisCacheId(linkedRedisCacheId) .withLinkedRedisCacheLocation(linkedServerLocation) .withServerRole(role); - RedisLinkedServerWithPropertiesInner linkedServerInner = - this - .manager() - .serviceClient() - .getLinkedServers() - .create(this.resourceGroupName(), this.name(), linkedRedisName, params); + RedisLinkedServerWithPropertiesInner linkedServerInner = this.manager() + .serviceClient() + .getLinkedServers() + .create(this.resourceGroupName(), this.name(), linkedRedisName, params); return linkedServerInner.name(); } @Override public void removeLinkedServer(String linkedServerName) { - RedisLinkedServerWithPropertiesInner linkedServer = this.manager().serviceClient().getLinkedServers() + RedisLinkedServerWithPropertiesInner linkedServer = this.manager() + .serviceClient() + .getLinkedServers() .get(this.resourceGroupName(), this.name(), linkedServerName); - this.manager().serviceClient().getLinkedServers() + this.manager() + .serviceClient() + .getLinkedServers() .delete(this.resourceGroupName(), this.name(), linkedServerName); RedisResourceInner innerLinkedResource = null; @@ -638,14 +626,11 @@ public void removeLinkedServer(String linkedServerName) { || innerResource.provisioningState() != ProvisioningState.SUCCEEDED) { ResourceManagerUtils.sleep(Duration.ofSeconds(30)); - innerLinkedResource = - this - .manager() - .serviceClient() - .getRedis() - .getByResourceGroup( - ResourceUtils.groupFromResourceId(linkedServer.id()), - ResourceUtils.nameFromResourceId(linkedServer.id())); + innerLinkedResource = this.manager() + .serviceClient() + .getRedis() + .getByResourceGroup(ResourceUtils.groupFromResourceId(linkedServer.id()), + ResourceUtils.nameFromResourceId(linkedServer.id())); innerResource = this.manager().serviceClient().getRedis().getByResourceGroup(resourceGroupName(), name()); } @@ -653,19 +638,14 @@ public void removeLinkedServer(String linkedServerName) { @Override public ReplicationRole getLinkedServerRole(String linkedServerName) { - RedisLinkedServerWithPropertiesInner linkedServer = this.manager().serviceClient().getLinkedServers() + RedisLinkedServerWithPropertiesInner linkedServer = this.manager() + .serviceClient() + .getLinkedServers() .get(this.resourceGroupName(), this.name(), linkedServerName); if (linkedServer == null) { - throw logger - .logExceptionAsError( - new IllegalArgumentException( - "Server returned `null` value for Linked Server '" - + linkedServerName - + "' for Redis Cache '" - + this.name() - + "' in Resource Group '" - + this.resourceGroupName() - + "'.")); + throw logger.logExceptionAsError( + new IllegalArgumentException("Server returned `null` value for Linked Server '" + linkedServerName + + "' for Redis Cache '" + this.name() + "' in Resource Group '" + this.resourceGroupName() + "'.")); } return linkedServer.serverRole(); } @@ -673,8 +653,8 @@ public ReplicationRole getLinkedServerRole(String linkedServerName) { @Override public Map listLinkedServers() { Map result = new TreeMap<>(); - PagedIterable paginatedResponse = - this.manager().serviceClient().getLinkedServers().list(this.resourceGroupName(), this.name()); + PagedIterable paginatedResponse + = this.manager().serviceClient().getLinkedServers().list(this.resourceGroupName(), this.name()); for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) { result.put(linkedServer.name(), linkedServer.serverRole()); @@ -689,7 +669,9 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getPrivateLinkResources() + return PagedConverter.mapPage(this.manager() + .serviceClient() + .getPrivateLinkResources() .listByRedisCacheAsync(this.resourceGroupName(), this.name()), PrivateLinkResourceImpl::new); } @@ -700,7 +682,9 @@ public PagedIterable listPrivateEndpointConnections() @Override public PagedFlux listPrivateEndpointConnectionsAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() + return PagedConverter.mapPage(this.manager() + .serviceClient() + .getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @@ -711,12 +695,13 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new com.azure.resourcemanager.redis.models.PrivateLinkServiceConnectionState() - .withStatus( - com.azure.resourcemanager.redis.models.PrivateEndpointServiceConnectionStatus.APPROVED))) + new com.azure.resourcemanager.redis.models.PrivateLinkServiceConnectionState().withStatus( + com.azure.resourcemanager.redis.models.PrivateEndpointServiceConnectionStatus.APPROVED))) .then(); } @@ -727,12 +712,13 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new com.azure.resourcemanager.redis.models.PrivateLinkServiceConnectionState() - .withStatus( - com.azure.resourcemanager.redis.models.PrivateEndpointServiceConnectionStatus.REJECTED))) + new com.azure.resourcemanager.redis.models.PrivateLinkServiceConnectionState().withStatus( + com.azure.resourcemanager.redis.models.PrivateEndpointServiceConnectionStatus.REJECTED))) .then(); } @@ -783,25 +769,23 @@ private static final class PrivateEndpointConnectionImpl implements PrivateEndpo private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; - private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState - privateLinkServiceConnectionState; + private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; - this.privateEndpoint = innerModel.privateEndpoint() == null - ? null - : new PrivateEndpoint(innerModel.privateEndpoint().id()); + this.privateEndpoint + = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( - innerModel.privateLinkServiceConnectionState().status() == null - ? null - : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus - .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), - innerModel.privateLinkServiceConnectionState().description(), - innerModel.privateLinkServiceConnectionState().actionsRequired()); + innerModel.privateLinkServiceConnectionState().status() == null + ? null + : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus + .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), + innerModel.privateLinkServiceConnectionState().description(), + innerModel.privateLinkServiceConnectionState().actionsRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRuleImpl.java index b2e90c45df5fc..88111bdebf67d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRuleImpl.java @@ -37,19 +37,17 @@ public String endIp() { @Override public Mono createResourceAsync() { final RedisFirewallRuleImpl self = this; - RedisFirewallRuleCreateParameters parameters = - new RedisFirewallRuleCreateParameters().withStartIp(this.startIp()).withEndIp(this.endIp()); - return this - .parent() + RedisFirewallRuleCreateParameters parameters + = new RedisFirewallRuleCreateParameters().withStartIp(this.startIp()).withEndIp(this.endIp()); + return this.parent() .manager() .serviceClient() .getFirewallRules() .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), parameters) - .map( - redisFirewallRuleInner -> { - self.setInner(redisFirewallRuleInner); - return self; - }); + .map(redisFirewallRuleInner -> { + self.setInner(redisFirewallRuleInner); + return self; + }); } @Override @@ -59,8 +57,7 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getFirewallRules() @@ -69,8 +66,7 @@ public Mono deleteResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getFirewallRules() diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRulesImpl.java index 4730e8605396f..baa704a198140 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisFirewallRulesImpl.java @@ -16,9 +16,8 @@ import java.util.Map; /** Represents a Redis firewall rules collection associated with a Redis cache instance. */ -class RedisFirewallRulesImpl - extends ExternalChildResourcesCachedImpl< - RedisFirewallRuleImpl, RedisFirewallRule, RedisFirewallRuleInner, RedisCacheImpl, RedisCache> { +class RedisFirewallRulesImpl extends + ExternalChildResourcesCachedImpl { private boolean load = false; RedisFirewallRulesImpl(RedisCacheImpl parent) { @@ -59,15 +58,13 @@ public RedisFirewallRuleImpl defineInlineFirewallRule(String name) { @Override protected Flux listChildResourcesAsync() { - return this - .getParent() + return this.getParent() .manager() .serviceClient() .getFirewallRules() .listAsync(this.getParent().resourceGroupName(), this.getParent().name()) - .map( - firewallRuleInner -> - new RedisFirewallRuleImpl(firewallRuleInner.name(), this.getParent(), firewallRuleInner)) + .map(firewallRuleInner -> new RedisFirewallRuleImpl(firewallRuleInner.name(), this.getParent(), + firewallRuleInner)) .onErrorResume(e -> Mono.empty()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchScheduleImpl.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchScheduleImpl.java index ffa4246869fb9..d5ca30a339e97 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchScheduleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchScheduleImpl.java @@ -35,21 +35,16 @@ public List scheduleEntries() { @Override public Mono createResourceAsync() { final RedisPatchScheduleImpl self = this; - return this - .parent() + return this.parent() .manager() .serviceClient() .getPatchSchedules() - .createOrUpdateAsync( - this.parent().resourceGroupName(), - this.parent().name(), - DefaultName.DEFAULT, + .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), DefaultName.DEFAULT, new RedisPatchScheduleInner().withScheduleEntries(this.innerModel().scheduleEntries())) - .map( - patchScheduleInner -> { - self.setInner(patchScheduleInner); - return self; - }); + .map(patchScheduleInner -> { + self.setInner(patchScheduleInner); + return self; + }); } @Override @@ -59,8 +54,7 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getPatchSchedules() @@ -69,8 +63,7 @@ public Mono deleteResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .parent() + return this.parent() .manager() .serviceClient() .getPatchSchedules() diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchSchedulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchSchedulesImpl.java index 20d7b516c2423..2049e1236283b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchSchedulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/implementation/RedisPatchSchedulesImpl.java @@ -16,9 +16,8 @@ import java.util.Map; /** Represents a Redis patch schedule collection associated with a Redis cache instance. */ -class RedisPatchSchedulesImpl - extends ExternalChildResourcesCachedImpl< - RedisPatchScheduleImpl, RedisPatchSchedule, RedisPatchScheduleInner, RedisCacheImpl, RedisCache> { +class RedisPatchSchedulesImpl extends + ExternalChildResourcesCachedImpl { // Currently Redis Cache has one PatchSchedule private static final String PATCH_SCHEDULE_NAME = "default"; private boolean load = false; @@ -79,15 +78,13 @@ public void deleteInlinePatchSchedule() { @Override protected Flux listChildResourcesAsync() { - return this - .getParent() + return this.getParent() .manager() .serviceClient() .getPatchSchedules() .listByRedisResourceAsync(this.getParent().resourceGroupName(), this.getParent().name()) - .map( - patchScheduleInner -> - new RedisPatchScheduleImpl(patchScheduleInner.name(), this.getParent(), patchScheduleInner)) + .map(patchScheduleInner -> new RedisPatchScheduleImpl(patchScheduleInner.name(), this.getParent(), + patchScheduleInner)) .onErrorResume(e -> Mono.empty()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCache.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCache.java index fa34488de218a..8131a1ae5a9df 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCache.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCache.java @@ -23,10 +23,8 @@ /** An immutable client-side representation of an Azure Redis Cache. */ @Fluent -public interface RedisCache - extends GroupableResource, Refreshable, Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, +public interface RedisCache extends GroupableResource, Refreshable, + Updatable, SupportsListingPrivateLinkResource, SupportsListingPrivateEndpointConnection, SupportsUpdatingPrivateEndpointConnection { /** @return exposes features available only to Premium Sku Redis Cache instances. */ @@ -116,12 +114,8 @@ public interface RedisCache **************************************************************/ /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSku, - DefinitionStages.WithCreate, - DefinitionStages.WithPremiumSkuCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSku, + DefinitionStages.WithCreate, DefinitionStages.WithPremiumSkuCreate { } /** Grouping of all the Redis Cache definition stages. */ @@ -458,7 +452,6 @@ interface WithRedisConfiguration { Update withoutRedisConfiguration(String key); } - /** The stage of redis cache update allowing to configure network access settings. */ interface WithPublicNetworkAccess { /** @@ -467,6 +460,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the redis cache. * @@ -477,13 +471,8 @@ interface WithPublicNetworkAccess { } /** The template for a Redis Cache update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - Resource.UpdateWithTags, - UpdateStages.WithSku, - UpdateStages.WithNonSslPort, - UpdateStages.WithRedisConfiguration, - UpdateStages.WithPublicNetworkAccess { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSku, + UpdateStages.WithNonSslPort, UpdateStages.WithRedisConfiguration, UpdateStages.WithPublicNetworkAccess { /** * The number of shards to be created on a Premium Cluster Cache. * diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCaches.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCaches.java index e14855e2626d4..848ebfe3a4fd2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCaches.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisCaches.java @@ -21,17 +21,10 @@ /** Entry point for Redis Cache management API. */ @Fluent -public interface RedisCaches - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface RedisCaches extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Lists all of the available Redis REST API operations. diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisCacheOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisCacheOperationsTests.java index 76d8ae593809f..c4b260c5684c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisCacheOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisCacheOperationsTests.java @@ -42,48 +42,42 @@ public class RedisCacheOperationsTests extends RedisManagementTest { @SuppressWarnings("unchecked") public void canCRUDRedisCache() throws Exception { // Create - Creatable resourceGroups = - resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); - - Creatable redisCacheDefinition1 = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup(rgName) - .withBasicSku(); - Creatable redisCacheDefinition2 = - redisManager - .redisCaches() - .define(rrNameSecond) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(resourceGroups) - .withPremiumSku() - .withShardCount(2) - .withPatchSchedule(DayOfWeek.SUNDAY, 10, Duration.ofMinutes(302)); - Creatable redisCacheDefinition3 = - redisManager - .redisCaches() - .define(rrNameThird) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(resourceGroups) - .withPremiumSku(2) - .withNonSslPort() - .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") - .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40"); + Creatable resourceGroups + = resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); + + Creatable redisCacheDefinition1 = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup(rgName) + .withBasicSku(); + Creatable redisCacheDefinition2 = redisManager.redisCaches() + .define(rrNameSecond) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(resourceGroups) + .withPremiumSku() + .withShardCount(2) + .withPatchSchedule(DayOfWeek.SUNDAY, 10, Duration.ofMinutes(302)); + Creatable redisCacheDefinition3 = redisManager.redisCaches() + .define(rrNameThird) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(resourceGroups) + .withPremiumSku(2) + .withNonSslPort() + .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") + .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40"); // Server throws "The 'minimumTlsVersion' property is not yet supported." exception. Uncomment when fixed. // .withMinimumTlsVersion(TlsVersion.ONE_FULL_STOP_ONE); - CreatedResources batchRedisCaches = - redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3); + CreatedResources batchRedisCaches + = redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3); -// StorageAccount storageAccount = -// storageManager -// .storageAccounts() -// .define(saName) -// .withRegion(Region.US_CENTRAL) -// .withExistingResourceGroup(rgNameSecond) -// .create(); + // StorageAccount storageAccount = + // storageManager + // .storageAccounts() + // .define(saName) + // .withRegion(Region.US_CENTRAL) + // .withExistingResourceGroup(rgNameSecond) + // .create(); RedisCache redisCache = batchRedisCaches.get(redisCacheDefinition1.key()); Assertions.assertEquals(rgName, redisCache.resourceGroupName()); @@ -100,8 +94,7 @@ public void canCRUDRedisCache() throws Exception { Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule2")); // Redis configuration update - premiumCache - .update() + premiumCache.update() .withoutFirewallRule("rule1") .withFirewallRule("rule3", "192.168.0.10", "192.168.0.104") .withoutMinimumTlsVersion() @@ -137,8 +130,8 @@ public void canCRUDRedisCache() throws Exception { Assertions.assertNull(patchSchedule); // List by Resource Group - List redisCaches = - redisManager.redisCaches().listByResourceGroup(rgName).stream().collect(Collectors.toList()); + List redisCaches + = redisManager.redisCaches().listByResourceGroup(rgName).stream().collect(Collectors.toList()); boolean found = false; for (RedisCache existingRedisCache : redisCaches) { if (existingRedisCache.name().equals(rrName)) { @@ -213,7 +206,7 @@ public void canCRUDRedisCache() throws Exception { // com.microsoft.azure.CloudException: One of the SAS URIs provided could not be used for the following reason: // The SAS token is poorly formatted. /*premiumCache.exportData(storageAccount.name(),"snapshot1"); - + premiumCache.importData(Arrays.asList("snapshot1"));*/ } @@ -222,22 +215,18 @@ public void canCRUDRedisCache() throws Exception { public void canRedisVersionUpdate() { RedisCache.RedisVersion redisVersion = RedisCache.RedisVersion.V4; - RedisCache redisCache = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup(rgName) - .withBasicSku() - .withRedisVersion(redisVersion) - .create(); + RedisCache redisCache = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRedisVersion(redisVersion) + .create(); assertSameVersion(RedisCache.RedisVersion.V4, redisCache.redisVersion()); redisVersion = RedisCache.RedisVersion.V6; - redisCache = redisCache.update() - .withRedisVersion(redisVersion) - .apply(); // response with "provisioningState" : "Succeeded", but it takes quite a while for the client to detect the actual version change + redisCache = redisCache.update().withRedisVersion(redisVersion).apply(); // response with "provisioningState" : "Succeeded", but it takes quite a while for the client to detect the actual version change ResourceManagerUtils.sleep(Duration.ofSeconds(300)); // let redis cache take its time @@ -247,38 +236,31 @@ public void canRedisVersionUpdate() { RedisCache redisCacheLocal = redisCache; // Cannot downgrade redisCache version. - Assertions.assertThrows( - ManagementException.class, - () -> redisCacheLocal.update() - .withRedisVersion(RedisCache.RedisVersion.V4) - .apply()); + Assertions.assertThrows(ManagementException.class, + () -> redisCacheLocal.update().withRedisVersion(RedisCache.RedisVersion.V4).apply()); } @Test public void canCRUDLinkedServers() throws Exception { - RedisCache rgg = - redisManager - .redisCaches() - .define(rrNameThird) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(rgNameSecond) - .withPremiumSku(2) - .withPatchSchedule(DayOfWeek.SATURDAY, 5, Duration.ofHours(5)) - .withRedisConfiguration("maxclients", "2") - .withNonSslPort() - .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") - .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40") - .create(); - - RedisCache rggLinked = - redisManager - .redisCaches() - .define(rrNameSecond) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgNameSecond) - .withPremiumSku(2) - .create(); + RedisCache rgg = redisManager.redisCaches() + .define(rrNameThird) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgNameSecond) + .withPremiumSku(2) + .withPatchSchedule(DayOfWeek.SATURDAY, 5, Duration.ofHours(5)) + .withRedisConfiguration("maxclients", "2") + .withNonSslPort() + .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") + .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40") + .create(); + + RedisCache rggLinked = redisManager.redisCaches() + .define(rrNameSecond) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgNameSecond) + .withPremiumSku(2) + .create(); Assertions.assertNotNull(rgg); Assertions.assertNotNull(rggLinked); @@ -317,31 +299,27 @@ public void canCRUDLinkedServers() throws Exception { @Test public void canCreateRedisWithRdbAof() { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_WEST3) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_WEST3) + .withNewResourceGroup(rgName) + .create(); - String connectionString = ResourceManagerUtils.getStorageConnectionString(saName, storageAccount.getKeys().get(0).value(), AzureEnvironment.AZURE); + String connectionString = ResourceManagerUtils.getStorageConnectionString(saName, + storageAccount.getKeys().get(0).value(), AzureEnvironment.AZURE); // RDB - RedisCache redisCache = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.US_WEST3) - .withExistingResourceGroup(rgName) - .withPremiumSku() - .withMinimumTlsVersion(TlsVersion.ONE_TWO) - .withRedisConfiguration(new RedisConfiguration() - .withRdbBackupEnabled("true") - .withRdbBackupFrequency("15") - .withRdbBackupMaxSnapshotCount("1") - .withRdbStorageConnectionString(connectionString)) - .create(); + RedisCache redisCache = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.US_WEST3) + .withExistingResourceGroup(rgName) + .withPremiumSku() + .withMinimumTlsVersion(TlsVersion.ONE_TWO) + .withRedisConfiguration(new RedisConfiguration().withRdbBackupEnabled("true") + .withRdbBackupFrequency("15") + .withRdbBackupMaxSnapshotCount("1") + .withRdbStorageConnectionString(connectionString)) + .create(); Assertions.assertEquals("true", redisCache.innerModel().redisConfiguration().rdbBackupEnabled()); Assertions.assertEquals("15", redisCache.innerModel().redisConfiguration().rdbBackupFrequency()); Assertions.assertEquals("1", redisCache.innerModel().redisConfiguration().rdbBackupMaxSnapshotCount()); @@ -351,18 +329,16 @@ public void canCreateRedisWithRdbAof() { redisManager.redisCaches().deleteById(redisCache.id()); // AOF - redisCache = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.US_WEST3) - .withExistingResourceGroup(rgName) - .withPremiumSku() - .withMinimumTlsVersion(TlsVersion.ONE_TWO) - .withRedisConfiguration("aof-backup-enabled", "true") - .withRedisConfiguration("aof-storage-connection-string-0", connectionString) - .withRedisConfiguration("aof-storage-connection-string-1", connectionString) - .create(); + redisCache = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.US_WEST3) + .withExistingResourceGroup(rgName) + .withPremiumSku() + .withMinimumTlsVersion(TlsVersion.ONE_TWO) + .withRedisConfiguration("aof-backup-enabled", "true") + .withRedisConfiguration("aof-storage-connection-string-0", connectionString) + .withRedisConfiguration("aof-storage-connection-string-1", connectionString) + .create(); Assertions.assertEquals("true", redisCache.innerModel().redisConfiguration().aofBackupEnabled()); if (!isPlaybackMode()) { Assertions.assertNotNull(redisCache.innerModel().redisConfiguration().aofStorageConnectionString0()); @@ -376,15 +352,13 @@ public void canCreateRedisWithRdbAof() { public void canCreateRedisCacheWithDisablePublicNetworkAccess() { resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); - RedisCache redisCache = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup(rgName) - .withBasicSku() - .disablePublicNetworkAccess() - .create(); + RedisCache redisCache = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup(rgName) + .withBasicSku() + .disablePublicNetworkAccess() + .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, redisCache.publicNetworkAccess()); } @@ -392,14 +366,12 @@ public void canCreateRedisCacheWithDisablePublicNetworkAccess() { public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); - RedisCache redisCache = - redisManager - .redisCaches() - .define(rrName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup(rgName) - .withBasicSku() - .create(); + RedisCache redisCache = redisManager.redisCaches() + .define(rrName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup(rgName) + .withBasicSku() + .create(); redisCache.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, redisCache.publicNetworkAccess()); diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisManagementTest.java index 43c6a315a1a3f..9e3df8845d97a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/RedisManagementTest.java @@ -33,21 +33,10 @@ public class RedisManagementTest extends ResourceManagerTestProxyTestBase { protected String saName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/implementation/RedisConfigurationTests.java b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/implementation/RedisConfigurationTests.java index 802badd5ee82e..0eb1f6e7a4385 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/implementation/RedisConfigurationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-redis/src/test/java/com/azure/resourcemanager/redis/implementation/RedisConfigurationTests.java @@ -36,8 +36,7 @@ public void generateConfigurationUtils() throws IOException { @Test public void testConfigurationUtils() { - RedisConfiguration configuration = new RedisConfiguration() - .withRdbBackupEnabled("true") + RedisConfiguration configuration = new RedisConfiguration().withRdbBackupEnabled("true") .withAofBackupEnabled("true") .withAofStorageConnectionString0("connection"); @@ -52,8 +51,7 @@ public void testConfigurationUtils() { Assertions.assertEquals("connection", configuration1.aofStorageConnectionString0()); Assertions.assertTrue(CoreUtils.isNullOrEmpty(configuration1.additionalProperties())); - configuration - .withAdditionalProperties(Collections.singletonMap("key1", "value1")); + configuration.withAdditionalProperties(Collections.singletonMap("key1", "value1")); map = ConfigurationUtils.toMap(configuration); Assertions.assertEquals(4, map.size()); Assertions.assertEquals("value1", map.get("key1")); @@ -97,7 +95,11 @@ private static String generateToMap() throws IOException { getFieldsWithJsonProperty(false).forEach((key, value) -> { sb.append(" if (configuration.").append(value.getName()).append("() != null) {\n"); - sb.append(" map.put(\"").append(key).append("\", configuration.").append(value.getName()).append("());\n"); + sb.append(" map.put(\"") + .append(key) + .append("\", configuration.") + .append(value.getName()) + .append("());\n"); sb.append(" }\n"); }); @@ -123,8 +125,8 @@ private static String generatePutConfiguration() throws IOException { sb.append(" }\n"); sb.append(" switch (key) {\n"); - getFieldsWithJsonProperty(true).forEach((key, value) -> sb.append(writeSwitchCase(key, value, - "configuration." + setterMethodName(value) + "(value)"))); + getFieldsWithJsonProperty(true).forEach((key, value) -> sb + .append(writeSwitchCase(key, value, "configuration." + setterMethodName(value) + "(value)"))); sb.append(" default:\n"); sb.append(" if (configuration.additionalProperties() == null) {\n"); sb.append(" configuration.withAdditionalProperties(new HashMap<>());\n"); @@ -152,8 +154,8 @@ private static String generateRemoveConfiguration() throws IOException { sb.append(" }\n"); sb.append(" switch (key) {\n"); - getFieldsWithJsonProperty(true).forEach((key, value) -> sb.append(writeSwitchCase(key, value, - "configuration." + setterMethodName(value) + "(null)"))); + getFieldsWithJsonProperty(true).forEach((key, value) -> sb + .append(writeSwitchCase(key, value, "configuration." + setterMethodName(value) + "(null)"))); sb.append(" default:\n"); sb.append(" break;\n"); sb.append(" }\n"); @@ -179,7 +181,9 @@ private static String setterMethodName(Field field) { private static Map getFieldsWithJsonProperty(boolean modifiable) throws IOException { Class aClass = RedisConfiguration.class; - String content = new String(Files.readAllBytes(Paths.get("../../resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisConfiguration.java")), Charset.defaultCharset()); + String content = new String(Files.readAllBytes(Paths.get( + "../../resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/models/RedisConfiguration.java")), + Charset.defaultCharset()); Stream fields = Stream.of(aClass.getDeclaredFields()) .filter(f -> toJsonField(f, content).exists || fromJsonField(f, content).exists); if (modifiable) { @@ -187,26 +191,27 @@ private static Map getFieldsWithJsonProperty(boolean modifiable) // Appearance in `toJson` method means the field is modifiable. .filter(f -> toJsonField(f, content).exists); } - return fields.collect(Collectors.toMap( - f -> { - FieldInfo fromJsonField = fromJsonField(f, content); - if (fromJsonField.exists) { - return fromJsonField.serializedName; - } - FieldInfo toJsonField = toJsonField(f, content); - if (toJsonField.exists) { - return toJsonField.serializedName; - } - throw new IllegalStateException("Shouldn't reach here, as we've already made sure that either fromJsonField or toJsonField exists."); - }, - Function.identity())); + return fields.collect(Collectors.toMap(f -> { + FieldInfo fromJsonField = fromJsonField(f, content); + if (fromJsonField.exists) { + return fromJsonField.serializedName; + } + FieldInfo toJsonField = toJsonField(f, content); + if (toJsonField.exists) { + return toJsonField.serializedName; + } + throw new IllegalStateException( + "Shouldn't reach here, as we've already made sure that either fromJsonField or toJsonField exists."); + }, Function.identity())); } private static FieldInfo fromJsonField(Field f, String content) { // e.g. if ("rdb-backup-enabled".equals(fieldName)) { // deserializedRedisConfiguration.rdbBackupEnabled = reader.getString(); // } - Pattern fromJsonFieldPattern = Pattern.compile("if \\(\"([\\w|-]+)\"\\.equals\\(fieldName\\)\\) \\{\\W*[\\w]+\\." + f.getName() + " = reader.getString\\(\\);"); + Pattern fromJsonFieldPattern + = Pattern.compile("if \\(\"([\\w|-]+)\"\\.equals\\(fieldName\\)\\) \\{\\W*[\\w]+\\." + f.getName() + + " = reader.getString\\(\\);"); Matcher matcher = fromJsonFieldPattern.matcher(content); FieldInfo fieldInfo = new FieldInfo(); if (matcher.find()) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml index f2bd88db82f84..e7e62d61e8b6b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml @@ -48,6 +48,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/ResourceManager.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/ResourceManager.java index 92d74245f5bd4..dad0b9c1126e2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/ResourceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/ResourceManager.java @@ -184,10 +184,9 @@ private static final class AuthenticatedImpl implements Authenticated { AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) { this.httpPipeline = httpPipeline; this.profile = profile; - this.subscriptionClient = new SubscriptionClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .buildClient(); + this.subscriptionClient = new SubscriptionClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .buildClient(); } public Subscriptions subscriptions() { @@ -222,55 +221,45 @@ public ResourceManager withDefaultSubscription() { } private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - null, - profile, - new ResourceManagementClientBuilder() - .pipeline(httpPipeline) + super(null, profile, + new ResourceManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); super.withResourceManager(this); - this.featureClient = new FeatureClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .subscriptionId(profile.getSubscriptionId()) - .buildClient(); + this.featureClient = new FeatureClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .buildClient(); - this.subscriptionClient = new SubscriptionClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .buildClient(); + this.subscriptionClient = new SubscriptionClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .buildClient(); - this.policyClient = new PolicyClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .subscriptionId(profile.getSubscriptionId()) - .buildClient(); + this.policyClient = new PolicyClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .buildClient(); - this.managementLockClient = new ManagementLockClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .subscriptionId(profile.getSubscriptionId()) - .buildClient(); + this.managementLockClient = new ManagementLockClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .buildClient(); - this.resourceChangeClient = new ChangesManagementClientBuilder() - .pipeline(httpPipeline) + this.resourceChangeClient = new ChangesManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient(); - this.deploymentStackClient = new DeploymentStacksManagementClientBuilder() - .pipeline(httpPipeline) + this.deploymentStackClient = new DeploymentStacksManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient(); - this.dataBoundaryClient = new DataBoundariesManagementClientBuilder() - .pipeline(httpPipeline) - .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) - .buildClient(); + this.dataBoundaryClient = new DataBoundariesManagementClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .buildClient(); for (int i = 0; i < httpPipeline.getPolicyCount(); ++i) { if (httpPipeline.getPolicy(i) instanceof ProviderRegistrationPolicy) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClient.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClient.java index cd6b1c0f44cb9..695caf851ee31 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClient.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClient.java @@ -39,8 +39,7 @@ public abstract class AzureServiceClient { private final ClientLogger logger = new ClientLogger(getClass()); - private static final Map PROPERTIES = - CoreUtils.getProperties("azure.properties"); + private static final Map PROPERTIES = CoreUtils.getProperties("azure.properties"); private static final String SDK_VERSION; static { @@ -60,7 +59,7 @@ public abstract class AzureServiceClient { * @param environment The AzureEnvironment used by the client. */ protected AzureServiceClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - AzureEnvironment environment) { + AzureEnvironment environment) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; @@ -103,8 +102,7 @@ public HttpPipeline getHttpPipeline() { * @return the default client context. */ public Context getContext() { - return new Context("Sdk-Name", sdkName) - .addData("Sdk-Version", SDK_VERSION); + return new Context("Sdk-Name", sdkName).addData("Sdk-Version", SDK_VERSION); } /** @@ -131,18 +129,10 @@ public Context mergeContext(Context context) { * @return poller flux for poll result and final result. */ public PollerFlux, U> getLroResult(Mono>> lroInit, - HttpPipeline httpPipeline, - Type pollResultType, Type finalResultType, - Context context) { - return PollerFactory.create( - getSerializerAdapter(), - httpPipeline, - pollResultType, - finalResultType, - ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(this.getDefaultPollInterval()), - lroInit, - context - ); + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(getSerializerAdapter(), httpPipeline, pollResultType, finalResultType, + ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(this.getDefaultPollInterval()), lroInit, + context); } /** @@ -160,18 +150,16 @@ public Mono getLroFinalResultOrError(AsyncPollResponse, HttpResponse errorResponse = null; PollResult.Error lroError = response.getValue().getError(); if (lroError != null) { - errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), - lroError.getResponseHeaders(), lroError.getResponseBody()); + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); errorMessage = response.getValue().getError().getMessage(); String errorBody = response.getValue().getError().getResponseBody(); if (errorBody != null) { // try to deserialize error body to ManagementError try { - managementError = this.getSerializerAdapter().deserialize( - errorBody, - ManagementError.class, - SerializerEncoding.JSON); + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); if (managementError.getCode() == null || managementError.getMessage() == null) { managementError = null; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/AzureConfigurable.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/AzureConfigurable.java index e061f497bb4b1..3866466ba76a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/AzureConfigurable.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/AzureConfigurable.java @@ -34,7 +34,7 @@ public interface AzureConfigurable> { * * If set, this configure will override {@link HttpLogOptions#setLogLevel(HttpLogDetailLevel)} configure of * {@link AzureConfigurable#withLogOptions(HttpLogOptions)}. - + * @param logLevel the logging level * @return the configurable object itself */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/ResourceUtils.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/ResourceUtils.java index b1a3ce18a0892..cebc02d0a75cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/ResourceUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/ResourceUtils.java @@ -191,25 +191,15 @@ public static String defaultApiVersion(String id, Provider provider) { * if the resource is a generic resource * @return the resource ID string */ - public static String constructResourceId( - final String subscriptionId, - final String resourceGroupName, - final String resourceProviderNamespace, - final String resourceType, - final String resourceName, - final String parentResourcePath) { + public static String constructResourceId(final String subscriptionId, final String resourceGroupName, + final String resourceProviderNamespace, final String resourceType, final String resourceName, + final String parentResourcePath) { String prefixedParentPath = parentResourcePath; if (parentResourcePath != null && !parentResourcePath.isEmpty()) { prefixedParentPath = "/" + parentResourcePath; } - return String.format( - "/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", - subscriptionId, - resourceGroupName, - resourceProviderNamespace, - prefixedParentPath, - resourceType, - resourceName); + return String.format("/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s", subscriptionId, + resourceGroupName, resourceProviderNamespace, prefixedParentPath, resourceType, resourceName); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/SupportsGettingByName.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/SupportsGettingByName.java index cf633a6e3a16c..6b4957a6f09b7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/SupportsGettingByName.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/SupportsGettingByName.java @@ -1,10 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - package com.azure.resourcemanager.resources.fluentcore.arm.collection; - import reactor.core.publisher.Mono; /** @@ -23,7 +21,6 @@ public interface SupportsGettingByName { */ T getByName(String name); - /** * Gets the information about a resource based on the resource name ithin the current resource group. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/BatchDeletionImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/BatchDeletionImpl.java index 5a2372806236c..aab1fd2e457a7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/BatchDeletionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/BatchDeletionImpl.java @@ -25,16 +25,15 @@ public class BatchDeletionImpl { * @return Flux of IDs that successfully deleted. */ public static Flux deleteByIdsAsync(Collection ids, - BiFunction> deleteByGroupAndNameAsync) { + BiFunction> deleteByGroupAndNameAsync) { if (ids == null || ids.isEmpty()) { return Flux.empty(); } else { - return Flux.fromIterable(ids) - .flatMapDelayError(id -> { - final String resourceGroupName = ResourceUtils.groupFromResourceId(id); - final String name = ResourceUtils.nameFromResourceId(id); - return deleteByGroupAndNameAsync.apply(resourceGroupName, name).then(Mono.just(id)); - }, 32, 32) + return Flux.fromIterable(ids).flatMapDelayError(id -> { + final String resourceGroupName = ResourceUtils.groupFromResourceId(id); + final String name = ResourceUtils.nameFromResourceId(id); + return deleteByGroupAndNameAsync.apply(resourceGroupName, name).then(Mono.just(id)); + }, 32, 32) .onErrorMap(AggregatedManagementException::convertToManagementException) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableResourcesImpl.java index c04fb8d1c80ac..1db75f63c0739 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableResourcesImpl.java @@ -31,9 +31,7 @@ * @param the wrapper inner type */ public abstract class CreatableResourcesImpl - extends CreatableWrappersImpl - implements - SupportsBatchCreation { + extends CreatableWrappersImpl implements SupportsBatchCreation { protected CreatableResourcesImpl() { } @@ -41,14 +39,12 @@ protected CreatableResourcesImpl() { @Override @SafeVarargs public final CreatedResources create(Creatable... creatables) { - return createAsyncNonStream(creatables) - .block(); + return createAsyncNonStream(creatables).block(); } @Override public final CreatedResources create(List> creatables) { - return createAsyncNonStream(creatables) - .block(); + return createAsyncNonStream(creatables).block(); } @Override @@ -68,8 +64,7 @@ public final Flux createAsync(List> creatables) { @SuppressWarnings("unchecked") private Mono> createAsyncNonStream(List> creatables) { - return createWithRootResourceAsync(creatables) - .map(CreatedResourcesImpl::new); + return createWithRootResourceAsync(creatables).map(CreatedResourcesImpl::new); } @SuppressWarnings("unchecked") @@ -77,8 +72,8 @@ private Mono> createAsyncNonStream(Creatable... creatable return createAsyncNonStream(Arrays.asList(creatables)); } - private Mono> createWithRootResourceAsync( - List> creatables) { + private Mono> + createWithRootResourceAsync(List> creatables) { CreatableUpdatableResourcesRootImpl rootResource = new CreatableUpdatableResourcesRootImpl<>(); rootResource.addCreatableDependencies(creatables); return rootResource.createAsync(); @@ -89,8 +84,7 @@ private Mono> createWithRootResourceAsync( * * @param the type of the resources in the batch. */ - private class CreatedResourcesImpl - implements CreatedResources { + private class CreatedResourcesImpl implements CreatedResources { private final ClientLogger logger = new ClientLogger(this.getClass()); private CreatableUpdatableResourcesRoot creatableUpdatableResourcesRoot; private Map resources = new HashMap<>(); @@ -185,11 +179,9 @@ interface CreatableUpdatableResourcesRoot extends I * * @param the type of the resources in the batch. */ - private class CreatableUpdatableResourcesRootImpl - extends CreatableUpdatableImpl, - Object, - CreatableUpdatableResourcesRootImpl> - implements CreatableUpdatableResourcesRoot { + private class CreatableUpdatableResourcesRootImpl extends + CreatableUpdatableImpl, Object, CreatableUpdatableResourcesRootImpl> + implements CreatableUpdatableResourcesRoot { /** * Collection of keys of top level resources in this batch. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableWrappersImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableWrappersImpl.java index ab2c375d8fb8c..4bed14d89ee03 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableWrappersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/CreatableWrappersImpl.java @@ -12,11 +12,10 @@ * @param the individual resource implementation * @param the wrapper inner type */ -public abstract class CreatableWrappersImpl - extends ReadableWrappersImpl - implements - // Assume anything creatable is deletable - SupportsDeletingById { +public abstract class CreatableWrappersImpl extends ReadableWrappersImpl + implements + // Assume anything creatable is deletable + SupportsDeletingById { protected CreatableWrappersImpl() { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourceCollectionImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourceCollectionImpl.java index 6c5d3bba8b6ac..ac858df6e78fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourceCollectionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourceCollectionImpl.java @@ -29,12 +29,7 @@ * @param the parent Azure resource impl class type that implements {@link ParentT} * @param the parent interface */ -public abstract class ExternalChildResourceCollectionImpl< - FluentModelTImpl extends ExternalChildResourceImpl, - FluentModelT extends ExternalChildResource, - InnerModelT, - ParentImplT extends ParentT, - ParentT> { +public abstract class ExternalChildResourceCollectionImpl, FluentModelT extends ExternalChildResource, InnerModelT, ParentImplT extends ParentT, ParentT> { /** * The parent resource of this collection of child resources. */ @@ -67,8 +62,8 @@ public abstract class ExternalChildResourceCollectionImpl< * @param parentTaskGroup the TaskGroup the parent Azure resource belongs to * @param childResourceName the child resource name */ - protected ExternalChildResourceCollectionImpl(ParentImplT parent, - TaskGroup parentTaskGroup, String childResourceName) { + protected ExternalChildResourceCollectionImpl(ParentImplT parent, TaskGroup parentTaskGroup, + String childResourceName) { this.parent = parent; this.parentTaskGroup = parentTaskGroup; this.childResourceName = childResourceName; @@ -126,12 +121,12 @@ protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl chil */ public Flux commitAsync() { if (this.isPostRunMode) { - return Flux.error( - new IllegalStateException("commitAsync() cannot be invoked when 'post run' mode is enabled")); + return Flux + .error(new IllegalStateException("commitAsync() cannot be invoked when 'post run' mode is enabled")); } - final ExternalChildResourceCollectionImpl - self = this; + final ExternalChildResourceCollectionImpl self + = this; List items = new ArrayList<>(); for (FluentModelTImpl item : this.childCollection.values()) { items.add(item); @@ -142,61 +137,60 @@ public Flux commitAsync() { Sinks.Many aggregatedErrorStream = Sinks.many().replay().all(); Flux deleteStream = Flux.fromIterable(items) - .filter(childResource -> - childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeRemoved) - .flatMap(childResource -> childResource.deleteResourceAsync() - .map(response -> childResource) - .doOnSuccess(fluentModelT -> { - childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None); - self.childCollection.remove(childResource.name()); - successfullyRemoved.add(childResource); - }) - .onErrorResume(throwable -> { - exceptionsList.add(throwable); - return Mono.empty(); - })); + .filter(childResource -> childResource.pendingOperation() + == ExternalChildResourceImpl.PendingOperation.ToBeRemoved) + .flatMap(childResource -> childResource.deleteResourceAsync() + .map(response -> childResource) + .doOnSuccess(fluentModelT -> { + childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None); + self.childCollection.remove(childResource.name()); + successfullyRemoved.add(childResource); + }) + .onErrorResume(throwable -> { + exceptionsList.add(throwable); + return Mono.empty(); + })); Flux createStream = Flux.fromIterable(items) - .filter(childResource -> - childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated) - .flatMap(childResource -> childResource.createResourceAsync() - .map(fluentModelT -> childResource) - .doOnNext(fluentModelT -> - childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None)) - .onErrorResume(throwable -> { - self.childCollection.remove(childResource.name()); - exceptionsList.add(throwable); - return Mono.empty(); - })); + .filter(childResource -> childResource.pendingOperation() + == ExternalChildResourceImpl.PendingOperation.ToBeCreated) + .flatMap(childResource -> childResource.createResourceAsync() + .map(fluentModelT -> childResource) + .doOnNext( + fluentModelT -> childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None)) + .onErrorResume(throwable -> { + self.childCollection.remove(childResource.name()); + exceptionsList.add(throwable); + return Mono.empty(); + })); Flux updateStream = Flux.fromIterable(items) - .filter(childResource -> - childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeUpdated) - .flatMap(childResource -> childResource.updateResourceAsync() - .map(e -> childResource) - .doOnNext(resource -> - resource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None)) - .onErrorResume(throwable -> { - exceptionsList.add(throwable); - return Mono.empty(); - })); - - Flux operationsStream = Flux.merge(deleteStream, createStream, updateStream) - .doOnTerminate(() -> { - if (clearAfterCommit()) { - self.childCollection.clear(); + .filter(childResource -> childResource.pendingOperation() + == ExternalChildResourceImpl.PendingOperation.ToBeUpdated) + .flatMap(childResource -> childResource.updateResourceAsync() + .map(e -> childResource) + .doOnNext(resource -> resource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None)) + .onErrorResume(throwable -> { + exceptionsList.add(throwable); + return Mono.empty(); + })); + + Flux operationsStream + = Flux.merge(deleteStream, createStream, updateStream).doOnTerminate(() -> { + if (clearAfterCommit()) { + self.childCollection.clear(); + } + if (successfullyRemoved.size() > 0) { + for (FluentModelTImpl removed : successfullyRemoved) { + aggregatedErrorStream.tryEmitNext(removed); } - if (successfullyRemoved.size() > 0) { - for (FluentModelTImpl removed : successfullyRemoved) { - aggregatedErrorStream.tryEmitNext(removed); - } - } - if (!exceptionsList.isEmpty()) { - aggregatedErrorStream.tryEmitError(Exceptions.multiple(exceptionsList)); - } else { - aggregatedErrorStream.tryEmitComplete(); - } - }); + } + if (!exceptionsList.isEmpty()) { + aggregatedErrorStream.tryEmitError(Exceptions.multiple(exceptionsList)); + } else { + aggregatedErrorStream.tryEmitComplete(); + } + }); return Flux.concat(operationsStream, aggregatedErrorStream.asFlux()); } @@ -210,11 +204,9 @@ public Flux commitAsync() { * @return the Mono stream */ public Mono> commitAndGetAllAsync() { - return commitAsync().collect(() -> new ArrayList(), - (state, item) -> state.add(item)); + return commitAsync().collect(() -> new ArrayList(), (state, item) -> state.add(item)); } - /** * Finds a child resource with the given key. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesCachedImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesCachedImpl.java index c677e24a48ae3..edf4dd69fdd60 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesCachedImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesCachedImpl.java @@ -28,15 +28,11 @@ * @param the parent Azure resource impl class type that implements {@link ParentT} * @param the parent interface */ -public abstract class ExternalChildResourcesCachedImpl< - FluentModelTImpl extends ExternalChildResourceImpl, - FluentModelT extends ExternalChildResource, - InnerModelT, - ParentImplT extends ParentT, - ParentT> - extends ExternalChildResourceCollectionImpl { +public abstract class ExternalChildResourcesCachedImpl, FluentModelT extends ExternalChildResource, InnerModelT, ParentImplT extends ParentT, ParentT> + extends ExternalChildResourceCollectionImpl { private final ClientLogger logger = new ClientLogger(this.getClass()); private static final String ERROR_MESSAGE_FORMAT = "A child resource ('%s') with name (key) '%s (%s)' %s"; + /** * Creates a new ExternalChildResourcesImpl. * @@ -44,8 +40,8 @@ public abstract class ExternalChildResourcesCachedImpl< * @param parentTaskGroup the TaskGroup the parent Azure resource belongs to * @param childResourceName the child resource name */ - protected ExternalChildResourcesCachedImpl(ParentImplT parent, - TaskGroup parentTaskGroup, String childResourceName) { + protected ExternalChildResourcesCachedImpl(ParentImplT parent, TaskGroup parentTaskGroup, + String childResourceName) { super(parent, parentTaskGroup, childResourceName); } @@ -131,13 +127,13 @@ protected final FluentModelTImpl prepareInlineUpdate(String name) { protected final FluentModelTImpl prepareInlineUpdate(String name, String key) { FluentModelTImpl childResource = find(key); if (childResource == null - || childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated) { + || childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated) { String errorMessage = String.format(ERROR_MESSAGE_FORMAT, childResourceName, name, key, "not found"); throw logger.logExceptionAsError(new IllegalArgumentException(errorMessage)); } if (childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeRemoved) { - String errorMessage = String.format(ERROR_MESSAGE_FORMAT, - childResourceName, name, key, "is marked for deletion"); + String errorMessage + = String.format(ERROR_MESSAGE_FORMAT, childResourceName, name, key, "is marked for deletion"); throw logger.logExceptionAsError(new IllegalArgumentException(errorMessage)); } childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.ToBeUpdated); @@ -162,7 +158,7 @@ protected final void prepareInlineRemove(String name) { protected final void prepareInlineRemove(String name, String key) { FluentModelTImpl childResource = find(key); if (childResource == null - || childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated) { + || childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated) { String errorMessage = String.format(ERROR_MESSAGE_FORMAT, childResourceName, name, key, "not found"); throw logger.logExceptionAsError(new IllegalArgumentException(errorMessage)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesNonCachedImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesNonCachedImpl.java index f33ea95de61ff..0650d2914ea04 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesNonCachedImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ExternalChildResourcesNonCachedImpl.java @@ -23,14 +23,10 @@ * @param the parent Azure resource impl class type that implements {@link ParentT} * @param the parent interface */ -public abstract class ExternalChildResourcesNonCachedImpl< - FluentModelTImpl extends ExternalChildResourceImpl, - FluentModelT extends ExternalChildResource, - InnerModelT, - ParentImplT extends ParentT, - ParentT> - extends ExternalChildResourceCollectionImpl { +public abstract class ExternalChildResourcesNonCachedImpl, FluentModelT extends ExternalChildResource, InnerModelT, ParentImplT extends ParentT, ParentT> + extends ExternalChildResourceCollectionImpl { private ClientLogger logger = new ClientLogger(this.getClass()); + /** * Creates a new ExternalNonInlineChildResourcesImpl. * @@ -38,8 +34,8 @@ public abstract class ExternalChildResourcesNonCachedImpl< * @param parentTaskGroup the TaskGroup the parent Azure resource belongs to * @param childResourceName the child resource name */ - protected ExternalChildResourcesNonCachedImpl(ParentImplT parent, - TaskGroup parentTaskGroup, String childResourceName) { + protected ExternalChildResourcesNonCachedImpl(ParentImplT parent, TaskGroup parentTaskGroup, + String childResourceName) { super(parent, parentTaskGroup, childResourceName); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/GroupableResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/GroupableResourcesImpl.java index d57883361dae2..96074a7342feb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/GroupableResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/GroupableResourcesImpl.java @@ -25,25 +25,14 @@ * @param the inner type of the collection object * @param the manager type for this resource provider type */ -public abstract class GroupableResourcesImpl< - T extends GroupableResource, - ImplT extends T, - InnerT extends Resource, - InnerCollectionT, - ManagerT extends Manager> - extends CreatableResourcesImpl - implements - SupportsGettingById, - SupportsGettingByResourceGroup, - SupportsDeletingByResourceGroup, - HasManager { +public abstract class GroupableResourcesImpl, ImplT extends T, InnerT extends Resource, InnerCollectionT, ManagerT extends Manager> + extends CreatableResourcesImpl implements SupportsGettingById, + SupportsGettingByResourceGroup, SupportsDeletingByResourceGroup, HasManager { private final InnerCollectionT innerCollection; private final ManagerT myManager; - protected GroupableResourcesImpl( - InnerCollectionT innerCollection, - ManagerT manager) { + protected GroupableResourcesImpl(InnerCollectionT innerCollection, ManagerT manager) { this.innerCollection = innerCollection; this.myManager = manager; } @@ -65,8 +54,7 @@ public T getById(String id) { @Override public Mono getByIdAsync(String id) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } ResourceId resourceId = ResourceId.fromString(id); @@ -81,12 +69,11 @@ public final void deleteByResourceGroup(String groupName, String name) { @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } return this.deleteInnerAsync(resourceGroupName, name) .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()); @@ -95,8 +82,7 @@ public Mono deleteByResourceGroupAsync(String resourceGroupName, String na @Override public Mono deleteByIdAsync(String id) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } return deleteByResourceGroupAsync(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } @@ -109,15 +95,13 @@ public T getByResourceGroup(String resourceGroupName, String name) { @Override public Mono getByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this.getInnerAsync(resourceGroupName, name) - .map(this::wrapModel); + return this.getInnerAsync(resourceGroupName, name).map(this::wrapModel); } protected abstract Mono getInnerAsync(String resourceGroupName, String name); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildResourcesImpl.java index 8024b672d2880..c5fda68e3ac5d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildResourcesImpl.java @@ -19,14 +19,8 @@ * @param the manager type for this resource provider type * @param the type of the parent resource */ -public abstract class IndependentChildResourcesImpl< - T extends IndependentChildResource, - ImplT extends T, - InnerT, - InnerCollectionT, - ManagerT extends Manager, - ParentT extends Resource & HasResourceGroup> - extends IndependentChildrenImpl { +public abstract class IndependentChildResourcesImpl, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends Manager, ParentT extends Resource & HasResourceGroup> + extends IndependentChildrenImpl { protected IndependentChildResourcesImpl(InnerCollectionT innerCollection, ManagerT manager) { super(innerCollection, manager); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildrenImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildrenImpl.java index d2d599937859d..eb0dfd956c2f1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildrenImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/IndependentChildrenImpl.java @@ -28,21 +28,10 @@ * @param the manager type for this resource provider type * @param the type of the parent resource */ -public abstract class IndependentChildrenImpl< - T extends IndependentChild, - ImplT extends T, - InnerT, - InnerCollectionT, - ManagerT extends Manager, - ParentT extends Resource & HasResourceGroup> - extends CreatableResourcesImpl - implements - SupportsGettingById, - SupportsGettingByParent, - SupportsListingByParent, - SupportsDeletingByParent, - HasManager, - HasInnerModel { +public abstract class IndependentChildrenImpl, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends Manager, ParentT extends Resource & HasResourceGroup> + extends CreatableResourcesImpl implements SupportsGettingById, + SupportsGettingByParent, SupportsListingByParent, + SupportsDeletingByParent, HasManager, HasInnerModel { protected final InnerCollectionT innerCollection; protected final ManagerT manager; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ReadableWrappersImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ReadableWrappersImpl.java index 36330b7df4974..3766e9b93cdac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ReadableWrappersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/ReadableWrappersImpl.java @@ -14,10 +14,7 @@ * @param the individual resource implementation * @param the wrapper inner type */ -public abstract class ReadableWrappersImpl< - T, - ImplT extends T, - InnerT> { +public abstract class ReadableWrappersImpl { protected ReadableWrappersImpl() { } @@ -32,61 +29,61 @@ protected PagedFlux wrapPageAsync(PagedFlux innerPage) { return PagedConverter.mapPage(innerPage, innerT -> wrapModel(innerT)); } -// protected PagedIterable wrapList(List list) { -// return wrapList(ReadableWrappersImpl.convertToPagedList(list)); -// } -// -// /** -// * Converts the List to PagedList. -// * -// * @param list list to be converted in to paged list -// * @param the wrapper inner type -// * @return the Paged list for the inner type. -// */ -// public static PagedIterable convertToPagedList(List list) { -// PageImpl page = new PageImpl<>(); -// page.setItems(list); -// page.setNextPageLink(null); -// return new PagedIterable<>(page) { -// @Override -// public Page nextPage(String nextPageLink) { -// return null; -// } -// }; -// } -// -// -// protected Flux wrapPageAsync(Flux> innerPage) { -// return wrapModelAsync(convertPageToInnerAsync(innerPage)); -// } -// -// protected Flux wrapListAsync(Flux> innerList) { -// return wrapModelAsync(convertListToInnerAsync(innerList)); -// } -// -// /** -// * Converts Flux of list to Flux of Inner. -// * -// * @param innerList list to be converted. -// * @param type of inner. -// * @return Flux for list of inner. -// */ -// public static Flux convertListToInnerAsync(Flux> innerList) { -// return innerList.flatMap(list -> Flux.fromIterable(list)); -// } -// -// /** -// * Converts Flux of page to Flux of Inner. -// * -// * @param type of inner. -// * @param innerPage Page to be converted. -// * @return Flux for list of inner. -// */ -// public static Flux convertPageToInnerAsync(Flux> innerPage) { -// return innerPage.flatMap(page -> Flux.fromIterable(page.getItems())); -// } -// -// private Flux wrapModelAsync(Flux inner) { -// return inner.map(i -> wrapModel(i)); -// } + // protected PagedIterable wrapList(List list) { + // return wrapList(ReadableWrappersImpl.convertToPagedList(list)); + // } + // + // /** + // * Converts the List to PagedList. + // * + // * @param list list to be converted in to paged list + // * @param the wrapper inner type + // * @return the Paged list for the inner type. + // */ + // public static PagedIterable convertToPagedList(List list) { + // PageImpl page = new PageImpl<>(); + // page.setItems(list); + // page.setNextPageLink(null); + // return new PagedIterable<>(page) { + // @Override + // public Page nextPage(String nextPageLink) { + // return null; + // } + // }; + // } + // + // + // protected Flux wrapPageAsync(Flux> innerPage) { + // return wrapModelAsync(convertPageToInnerAsync(innerPage)); + // } + // + // protected Flux wrapListAsync(Flux> innerList) { + // return wrapModelAsync(convertListToInnerAsync(innerList)); + // } + // + // /** + // * Converts Flux of list to Flux of Inner. + // * + // * @param innerList list to be converted. + // * @param type of inner. + // * @return Flux for list of inner. + // */ + // public static Flux convertListToInnerAsync(Flux> innerList) { + // return innerList.flatMap(list -> Flux.fromIterable(list)); + // } + // + // /** + // * Converts Flux of page to Flux of Inner. + // * + // * @param type of inner. + // * @param innerPage Page to be converted. + // * @return Flux for list of inner. + // */ + // public static Flux convertPageToInnerAsync(Flux> innerPage) { + // return innerPage.flatMap(page -> Flux.fromIterable(page.getItems())); + // } + // + // private Flux wrapModelAsync(Flux inner) { + // return inner.map(i -> wrapModel(i)); + // } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByIdImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByIdImpl.java index 2e588eca84ab4..a7a8f6aa553f1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByIdImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByIdImpl.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - package com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingById; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByResourceGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByResourceGroupImpl.java index 593713eb2afe4..558e32678b437 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByResourceGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/SupportsGettingByResourceGroupImpl.java @@ -14,16 +14,13 @@ * * @param the type of the resource to get. */ -public abstract class SupportsGettingByResourceGroupImpl - extends SupportsGettingByIdImpl - implements - SupportsGettingByResourceGroup { +public abstract class SupportsGettingByResourceGroupImpl extends SupportsGettingByIdImpl + implements SupportsGettingByResourceGroup { @Override public T getByResourceGroup(String resourceGroupName, String name) { return this.getByResourceGroupAsync(resourceGroupName, name).block(); } - @Override public Mono getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java index 865544b6ea9a7..5d702e35af5bc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java @@ -31,17 +31,9 @@ * @param the inner type of the collection object * @param the manager type for this resource provider type */ -public abstract class TopLevelModifiableResourcesImpl< - T extends GroupableResource, - ImplT extends T, - InnerT extends Resource, - InnerCollectionT extends InnerSupportsListing & InnerSupportsGet & InnerSupportsDelete, - ManagerT extends Manager> - extends GroupableResourcesImpl - implements - SupportsListing, - SupportsListingByResourceGroup, - SupportsBatchDeletion { +public abstract class TopLevelModifiableResourcesImpl, ImplT extends T, InnerT extends Resource, InnerCollectionT extends InnerSupportsListing & InnerSupportsGet & InnerSupportsDelete, ManagerT extends Manager> + extends GroupableResourcesImpl + implements SupportsListing, SupportsListingByResourceGroup, SupportsBatchDeletion { protected TopLevelModifiableResourcesImpl(InnerCollectionT innerCollection, ManagerT manager) { super(innerCollection, manager); @@ -87,8 +79,8 @@ public PagedFlux listAsync() { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/implementation/AzureConfigurableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/implementation/AzureConfigurableImpl.java index e9e91358015d2..767d7b21a0d15 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/implementation/AzureConfigurableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/implementation/AzureConfigurableImpl.java @@ -27,8 +27,7 @@ * * @param the type of the configurable interface */ -public class AzureConfigurableImpl> - implements AzureConfigurable { +public class AzureConfigurableImpl> implements AzureConfigurable { private HttpClient httpClient; private HttpLogOptions httpLogOptions; private final List policies; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ChildResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ChildResource.java index 13f82e27f11a0..4d8d1d5ced2c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ChildResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ChildResource.java @@ -11,8 +11,5 @@ * @param parent interface */ @Fluent -public interface ChildResource extends - Indexable, - HasName, - HasParent { +public interface ChildResource extends Indexable, HasName, HasParent { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ExternalChildResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ExternalChildResource.java index 8727ff95d266e..db8f5657d9613 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ExternalChildResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ExternalChildResource.java @@ -11,7 +11,7 @@ * @param parent interface */ public interface ExternalChildResource - extends ChildResource, Refreshable { + extends ChildResource, Refreshable { /** * @return the id of the external child resource */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/GroupableResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/GroupableResource.java index 21e7ccabbac96..2cc77ed6167c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/GroupableResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/GroupableResource.java @@ -16,11 +16,8 @@ * @param the wrapped, inner, auto-generated implementation object type */ @Fluent() -public interface GroupableResource extends - Resource, - HasResourceGroup, - HasManager, - HasInnerModel { +public interface GroupableResource + extends Resource, HasResourceGroup, HasManager, HasInnerModel { /** * Grouping of all the definition stages. @@ -33,9 +30,7 @@ interface DefinitionStages { * * @param the next stage of the definition */ - interface WithGroup extends - WithExistingResourceGroup, - WithNewResourceGroup { + interface WithGroup extends WithExistingResourceGroup, WithNewResourceGroup { } /** @@ -45,9 +40,7 @@ interface WithGroup extends * * @param the next stage of the definition */ - interface WithGroupAndRegion extends - WithExistingResourceGroup, - WithNewResourceGroupWithRegion { + interface WithGroupAndRegion extends WithExistingResourceGroup, WithNewResourceGroupWithRegion { } /** @@ -56,8 +49,7 @@ interface WithGroupAndRegion extends * * @param the next stage of the definition */ - interface WithNewResourceGroup extends - WithCreatableResourceGroup { + interface WithNewResourceGroup extends WithCreatableResourceGroup { /** * Creates a new resource group to put the resource in. *

@@ -85,8 +77,7 @@ interface WithNewResourceGroup extends * * @param the next stage of the definition */ - interface WithNewResourceGroupWithRegion extends - WithCreatableResourceGroup { + interface WithNewResourceGroupWithRegion extends WithCreatableResourceGroup { /** * Creates a new resource group to put the resource in. *

diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/HasName.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/HasName.java index fbd0b0b98b745..62677c063217e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/HasName.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/HasName.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.resources.fluentcore.arm.models; - import com.azure.core.annotation.Fluent; /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChild.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChild.java index b97c6304edea7..a00ff39a2a85c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChild.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChild.java @@ -13,12 +13,7 @@ * @param the client manager type representing the service */ @Fluent -public interface IndependentChild extends - HasName, - HasId, - Indexable, - HasResourceGroup, - HasManager { +public interface IndependentChild extends HasName, HasId, Indexable, HasResourceGroup, HasManager { /** * Grouping of all the definition stages. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChildResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChildResource.java index 34d82b75b01c3..034292b87dd61 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChildResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/IndependentChildResource.java @@ -12,7 +12,6 @@ * @param the inner, auto-generated implementation logic object type */ @Fluent -public interface IndependentChildResource extends - GroupableResource, - IndependentChild { +public interface IndependentChildResource + extends GroupableResource, IndependentChild { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ParentlessChildResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ParentlessChildResource.java index 9e58df4c0f9cb..72743f089f90b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ParentlessChildResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/ParentlessChildResource.java @@ -12,9 +12,7 @@ * @param parent interface */ @Fluent -public interface ParentlessChildResource extends - Indexable, - HasName { +public interface ParentlessChildResource extends Indexable, HasName { /** * @return the parent of this child object diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/PrivateLinkServiceConnectionState.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/PrivateLinkServiceConnectionState.java index 995f7b81ad225..1328918779301 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/PrivateLinkServiceConnectionState.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/PrivateLinkServiceConnectionState.java @@ -17,8 +17,8 @@ public final class PrivateLinkServiceConnectionState { * @param description the description of the connection. * @param actionsRequired the required action for the connection. */ - public PrivateLinkServiceConnectionState(PrivateEndpointServiceConnectionStatus status, - String description, String actionsRequired) { + public PrivateLinkServiceConnectionState(PrivateEndpointServiceConnectionStatus status, String description, + String actionsRequired) { this.status = status; this.description = description; this.actionsRequired = actionsRequired; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/Resource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/Resource.java index 035937c7b939c..9142e248f0747 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/Resource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/Resource.java @@ -11,10 +11,7 @@ /** * Base interfaces for fluent resources. */ -public interface Resource extends - Indexable, - HasId, - HasName { +public interface Resource extends Indexable, HasId, HasName { /** * A dummy resource that does nothing. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ChildResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ChildResourceImpl.java index c89de60be3fb2..2da683df5155a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ChildResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ChildResourceImpl.java @@ -14,8 +14,7 @@ * @param parent interface */ public abstract class ChildResourceImpl - extends IndexableWrapperImpl - implements ChildResource { + extends IndexableWrapperImpl implements ChildResource { private final ParentImplT parent; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ExternalChildResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ExternalChildResourceImpl.java index 236847454f620..9b60221ee90fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ExternalChildResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ExternalChildResourceImpl.java @@ -35,18 +35,10 @@ * @param the parent Azure resource impl class type that implements {@link ParentT} * @param parent interface */ -public abstract class ExternalChildResourceImpl - extends - ChildResourceImpl - implements - Appliable, - Creatable, - TaskGroup.HasTaskGroup, - ExternalChildResource, - Refreshable { +public abstract class ExternalChildResourceImpl + extends ChildResourceImpl + implements Appliable, Creatable, TaskGroup.HasTaskGroup, + ExternalChildResource, Refreshable { /** * State representing any pending action that needs to be performed on this child resource. */ @@ -67,9 +59,7 @@ public abstract class ExternalChildResourceImpl externalChild) { + final ExternalChildResourceImpl externalChild) { this.externalChild = externalChild; } @@ -426,7 +413,7 @@ private class ExternalChildActionTaskItem extends IndexableTaskItem { * @param externalChild an external child this TaskItem composes. */ ExternalChildActionTaskItem(final String key, - final ExternalChildResourceImpl externalChild) { + final ExternalChildResourceImpl externalChild) { super(key); this.externalChild = externalChild; } @@ -441,22 +428,25 @@ public Mono invokeTaskAsync(TaskGroup.InvocationContext context) { switch (this.externalChild.pendingOperation()) { case ToBeCreated: return this.externalChild.createResourceAsync() - .doOnNext(createdExternalChild -> externalChild.setPendingOperation(PendingOperation.None)) - .map(createdExternalChild -> createdExternalChild); + .doOnNext(createdExternalChild -> externalChild.setPendingOperation(PendingOperation.None)) + .map(createdExternalChild -> createdExternalChild); + case ToBeUpdated: return this.externalChild.updateResourceAsync() - .doOnNext(createdExternalChild -> externalChild.setPendingOperation(PendingOperation.None)) - .map(updatedExternalChild -> updatedExternalChild); + .doOnNext(createdExternalChild -> externalChild.setPendingOperation(PendingOperation.None)) + .map(updatedExternalChild -> updatedExternalChild); + case ToBeRemoved: return this.externalChild.deleteResourceAsync() - .doOnSuccess(aVoid -> externalChild.setPendingOperation(PendingOperation.None)) - .map(aVoid -> voidIndexable()); + .doOnSuccess(aVoid -> externalChild.setPendingOperation(PendingOperation.None)) + .map(aVoid -> voidIndexable()); + default: // PendingOperation.None // return Mono.error(new IllegalStateException( String.format("No action pending on child resource: %s, invokeAsync should not be called ", - externalChild.name))); + externalChild.name))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableParentResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableParentResourceImpl.java index acf38633539a9..a154d8e47d376 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableParentResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableParentResourceImpl.java @@ -16,18 +16,10 @@ * @param the implementation type of the fluent model type * @param the service manager type */ -public abstract class GroupableParentResourceImpl< - FluentModelT extends Resource, - InnerModelT extends com.azure.core.management.Resource, - FluentModelImplT extends GroupableParentResourceImpl, - ManagerT extends Manager> - extends - GroupableResourceImpl { - - protected GroupableParentResourceImpl( - String name, - InnerModelT innerObject, - ManagerT manager) { +public abstract class GroupableParentResourceImpl, ManagerT extends Manager> + extends GroupableResourceImpl { + + protected GroupableParentResourceImpl(String name, InnerModelT innerObject, ManagerT manager) { super(name, innerObject, manager); initializeChildrenFromInner(); } @@ -36,24 +28,26 @@ protected GroupableParentResourceImpl( protected abstract void initializeChildrenFromInner(); - protected void beforeCreating() { } + protected void beforeCreating() { + } - protected void afterCreating() { } + protected void afterCreating() { + } @Override public Mono createResourceAsync() { - @SuppressWarnings("unchecked") final FluentModelT self = (FluentModelT) this; + @SuppressWarnings("unchecked") + final FluentModelT self = (FluentModelT) this; beforeCreating(); - return createInner() - .flatMap(inner -> { - setInner(inner); - try { - initializeChildrenFromInner(); - afterCreating(); - return Mono.just(self); - } catch (Exception e) { - return Mono.error(e); - } - }); + return createInner().flatMap(inner -> { + setInner(inner); + try { + initializeChildrenFromInner(); + afterCreating(); + return Mono.just(self); + } catch (Exception e) { + return Mono.error(e); + } + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableResourceImpl.java index 66e445866c37b..401b6e343355e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/GroupableResourceImpl.java @@ -20,24 +20,15 @@ * @param the implementation type of the fluent model type * @param the service manager type */ -public abstract class GroupableResourceImpl< - FluentModelT extends Resource, - InnerModelT extends com.azure.core.management.Resource, - FluentModelImplT extends GroupableResourceImpl, - ManagerT extends Manager> - extends - ResourceImpl - implements - GroupableResource { +public abstract class GroupableResourceImpl, ManagerT extends Manager> + extends ResourceImpl + implements GroupableResource { protected final ManagerT myManager; protected Creatable creatableGroup; private String groupName; - protected GroupableResourceImpl( - String name, - InnerModelT innerObject, - ManagerT manager) { + protected GroupableResourceImpl(String name, InnerModelT innerObject, ManagerT manager) { super(name, innerObject); this.myManager = manager; } @@ -45,10 +36,11 @@ protected GroupableResourceImpl( // Helpers protected String resourceIdBase() { - return new StringBuilder() - .append("/subscriptions/").append(this.myManager.subscriptionId()) - .append("/resourceGroups/").append(this.resourceGroupName()) - .toString(); + return new StringBuilder().append("/subscriptions/") + .append(this.myManager.subscriptionId()) + .append("/resourceGroups/") + .append(this.resourceGroupName()) + .toString(); } /******************************************* @@ -87,7 +79,7 @@ protected Creatable creatableGroup() { */ public final FluentModelImplT withNewResourceGroup(String groupName) { return this.withNewResourceGroup( - this.myManager.resourceManager().resourceGroups().define(groupName).withRegion(this.regionName())); + this.myManager.resourceManager().resourceGroups().define(groupName).withRegion(this.regionName())); } /** @@ -101,7 +93,7 @@ public final FluentModelImplT withNewResourceGroup(String groupName) { */ public final FluentModelImplT withNewResourceGroup(String groupName, Region region) { return this.withNewResourceGroup( - this.myManager.resourceManager().resourceGroups().define(groupName).withRegion(region)); + this.myManager.resourceManager().resourceGroups().define(groupName).withRegion(region)); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildImpl.java index 3c6f92fef320a..858b6c9025857 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildImpl.java @@ -22,18 +22,9 @@ * @param the implementation type of the fluent model type * @param the client manager type representing the service */ -public abstract class IndependentChildImpl< - FluentModelT extends IndependentChild, - FluentParentModelT extends Resource & HasResourceGroup, - InnerModelT, - FluentModelImplT extends IndependentChildImpl, - ManagerT> - extends - CreatableUpdatableImpl - implements - IndependentChild, - IndependentChild.DefinitionStages.WithParentResource { +public abstract class IndependentChildImpl, FluentParentModelT extends Resource & HasResourceGroup, InnerModelT, FluentModelImplT extends IndependentChildImpl, ManagerT> + extends CreatableUpdatableImpl implements IndependentChild, + IndependentChild.DefinitionStages.WithParentResource { private String groupName; protected String parentName; private String creatableParentResourceKey; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildResourceImpl.java index b42cd4173876c..747c982942159 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/IndependentChildResourceImpl.java @@ -23,17 +23,9 @@ * @param the implementation type of the fluent model type * @param the client manager type representing the service */ -public abstract class IndependentChildResourceImpl< - FluentModelT extends IndependentChildResource, - FluentParentModelT extends Resource & HasResourceGroup, - InnerModelT extends com.azure.core.management.Resource, - FluentModelImplT extends IndependentChildResourceImpl, - ManagerT> - extends - IndependentChildImpl - implements - IndependentChildResource { +public abstract class IndependentChildResourceImpl, FluentParentModelT extends Resource & HasResourceGroup, InnerModelT extends com.azure.core.management.Resource, FluentModelImplT extends IndependentChildResourceImpl, ManagerT> + extends IndependentChildImpl + implements IndependentChildResource { /** * Creates a new instance of CreatableUpdatableImpl. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ResourceImpl.java index f61dba8dbd965..9b2693a690032 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/arm/models/implementation/ResourceImpl.java @@ -25,14 +25,8 @@ * @param Azure inner resource class type * @param the implementation type of the fluent model type */ -public abstract class ResourceImpl< - FluentModelT extends Resource, - InnerModelT extends com.azure.core.management.Resource, - FluentModelImplT extends ResourceImpl> - extends - CreatableUpdatableImpl - implements - Resource { +public abstract class ResourceImpl> + extends CreatableUpdatableImpl implements Resource { protected ResourceImpl(String name, InnerModelT innerObject) { super(name, innerObject); if (innerObject.tags() == null) { @@ -167,7 +161,7 @@ protected List innersFromWrappers(Collection List innersFromWrappers(Collection> wrappers, - List inners) { + List inners) { if (wrappers == null || wrappers.size() == 0) { return inners; } else { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsBeginDeletingByName.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsBeginDeletingByName.java index f69d47ef9e17b..0743e7c293cb3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsBeginDeletingByName.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsBeginDeletingByName.java @@ -19,7 +19,6 @@ public interface SupportsBeginDeletingByName { */ void beginDeleteByName(String name); - /** * Asynchronously begins deleting a resource from Azure, identifying it by its resource name. * The resource will stay until get() returns null. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsDeletingByName.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsDeletingByName.java index bb3bd688b9208..029ec8892c778 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsDeletingByName.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/collection/SupportsDeletingByName.java @@ -18,7 +18,6 @@ public interface SupportsDeletingByName { */ void deleteByName(String name); - /** * Asynchronously delete a resource from Azure, identifying it by its resource name. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGNode.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGNode.java index a168920a9c88d..942f301e2c031 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGNode.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGNode.java @@ -35,8 +35,8 @@ public class DAGNode> extends Node node) { String dependentKey = node.key(); for (String dependencyKey : dagNode.dependencyKeys()) { - nodeTable.get(dependencyKey) - .addDependent(dependentKey); + nodeTable.get(dependencyKey).addDependent(dependentKey); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/FunctionalTaskItem.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/FunctionalTaskItem.java index aec21c1111e41..ede72b3c211d4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/FunctionalTaskItem.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/FunctionalTaskItem.java @@ -12,8 +12,7 @@ /** * Simplified functional interface equivalent to abstract class {@link IndexableTaskItem}. */ -public interface FunctionalTaskItem - extends Function> { +public interface FunctionalTaskItem extends Function> { /** * Type representing context of an {@link FunctionalTaskItem}. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/Graph.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/Graph.java index 315574380759c..6f374036d3024 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/Graph.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/Graph.java @@ -142,9 +142,8 @@ private EdgeType edgeType(String fromKey, String toKey) { } } - throw logger.logExceptionAsError( - new IllegalStateException("Internal Error: Unable to locate the edge type {" + fromKey + ", " + toKey + "}") - ); + throw logger.logExceptionAsError(new IllegalStateException( + "Internal Error: Unable to locate the edge type {" + fromKey + ", " + toKey + "}")); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/IndexableTaskItem.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/IndexableTaskItem.java index 7797f2b297b42..2e71fbbedc7f0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/IndexableTaskItem.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/IndexableTaskItem.java @@ -16,8 +16,7 @@ /** * An index-able TaskItem with a TaskGroup. */ -public abstract class IndexableTaskItem - implements Indexable, TaskItem, TaskGroup.HasTaskGroup { +public abstract class IndexableTaskItem implements Indexable, TaskItem, TaskGroup.HasTaskGroup { /** * The key that is unique to this TaskItem which is used to index this * TaskItem. @@ -83,8 +82,8 @@ protected Mono invokeTaskAsync(TaskGroup.InvocationContext context) { * @param internalContext the internal runtime context * @return IndexableTaskItem */ - public static IndexableTaskItem create( - final FunctionalTaskItem taskItem, ResourceManagerUtils.InternalRuntimeContext internalContext) { + public static IndexableTaskItem create(final FunctionalTaskItem taskItem, + ResourceManagerUtils.InternalRuntimeContext internalContext) { return new IndexableTaskItem(internalContext) { @Override protected Mono invokeTaskAsync(TaskGroup.InvocationContext context) { @@ -274,11 +273,11 @@ public boolean isHot() { @Override public Mono invokeAsync(TaskGroup.InvocationContext context) { return this.invokeTaskAsync(context) - .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) - .map(result -> { - taskResult = result; - return result; - }); + .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) + .map(result -> { + taskResult = result; + return result; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroup.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroup.java index ae71919b6aa4f..fc00a93d70b6f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroup.java @@ -39,9 +39,7 @@ *

* The result produced by the tasks in the group are of type {@link Indexable}. */ -public class TaskGroup - extends DAGraph> - implements Indexable { +public class TaskGroup extends DAGraph> implements Indexable { /** * The root task in this task group. */ @@ -89,8 +87,7 @@ private TaskGroup(TaskGroupEntry rootTaskEntry) { * @param rootTaskItemId the id of the root task in the group * @param rootTaskItem the root task */ - public TaskGroup(String rootTaskItemId, - TaskItem rootTaskItem) { + public TaskGroup(String rootTaskItemId, TaskItem rootTaskItem) { this(new TaskGroupEntry(rootTaskItemId, rootTaskItem)); } @@ -217,8 +214,8 @@ public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) { * @return key to be used as parameter to taskResult(string) method to retrieve result of * invocation of given task item. */ - public String addPostRunDependent( - FunctionalTaskItem dependentTaskItem, ResourceManagerUtils.InternalRuntimeContext internalContext) { + public String addPostRunDependent(FunctionalTaskItem dependentTaskItem, + ResourceManagerUtils.InternalRuntimeContext internalContext) { IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem, internalContext); this.addPostRunDependent(taskItem); return taskItem.key(); @@ -277,13 +274,12 @@ public Flux invokeAsync(final InvocationContext context) { * @return the root result of task group. */ public Mono invokeAsync() { - return invokeAsync(this.newInvocationContext()) - .then(Mono.defer(() -> { - if (proxyTaskGroupWrapper.isActive()) { - return Mono.just(proxyTaskGroupWrapper.taskGroup().root().taskResult()); - } - return Mono.just(root().taskResult()); - })); + return invokeAsync(this.newInvocationContext()).then(Mono.defer(() -> { + if (proxyTaskGroupWrapper.isActive()) { + return Mono.just(proxyTaskGroupWrapper.taskGroup().root().taskResult()); + } + return Mono.just(root().taskResult()); + })); } /** @@ -323,12 +319,11 @@ public Flux invokeDependencyAsync(final InvocationContext context) { * before invoking them * @return an observable that emits the result of tasks in the order they finishes. */ - private Flux invokeInternAsync(final InvocationContext context, - final boolean shouldRunBeforeGroupInvoke, - final Set skipBeforeGroupInvoke) { + private Flux invokeInternAsync(final InvocationContext context, final boolean shouldRunBeforeGroupInvoke, + final Set skipBeforeGroupInvoke) { if (!isPreparer()) { - return Flux.error(new IllegalStateException( - "invokeInternAsync(cxt) can be called only from root TaskGroup")); + return Flux + .error(new IllegalStateException("invokeInternAsync(cxt) can be called only from root TaskGroup")); } this.taskGroupTerminateOnErrorStrategy = context.terminateOnErrorStrategy(); if (shouldRunBeforeGroupInvoke) { @@ -401,7 +396,7 @@ private List> entriesSnapshot() { */ // Due to it takes approximate 3ms in flux for returning, it cannot be guaranteed to return in topological order. // One simply fix for guaranteeing the last element could be https://github.com/Azure/azure-sdk-for-java/pull/15074 - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) private Flux invokeReadyTasksAsync(final InvocationContext context) { TaskGroupEntry readyTaskEntry = super.getNext(); final List> observables = new ArrayList<>(); @@ -443,8 +438,8 @@ private Flux invokeTaskAsync(final TaskGroupEntry entry, fi } else { // Any cached result will be ignored for root resource // - boolean ignoreCachedResult = isRootEntry(entry) - || (entry.proxy() != null && isRootEntry(entry.proxy())); + boolean ignoreCachedResult + = isRootEntry(entry) || (entry.proxy() != null && isRootEntry(entry.proxy())); Mono taskObservable; Object skipTasks = context.get(InvocationContext.KEY_SKIP_TASKS); @@ -473,7 +468,7 @@ private Flux invokeTaskAsync(final TaskGroupEntry entry, fi * result produced by actual TaskItem. */ private Flux invokeAfterPostRunAsync(final TaskGroupEntry entry, - final InvocationContext context) { + final InvocationContext context) { return Flux.defer(() -> { final ProxyTaskItem proxyTaskItem = (ProxyTaskItem) entry.data(); if (proxyTaskItem == null) { @@ -482,22 +477,19 @@ private Flux invokeAfterPostRunAsync(final TaskGroupEntry e final boolean isFaulted = entry.hasFaultedDescentDependencyTasks() || isGroupCancelled.get(); return proxyTaskItem.invokeAfterPostRunAsync(isFaulted) - .flatMapMany(indexable -> Flux.error( - new IllegalStateException("This onNext should never be called")), - (error) -> processFaultedTaskAsync(entry, error, context), - () -> { - if (isFaulted) { - if (entry.hasFaultedDescentDependencyTasks()) { - return processFaultedTaskAsync(entry, - new ErroredDependencyTaskException(), context); - } else { - return processFaultedTaskAsync(entry, taskCancelledException, context); - } + .flatMapMany(indexable -> Flux.error(new IllegalStateException("This onNext should never be called")), + (error) -> processFaultedTaskAsync(entry, error, context), () -> { + if (isFaulted) { + if (entry.hasFaultedDescentDependencyTasks()) { + return processFaultedTaskAsync(entry, new ErroredDependencyTaskException(), context); } else { - return Flux.concat(Flux.just(proxyTaskItem.result()), - processCompletedTaskAsync(entry, context)); + return processFaultedTaskAsync(entry, taskCancelledException, context); } - }); + } else { + return Flux.concat(Flux.just(proxyTaskItem.result()), + processCompletedTaskAsync(entry, context)); + } + }); }); } @@ -512,7 +504,7 @@ private Flux invokeAfterPostRunAsync(final TaskGroupEntry e * @return an observable represents asynchronous operation in the next stage */ private Flux processCompletedTaskAsync(final TaskGroupEntry completedEntry, - final InvocationContext context) { + final InvocationContext context) { reportCompletion(completedEntry); if (isRootEntry(completedEntry)) { return Flux.empty(); @@ -530,8 +522,7 @@ private Flux processCompletedTaskAsync(final TaskGroupEntry * @return an observable represents asynchronous operation in the next stage */ private Flux processFaultedTaskAsync(final TaskGroupEntry faultedEntry, - final Throwable throwable, - final InvocationContext context) { + final Throwable throwable, final InvocationContext context) { markGroupAsCancelledIfTerminationStrategyIsIPTC(); reportError(faultedEntry, throwable); if (isRootEntry(faultedEntry)) { @@ -575,7 +566,7 @@ private boolean isRootEntry(TaskGroupEntry taskGroupEntry) { */ private static boolean shouldPropagateException(Throwable throwable) { return (!(throwable instanceof ErroredDependencyTaskException) - && !(throwable instanceof TaskCancelledException)); + && !(throwable instanceof TaskCancelledException)); } /** @@ -769,8 +760,7 @@ private void initProxyTaskGroup() { // it to "actual TaskGroup"'s root. // ProxyTaskItem proxyTaskItem = new ProxyTaskItem(this.actualTaskGroup.root().data()); - this.proxyTaskGroup = new TaskGroup("proxy-" + this.actualTaskGroup.root().key(), - proxyTaskItem); + this.proxyTaskGroup = new TaskGroup("proxy-" + this.actualTaskGroup.root().key(), proxyTaskItem); if (this.actualTaskGroup.hasParents()) { // Once "proxy TaskGroup" is enabled, all existing TaskGroups depends on "actual TaskGroup" should @@ -810,7 +800,6 @@ public Indexable result() { return actualTaskItem.result(); } - @Override public void beforeGroupInvoke() { // NOP @@ -829,11 +818,10 @@ public Mono invokeAsync(InvocationContext context) { @Override public Mono invokeAfterPostRunAsync(final boolean isGroupFaulted) { if (actualTaskItem.isHot()) { - return Mono.defer(() -> - actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted).subscribeOn(Schedulers.immediate())); + return Mono.defer( + () -> actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted).subscribeOn(Schedulers.immediate())); } else { - return this.actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted) - .subscribeOn(Schedulers.immediate()); + return this.actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted).subscribeOn(Schedulers.immediate()); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroupEntry.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroupEntry.java index f52d3165e0a28..0f2b215456ec3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroupEntry.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/dag/TaskGroupEntry.java @@ -14,8 +14,7 @@ * * @param the task type that can return a value */ -public final class TaskGroupEntry - extends DAGNode> { +public final class TaskGroupEntry extends DAGNode> { /** * The proxy entry for this entry if exists. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/exception/AggregatedManagementException.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/exception/AggregatedManagementException.java index 0fab205faa15f..f9a7cad13f23a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/exception/AggregatedManagementException.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/exception/AggregatedManagementException.java @@ -20,9 +20,9 @@ public final class AggregatedManagementException extends ManagementException { * @param firstManagementException the first ManagementException in suppressed. */ private AggregatedManagementException(RuntimeException aggregatedException, - ManagementException firstManagementException) { - super(aggregatedException.getMessage(), - firstManagementException.getResponse(), firstManagementException.getValue()); + ManagementException firstManagementException) { + super(aggregatedException.getMessage(), firstManagementException.getResponse(), + firstManagementException.getValue()); for (Throwable exception : aggregatedException.getSuppressed()) { this.addSuppressed(exception); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/Creatable.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/Creatable.java index e26827abc3b00..d10c172f6c4d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/Creatable.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/Creatable.java @@ -12,9 +12,7 @@ * * @param the fluent type of the resource to be created */ -public interface Creatable extends - Indexable, - HasName { +public interface Creatable extends Indexable, HasName { /** * Execute the create request. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AcceptedImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AcceptedImpl.java index fda5e281bacda..503e41adef618 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AcceptedImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AcceptedImpl.java @@ -62,14 +62,9 @@ public class AcceptedImpl implements Accepted { private PollerFlux, InnerT> pollerFlux; private SyncPoller syncPoller; - public AcceptedImpl(Response> activationResponse, - SerializerAdapter serializerAdapter, - HttpPipeline httpPipeline, - Duration defaultPollInterval, - Type pollResultType, - Type finalResultType, - Function wrapOperation, - Context context) { + public AcceptedImpl(Response> activationResponse, SerializerAdapter serializerAdapter, + HttpPipeline httpPipeline, Duration defaultPollInterval, Type pollResultType, Type finalResultType, + Function wrapOperation, Context context) { this.activationResponse = Objects.requireNonNull(activationResponse); this.serializerAdapter = Objects.requireNonNull(serializerAdapter); this.httpPipeline = Objects.requireNonNull(httpPipeline); @@ -83,17 +78,15 @@ public AcceptedImpl(Response> activationResponse, @Override public ActivationResponse getActivationResponse() { try { - T value = wrapOperation.apply(serializerAdapter.deserialize( - new String(getResponse(), StandardCharsets.UTF_8), - finalResultType, - SerializerEncoding.JSON)); + T value + = wrapOperation.apply(serializerAdapter.deserialize(new String(getResponse(), StandardCharsets.UTF_8), + finalResultType, SerializerEncoding.JSON)); Duration retryAfter = getRetryAfter(activationResponse.getHeaders()); return new ActivationResponse<>(activationResponse.getRequest(), activationResponse.getStatusCode(), - activationResponse.getHeaders(), value, - getActivationResponseStatus(), retryAfter); + activationResponse.getHeaders(), value, getActivationResponseStatus(), retryAfter); } catch (IOException e) { - throw logger.logExceptionAsError( - new IllegalStateException("Failed to deserialize activation response body", e)); + throw logger + .logExceptionAsError(new IllegalStateException("Failed to deserialize activation response body", e)); } } @@ -115,9 +108,7 @@ public SyncPoller getSyncPoller() { if (errorBody != null) { // try to deserialize error body to ManagementError try { - managementError = serializerAdapter.deserialize( - errorBody, - ManagementError.class, + managementError = serializerAdapter.deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); if (managementError.getCode() == null || managementError.getMessage() == null) { managementError = null; @@ -137,8 +128,8 @@ public SyncPoller getSyncPoller() { return new ManagementException(errorMessage, errorResponse, managementError); }; - syncPoller = new SyncPollerImpl(this.getPollerFlux().getSyncPoller(), - wrapOperation, errorOperation); + syncPoller + = new SyncPollerImpl(this.getPollerFlux().getSyncPoller(), wrapOperation, errorOperation); } return syncPoller; } @@ -148,15 +139,8 @@ private PollerFlux, InnerT> getPollerFlux() { Flux content = Flux.just(ByteBuffer.wrap(getResponse())); Response> clonedResponse = new SimpleResponse<>(activationResponse, content); - pollerFlux = PollerFactory.create( - serializerAdapter, - httpPipeline, - pollResultType, - finalResultType, - defaultPollInterval, - Mono.just(clonedResponse), - context - ); + pollerFlux = PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, Mono.just(clonedResponse), context); } return pollerFlux; } @@ -174,9 +158,7 @@ private LongRunningOperationStatus getActivationResponseStatus() { try { ResourceWithProvisioningState resource = serializerAdapter.deserialize(responseBody, ResourceWithProvisioningState.class, SerializerEncoding.JSON); - provisioningState = resource != null - ? resource.getProvisioningState() - : null; + provisioningState = resource != null ? resource.getProvisioningState() : null; } catch (IOException ignored) { } @@ -227,8 +209,7 @@ private byte[] getResponse() { return responseBytes; } - private static class SyncPollerImpl - implements SyncPoller { + private static class SyncPollerImpl implements SyncPoller { private final SyncPoller, InnerT> syncPoller; private final Function wrapOperation; @@ -237,7 +218,7 @@ private static class SyncPollerImpl private ManagementException exception; SyncPollerImpl(SyncPoller, InnerT> syncPoller, Function wrapOperation, - Function>, ManagementException> errorOperation) { + Function>, ManagementException> errorOperation) { this.syncPoller = syncPoller; this.wrapOperation = wrapOperation; this.errorOperation = errorOperation; @@ -312,10 +293,7 @@ private String getProvisioningState() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter - .writeStartObject() - .writeJsonField("properties", properties) - .writeEndObject(); + return jsonWriter.writeStartObject().writeJsonField("properties", properties).writeEndObject(); } public static ResourceWithProvisioningState fromJson(JsonReader jsonReader) throws IOException { @@ -340,8 +318,7 @@ private static class Properties implements JsonSerializable { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter - .writeStartObject() + return jsonWriter.writeStartObject() .writeStringField("provisioningState", provisioningState) .writeEndObject(); } @@ -420,15 +397,9 @@ public Mono getBodyAsString(Charset charset) { } } - public static Accepted newAccepted( - ClientLogger logger, - HttpPipeline httpPipeline, - Duration pollInterval, - Supplier>> activationOperation, - Function convertOperation, - Type innerType, - Runnable preActivation, - Context context) { + public static Accepted newAccepted(ClientLogger logger, HttpPipeline httpPipeline, + Duration pollInterval, Supplier>> activationOperation, + Function convertOperation, Type innerType, Runnable preActivation, Context context) { if (preActivation != null) { preActivation.run(); @@ -438,27 +409,18 @@ public static Accepted newAccepted( if (activationResponse == null) { throw logger.logExceptionAsError(new NullPointerException()); } else { - Accepted accepted = new AcceptedImpl( - activationResponse, - SerializerFactory.createDefaultManagementSerializerAdapter(), - httpPipeline, - ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval), - innerType, innerType, - convertOperation, - context); + Accepted accepted = new AcceptedImpl(activationResponse, + SerializerFactory.createDefaultManagementSerializerAdapter(), httpPipeline, + ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval), innerType, innerType, + convertOperation, context); return accepted; } } - public static , InnerT> Accepted newAccepted( - ClientLogger logger, - HttpPipeline httpPipeline, - Duration pollInterval, - Supplier>> activationOperation, - Function convertOperation, - Type innerType, - Runnable preActivation, Consumer postActivation, + public static , InnerT> Accepted newAccepted(ClientLogger logger, + HttpPipeline httpPipeline, Duration pollInterval, Supplier>> activationOperation, + Function convertOperation, Type innerType, Runnable preActivation, Consumer postActivation, Context context) { if (preActivation != null) { @@ -469,14 +431,10 @@ public static , InnerT> Accepted newAccepted( if (activationResponse == null) { throw logger.logExceptionAsError(new NullPointerException()); } else { - Accepted accepted = new AcceptedImpl( - activationResponse, - SerializerFactory.createDefaultManagementSerializerAdapter(), - httpPipeline, - ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval), - innerType, innerType, - convertOperation, - context); + Accepted accepted = new AcceptedImpl(activationResponse, + SerializerFactory.createDefaultManagementSerializerAdapter(), httpPipeline, + ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(pollInterval), innerType, innerType, + convertOperation, context); if (postActivation != null) { postActivation.accept(accepted.getActivationResponse().getValue().innerModel()); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AppliableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AppliableImpl.java index 6f654f97af3b6..40f0872c4dde7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AppliableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/AppliableImpl.java @@ -15,15 +15,10 @@ * @param the model inner type that the fluent model type wraps * @param the fluent model implementation type */ -public abstract class AppliableImpl< - FluentModelT extends Indexable, - InnerModelT, - FluentModelImplT extends IndexableRefreshableWrapperImpl> - extends - CreatableUpdatableImpl - implements - Updatable { +public abstract class AppliableImpl> + extends CreatableUpdatableImpl implements Updatable { private final ClientLogger logger = new ClientLogger(getClass()); + /** * Creates an AppliableImpl. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableImpl.java index 51fc9b7839515..33e8c95c30b30 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableImpl.java @@ -14,13 +14,10 @@ * @param the model inner type that the fluent model type wraps * @param the fluent model implementation type */ -public abstract class CreatableImpl< - FluentModelT extends Indexable, - InnerModelT, - FluentModelImplT extends IndexableRefreshableWrapperImpl> - extends - CreatableUpdatableImpl { +public abstract class CreatableImpl> + extends CreatableUpdatableImpl { private final ClientLogger logger = new ClientLogger(getClass()); + /** * Creates a CreatableImpl. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableUpdatableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableUpdatableImpl.java index d50d096ca009b..7c163629559a1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableUpdatableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreatableUpdatableImpl.java @@ -26,16 +26,9 @@ * @param the inner model type that the fluent model wraps * @param the implementation type of the fluent model */ -public abstract class CreatableUpdatableImpl< - FluentModelT extends Indexable, - InnerModelT, - FluentModelImplT extends IndexableRefreshableWrapperImpl> - extends IndexableRefreshableWrapperImpl - implements - Appliable, - Creatable, - TaskGroup.HasTaskGroup, - CreateUpdateTask.ResourceCreatorUpdater { +public abstract class CreatableUpdatableImpl> + extends IndexableRefreshableWrapperImpl implements Appliable, + Creatable, TaskGroup.HasTaskGroup, CreateUpdateTask.ResourceCreatorUpdater { /** * The name of the creatable updatable model. */ @@ -65,8 +58,7 @@ protected CreatableUpdatableImpl(String name, InnerModelT innerObject) { protected CreatableUpdatableImpl(String name, String key, InnerModelT innerObject) { super(key, innerObject); this.name = name; - taskGroup = new TaskGroup(this.key(), - new CreateUpdateTask(this)); + taskGroup = new TaskGroup(this.key(), new CreateUpdateTask(this)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreateUpdateTask.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreateUpdateTask.java index bfb2c605ccb46..ba319288c313b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreateUpdateTask.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/CreateUpdateTask.java @@ -70,7 +70,6 @@ public boolean isHot() { return this.resourceCreatorUpdater.isHot(); } - /** * Represents a type that know how to create or update a resource of type {@link T}. *

diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecutableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecutableImpl.java index f16b32e9661e2..d990c1e592261 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecutableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecutableImpl.java @@ -20,13 +20,8 @@ * * @param the fluent model type */ -public abstract class ExecutableImpl - extends - IndexableImpl - implements - TaskGroup.HasTaskGroup, - Executable, - ExecuteTask.Executor { +public abstract class ExecutableImpl extends IndexableImpl + implements TaskGroup.HasTaskGroup, Executable, ExecuteTask.Executor { /** * The group of tasks to the produces this result and it's dependencies results. */ @@ -213,7 +208,6 @@ public FluentModelT execute() { return executeAsync().block(); } - @Override public Mono afterPostRunAsync(boolean isGroupFaulted) { return Mono.empty(); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecuteTask.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecuteTask.java index 11caabe24e91e..33c04e366c48c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecuteTask.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/ExecuteTask.java @@ -53,9 +53,9 @@ public boolean isHot() { @Override public Mono invokeAsync(TaskGroup.InvocationContext context) { return this.executor.executeWorkAsync() - .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) - .doOnNext(resultT -> result = resultT) - .map(resourceT -> resourceT); + .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) + .doOnNext(resultT -> result = resultT) + .map(resourceT -> resourceT); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableImpl.java index 549d4377f5d31..0e1d14f715a76 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableImpl.java @@ -32,5 +32,3 @@ public String toString() { return this.key(); } } - - diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableImpl.java index e354c3dc21f65..10f732d7a7035 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableImpl.java @@ -11,9 +11,7 @@ * * @param the fluent type of the resource */ -public abstract class IndexableRefreshableImpl - extends IndexableImpl - implements Refreshable { +public abstract class IndexableRefreshableImpl extends IndexableImpl implements Refreshable { protected IndexableRefreshableImpl() { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableWrapperImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableWrapperImpl.java index 3dd9f33e08a43..5d07529a7b913 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableWrapperImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableRefreshableWrapperImpl.java @@ -15,8 +15,7 @@ * @param Azure inner resource class type */ public abstract class IndexableRefreshableWrapperImpl - extends IndexableRefreshableImpl - implements HasInnerModel { + extends IndexableRefreshableImpl implements HasInnerModel { private InnerModelT innerObject; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableWrapperImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableWrapperImpl.java index 6929e1b8d81ca..1bf4502744090 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableWrapperImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/IndexableWrapperImpl.java @@ -11,9 +11,7 @@ * * @param wrapped type */ -public abstract class IndexableWrapperImpl - extends IndexableImpl - implements HasInnerModel { +public abstract class IndexableWrapperImpl extends IndexableImpl implements HasInnerModel { private InnerT innerObject; protected IndexableWrapperImpl(InnerT innerObject) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/RefreshableWrapperImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/RefreshableWrapperImpl.java index 0e20a9721b5ed..1f6a790389a86 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/RefreshableWrapperImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/model/implementation/RefreshableWrapperImpl.java @@ -12,9 +12,7 @@ * @param wrapped type * @param impl type */ -public abstract class RefreshableWrapperImpl - extends WrapperImpl - implements Refreshable { +public abstract class RefreshableWrapperImpl extends WrapperImpl implements Refreshable { protected RefreshableWrapperImpl(InnerT innerObject) { super(innerObject); @@ -30,11 +28,10 @@ public final Impl refresh() { public Mono refreshAsync() { final RefreshableWrapperImpl self = this; - return this.getInnerAsync() - .map(innerT -> { - self.setInner(innerT); - return (Impl) self; - }); + return this.getInnerAsync().map(innerT -> { + self.setInner(innerT); + return (Impl) self; + }); } protected abstract Mono getInnerAsync(); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/AuxiliaryAuthenticationPolicy.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/AuxiliaryAuthenticationPolicy.java index 9d47c14855fc1..44bcfb6aa500c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/AuxiliaryAuthenticationPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/AuxiliaryAuthenticationPolicy.java @@ -43,18 +43,14 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN if (tokenCredentials == null || tokenCredentials.length == 0) { return next.process(); } - return Flux.fromIterable(Arrays.asList(tokenCredentials)) - .flatMap(credential -> { - String defaultScope = ResourceManagerUtils.getDefaultScopeFromRequest( - context.getHttpRequest(), environment); - return credential.getToken(new TokenRequestContext().addScopes(defaultScope)) - .map(token -> String.format(SCHEMA_FORMAT, token.getToken())); - }) - .collectList() - .flatMap(tokenList -> { - context.getHttpRequest() - .setHeader(AUTHORIZATION_AUXILIARY_HEADER, String.join(",", tokenList)); - return next.process(); - }); + return Flux.fromIterable(Arrays.asList(tokenCredentials)).flatMap(credential -> { + String defaultScope + = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment); + return credential.getToken(new TokenRequestContext().addScopes(defaultScope)) + .map(token -> String.format(SCHEMA_FORMAT, token.getToken())); + }).collectList().flatMap(tokenList -> { + context.getHttpRequest().setHeader(AUTHORIZATION_AUXILIARY_HEADER, String.join(",", tokenList)); + return next.process(); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ProviderRegistrationPolicy.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ProviderRegistrationPolicy.java index 39d122000fbbe..4095ea5505d70 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ProviderRegistrationPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ProviderRegistrationPolicy.java @@ -78,80 +78,74 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN if (providers == null) { return next.process(); } - return next.clone().process().flatMap( - response -> { - if (!isResponseSuccessful(response)) { - HttpResponse bufferedResponse = response.buffer(); - return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( - body -> { - String bodyStr = new String(body, StandardCharsets.UTF_8); - - SerializerAdapter jacksonAdapter = - SerializerFactory.createDefaultManagementSerializerAdapter(); - ManagementError managementError; - try { - managementError = jacksonAdapter.deserialize( - bodyStr, ManagementError.class, SerializerEncoding.JSON); - } catch (IOException e) { - return Mono.just(bufferedResponse); - } + return next.clone().process().flatMap(response -> { + if (!isResponseSuccessful(response)) { + HttpResponse bufferedResponse = response.buffer(); + return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap(body -> { + String bodyStr = new String(body, StandardCharsets.UTF_8); + + SerializerAdapter jacksonAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); + ManagementError managementError; + try { + managementError + = jacksonAdapter.deserialize(bodyStr, ManagementError.class, SerializerEncoding.JSON); + } catch (IOException e) { + return Mono.just(bufferedResponse); + } - if (managementError != null - && MISSING_SUBSCRIPTION_REGISTRATION.equals(managementError.getCode())) { - - String resourceNamespace = null; - - if (managementError.getDetails() != null) { - // find in details.target - resourceNamespace = managementError.getDetails().stream() - .filter(d -> MISSING_SUBSCRIPTION_REGISTRATION.equals(d.getCode()) - && d.getTarget() != null) - .map(ManagementError::getTarget) - .findFirst().orElse(null); - } - if (resourceNamespace == null) { - // find in message - Pattern providerPattern = Pattern.compile(".*'(.*)'"); - Matcher providerMatcher = providerPattern.matcher(managementError.getMessage()); - if (!providerMatcher.find()) { - return Mono.just(bufferedResponse); - } - resourceNamespace = providerMatcher.group(1); - } - - // Retry after registration - return registerProviderUntilSuccess(resourceNamespace) - // in case error, return the response before registering resource provider - // if not error, this will be ignored - .then(Mono.just(bufferedResponse)) - .onErrorReturn(bufferedResponse) - .then(next.clone().process()); + if (managementError != null + && MISSING_SUBSCRIPTION_REGISTRATION.equals(managementError.getCode())) { + + String resourceNamespace = null; + + if (managementError.getDetails() != null) { + // find in details.target + resourceNamespace = managementError.getDetails() + .stream() + .filter( + d -> MISSING_SUBSCRIPTION_REGISTRATION.equals(d.getCode()) && d.getTarget() != null) + .map(ManagementError::getTarget) + .findFirst() + .orElse(null); + } + if (resourceNamespace == null) { + // find in message + Pattern providerPattern = Pattern.compile(".*'(.*)'"); + Matcher providerMatcher = providerPattern.matcher(managementError.getMessage()); + if (!providerMatcher.find()) { + return Mono.just(bufferedResponse); } - return Mono.just(bufferedResponse); + resourceNamespace = providerMatcher.group(1); } - ); - } - return Mono.just(response); + + // Retry after registration + return registerProviderUntilSuccess(resourceNamespace) + // in case error, return the response before registering resource provider + // if not error, this will be ignored + .then(Mono.just(bufferedResponse)) + .onErrorReturn(bufferedResponse) + .then(next.clone().process()); + } + return Mono.just(bufferedResponse); + }); } - ); + return Mono.just(response); + }); } private Mono registerProviderUntilSuccess(String namespace) { - return providers.registerAsync(namespace) - .flatMap( - provider -> { - if (isProviderRegistered(provider)) { - return Mono.empty(); - } - return providers.getByNameAsync(namespace) - .flatMap(this::checkProviderRegistered) - .retryWhen(Retry - // 30 * 10sec - .fixedDelay(30, - ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(10))) - .filter(ProviderUnregisteredException.class::isInstance)); - } - ); + return providers.registerAsync(namespace).flatMap(provider -> { + if (isProviderRegistered(provider)) { + return Mono.empty(); + } + return providers.getByNameAsync(namespace) + .flatMap(this::checkProviderRegistered) + .retryWhen(Retry + // 30 * 10sec + .fixedDelay(30, + ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(10))) + .filter(ProviderUnregisteredException.class::isInstance)); + }); } private Mono checkProviderRegistered(Provider provider) throws ProviderUnregisteredException { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ResourceManagerThrottlingPolicy.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ResourceManagerThrottlingPolicy.java index dabfe7530bf43..43fa45a3bfd64 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ResourceManagerThrottlingPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/ResourceManagerThrottlingPolicy.java @@ -29,11 +29,10 @@ public ResourceManagerThrottlingPolicy( @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - return next.clone().process() - .flatMap(response -> { - HttpResponse bufferedResponse = response.buffer(); - callback.accept(bufferedResponse, ResourceManagerThrottlingInfo.fromHeaders(response.getHeaders())); - return Mono.just(bufferedResponse); - }); + return next.clone().process().flatMap(response -> { + HttpResponse bufferedResponse = response.buffer(); + callback.accept(bufferedResponse, ResourceManagerThrottlingInfo.fromHeaders(response.getHeaders())); + return Mono.just(bufferedResponse); + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/UserAgentPolicy.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/UserAgentPolicy.java index 440da636b1755..4e7d10a18960d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/UserAgentPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/policy/UserAgentPolicy.java @@ -74,8 +74,9 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN applicationId = httpLogOptions.getApplicationId(); } - context.getHttpRequest().setHeader(USER_AGENT_KEY, - UserAgentUtil.toUserAgentString(applicationId, sdkName, sdkVersion, configuration)); + context.getHttpRequest() + .setHeader(USER_AGENT_KEY, + UserAgentUtil.toUserAgentString(applicationId, sdkName, sdkVersion, configuration)); return next.process(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/rest/ActivationResponse.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/rest/ActivationResponse.java index 9abd366f849ed..f2b2b7254b425 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/rest/ActivationResponse.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/rest/ActivationResponse.java @@ -33,7 +33,7 @@ public class ActivationResponse extends SimpleResponse { * own when the next poll operation is to occur. */ public ActivationResponse(HttpRequest request, int statusCode, HttpHeaders headers, T value, - LongRunningOperationStatus status, Duration retryAfter) { + LongRunningOperationStatus status, Duration retryAfter) { super(request, statusCode, headers, value); this.status = status; this.retryAfter = retryAfter; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ETagState.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ETagState.java index cbaa4db359295..b79c58f85f495 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ETagState.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ETagState.java @@ -46,7 +46,6 @@ public ETagState withExplicitETagCheckOnDelete(String eTagValue) { return this; } - /** * Clears the stored values in ETag state * @return the ETag state. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/HttpPipelineProvider.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/HttpPipelineProvider.java index b6b563da4d27c..76cf5a68468cf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/HttpPipelineProvider.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/HttpPipelineProvider.java @@ -63,10 +63,9 @@ public static HttpPipeline buildHttpPipeline(TokenCredential credential, AzurePr * @param httpClient the http client * @return the http pipeline */ - public static HttpPipeline buildHttpPipeline( - TokenCredential credential, AzureProfile profile, String[] scopes, HttpLogOptions httpLogOptions, - Configuration configuration, RetryPolicy retryPolicy, List additionalPolicies, - HttpClient httpClient) { + public static HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, String[] scopes, + HttpLogOptions httpLogOptions, Configuration configuration, RetryPolicy retryPolicy, + List additionalPolicies, HttpClient httpClient) { if (retryPolicy == null) { retryPolicy = new RetryPolicy("Retry-After", ChronoUnit.SECONDS); @@ -78,12 +77,9 @@ public static HttpPipeline buildHttpPipeline( policies.add(new RequestIdPolicy()); policies.add(new ReturnRequestIdHeaderPolicy(ReturnRequestIdHeaderPolicy.Option.COPY_CLIENT_REQUEST_ID)); if (!CoreUtils.isNullOrEmpty(additionalPolicies)) { - policies.addAll( - additionalPolicies - .stream() - .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) - .collect(Collectors.toList()) - ); + policies.addAll(additionalPolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .collect(Collectors.toList())); } HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); @@ -93,17 +89,13 @@ public static HttpPipeline buildHttpPipeline( } policies.add(new ProviderRegistrationPolicy()); if (!CoreUtils.isNullOrEmpty(additionalPolicies)) { - policies.addAll( - additionalPolicies - .stream() - .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) - .collect(Collectors.toList()) - ); + policies.addAll(additionalPolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .collect(Collectors.toList())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); - return new HttpPipelineBuilder() - .policies(policies.toArray(new HttpPipelinePolicy[0])) + return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverter.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverter.java index 826a173422472..c8792ea97f64a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverter.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverter.java @@ -70,12 +70,12 @@ public static PagedFlux mapPage(PagedFlux pagedFlux, Function * @return the PagedFlux with elements in PagedResponse transformed. */ public static PagedFlux flatMapPage(PagedFlux pagedFlux, - Function> mapper) { + Function> mapper) { Supplier>> provider = () -> (continuationToken, pageSize) -> { // retrieve single page Flux> flux = (continuationToken == null) - ? pagedFlux.byPage().take(1) - : pagedFlux.byPage(continuationToken).take(1); + ? pagedFlux.byPage().take(1) + : pagedFlux.byPage(continuationToken).take(1); return flux.concatMap(PagedConverter.flatMapPagedResponse(mapper)); }; return PagedFlux.create(provider); @@ -91,14 +91,13 @@ public static PagedFlux flatMapPage(PagedFlux pagedFlux, * @return the merged PagedFlux. */ public static PagedFlux mergePagedFlux(PagedFlux pagedFlux, - Function> transformer) { + Function> transformer) { // one possible issue is that when inner PagedFlux ends, that PagedResponse will have continuationToken == null Supplier>> provider = () -> (continuationToken, pageSize) -> { // here retrieve all pages, as the continuationToken in mergePagedFluxPagedResponse would confuse this outer paging - Flux> flux = (continuationToken == null) - ? pagedFlux.byPage() - : pagedFlux.byPage(continuationToken); + Flux> flux + = (continuationToken == null) ? pagedFlux.byPage() : pagedFlux.byPage(continuationToken); return flux.concatMap(PagedConverter.mergePagedFluxPagedResponse(transformer)); }; return PagedFlux.create(provider); @@ -106,11 +105,9 @@ public static PagedFlux mergePagedFlux(PagedFlux pagedFlux, private static Function, PagedResponse> mapPagedResponse(Function mapper) { return pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), - pagedResponse.getStatusCode(), - pagedResponse.getHeaders(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()), - pagedResponse.getContinuationToken(), - null); + pagedResponse.getContinuationToken(), null); } /** @@ -121,18 +118,13 @@ private static Function, PagedResponse> mapPagedRespo * @param return type of pagedFlux. * @return the lifted transform on PagedResponse. */ - private static Function, Mono>> flatMapPagedResponse( - Function> mapper) { - return pagedResponse -> - Flux.fromIterable(pagedResponse.getValue()) - .flatMapSequential(mapper) - .collectList() - .map(values -> new PagedResponseBase(pagedResponse.getRequest(), - pagedResponse.getStatusCode(), - pagedResponse.getHeaders(), - values, - pagedResponse.getContinuationToken(), - null)); + private static Function, Mono>> + flatMapPagedResponse(Function> mapper) { + return pagedResponse -> Flux.fromIterable(pagedResponse.getValue()) + .flatMapSequential(mapper) + .collectList() + .map(values -> new PagedResponseBase(pagedResponse.getRequest(), pagedResponse.getStatusCode(), + pagedResponse.getHeaders(), values, pagedResponse.getContinuationToken(), null)); } /** @@ -143,13 +135,14 @@ private static Function, Mono>> flatMap * @param return type of pagedFlux. * @return the the merged PagedFlux. */ - private static Function, Flux>> mergePagedFluxPagedResponse( - Function> transformer) { + private static Function, Flux>> + mergePagedFluxPagedResponse(Function> transformer) { return pagedResponse -> { - List>> fluxList = pagedResponse.getValue().stream() - .map(item -> transformer.apply(item).byPage()).collect(Collectors.toList()); - return Flux.concat(fluxList) - .filter(p -> !p.getValue().isEmpty()); + List>> fluxList = pagedResponse.getValue() + .stream() + .map(item -> transformer.apply(item).byPage()) + .collect(Collectors.toList()); + return Flux.concat(fluxList).filter(p -> !p.getValue().isEmpty()); }; } @@ -161,14 +154,8 @@ private static Function, Flux>> mergePa * @return the PagedFlux. */ public static PagedFlux convertListToPagedFlux(Mono>> responseMono) { - return new PagedFlux<>(() -> responseMono.map(response -> new PagedResponseBase( - response.getRequest(), - response.getStatusCode(), - response.getHeaders(), - response.getValue(), - null, - null - ))); + return new PagedFlux<>(() -> responseMono.map(response -> new PagedResponseBase(response.getRequest(), + response.getStatusCode(), response.getHeaders(), response.getValue(), null, null))); } private static final class PagedIterableImpl extends PagedIterable { @@ -178,20 +165,16 @@ private static final class PagedIterableImpl extends PagedIterable { private final Function, PagedResponse> pageMapper; private PagedIterableImpl(PagedIterable pagedIterable, Function mapper) { - super(PagedFlux.create(() -> (continuationToken, pageSize) - -> Flux.fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); + super(PagedFlux.create(() -> (continuationToken, pageSize) -> Flux + .fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); this.pagedIterable = pagedIterable; this.mapper = mapper; this.pageMapper = getPageMapper(mapper); } private static Function, PagedResponse> getPageMapper(Function mapper) { - return page -> new PagedResponseBase( - page.getRequest(), - page.getStatusCode(), - page.getHeaders(), - page.getElements().stream().map(mapper).collect(Collectors.toList()), - page.getContinuationToken(), + return page -> new PagedResponseBase(page.getRequest(), page.getStatusCode(), page.getHeaders(), + page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), null); } @@ -227,20 +210,19 @@ public Iterator iterator() { @Override public Iterable> iterableByPage() { - return new IterableImpl, PagedResponse>( - pagedIterable.iterableByPage(), pageMapper); + return new IterableImpl, PagedResponse>(pagedIterable.iterableByPage(), pageMapper); } @Override public Iterable> iterableByPage(String continuationToken) { - return new IterableImpl, PagedResponse>( - pagedIterable.iterableByPage(continuationToken), pageMapper); + return new IterableImpl, PagedResponse>(pagedIterable.iterableByPage(continuationToken), + pageMapper); } @Override public Iterable> iterableByPage(int preferredPageSize) { - return new IterableImpl, PagedResponse>( - pagedIterable.iterableByPage(preferredPageSize), pageMapper); + return new IterableImpl, PagedResponse>(pagedIterable.iterableByPage(preferredPageSize), + pageMapper); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfo.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfo.java index 9d00d681ca5ce..389c3b75214a4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfo.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfo.java @@ -21,15 +21,11 @@ public class ResourceManagerThrottlingInfo { // refer https://docs.microsoft.com/azure/azure-resource-manager/management/request-limits-and-throttling private static final List COMMON_RATE_LIMIT_HEADERS = Arrays.asList( - "x-ms-ratelimit-remaining-subscription-reads", - "x-ms-ratelimit-remaining-subscription-writes", - "x-ms-ratelimit-remaining-tenant-reads", - "x-ms-ratelimit-remaining-tenant-writes", + "x-ms-ratelimit-remaining-subscription-reads", "x-ms-ratelimit-remaining-subscription-writes", + "x-ms-ratelimit-remaining-tenant-reads", "x-ms-ratelimit-remaining-tenant-writes", "x-ms-ratelimit-remaining-subscription-resource-requests", "x-ms-ratelimit-remaining-subscription-resource-entities-read", - "x-ms-ratelimit-remaining-tenant-resource-requests", - "x-ms-ratelimit-remaining-tenant-resource-entities-read" - ); + "x-ms-ratelimit-remaining-tenant-resource-requests", "x-ms-ratelimit-remaining-tenant-resource-entities-read"); // refer https://docs.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors private static final String RESOURCE_RATE_LIMIT_HEADER = "x-ms-ratelimit-remaining-resource"; @@ -54,8 +50,8 @@ public ResourceManagerThrottlingInfo(HttpHeaders headers) { if (resourceRateLimit != null) { Matcher matcher = RESOURCE_RATE_LIMIT_HEADER_PATTERN.matcher(resourceRateLimit); while (matcher.find()) { - commonRateLimits.put( - String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADER, matcher.group(1)), matcher.group(2)); + commonRateLimits.put(String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADER, matcher.group(1)), + matcher.group(2)); } } } @@ -80,7 +76,8 @@ public Optional getRateLimit() { if (!result.isPresent() || result.get() > limit) { result = Optional.of(limit); } - } catch (NumberFormatException e) { } + } catch (NumberFormatException e) { + } } return result; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerUtils.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerUtils.java index 8888fea379776..f3ba29afd514d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerUtils.java @@ -125,7 +125,7 @@ public static String getDefaultSubscription(PagedIterable subscrip if (subscriptionList.size() == 0) { throw new ClientLogger(ResourceManagerUtils.class).logExceptionAsError( new IllegalStateException("Please create a subscription before you start resource management. " - + "To learn more, see: https://azure.microsoft.com/free/.")); + + "To learn more, see: https://azure.microsoft.com/free/.")); } else if (subscriptionList.size() > 1) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("More than one subscription found in your tenant. " @@ -133,8 +133,8 @@ public static String getDefaultSubscription(PagedIterable subscrip subscriptionList.forEach(subscription -> { stringBuilder.append("\n" + subscription.displayName() + " : " + subscription.subscriptionId()); }); - throw new ClientLogger(ResourceManagerUtils.class).logExceptionAsError( - new IllegalStateException(stringBuilder.toString())); + throw new ClientLogger(ResourceManagerUtils.class) + .logExceptionAsError(new IllegalStateException(stringBuilder.toString())); } return subscriptionList.get(0).subscriptionId(); } @@ -230,7 +230,7 @@ private static String removeTrailingSlash(String s) { * @return the storage account connection string. */ public static String getStorageConnectionString(String accountName, String accountKey, - AzureEnvironment environment) { + AzureEnvironment environment) { if (environment == null || environment.getStorageEndpointSuffix() == null) { environment = AzureEnvironment.AZURE; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceNamer.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceNamer.java index 489843e60459e..c3ae5992ffa83 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceNamer.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceNamer.java @@ -60,7 +60,8 @@ private String randomString(int length) { str.append(UUID.randomUUID() .toString() .replace("-", "") - .substring(0, Math.min(32, length)).toLowerCase(Locale.ROOT)); + .substring(0, Math.min(32, length)) + .toLowerCase(Locale.ROOT)); } return str.toString(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentExportResultImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentExportResultImpl.java index 30a92cb15a784..3d113b3ba99ec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentExportResultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentExportResultImpl.java @@ -15,10 +15,8 @@ /** * Implementation for {@link DeploymentExportResult}. */ -final class DeploymentExportResultImpl extends - WrapperImpl - implements - DeploymentExportResult { +final class DeploymentExportResultImpl extends WrapperImpl + implements DeploymentExportResult { private SerializerAdapter serializerAdapter; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentImpl.java index 34c2e3eb6a0e9..0e18426a4c2cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentImpl.java @@ -57,20 +57,15 @@ /** * The implementation of {@link Deployment} and its nested interfaces. */ -public final class DeploymentImpl extends - CreatableUpdatableImpl - implements - Deployment, - Deployment.Definition, - Deployment.Update, - Deployment.Execution { +public final class DeploymentImpl extends CreatableUpdatableImpl + implements Deployment, Deployment.Definition, Deployment.Update, Deployment.Execution { private final ClientLogger logger = new ClientLogger(DeploymentImpl.class); - private static final SerializerAdapter SERIALIZER_ADAPTER = - SerializerFactory.createDefaultManagementSerializerAdapter(); - private static final TypeReference> TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER = - new TypeReference>() { + private static final SerializerAdapter SERIALIZER_ADAPTER + = SerializerFactory.createDefaultManagementSerializerAdapter(); + private static final TypeReference> TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER + = new TypeReference>() { }; private final ResourceManager resourceManager; @@ -215,7 +210,6 @@ public Mono cancelAsync() { return this.manager().serviceClient().getDeployments().cancelAsync(resourceGroupName, name()); } - @Override public DeploymentExportResult exportTemplate() { return this.exportTemplateAsync().block(); @@ -223,7 +217,10 @@ public DeploymentExportResult exportTemplate() { @Override public Mono exportTemplateAsync() { - return this.manager().serviceClient().getDeployments().exportTemplateAsync(resourceGroupName(), name()) + return this.manager() + .serviceClient() + .getDeployments() + .exportTemplateAsync(resourceGroupName(), name()) .map(DeploymentExportResultImpl::new); } @@ -236,9 +233,8 @@ public DeploymentImpl prepareWhatIf() { @Override public DeploymentImpl withNewResourceGroup(String resourceGroupName, Region region) { - this.creatableResourceGroup = this.resourceManager.resourceGroups() - .define(resourceGroupName) - .withRegion(region); + this.creatableResourceGroup + = this.resourceManager.resourceGroups().define(resourceGroupName).withRegion(region); this.addDependency(this.creatableResourceGroup); this.resourceGroupName = resourceGroupName; return this; @@ -286,8 +282,8 @@ public DeploymentImpl withTemplateLink(String uri, String contentVersion) { if (this.deploymentCreateUpdateParameters.properties() == null) { this.deploymentCreateUpdateParameters.withProperties(new DeploymentProperties()); } - this.deploymentCreateUpdateParameters.properties().withTemplateLink( - new TemplateLink().withUri(uri).withContentVersion(contentVersion)); + this.deploymentCreateUpdateParameters.properties() + .withTemplateLink(new TemplateLink().withUri(uri).withContentVersion(contentVersion)); this.deploymentCreateUpdateParameters.properties().withTemplate(null); return this; } @@ -328,8 +324,8 @@ public DeploymentImpl withParametersLink(String uri, String contentVersion) { if (this.deploymentCreateUpdateParameters.properties() == null) { this.deploymentCreateUpdateParameters.withProperties(new DeploymentProperties()); } - this.deploymentCreateUpdateParameters.properties().withParametersLink( - new ParametersLink().withUri(uri).withContentVersion(contentVersion)); + this.deploymentCreateUpdateParameters.properties() + .withParametersLink(new ParametersLink().withUri(uri).withContentVersion(contentVersion)); this.deploymentCreateUpdateParameters.properties().withParameters(null); return this; } @@ -341,25 +337,22 @@ public Accepted beginCreate() { @Override public Accepted beginCreate(Context context) { - return AcceptedImpl.newAccepted(logger, - this.manager().serviceClient().getHttpPipeline(), + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), - () -> this.manager().serviceClient().getDeployments() + () -> this.manager() + .serviceClient() + .getDeployments() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), deploymentCreateUpdateParameters) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) .block(), - inner -> new DeploymentImpl(inner, inner.name(), resourceManager), - DeploymentExtendedInner.class, - () -> { + inner -> new DeploymentImpl(inner, inner.name(), resourceManager), DeploymentExtendedInner.class, () -> { if (this.creatableResourceGroup != null) { this.creatableResourceGroup.create(context); } - }, - inner -> { + }, inner -> { setInner(inner); prepareForUpdate(inner); - }, - context); + }, context); } @Override @@ -371,29 +364,32 @@ public Mono beginCreateAsync() { return Mono.just((Indexable) DeploymentImpl.this); } }) - .flatMap(indexable -> manager().serviceClient().getDeployments() - .createOrUpdateWithResponseAsync(resourceGroupName(), name(), deploymentCreateUpdateParameters)) - .flatMap(activationResponse -> FluxUtil.collectBytesInByteBufferStream(activationResponse.getValue())) - .map(response -> { - try { - return (DeploymentExtendedInner) SerializerFactory.createDefaultManagementSerializerAdapter() - .deserialize(new String(response, StandardCharsets.UTF_8), - DeploymentExtendedInner.class, SerializerEncoding.JSON); - } catch (IOException ioe) { - throw logger.logExceptionAsError( - new IllegalStateException("Failed to deserialize activation response body", ioe)); - } - }) - .map(deploymentExtendedInner -> { - prepareForUpdate(deploymentExtendedInner); - return deploymentExtendedInner; - }) - .map(innerToFluentMap(this)); + .flatMap(indexable -> manager().serviceClient() + .getDeployments() + .createOrUpdateWithResponseAsync(resourceGroupName(), name(), deploymentCreateUpdateParameters)) + .flatMap(activationResponse -> FluxUtil.collectBytesInByteBufferStream(activationResponse.getValue())) + .map(response -> { + try { + return (DeploymentExtendedInner) SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize(new String(response, StandardCharsets.UTF_8), DeploymentExtendedInner.class, + SerializerEncoding.JSON); + } catch (IOException ioe) { + throw logger.logExceptionAsError( + new IllegalStateException("Failed to deserialize activation response body", ioe)); + } + }) + .map(deploymentExtendedInner -> { + prepareForUpdate(deploymentExtendedInner); + return deploymentExtendedInner; + }) + .map(innerToFluentMap(this)); } @Override public Mono createResourceAsync() { - return this.manager().serviceClient().getDeployments() + return this.manager() + .serviceClient() + .getDeployments() .createOrUpdateAsync(resourceGroupName(), name(), deploymentCreateUpdateParameters) .map(deploymentExtendedInner -> { prepareForUpdate(deploymentExtendedInner); @@ -416,10 +412,12 @@ private void prepareForUpdate(DeploymentExtendedInner inner) { deploymentCreateUpdateParameters.properties().withTemplateLink(inner.properties().templateLink()); if (inner.properties().onErrorDeployment() != null) { deploymentCreateUpdateParameters.properties().withOnErrorDeployment(new OnErrorDeployment()); - deploymentCreateUpdateParameters.properties().onErrorDeployment().withDeploymentName( - inner.properties().onErrorDeployment().deploymentName()); - deploymentCreateUpdateParameters.properties().onErrorDeployment().withType( - inner.properties().onErrorDeployment().type()); + deploymentCreateUpdateParameters.properties() + .onErrorDeployment() + .withDeploymentName(inner.properties().onErrorDeployment().deploymentName()); + deploymentCreateUpdateParameters.properties() + .onErrorDeployment() + .withType(inner.properties().onErrorDeployment().type()); } } } @@ -431,7 +429,9 @@ public Mono applyAsync() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getDeployments() + return this.manager() + .serviceClient() + .getDeployments() .getAtManagementGroupScopeAsync(resourceGroupName(), name()); } @@ -557,8 +557,8 @@ public DeploymentImpl withWhatIfTemplateLink(String uri, String contentVersion) if (deploymentWhatIf.properties() == null) { deploymentWhatIf.withProperties(new DeploymentWhatIfProperties()); } - deploymentWhatIf.properties().withTemplateLink( - new TemplateLink().withUri(uri).withContentVersion(contentVersion)); + deploymentWhatIf.properties() + .withTemplateLink(new TemplateLink().withUri(uri).withContentVersion(contentVersion)); return this; } @@ -576,8 +576,8 @@ public DeploymentImpl withWhatIfParametersLink(String uri, String contentVersion if (deploymentWhatIf.properties() == null) { deploymentWhatIf.withProperties(new DeploymentWhatIfProperties()); } - deploymentWhatIf.properties().withParametersLink( - new ParametersLink().withUri(uri).withContentVersion(contentVersion)); + deploymentWhatIf.properties() + .withParametersLink(new ParametersLink().withUri(uri).withContentVersion(contentVersion)); return this; } @@ -588,12 +588,13 @@ public WhatIfOperationResult whatIf() { @Override public Mono whatIfAsync() { - return this.manager().serviceClient().getDeployments() + return this.manager() + .serviceClient() + .getDeployments() .whatIfAsync(resourceGroupName(), name(), deploymentWhatIf) .map(WhatIfOperationResultImpl::new); } - @Override public WhatIfOperationResult whatIfAtSubscriptionScope() { return this.whatIfAtSubscriptionScopeAsync().block(); @@ -601,15 +602,16 @@ public WhatIfOperationResult whatIfAtSubscriptionScope() { @Override public Mono whatIfAtSubscriptionScopeAsync() { - return this.manager().serviceClient().getDeployments().whatIfAtSubscriptionScopeAsync(name(), deploymentWhatIf) + return this.manager() + .serviceClient() + .getDeployments() + .whatIfAtSubscriptionScopeAsync(name(), deploymentWhatIf) .map(WhatIfOperationResultImpl::new); } private Map getParametersFromObject(Object parameters) { try { - String parametersJson = SERIALIZER_ADAPTER.serialize( - parameters, - SerializerEncoding.JSON); + String parametersJson = SERIALIZER_ADAPTER.serialize(parameters, SerializerEncoding.JSON); return getParametersFromJsonString(parametersJson); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); @@ -617,9 +619,7 @@ private Map getParametersFromObject(Object paramete } private Map getParametersFromJsonString(String parametersJson) throws IOException { - return SERIALIZER_ADAPTER.deserialize( - parametersJson, - TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER.getJavaType(), + return SERIALIZER_ADAPTER.deserialize(parametersJson, TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER.getJavaType(), SerializerEncoding.JSON); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationImpl.java index 7d2c944fa5447..ea8fdea13a88d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationImpl.java @@ -18,9 +18,7 @@ * The implementation of {@link DeploymentOperation}. */ final class DeploymentOperationImpl extends - IndexableRefreshableWrapperImpl - implements - DeploymentOperation { + IndexableRefreshableWrapperImpl implements DeploymentOperation { private String resourceGroupName; private String deploymentName; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationsImpl.java index f038b46c9b325..e397d47a51476 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentOperationsImpl.java @@ -17,13 +17,12 @@ * The implementation of {@link DeploymentOperations}. */ final class DeploymentOperationsImpl - extends ReadableWrappersImpl - implements DeploymentOperations { + extends ReadableWrappersImpl + implements DeploymentOperations { private final DeploymentOperationsClient client; private final Deployment deployment; - DeploymentOperationsImpl(final DeploymentOperationsClient client, - final Deployment deployment) { + DeploymentOperationsImpl(final DeploymentOperationsClient client, final Deployment deployment) { this.client = client; this.deployment = deployment; } @@ -54,7 +53,7 @@ protected DeploymentOperationImpl wrapModel(DeploymentOperationInner inner) { @Override public PagedFlux listAsync() { - return wrapPageAsync(this.client - .listAtManagementGroupScopeAsync(deployment.resourceGroupName(), deployment.name())); + return wrapPageAsync( + this.client.listAtManagementGroupScopeAsync(deployment.resourceGroupName(), deployment.name())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentStacksClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentStacksClientImpl.java index 630c437d7f9ee..6a60e773beb4e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentStacksClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentStacksClientImpl.java @@ -1254,7 +1254,7 @@ public Mono deleteAsync(String resourceGroupName, String deploymentStackNa UnmanageActionManagementGroupMode unmanageActionManagementGroups, Boolean bypassStackOutOfSyncError) { return beginDeleteAsync(resourceGroupName, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1276,7 +1276,7 @@ public Mono deleteAsync(String resourceGroupName, String deploymentStackNa final Boolean bypassStackOutOfSyncError = null; return beginDeleteAsync(resourceGroupName, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1304,7 +1304,7 @@ private Mono deleteAsync(String resourceGroupName, String deploymentStackN Context context) { return beginDeleteAsync(resourceGroupName, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1910,7 +1910,7 @@ public Mono deleteAtSubscriptionAsync(String deploymentStackName, UnmanageActionManagementGroupMode unmanageActionManagementGroups, Boolean bypassStackOutOfSyncError) { return beginDeleteAtSubscriptionAsync(deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1931,7 +1931,7 @@ public Mono deleteAtSubscriptionAsync(String deploymentStackName) { final Boolean bypassStackOutOfSyncError = null; return beginDeleteAtSubscriptionAsync(deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -1958,7 +1958,7 @@ private Mono deleteAtSubscriptionAsync(String deploymentStackName, Context context) { return beginDeleteAtSubscriptionAsync(deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -2592,7 +2592,7 @@ public Mono deleteAtManagementGroupAsync(String managementGroupId, String UnmanageActionManagementGroupMode unmanageActionManagementGroups, Boolean bypassStackOutOfSyncError) { return beginDeleteAtManagementGroupAsync(managementGroupId, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -2614,7 +2614,7 @@ public Mono deleteAtManagementGroupAsync(String managementGroupId, String final Boolean bypassStackOutOfSyncError = null; return beginDeleteAtManagementGroupAsync(managementGroupId, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -2642,7 +2642,7 @@ private Mono deleteAtManagementGroupAsync(String managementGroupId, String Context context) { return beginDeleteAtManagementGroupAsync(managementGroupId, deploymentStackName, unmanageActionResources, unmanageActionResourceGroups, unmanageActionManagementGroups, bypassStackOutOfSyncError, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentsImpl.java index 8d6eea3a79edf..92a01ca5bb362 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/DeploymentsImpl.java @@ -20,10 +20,8 @@ /** * The implementation for {@link Deployments}. */ -public final class DeploymentsImpl - extends SupportsGettingByResourceGroupImpl - implements Deployments, - HasManager { +public final class DeploymentsImpl extends SupportsGettingByResourceGroupImpl + implements Deployments, HasManager { private final ResourceManager resourceManager; @@ -38,8 +36,8 @@ public PagedIterable list() { @Override public PagedIterable listByResourceGroup(String groupName) { - return PagedConverter.mapPage(this.manager().serviceClient().getDeployments() - .listByResourceGroup(groupName), inner -> createFluentModel(inner)); + return PagedConverter.mapPage(this.manager().serviceClient().getDeployments().listByResourceGroup(groupName), + inner -> createFluentModel(inner)); } @Override @@ -49,22 +47,27 @@ public Deployment getByName(String name) { @Override public Mono getByNameAsync(String name) { - return this.manager().serviceClient().getDeployments().getAtTenantScopeAsync(name) + return this.manager() + .serviceClient() + .getDeployments() + .getAtTenantScopeAsync(name) .map(inner -> new DeploymentImpl(inner, inner.name(), this.resourceManager)); } @Override public Mono getByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this.manager().serviceClient().getDeployments() - .getByResourceGroupAsync(resourceGroupName, name).map(deploymentExtendedInner -> { + return this.manager() + .serviceClient() + .getDeployments() + .getByResourceGroupAsync(resourceGroupName, name) + .map(deploymentExtendedInner -> { if (deploymentExtendedInner != null) { return createFluentModel(deploymentExtendedInner); } else { @@ -78,16 +81,14 @@ public void deleteByResourceGroup(String groupName, String name) { deleteByResourceGroupAsync(groupName, name).block(); } - @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } return this.manager().serviceClient().getDeployments().deleteAsync(resourceGroupName, name); } @@ -112,9 +113,7 @@ protected DeploymentImpl createFluentModel(DeploymentExtendedInner deploymentExt @Override public Deployment getById(String id) { - return this.getByResourceGroup( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(id)); + return this.getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } @Override @@ -138,12 +137,11 @@ public PagedFlux listAsync() { resourceGroup -> listByResourceGroupAsync(resourceGroup.name())); } - @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } final DeploymentsClient client = this.manager().serviceClient().getDeployments(); return PagedConverter.mapPage(client.listByResourceGroupAsync(resourceGroupName), diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeatureImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeatureImpl.java index 8c1a535e342c9..d2d1f9808a276 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeatureImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeatureImpl.java @@ -12,10 +12,7 @@ /** * The implementation of {@link Feature}. */ -final class FeatureImpl extends - IndexableWrapperImpl - implements - Feature { +final class FeatureImpl extends IndexableWrapperImpl implements Feature { FeatureImpl(FeatureResultInner innerModel) { super(innerModel); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeaturesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeaturesImpl.java index a28e544a8bab4..a69798a76ebbb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeaturesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/FeaturesImpl.java @@ -15,9 +15,8 @@ /** * The implementation of {@link Features}. */ -public final class FeaturesImpl - extends ReadableWrappersImpl - implements Features { +public final class FeaturesImpl extends ReadableWrappersImpl + implements Features { private final FeaturesClient client; public FeaturesImpl(final FeaturesClient client) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourceImpl.java index c2c61a5ecc9a0..e0ed0e3dfcdd3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourceImpl.java @@ -23,17 +23,9 @@ /** * The implementation for GenericResource and its nested interfaces. */ -final class GenericResourceImpl - extends GroupableResourceImpl< - GenericResource, - GenericResourceInner, - GenericResourceImpl, - ResourceManager> - implements - GenericResource, - GenericResource.Definition, - GenericResource.UpdateStages.WithApiVersion, - GenericResource.Update { +final class GenericResourceImpl extends + GroupableResourceImpl implements + GenericResource, GenericResource.Definition, GenericResource.UpdateStages.WithApiVersion, GenericResource.Update { private final ClientLogger logger = new ClientLogger(GenericResourceImpl.class); @@ -44,9 +36,7 @@ final class GenericResourceImpl private GenericResourceInner createUpdateParameter = new GenericResourceInner(); - GenericResourceImpl(String key, - GenericResourceInner innerModel, - final ResourceManager resourceManager) { + GenericResourceImpl(String key, GenericResourceInner innerModel, final ResourceManager resourceManager) { super(key, innerModel, resourceManager); resourceProviderNamespace = ResourceUtils.resourceProviderFromResourceId(innerModel.id()); resourceType = ResourceUtils.resourceTypeFromResourceId(innerModel.id()); @@ -74,8 +64,8 @@ public String resourceType() { @Override public String apiVersion() { if (apiVersion == null) { - apiVersion = ResourceUtils.defaultApiVersion( - id(), manager().providers().getByName(ResourceUtils.resourceProviderFromResourceId(id()))); + apiVersion = ResourceUtils.defaultApiVersion(id(), + manager().providers().getByName(ResourceUtils.resourceProviderFromResourceId(id()))); } return apiVersion; } @@ -112,13 +102,11 @@ public String managedBy() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getResources().getAsync( - resourceGroupName(), - resourceProviderNamespace(), - parentResourcePath(), - resourceType(), - this.name(), - this.apiVersion()); + return this.manager() + .serviceClient() + .getResources() + .getAsync(resourceGroupName(), resourceProviderNamespace(), parentResourcePath(), resourceType(), + this.name(), this.apiVersion()); } @Override @@ -169,11 +157,7 @@ public GenericResourceImpl withParentResourcePath(String parentResourcePath) { public GenericResourceImpl withPlan(String name, String publisher, String product, String promotionCode) { this.withPlan( - new Plan() - .withName(name) - .withPublisher(publisher) - .withProduct(product) - .withPromotionCode(promotionCode)); + new Plan().withName(name).withPublisher(publisher).withProduct(product).withPromotionCode(promotionCode)); return this; } @@ -213,23 +197,16 @@ public Accepted beginCreate() { createUpdateParameter.withLocation(innerModel().location()); createUpdateParameter.withTags(innerModel().tags()); - return AcceptedImpl.newAccepted(logger, - this.manager().serviceClient().getHttpPipeline(), + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), - () -> this.manager().serviceClient().getResources() - .createOrUpdateWithResponseAsync( - resourceGroupName(), - resourceProviderNamespace, - parentResourcePath(), - resourceType, - name, - apiVersion, - createUpdateParameter).block(), - inner -> new GenericResourceImpl(inner.id(), inner, this.manager()), - GenericResourceInner.class, - null, - this::setInner, - Context.NONE); + () -> this.manager() + .serviceClient() + .getResources() + .createOrUpdateWithResponseAsync(resourceGroupName(), resourceProviderNamespace, parentResourcePath(), + resourceType, name, apiVersion, createUpdateParameter) + .block(), + inner -> new GenericResourceImpl(inner.id(), inner, this.manager()), GenericResourceInner.class, null, + this::setInner, Context.NONE); } // CreateUpdateTaskGroup.ResourceCreator implementation @@ -237,43 +214,31 @@ public Accepted beginCreate() { public Mono createResourceAsync() { Mono observable = this.getApiVersionAsync(); final ResourcesClient resourceClient = this.manager().serviceClient().getResources(); - return observable - .flatMap(api -> { - String name = this.name(); - createUpdateParameter.withLocation(innerModel().location()); - createUpdateParameter.withTags(innerModel().tags()); - return resourceClient.createOrUpdateAsync( - resourceGroupName(), - resourceProviderNamespace, - parentResourcePath(), - resourceType, - name, - api, - createUpdateParameter) - .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) - .map(innerToFluentMap(this)); - }); + return observable.flatMap(api -> { + String name = this.name(); + createUpdateParameter.withLocation(innerModel().location()); + createUpdateParameter.withTags(innerModel().tags()); + return resourceClient + .createOrUpdateAsync(resourceGroupName(), resourceProviderNamespace, parentResourcePath(), resourceType, + name, api, createUpdateParameter) + .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) + .map(innerToFluentMap(this)); + }); } @Override public Mono updateResourceAsync() { Mono observable = this.getApiVersionAsync(); final ResourcesClient resourceClient = this.manager().serviceClient().getResources(); - return observable - .flatMap(api -> { - String name = ResourceUtils.nameFromResourceId(innerModel().id()); - createUpdateParameter.withTags(innerModel().tags()); - return resourceClient.updateAsync( - resourceGroupName(), - resourceProviderNamespace, - parentResourcePath(), - resourceType, - name, - api, - createUpdateParameter) - .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) - .map(innerToFluentMap(this)); - }); + return observable.flatMap(api -> { + String name = ResourceUtils.nameFromResourceId(innerModel().id()); + createUpdateParameter.withTags(innerModel().tags()); + return resourceClient + .updateAsync(resourceGroupName(), resourceProviderNamespace, parentResourcePath(), resourceType, name, + api, createUpdateParameter) + .subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler()) + .map(innerToFluentMap(this)); + }); } private Mono getApiVersionAsync() { @@ -281,23 +246,17 @@ private Mono getApiVersionAsync() { if (this.apiVersion != null) { apiVersion = Mono.just(this.apiVersion); } else { - apiVersion = this.manager().providers().getByNameAsync(resourceProviderNamespace) - .flatMap(provider -> { - String id; - if (!isInCreateMode()) { - id = innerModel().id(); - } else { - id = ResourceUtils.constructResourceId( - this.manager().subscriptionId(), - resourceGroupName(), - resourceProviderNamespace(), - resourceType(), - this.name(), - parentResourcePath()); - } - this.apiVersion = ResourceUtils.defaultApiVersion(id, provider); - return Mono.just(this.apiVersion); - }); + apiVersion = this.manager().providers().getByNameAsync(resourceProviderNamespace).flatMap(provider -> { + String id; + if (!isInCreateMode()) { + id = innerModel().id(); + } else { + id = ResourceUtils.constructResourceId(this.manager().subscriptionId(), resourceGroupName(), + resourceProviderNamespace(), resourceType(), this.name(), parentResourcePath()); + } + this.apiVersion = ResourceUtils.defaultApiVersion(id, provider); + return Mono.just(this.apiVersion); + }); } return apiVersion; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourcesImpl.java index 3f9d4c20fe187..911d2029571ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/GenericResourcesImpl.java @@ -29,14 +29,9 @@ /** * Implementation of the {@link GenericResources}. */ -public final class GenericResourcesImpl - extends GroupableResourcesImpl< - GenericResource, - GenericResourceImpl, - GenericResourceInner, - ResourcesClient, - ResourceManager> - implements GenericResources { +public final class GenericResourcesImpl extends + GroupableResourcesImpl + implements GenericResources { private final ClientLogger logger = new ClientLogger(getClass()); public GenericResourcesImpl(ResourceManager resourceManager) { @@ -60,37 +55,33 @@ public PagedIterable listByTag(String resourceGroupName, String @Override public PagedFlux listByTagAsync(String resourceGroupName, String tagName, String tagValue) { - return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources() + return wrapPageAsync(PagedConverter.mapPage( + this.manager() + .serviceClient() + .getResources() .listByResourceGroupAsync(resourceGroupName, ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null), - res -> (GenericResourceInner) res)); + res -> (GenericResourceInner) res)); } @Override public GenericResource.DefinitionStages.Blank define(String name) { - return new GenericResourceImpl( - name, - new GenericResourceInner(), - this.manager()); + return new GenericResourceImpl(name, new GenericResourceInner(), this.manager()); } @Override - public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace, - String parentResourcePath, String resourceType, String resourceName, String apiVersion) { - return this.inner().checkExistence( - resourceGroupName, - resourceProviderNamespace, - parentResourcePath, - resourceType, - resourceName, - apiVersion); + public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion) { + return this.inner() + .checkExistence(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, + resourceName, apiVersion); } @Override public boolean checkExistenceById(String id) { if (CoreUtils.isNullOrEmpty(id)) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + throw logger + .logExceptionAsError(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } String apiVersion = getApiVersionFromIdAsync(id).block(); return this.checkExistenceById(id, apiVersion); @@ -99,8 +90,8 @@ public boolean checkExistenceById(String id) { @Override public boolean checkExistenceById(String id, String apiVersion) { if (CoreUtils.isNullOrEmpty(id)) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + throw logger + .logExceptionAsError(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(apiVersion)) { throw logger.logExceptionAsError( @@ -112,8 +103,7 @@ public boolean checkExistenceById(String id, String apiVersion) { @Override public Mono getByIdAsync(String id) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } return this.getApiVersionFromIdAsync(id) .flatMap(apiVersion -> this.getByIdAsync(ResourceUtils.encodeResourceId(id), apiVersion)); @@ -127,14 +117,13 @@ public GenericResource getById(String id, String apiVersion) { @Override public Mono getByIdAsync(String id, String apiVersion) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(apiVersion)) { - return Mono.error( - new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null.")); } - return this.inner().getByIdAsync(ResourceUtils.encodeResourceId(id), apiVersion) + return this.inner() + .getByIdAsync(ResourceUtils.encodeResourceId(id), apiVersion) .map(this::wrapModel) .map(r -> r.withApiVersion(apiVersion)); } @@ -142,8 +131,7 @@ public Mono getByIdAsync(String id, String apiVersion) { @Override public Mono deleteByIdAsync(final String id) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } return getApiVersionFromIdAsync(id) .flatMap(apiVersion -> this.deleteByIdAsync(ResourceUtils.encodeResourceId(id), apiVersion)); @@ -157,28 +145,22 @@ public void deleteById(String id, String apiVersion) { @Override public Mono deleteByIdAsync(String id, String apiVersion) { if (CoreUtils.isNullOrEmpty(id)) { - return Mono.error( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(apiVersion)) { - return Mono.error( - new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null.")); } return this.inner().deleteByIdAsync(ResourceUtils.encodeResourceId(id), apiVersion); } @Override - public GenericResource get( - String resourceGroupName, - String providerNamespace, - String resourceType, - String name) { + public GenericResource get(String resourceGroupName, String providerNamespace, String resourceType, String name) { PagedIterable genericResources = this.listByResourceGroup(resourceGroupName); for (GenericResource resource : genericResources) { if (resource.name().equalsIgnoreCase(name) - && resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace) - && resource.resourceType().equalsIgnoreCase(resourceType)) { + && resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace) + && resource.resourceType().equalsIgnoreCase(resourceType)) { return resource; } } @@ -187,13 +169,13 @@ public GenericResource get( @Override public void validateMoveResources(String sourceResourceGroupName, ResourceGroup targetResourceGroup, - List resourceIds) { + List resourceIds) { validateMoveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resourceIds).block(); } @Override public Mono validateMoveResourcesAsync(String sourceResourceGroupName, ResourceGroup targetResourceGroup, - List resourceIds) { + List resourceIds) { ResourcesMoveInfo moveInfo = new ResourcesMoveInfo(); moveInfo.withTargetResourceGroup(targetResourceGroup.id()); moveInfo.withResources(resourceIds); @@ -201,13 +183,8 @@ public Mono validateMoveResourcesAsync(String sourceResourceGroupName, Res } @Override - public GenericResource get( - String resourceGroupName, - String resourceProviderNamespace, - String parentResourcePath, - String resourceType, - String resourceName, - String apiVersion) { + public GenericResource get(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion) { // Correct for auto-gen'd API's treatment parent path as required // even though it makes sense only for child resources @@ -215,61 +192,55 @@ public GenericResource get( parentResourcePath = ""; } - GenericResourceInner inner = this.inner().get( - resourceGroupName, - resourceProviderNamespace, - parentResourcePath, - resourceType, - resourceName, + GenericResourceInner inner = this.inner() + .get(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion); - GenericResourceImpl resource = new GenericResourceImpl( - resourceName, - inner, - this.manager()); + GenericResourceImpl resource = new GenericResourceImpl(resourceName, inner, this.manager()); return resource.withExistingResourceGroup(resourceGroupName) - .withProviderNamespace(resourceProviderNamespace) - .withParentResourcePath(parentResourcePath) - .withResourceType(resourceType) - .withApiVersion(apiVersion); + .withProviderNamespace(resourceProviderNamespace) + .withParentResourcePath(parentResourcePath) + .withResourceType(resourceType) + .withApiVersion(apiVersion); } @Override - public void moveResources(String sourceResourceGroupName, - ResourceGroup targetResourceGroup, List resourceIds) { + public void moveResources(String sourceResourceGroupName, ResourceGroup targetResourceGroup, + List resourceIds) { this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resourceIds).block(); } @Override - public Mono moveResourcesAsync(String sourceResourceGroupName, - ResourceGroup targetResourceGroup, List resourceIds) { + public Mono moveResourcesAsync(String sourceResourceGroupName, ResourceGroup targetResourceGroup, + List resourceIds) { ResourcesMoveInfo moveInfo = new ResourcesMoveInfo(); moveInfo.withTargetResourceGroup(targetResourceGroup.id()); moveInfo.withResources(resourceIds); return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo); } - public void delete(String resourceGroupName, String resourceProviderNamespace, - String parentResourcePath, String resourceType, String resourceName, String apiVersion) { - deleteAsync(resourceGroupName, resourceProviderNamespace, - parentResourcePath, resourceType, resourceName, apiVersion).block(); + public void delete(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion) { + deleteAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, + apiVersion).block(); } @Override - public Mono deleteAsync(String resourceGroupName, String resourceProviderNamespace, - String parentResourcePath, String resourceType, String resourceName, String apiVersion) { - return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace, - parentResourcePath, resourceType, resourceName, apiVersion); + public Mono deleteAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion) { + return this.inner() + .deleteAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, + apiVersion); } @Override protected GenericResourceImpl wrapModel(String id) { return new GenericResourceImpl(id, new GenericResourceInner(), this.manager()) - .withExistingResourceGroup(ResourceUtils.groupFromResourceId(id)) - .withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id)) - .withResourceType(ResourceUtils.resourceTypeFromResourceId(id)) - .withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id)); + .withExistingResourceGroup(ResourceUtils.groupFromResourceId(id)) + .withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id)) + .withResourceType(ResourceUtils.resourceTypeFromResourceId(id)) + .withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id)); } @Override @@ -278,10 +249,10 @@ protected GenericResourceImpl wrapModel(GenericResourceInner inner) { return null; } return new GenericResourceImpl(inner.id(), inner, this.manager()) - .withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id())) - .withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id())) - .withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id())) - .withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id())); + .withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id())) + .withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id())) + .withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id())) + .withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id())); } @Override @@ -301,8 +272,8 @@ protected Mono deleteInnerAsync(String resourceGroupName, String name) { @Override public Accepted beginDeleteById(String id) { if (CoreUtils.isNullOrEmpty(id)) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + throw logger + .logExceptionAsError(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } String apiVersion = getApiVersionFromIdAsync(id).block(); return this.beginDeleteById(id, apiVersion); @@ -311,42 +282,39 @@ public Accepted beginDeleteById(String id) { @Override public Accepted beginDeleteById(String id, String apiVersion) { if (CoreUtils.isNullOrEmpty(id)) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); + throw logger + .logExceptionAsError(new IllegalArgumentException("Parameter 'id' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(apiVersion)) { throw logger.logExceptionAsError( new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null.")); } - return AcceptedImpl.newAccepted(logger, - this.manager().serviceClient().getHttpPipeline(), + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), - () -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + () -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(), Function.identity(), Void.class, + null, Context.NONE); } private Mono getApiVersionFromIdAsync(final String id) { - return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id)) - .map(provider -> ResourceUtils.defaultApiVersion(id, provider)); + return this.manager() + .providers() + .getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id)) + .map(provider -> ResourceUtils.defaultApiVersion(id, provider)); } @Override public PagedFlux listAsync() { - return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(), - res -> (GenericResourceInner) res)); + return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(), res -> (GenericResourceInner) res)); } @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } - return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources() - .listByResourceGroupAsync(resourceGroupName), + return wrapPageAsync(PagedConverter.mapPage( + this.manager().serviceClient().getResources().listByResourceGroupAsync(resourceGroupName), res -> (GenericResourceInner) res)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/LocationImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/LocationImpl.java index 1f9b144ee4230..7ccf175d7b62b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/LocationImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/LocationImpl.java @@ -13,10 +13,7 @@ /** * The implementation of {@link Location}. */ -final class LocationImpl extends - IndexableWrapperImpl - implements - Location { +final class LocationImpl extends IndexableWrapperImpl implements Location { LocationImpl(LocationInner innerModel) { super(innerModel); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLockImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLockImpl.java index 524ce32e865a5..c99259332d5f7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLockImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLockImpl.java @@ -23,26 +23,22 @@ */ final class ManagementLockImpl extends CreatableUpdatableImpl - implements - ManagementLock, - ManagementLock.Definition, - ManagementLock.Update { + implements ManagementLock, ManagementLock.Definition, ManagementLock.Update { private final ResourceManager manager; private String lockedResourceId = null; private final ClientLogger logger = new ClientLogger(ManagementLockImpl.class); - ManagementLockImpl( - String name, - ManagementLockObjectInner innerModel, - final ResourceManager manager) { + ManagementLockImpl(String name, ManagementLockObjectInner innerModel, final ResourceManager manager) { super(name, innerModel); this.manager = manager; } @Override protected Mono getInnerAsync() { - return this.manager().managementLockClient().getManagementLocks() + return this.manager() + .managementLockClient() + .getManagementLocks() .getByScopeAsync(this.lockedResourceId(), this.name()); } @@ -101,7 +97,8 @@ public ResourceManager manager() { @Override public Mono createResourceAsync() { - return this.manager().managementLockClient() + return this.manager() + .managementLockClient() .getManagementLocks() .createOrUpdateByScopeAsync(this.lockedResourceId(), this.name(), this.innerModel()) .map(innerToFluentMap(this)); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksClientImpl.java index ce702480234ca..162fe33c728aa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksClientImpl.java @@ -1183,7 +1183,7 @@ public Mono createOrUpdateAtResourceLevelAsync(String String lockName, ManagementLockObjectInner parameters) { return createOrUpdateAtResourceLevelWithResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, lockName, parameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksImpl.java index fb7b68f508d2a..6e3ac4534dcd3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ManagementLocksImpl.java @@ -22,9 +22,8 @@ /** * Implementation for ManagementLocks. */ -public final class ManagementLocksImpl - extends CreatableResourcesImpl - implements ManagementLocks { +public final class ManagementLocksImpl extends + CreatableResourcesImpl implements ManagementLocks { private final ResourceManager manager; @@ -66,8 +65,8 @@ private static String[] lockIdParts(String lockId) { } if (!parts[parts.length - 2].equalsIgnoreCase("locks") - || !parts[parts.length - 3].equalsIgnoreCase("Microsoft.Authorization") - || !parts[parts.length - 4].equalsIgnoreCase("providers")) { + || !parts[parts.length - 3].equalsIgnoreCase("Microsoft.Authorization") + || !parts[parts.length - 4].equalsIgnoreCase("providers")) { // Not a lock ID return new String[0]; } @@ -118,18 +117,18 @@ public Mono deleteByIdAsync(String id) { @Override public PagedIterable listByResourceGroup(String resourceGroupName) { - return wrapList(this.manager().managementLockClient().getManagementLocks() - .listByResourceGroup(resourceGroupName)); + return wrapList( + this.manager().managementLockClient().getManagementLocks().listByResourceGroup(resourceGroupName)); } @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } - return wrapPageAsync(this.manager().managementLockClient().getManagementLocks() - .listByResourceGroupAsync(resourceGroupName)); + return wrapPageAsync( + this.manager().managementLockClient().getManagementLocks().listByResourceGroupAsync(resourceGroupName)); } @Override @@ -140,14 +139,15 @@ public ManagementLock getByResourceGroup(String resourceGroupName, String name) @Override public Mono getByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this.manager().managementLockClient().getManagementLocks() + return this.manager() + .managementLockClient() + .getManagementLocks() .getByResourceGroupAsync(resourceGroupName, name) .map(this::wrapModel); } @@ -161,7 +161,10 @@ public ManagementLock getById(String id) { public Mono getByIdAsync(String id) { String resourceId = resourceIdFromLockId(id); String lockName = ResourceUtils.nameFromResourceId(id); - return this.manager().managementLockClient().getManagementLocks().getByScopeAsync(resourceId, lockName) + return this.manager() + .managementLockClient() + .getManagementLocks() + .getByScopeAsync(resourceId, lockName) .map(this::wrapModel); } @@ -173,15 +176,13 @@ public void deleteByResourceGroup(String resourceGroupName, String name) { @Override public Mono deleteByResourceGroupAsync(String resourceGroupName, String name) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); + return Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")); } if (CoreUtils.isNullOrEmpty(name)) { - return Mono.error( - new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); + return Mono.error(new IllegalArgumentException("Parameter 'name' is required and cannot be null.")); } - return this.manager().managementLockClient().getManagementLocks() - .deleteAsync(resourceGroupName, name); + return this.manager().managementLockClient().getManagementLocks().deleteAsync(resourceGroupName, name); } @Override @@ -190,14 +191,15 @@ public Flux deleteByIdsAsync(Collection ids) { return Flux.empty(); } - return Flux.fromIterable(ids) - .flatMapDelayError(id -> { - String lockName = ResourceUtils.nameFromResourceId(id); - String scopeName = ManagementLocksImpl.resourceIdFromLockId(id); - return this.manager().managementLockClient().getManagementLocks() - .deleteByScopeAsync(scopeName, lockName) - .then(Mono.just(id)); - }, 32, 32); + return Flux.fromIterable(ids).flatMapDelayError(id -> { + String lockName = ResourceUtils.nameFromResourceId(id); + String scopeName = ManagementLocksImpl.resourceIdFromLockId(id); + return this.manager() + .managementLockClient() + .getManagementLocks() + .deleteByScopeAsync(scopeName, lockName) + .then(Mono.just(id)); + }, 32, 32); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentImpl.java index fc3cc69607446..efb06bd31a4e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentImpl.java @@ -24,11 +24,8 @@ /** * Implementation for {@link PolicyAssignment}. */ -final class PolicyAssignmentImpl extends - CreatableImpl - implements - PolicyAssignment, - PolicyAssignment.Definition { +final class PolicyAssignmentImpl extends CreatableImpl + implements PolicyAssignment, PolicyAssignment.Definition { private final PolicyAssignmentsClient innerCollection; private String scope; @@ -121,7 +118,7 @@ public PolicyAssignmentImpl withPolicyDefinition(PolicyDefinition policyDefiniti @Override public Mono createResourceAsync() { return innerCollection.createAsync(ResourceUtils.encodeResourceId(this.scope), name(), innerModel()) - .map(innerToFluentMap(this)); + .map(innerToFluentMap(this)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentsImpl.java index bc4a4ff7b67a7..a38b29b1abccd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyAssignmentsImpl.java @@ -18,9 +18,8 @@ /** * The implementation for {@link ResourceGroups} and its parent interfaces. */ -public final class PolicyAssignmentsImpl - extends CreatableWrappersImpl - implements PolicyAssignments { +public final class PolicyAssignmentsImpl extends + CreatableWrappersImpl implements PolicyAssignments { private final PolicyAssignmentsClient client; /** @@ -49,9 +48,7 @@ public PolicyAssignmentImpl define(String name) { @Override protected PolicyAssignmentImpl wrapModel(String name) { - return new PolicyAssignmentImpl(name, - new PolicyAssignmentInner().withDisplayName(name), - client); + return new PolicyAssignmentImpl(name, new PolicyAssignmentInner().withDisplayName(name), client); } @Override @@ -64,13 +61,10 @@ protected PolicyAssignmentImpl wrapModel(PolicyAssignmentInner inner) { @Override public PagedIterable listByResource(String resourceId) { - return wrapList(client.listForResource( - ResourceUtils.groupFromResourceId(resourceId), - ResourceUtils.resourceProviderFromResourceId(resourceId), - ResourceUtils.relativePathFromResourceId(ResourceUtils.parentResourceIdFromResourceId(resourceId)), - ResourceUtils.resourceTypeFromResourceId(resourceId), - ResourceUtils.nameFromResourceId(resourceId) - )); + return wrapList(client.listForResource(ResourceUtils.groupFromResourceId(resourceId), + ResourceUtils.resourceProviderFromResourceId(resourceId), + ResourceUtils.relativePathFromResourceId(ResourceUtils.parentResourceIdFromResourceId(resourceId)), + ResourceUtils.resourceTypeFromResourceId(resourceId), ResourceUtils.nameFromResourceId(resourceId))); } @Override @@ -80,8 +74,7 @@ public PolicyAssignment getById(String id) { @Override public Mono getByIdAsync(String id) { - return client.getByIdAsync(ResourceUtils.encodeResourceId(id)) - .map(this::wrapModel); + return client.getByIdAsync(ResourceUtils.encodeResourceId(id)).map(this::wrapModel); } @Override @@ -97,8 +90,8 @@ public PagedFlux listAsync() { @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return wrapPageAsync(this.client.listByResourceGroupAsync(resourceGroupName)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionImpl.java index 920fb733de60c..234c82d0d45ef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionImpl.java @@ -23,16 +23,12 @@ /** * Implementation for {@link PolicyDefinition}. */ -final class PolicyDefinitionImpl extends - CreatableUpdatableImpl - implements - PolicyDefinition, - PolicyDefinition.Definition, - PolicyDefinition.Update { +final class PolicyDefinitionImpl + extends CreatableUpdatableImpl + implements PolicyDefinition, PolicyDefinition.Definition, PolicyDefinition.Update { private final PolicyDefinitionsClient innerCollection; private final ClientLogger logger = new ClientLogger(getClass()); - PolicyDefinitionImpl(String name, PolicyDefinitionInner innerModel, PolicyDefinitionsClient innerCollection) { super(name, innerModel); this.innerCollection = innerCollection; @@ -122,8 +118,7 @@ public PolicyDefinitionImpl withPolicyType(PolicyType policyType) { @Override public Mono createResourceAsync() { - return innerCollection.createOrUpdateAsync(name(), innerModel()) - .map(innerToFluentMap(this)); + return innerCollection.createOrUpdateAsync(name(), innerModel()).map(innerToFluentMap(this)); } @Override @@ -145,10 +140,8 @@ public PolicyDefinitionImpl withParameter(String name, ParameterType parameterTy if (innerModel().parameters() == null) { innerModel().withParameters(new TreeMap<>()); } - innerModel().parameters().put(name, - new ParameterDefinitionsValue() - .withType(parameterType) - .withDefaultValue(defaultValue)); + innerModel().parameters() + .put(name, new ParameterDefinitionsValue().withType(parameterType).withDefaultValue(defaultValue)); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionsImpl.java index 1d2f468970af8..159c6e31ca76f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/PolicyDefinitionsImpl.java @@ -17,9 +17,8 @@ /** * The implementation for {@link ResourceGroups} and its parent interfaces. */ -public final class PolicyDefinitionsImpl - extends ReadableWrappersImpl - implements PolicyDefinitions { +public final class PolicyDefinitionsImpl extends + ReadableWrappersImpl implements PolicyDefinitions { private final PolicyDefinitionsClient client; /** @@ -43,8 +42,7 @@ public PolicyDefinition getByName(String name) { @Override public Mono getByNameAsync(String name) { - return client.getAsync(name) - .map(this::wrapModel); + return client.getAsync(name).map(this::wrapModel); } @Override @@ -63,10 +61,8 @@ public PolicyDefinitionImpl define(String name) { } protected PolicyDefinitionImpl wrapModel(String name) { - return new PolicyDefinitionImpl( - name, - new PolicyDefinitionInner().withPolicyType(PolicyType.NOT_SPECIFIED).withDisplayName(name), - client); + return new PolicyDefinitionImpl(name, + new PolicyDefinitionInner().withPolicyType(PolicyType.NOT_SPECIFIED).withDisplayName(name), client); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProviderImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProviderImpl.java index 622c7df1ca847..86c63216bda36 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProviderImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProviderImpl.java @@ -13,10 +13,7 @@ /** * The implementation of {@link Provider}. */ -final class ProviderImpl extends - IndexableWrapperImpl - implements - Provider { +final class ProviderImpl extends IndexableWrapperImpl implements Provider { ProviderImpl(ProviderInner provider) { super(provider); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProvidersImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProvidersImpl.java index 20e9d74a393e7..4867b064d51e0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProvidersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ProvidersImpl.java @@ -16,9 +16,8 @@ /** * The implementation for {@link Providers}. */ -public final class ProvidersImpl - extends ReadableWrappersImpl - implements Providers { +public final class ProvidersImpl extends ReadableWrappersImpl + implements Providers { private final ProvidersClient client; public ProvidersImpl(final ProvidersClient client) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupExportResultImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupExportResultImpl.java index 38ed391f1fad9..31569f682fe5f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupExportResultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupExportResultImpl.java @@ -17,10 +17,8 @@ /** * Implementation for {@link DeploymentExportResult}. */ -final class ResourceGroupExportResultImpl extends - WrapperImpl - implements - ResourceGroupExportResult { +final class ResourceGroupExportResultImpl extends WrapperImpl + implements ResourceGroupExportResult { private final SerializerAdapter serializerAdapter; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupImpl.java index 6d03cd6dddea0..1e0e2e6b0529b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupImpl.java @@ -22,17 +22,13 @@ /** * The implementation for {@link ResourceGroup} and its create and update interfaces. */ -class ResourceGroupImpl extends - CreatableUpdatableImpl - implements - ResourceGroup, - ResourceGroup.Definition, - ResourceGroup.Update { +class ResourceGroupImpl extends CreatableUpdatableImpl + implements ResourceGroup, ResourceGroup.Definition, ResourceGroup.Update { private final ResourceGroupsClient client; protected ResourceGroupImpl(final ResourceGroupInner innerModel, String name, - final ResourceManagementClient serviceClient) { + final ResourceManagementClient serviceClient) { super(name, innerModel); this.client = serviceClient.getResourceGroups(); } @@ -78,11 +74,10 @@ public ResourceGroupExportResult exportTemplate(ResourceGroupExportTemplateOptio @Override public Mono exportTemplateAsync(ResourceGroupExportTemplateOptions options) { - ExportTemplateRequest inner = new ExportTemplateRequest() - .withResources(Arrays.asList("*")) - .withOptions(options.toString()); - return client.exportTemplateAsync(name(), inner).map(resourceGroupExportResultInner -> - new ResourceGroupExportResultImpl(resourceGroupExportResultInner)); + ExportTemplateRequest inner + = new ExportTemplateRequest().withResources(Arrays.asList("*")).withOptions(options.toString()); + return client.exportTemplateAsync(name(), inner) + .map(resourceGroupExportResultInner -> new ResourceGroupExportResultImpl(resourceGroupExportResultInner)); } @Override @@ -122,8 +117,7 @@ public Mono createResourceAsync() { ResourceGroupInner params = new ResourceGroupInner(); params.withLocation(this.innerModel().location()); params.withTags(this.innerModel().tags()); - return client.createOrUpdateAsync(this.name(), params) - .map(innerToFluentMap(this)); + return client.createOrUpdateAsync(this.name(), params).map(innerToFluentMap(this)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupsImpl.java index 62eb0689d667f..6f860c836d879 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceGroupsImpl.java @@ -28,8 +28,7 @@ * The implementation for ResourceGroups. */ public final class ResourceGroupsImpl - extends CreatableResourcesImpl - implements ResourceGroups { + extends CreatableResourcesImpl implements ResourceGroups { private final ClientLogger logger = new ClientLogger(ResourceGroupsImpl.class); @@ -51,7 +50,8 @@ public PagedIterable listByTag(String tagName, String tagValue) { @Override public PagedFlux listByTagAsync(String tagName, String tagValue) { - return wrapPageAsync(manager().serviceClient().getResourceGroups() + return wrapPageAsync(manager().serviceClient() + .getResourceGroups() .listAsync(ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null)); } @@ -72,7 +72,8 @@ public void deleteByName(String name) { @Override public Mono deleteByNameAsync(String name, Collection forceDeletionResourceTypes) { - return manager().serviceClient().getResourceGroups() + return manager().serviceClient() + .getResourceGroups() .deleteAsync(name, forceDeletionTypes(forceDeletionResourceTypes)); } @@ -114,25 +115,24 @@ public Accepted beginDeleteByName(String name) { return beginDeleteByName(name, null); } - @Override - public Accepted beginDeleteByName(String name, Collection forceDeletionResourceTypes) { - return AcceptedImpl.newAccepted(logger, - this.manager().serviceClient().getHttpPipeline(), + public Accepted beginDeleteByName(String name, + Collection forceDeletionResourceTypes) { + return AcceptedImpl.newAccepted(logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), - () -> this.manager().serviceClient().getResourceGroups() - .deleteWithResponseAsync(name, forceDeletionTypes(forceDeletionResourceTypes)).block(), - Function.identity(), - Void.class, - null, - Context.NONE); + () -> this.manager() + .serviceClient() + .getResourceGroups() + .deleteWithResponseAsync(name, forceDeletionTypes(forceDeletionResourceTypes)) + .block(), + Function.identity(), Void.class, null, Context.NONE); } -// @Override -// public Mono beginDeleteByNameAsync(String name) { -// // DELETE -// return client.beginDeleteWithoutPollingAsync(name); -// } + // @Override + // public Mono beginDeleteByNameAsync(String name) { + // // DELETE + // return client.beginDeleteWithoutPollingAsync(name); + // } @Override public Mono deleteByIdAsync(String id) { @@ -141,7 +141,8 @@ public Mono deleteByIdAsync(String id) { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getResourceGroups().listAsync(), inner -> wrapModel(inner)); + return PagedConverter.mapPage(this.manager().serviceClient().getResourceGroups().listAsync(), + inner -> wrapModel(inner)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionImpl.java index ed19dbe7f9415..2d6e382875609 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionImpl.java @@ -17,10 +17,7 @@ /** * The implementation of {@link Subscription}. */ -final class SubscriptionImpl extends - IndexableWrapperImpl - implements - Subscription { +final class SubscriptionImpl extends IndexableWrapperImpl implements Subscription { private final SubscriptionsClient client; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionsImpl.java index e21ef9a91cd70..3863e4d71f39f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/SubscriptionsImpl.java @@ -16,9 +16,7 @@ /** * The implementation of Subscriptions. */ -public final class SubscriptionsImpl - extends SupportsGettingByIdImpl - implements Subscriptions { +public final class SubscriptionsImpl extends SupportsGettingByIdImpl implements Subscriptions { private final SubscriptionsClient client; public SubscriptionsImpl(final SubscriptionsClient client) { @@ -30,11 +28,9 @@ public PagedIterable list() { return PagedConverter.mapPage(client.list(), inner -> wrapModel(inner)); } - @Override public Mono getByIdAsync(String id) { - return client.getAsync(id) - .map(inner -> wrapModel(inner)); + return client.getAsync(id).map(inner -> wrapModel(inner)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsImpl.java index c60e434235d4a..a9d1963274e3f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsImpl.java @@ -42,10 +42,11 @@ public Mono updateTagsAsync(Resource resource, Map @Override public Mono updateTagsAsync(String resourceId, Map tags) { - TagsPatchResource parameters = new TagsPatchResource() - .withOperation(TagsPatchOperation.REPLACE) + TagsPatchResource parameters = new TagsPatchResource().withOperation(TagsPatchOperation.REPLACE) .withProperties(new Tags().withTags(new TreeMap<>(tags))); - return this.manager().serviceClient().getTagOperations() + return this.manager() + .serviceClient() + .getTagOperations() .updateAtScopeAsync(ResourceUtils.encodeResourceId(resourceId), parameters) .map(TagResourceImpl::new); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TenantsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TenantsImpl.java index 32e19540a9587..4a062af65520d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TenantsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TenantsImpl.java @@ -14,8 +14,7 @@ /** * Implementation for {@link Tenants}. */ -public final class TenantsImpl - implements Tenants { +public final class TenantsImpl implements Tenants { private final TenantsClient client; public TenantsImpl(final TenantsClient client) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/WhatIfOperationResultImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/WhatIfOperationResultImpl.java index 7ab0303caca51..76a84ac3cdb95 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/WhatIfOperationResultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/WhatIfOperationResultImpl.java @@ -14,10 +14,8 @@ /** * Implementation for {@link WhatIfOperationResult}. */ -public class WhatIfOperationResultImpl extends - WrapperImpl - implements - WhatIfOperationResult { +public class WhatIfOperationResultImpl extends WrapperImpl + implements WhatIfOperationResult { WhatIfOperationResultImpl(WhatIfOperationResultInner inner) { super(inner); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployment.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployment.java index 32088f71222b8..d67dcdd1fae48 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployment.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployment.java @@ -30,14 +30,8 @@ * An immutable client-side representation of an Azure deployment. */ @Fluent -public interface Deployment extends - Indexable, - Refreshable, - Updatable, - HasInnerModel, - HasManager, - HasName, - HasId { +public interface Deployment extends Indexable, Refreshable, Updatable, + HasInnerModel, HasManager, HasName, HasId { /** * @return the name of this deployment's resource group @@ -153,13 +147,8 @@ public interface Deployment extends /** * Container interface for all the deployment definitions. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithTemplate, - DefinitionStages.WithParameters, - DefinitionStages.WithMode, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithTemplate, + DefinitionStages.WithParameters, DefinitionStages.WithMode, DefinitionStages.WithCreate { } /** @@ -384,26 +373,17 @@ interface WithParameters { *

* Call {@link Update#apply()} to apply the changes to the deployment in Azure. */ - interface Update extends - Appliable, - UpdateStages.WithTemplate, - UpdateStages.WithParameters, - UpdateStages.WithMode { + interface Update + extends Appliable, UpdateStages.WithTemplate, UpdateStages.WithParameters, UpdateStages.WithMode { } /** * Container interface for all the deployment execution. */ - interface Execution extends - ExecutionStages.Blank, - ExecutionStages.WithExecute, - ExecutionStages.WithWhatIf, - ExecutionStages.WithWhatIfDeploymentMode, - ExecutionStages.WithWhatIfLocation, - ExecutionStages.WithWhatIfOnErrorDeploymentType, - ExecutionStages.WithWhatIfParameter, - ExecutionStages.WithWhatIfResultFormat, - ExecutionStages.WithWhatIfTemplate { + interface Execution extends ExecutionStages.Blank, ExecutionStages.WithExecute, ExecutionStages.WithWhatIf, + ExecutionStages.WithWhatIfDeploymentMode, ExecutionStages.WithWhatIfLocation, + ExecutionStages.WithWhatIfOnErrorDeploymentType, ExecutionStages.WithWhatIfParameter, + ExecutionStages.WithWhatIfResultFormat, ExecutionStages.WithWhatIfTemplate { } /** @@ -419,14 +399,8 @@ interface Blank { /** * A deployment execution allowing What-if parameters to be specified. */ - interface WithWhatIf extends - WithExecute, - WithWhatIfDeploymentMode, - WithWhatIfLocation, - WithWhatIfOnErrorDeploymentType, - WithWhatIfParameter, - WithWhatIfResultFormat, - WithWhatIfTemplate { + interface WithWhatIf extends WithExecute, WithWhatIfDeploymentMode, WithWhatIfLocation, + WithWhatIfOnErrorDeploymentType, WithWhatIfParameter, WithWhatIfResultFormat, WithWhatIfTemplate { /** * Specifies the type of information to log for debugging. * @@ -579,7 +553,6 @@ interface WithExecute { */ Mono whatIfAsync(); - /** * Gets changes that will be made by the deployment if executed at the scope of the subscription. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentExportResult.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentExportResult.java index 32d8a54af1026..d85fdc2ed9562 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentExportResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentExportResult.java @@ -11,8 +11,7 @@ * An immutable client-side representation of an Azure deployment template export result. */ @Fluent -public interface DeploymentExportResult extends - HasInnerModel { +public interface DeploymentExportResult extends HasInnerModel { /** * @return the template content diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperation.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperation.java index 9c8a5721d6cd8..59f97f5e377f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperation.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperation.java @@ -15,10 +15,8 @@ * An immutable client-side representation of a deployment operation. */ @Fluent -public interface DeploymentOperation extends - Indexable, - Refreshable, - HasInnerModel { +public interface DeploymentOperation + extends Indexable, Refreshable, HasInnerModel { /** * @return the deployment operation id diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperations.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperations.java index 6a8fa0ca6e914..6211de303eb7e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentOperations.java @@ -11,7 +11,6 @@ * Entry point to deployment operation management API. */ @Fluent -public interface DeploymentOperations extends - SupportsListing, - SupportsGettingById { +public interface DeploymentOperations + extends SupportsListing, SupportsGettingById { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployments.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployments.java index 4a608c841ce4e..d08972368e00f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployments.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Deployments.java @@ -19,16 +19,10 @@ * Entry point to template deployment in Azure. */ @Fluent -public interface Deployments extends - SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByName, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface Deployments extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByName, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, HasManager { /** * Checks if a deployment exists in a resource group. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Feature.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Feature.java index 3a4951f7b38f3..7152f26b710fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Feature.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Feature.java @@ -14,11 +14,7 @@ * An immutable client-side representation of an Azure feature. */ @Fluent -public interface Feature extends - Indexable, - HasId, - HasInnerModel, - HasName { +public interface Feature extends Indexable, HasId, HasInnerModel, HasName { /** * @return the type of the feature diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Features.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Features.java index 6c2261c7e7537..7247b7e005ede 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Features.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Features.java @@ -11,8 +11,7 @@ * Entry point to features management API. */ @Fluent -public interface Features extends - SupportsListing { +public interface Features extends SupportsListing { /** * Registers a feature in a resource provider. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ForceDeletionResourceType.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ForceDeletionResourceType.java index df0275c06c2c6..da9ba621e5857 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ForceDeletionResourceType.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ForceDeletionResourceType.java @@ -13,12 +13,11 @@ public final class ForceDeletionResourceType extends ExpandableStringEnum { /** Static value Microsoft.Compute/virtualMachines for ForceDeletionResourceType. */ - public static final ForceDeletionResourceType VIRTUAL_MACHINES = - fromString("Microsoft.Compute/virtualMachines"); + public static final ForceDeletionResourceType VIRTUAL_MACHINES = fromString("Microsoft.Compute/virtualMachines"); /** Static value Microsoft.Compute/virtualMachineScaleSets for ForceDeletionResourceType. */ - public static final ForceDeletionResourceType VIRTUAL_MACHINE_SCALE_SETS = - fromString("Microsoft.Compute/virtualMachineScaleSets"); + public static final ForceDeletionResourceType VIRTUAL_MACHINE_SCALE_SETS + = fromString("Microsoft.Compute/virtualMachineScaleSets"); /** * Creates or finds a ForceDeletionResourceType from its string representation. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResource.java index dfe47d2d1ec8c..04f9cee5c5bac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResource.java @@ -18,10 +18,8 @@ * An immutable client-side representation of an Azure generic resource. */ @Fluent -public interface GenericResource extends - GroupableResource, - Refreshable, - Updatable { +public interface GenericResource extends GroupableResource, + Refreshable, Updatable { /** * @return the namespace of the resource provider */ @@ -75,15 +73,9 @@ public interface GenericResource extends /** * The entirety of the generic resource definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithResourceType, - DefinitionStages.WithProviderNamespace, - DefinitionStages.WithParentResource, - DefinitionStages.WithPlan, - DefinitionStages.WithApiVersion, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithResourceType, + DefinitionStages.WithProviderNamespace, DefinitionStages.WithParentResource, DefinitionStages.WithPlan, + DefinitionStages.WithApiVersion, DefinitionStages.WithCreate { } /** @@ -198,11 +190,8 @@ interface WithParentResource { * resource in the cloud, but exposing additional optional inputs to * specify. */ - interface WithCreate extends - WithParentResource, - WithApiVersion, - Creatable, - Resource.DefinitionWithTags { + interface WithCreate extends WithParentResource, WithApiVersion, Creatable, + Resource.DefinitionWithTags { /** * Specifies other properties. * @@ -376,15 +365,8 @@ interface WithIdentity { /** * The template for a generic resource update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithApiVersion, - UpdateStages.WithPlan, - UpdateStages.WithParentResource, - UpdateStages.WithProperties, - UpdateStages.WithKind, - UpdateStages.WithSku, - UpdateStages.WithIdentity, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithApiVersion, UpdateStages.WithPlan, + UpdateStages.WithParentResource, UpdateStages.WithProperties, UpdateStages.WithKind, UpdateStages.WithSku, + UpdateStages.WithIdentity, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResources.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResources.java index 516e5073c41c1..c41cd6fa23014 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResources.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/GenericResources.java @@ -21,14 +21,10 @@ * Entry point to generic resources management API. */ @Fluent -public interface GenericResources extends - SupportsListing, - SupportsListingByResourceGroup, - SupportsListingInResourceGroupByTag, - SupportsGettingById, - SupportsCreating, - SupportsDeletingById, - HasManager { +public interface GenericResources + extends SupportsListing, SupportsListingByResourceGroup, + SupportsListingInResourceGroupByTag, SupportsGettingById, + SupportsCreating, SupportsDeletingById, HasManager { /** * Deletes a resource from Azure, identifying it by its resource ID. * @@ -114,13 +110,8 @@ public interface GenericResources extends * @param apiVersion the API version * @return true if the resource exists; false otherwise */ - boolean checkExistence( - String resourceGroupName, - String resourceProviderNamespace, - String parentResourcePath, - String resourceType, - String resourceName, - String apiVersion); + boolean checkExistence(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion); /** * Checks if a resource exists. @@ -152,13 +143,8 @@ boolean checkExistence( * @param apiVersion the API version * @return the generic resource */ - GenericResource get( - String resourceGroupName, - String resourceProviderNamespace, - String parentResourcePath, - String resourceType, - String resourceName, - String apiVersion); + GenericResource get(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion); /** * Returns a resource belonging to a resource group. @@ -169,11 +155,7 @@ GenericResource get( * @param resourceName the name of the resource * @return the generic resource */ - GenericResource get( - String resourceGroupName, - String providerNamespace, - String resourceType, - String resourceName); + GenericResource get(String resourceGroupName, String providerNamespace, String resourceType, String resourceName); /** * Validates move resources from one resource group to another. @@ -184,7 +166,7 @@ GenericResource get( * @param resourceIds the list of IDs of the resources to move */ void validateMoveResources(String sourceResourceGroupName, ResourceGroup targetResourceGroup, - List resourceIds); + List resourceIds); /** * Validates move resources from one resource group to another asynchronously. @@ -196,7 +178,7 @@ void validateMoveResources(String sourceResourceGroupName, ResourceGroup targetR * @return a representation of the deferred computation of this call */ Mono validateMoveResourcesAsync(String sourceResourceGroupName, ResourceGroup targetResourceGroup, - List resourceIds); + List resourceIds); /** * Move resources from one resource group to another. @@ -216,7 +198,7 @@ Mono validateMoveResourcesAsync(String sourceResourceGroupName, ResourceGr * @return a representation of the deferred computation of this call */ Mono moveResourcesAsync(String sourceResourceGroupName, ResourceGroup targetResourceGroup, - List resourceIds); + List resourceIds); /** * Delete resource and all of its child resources. @@ -228,9 +210,8 @@ Mono moveResourcesAsync(String sourceResourceGroupName, ResourceGroup targ * @param resourceName Resource identity. * @param apiVersion the API version */ - void delete(String resourceGroupName, String resourceProviderNamespace, - String parentResourcePath, String resourceType, String resourceName, String apiVersion); - + void delete(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion); /** * Delete resource and all of its child resources asynchronously. @@ -243,8 +224,8 @@ void delete(String resourceGroupName, String resourceProviderNamespace, * @param apiVersion the API version * @return a representation of the deferred computation of this call */ - Mono deleteAsync(String resourceGroupName, String resourceProviderNamespace, - String parentResourcePath, String resourceType, String resourceName, String apiVersion); + Mono deleteAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, + String resourceType, String resourceName, String apiVersion); /** * Begins deleting a resource from Azure, identifying it by its resource ID. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Location.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Location.java index 6609e14da0e2e..ca000ea27aee2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Location.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Location.java @@ -14,10 +14,7 @@ * An immutable client-side representation of an Azure location. */ @Fluent -public interface Location extends - Indexable, - HasInnerModel, - HasName { +public interface Location extends Indexable, HasInnerModel, HasName { /** * @return the subscription UUID */ diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLock.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLock.java index f42702cf109df..dabdc8df52f16 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLock.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLock.java @@ -23,14 +23,8 @@ * Management lock. */ @Fluent -public interface ManagementLock extends - Indexable, - Refreshable, - Updatable, - HasInnerModel, - HasManager, - HasId, - HasName { +public interface ManagementLock extends Indexable, Refreshable, Updatable, + HasInnerModel, HasManager, HasId, HasName { /** * @return the lock level @@ -55,11 +49,8 @@ public interface ManagementLock extends /** * Container interface for all the definitions. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithLockedResource, - DefinitionStages.WithLevel, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLockedResource, + DefinitionStages.WithLevel, DefinitionStages.WithCreate { } /** @@ -69,8 +60,7 @@ interface DefinitionStages { /** * The first stage of a management lock definition. */ - interface Blank - extends WithLockedResource { + interface Blank extends WithLockedResource { } /** @@ -136,19 +126,14 @@ interface WithLockedResource { * the resource to be created but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - DefinitionStages.WithNotes { + interface WithCreate extends Creatable, DefinitionStages.WithNotes { } } /** * Container interface for all the updates. */ - interface Update extends - Appliable, - UpdateStages.WithLevel, - UpdateStages.WithLockedResource { + interface Update extends Appliable, UpdateStages.WithLevel, UpdateStages.WithLockedResource { } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLocks.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLocks.java index a2a7d884d1e1f..0e371c6ffcb09 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLocks.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagementLocks.java @@ -22,17 +22,11 @@ * Entry point to management lock management. */ @Fluent -public interface ManagementLocks extends - SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface ManagementLocks extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { /** * Lists management locks associated with the specified resource, its resource group diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignment.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignment.java index e9bf7e1461498..5f8357dbf172a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignment.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignment.java @@ -19,12 +19,8 @@ * An immutable client-side representation of an Azure policy assignment. */ @Fluent -public interface PolicyAssignment extends - HasName, - HasId, - Indexable, - Refreshable, - HasInnerModel { +public interface PolicyAssignment + extends HasName, HasId, Indexable, Refreshable, HasInnerModel { /** * @return the policy assignment display name @@ -64,10 +60,8 @@ public interface PolicyAssignment extends /** * Container interface for all the definitions that need to be implemented. */ - interface Definition extends - PolicyAssignment.DefinitionStages.Blank, - PolicyAssignment.DefinitionStages.WithPolicyDefinition, - PolicyAssignment.DefinitionStages.WithCreate { + interface Definition extends PolicyAssignment.DefinitionStages.Blank, + PolicyAssignment.DefinitionStages.WithPolicyDefinition, PolicyAssignment.DefinitionStages.WithCreate { } /** @@ -188,12 +182,8 @@ interface WithEnforcementMode { * assignment in the cloud, but exposing additional optional inputs to * specify. */ - interface WithCreate extends - Creatable, - DefinitionStages.WithDisplayName, - DefinitionStages.WithExcludedScopes, - DefinitionStages.WithParameters, - DefinitionStages.WithEnforcementMode { + interface WithCreate extends Creatable, DefinitionStages.WithDisplayName, + DefinitionStages.WithExcludedScopes, DefinitionStages.WithParameters, DefinitionStages.WithEnforcementMode { } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignments.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignments.java index 9908724a22c7d..7392f55b97e24 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignments.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyAssignments.java @@ -15,12 +15,9 @@ * Entry point to policy assignment management API. */ @Fluent -public interface PolicyAssignments extends - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingById, - SupportsCreating, - SupportsDeletingById { +public interface PolicyAssignments extends SupportsListing, + SupportsListingByResourceGroup, SupportsGettingById, + SupportsCreating, SupportsDeletingById { /** * List policy assignments of the resource. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinition.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinition.java index 5f99a0012303d..57b8d89345085 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinition.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinition.java @@ -20,13 +20,8 @@ * An immutable client-side representation of an Azure policy. */ @Fluent -public interface PolicyDefinition extends - HasName, - HasId, - Indexable, - Refreshable, - Updatable, - HasInnerModel { +public interface PolicyDefinition extends HasName, HasId, Indexable, Refreshable, + Updatable, HasInnerModel { /** * @return the type of the policy definition @@ -71,9 +66,7 @@ public interface PolicyDefinition extends /** * Container interface for all the definitions that need to be implemented. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate { } /** @@ -205,14 +198,9 @@ interface WithMetadata { * policy in the cloud, but exposing additional optional inputs to * specify. */ - interface WithCreate extends - Creatable, - DefinitionStages.WithDescription, - DefinitionStages.WithDisplayName, - DefinitionStages.WithPolicyType, - DefinitionStages.WithParameters, - DefinitionStages.WithMode, - DefinitionStages.WithMetadata { + interface WithCreate extends Creatable, DefinitionStages.WithDescription, + DefinitionStages.WithDisplayName, DefinitionStages.WithPolicyType, DefinitionStages.WithParameters, + DefinitionStages.WithMode, DefinitionStages.WithMetadata { } } @@ -306,13 +294,7 @@ interface WithMetadata { /** * The template for a policy update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - UpdateStages.WithDescription, - UpdateStages.WithDisplayName, - UpdateStages.WithPolicyRule, - UpdateStages.WithPolicyType, - UpdateStages.WithMode, - UpdateStages.WithMetadata { + interface Update extends Appliable, UpdateStages.WithDescription, UpdateStages.WithDisplayName, + UpdateStages.WithPolicyRule, UpdateStages.WithPolicyType, UpdateStages.WithMode, UpdateStages.WithMetadata { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinitions.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinitions.java index 9fc5c10aea348..e0d735ce957ca 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinitions.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/PolicyDefinitions.java @@ -13,9 +13,6 @@ * Entry point to tenant management API. */ @Fluent -public interface PolicyDefinitions extends - SupportsListing, - SupportsGettingByName, - SupportsCreating, - SupportsDeletingByName { +public interface PolicyDefinitions extends SupportsListing, SupportsGettingByName, + SupportsCreating, SupportsDeletingByName { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Provider.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Provider.java index e7d3955932316..9e59511720767 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Provider.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Provider.java @@ -14,9 +14,7 @@ * An immutable client-side representation of an Azure resource provider. */ @Fluent -public interface Provider extends - Indexable, - HasInnerModel { +public interface Provider extends Indexable, HasInnerModel { /** * @return the namespace of the provider diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Providers.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Providers.java index 9c54e866e9293..f8b3509218f0c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Providers.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Providers.java @@ -12,9 +12,7 @@ * Entry point to providers management API. */ @Fluent -public interface Providers extends - SupportsListing, - SupportsGettingByName { +public interface Providers extends SupportsListing, SupportsGettingByName { /** * Unregisters provider from a subscription. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroup.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroup.java index 8df97d114e003..8f3ec4cd505fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroup.java @@ -20,13 +20,8 @@ * An immutable client-side representation of an Azure resource group. */ @Fluent -public interface ResourceGroup extends - Indexable, - Resource, - Refreshable, - HasInnerModel, - Updatable, - HasName { +public interface ResourceGroup extends Indexable, Resource, Refreshable, + HasInnerModel, Updatable, HasName { /** * @return the provisioning state of the resource group @@ -49,13 +44,10 @@ public interface ResourceGroup extends */ Mono exportTemplateAsync(ResourceGroupExportTemplateOptions options); - /** * Container interface for all the definitions that need to be implemented. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate { } /** @@ -73,9 +65,7 @@ interface Blank extends GroupableResource.DefinitionWithRegion { * resource group in the cloud, but exposing additional optional inputs to * specify. */ - interface WithCreate extends - Creatable, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, Resource.DefinitionWithTags { } } @@ -90,8 +80,6 @@ interface UpdateStages { *

* Call {@link Update#apply()} to apply the changes to the resource group in Azure. */ - interface Update extends - Appliable, - Resource.UpdateWithTags { + interface Update extends Appliable, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroupExportResult.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroupExportResult.java index 57386219258d9..af16c72bbfcf9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroupExportResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroupExportResult.java @@ -12,8 +12,7 @@ * An immutable client-side representation of an Azure deployment template export result. */ @Fluent -public interface ResourceGroupExportResult extends - HasInnerModel { +public interface ResourceGroupExportResult extends HasInnerModel { /** * @return the template content diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroups.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroups.java index a29a862ef7c45..3c5523ce474d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceGroups.java @@ -21,15 +21,11 @@ * Entry point to resource group management API. */ @Fluent -public interface ResourceGroups extends - SupportsListing, - SupportsListingByTag, - SupportsGettingByName, - SupportsCreating, - SupportsDeletingByName, - //SupportsBeginDeletingByName, - SupportsBatchCreation, - HasManager { +public interface ResourceGroups + extends SupportsListing, SupportsListingByTag, SupportsGettingByName, + SupportsCreating, SupportsDeletingByName, + //SupportsBeginDeletingByName, + SupportsBatchCreation, HasManager { /** * Checks whether resource group exists. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscription.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscription.java index ef055b7662977..455b09ba375db 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscription.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscription.java @@ -14,9 +14,7 @@ * An immutable client-side representation of an Azure subscription. */ @Fluent -public interface Subscription extends - Indexable, - HasInnerModel { +public interface Subscription extends Indexable, HasInnerModel { /** * @return the UUID of the subscription diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscriptions.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscriptions.java index a8ad44227e647..a08c6f55f0aeb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscriptions.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Subscriptions.java @@ -11,7 +11,5 @@ * Entry point to subscription management API. */ @Fluent -public interface Subscriptions extends - SupportsListing, - SupportsGettingById { +public interface Subscriptions extends SupportsListing, SupportsGettingById { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TagResource.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TagResource.java index ede5a32ef4d42..e1ba8164956a3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TagResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TagResource.java @@ -13,8 +13,7 @@ /** * An immutable client-side representation of an Azure resource with tags. */ -public interface TagResource extends - HasId, HasName, HasInnerModel { +public interface TagResource extends HasId, HasName, HasInnerModel { /** * @return the type of the resource diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Tenants.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Tenants.java index 36bfb7500ccc1..36b9ba1139d68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Tenants.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Tenants.java @@ -10,6 +10,5 @@ * Entry point to tenant management API. */ @Fluent -public interface Tenants extends - SupportsListing { +public interface Tenants extends SupportsListing { } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfOperationResult.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfOperationResult.java index b5b9fc16e6fe9..deaec79d9a299 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfOperationResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfOperationResult.java @@ -14,8 +14,7 @@ * An immutable client-side representation of an Azure deployment What-if operation result. */ @Fluent -public interface WhatIfOperationResult extends - HasInnerModel { +public interface WhatIfOperationResult extends HasInnerModel { /** * @return status of the What-If operation. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/module-info.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/module-info.java index aa5ef8ccc420e..3971c649f46a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/module-info.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/module-info.java @@ -24,99 +24,42 @@ exports com.azure.resourcemanager.resources.fluentcore.utils; // export internal APIs only required for service implementation - exports com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation to - com.azure.resourcemanager.appplatform, - com.azure.resourcemanager.appservice, - com.azure.resourcemanager.authorization, - com.azure.resourcemanager.cdn, - com.azure.resourcemanager.compute, - com.azure.resourcemanager.containerinstance, - com.azure.resourcemanager.containerregistry, - com.azure.resourcemanager.containerservice, - com.azure.resourcemanager.cosmos, - com.azure.resourcemanager.dns, - com.azure.resourcemanager.eventhubs, - com.azure.resourcemanager.keyvault, - com.azure.resourcemanager.monitor, - com.azure.resourcemanager.msi, - com.azure.resourcemanager.network, - com.azure.resourcemanager.privatedns, - com.azure.resourcemanager.redis, - com.azure.resourcemanager.search, - com.azure.resourcemanager.servicebus, - com.azure.resourcemanager.sql, - com.azure.resourcemanager.storage, - com.azure.resourcemanager.trafficmanager; - exports com.azure.resourcemanager.resources.fluentcore.arm.implementation to - com.azure.resourcemanager.appplatform, - com.azure.resourcemanager.appservice, - com.azure.resourcemanager.authorization, - com.azure.resourcemanager.cdn, - com.azure.resourcemanager.compute, - com.azure.resourcemanager.containerinstance, - com.azure.resourcemanager.containerregistry, - com.azure.resourcemanager.containerservice, - com.azure.resourcemanager.cosmos, - com.azure.resourcemanager.dns, - com.azure.resourcemanager.eventhubs, - com.azure.resourcemanager.keyvault, - com.azure.resourcemanager.monitor, - com.azure.resourcemanager.msi, - com.azure.resourcemanager.network, - com.azure.resourcemanager.privatedns, - com.azure.resourcemanager.redis, - com.azure.resourcemanager.search, - com.azure.resourcemanager.servicebus, - com.azure.resourcemanager.sql, - com.azure.resourcemanager.storage, - com.azure.resourcemanager.trafficmanager, - com.azure.resourcemanager; - exports com.azure.resourcemanager.resources.fluentcore.arm.models.implementation to - com.azure.resourcemanager.appplatform, - com.azure.resourcemanager.appservice, - com.azure.resourcemanager.authorization, - com.azure.resourcemanager.cdn, - com.azure.resourcemanager.compute, - com.azure.resourcemanager.containerinstance, - com.azure.resourcemanager.containerregistry, - com.azure.resourcemanager.containerservice, - com.azure.resourcemanager.cosmos, - com.azure.resourcemanager.dns, - com.azure.resourcemanager.eventhubs, - com.azure.resourcemanager.keyvault, - com.azure.resourcemanager.monitor, - com.azure.resourcemanager.msi, - com.azure.resourcemanager.network, - com.azure.resourcemanager.privatedns, - com.azure.resourcemanager.redis, - com.azure.resourcemanager.search, - com.azure.resourcemanager.servicebus, - com.azure.resourcemanager.sql, - com.azure.resourcemanager.storage, - com.azure.resourcemanager.trafficmanager; - exports com.azure.resourcemanager.resources.fluentcore.model.implementation to - com.azure.resourcemanager.appplatform, - com.azure.resourcemanager.appservice, - com.azure.resourcemanager.authorization, - com.azure.resourcemanager.cdn, - com.azure.resourcemanager.compute, - com.azure.resourcemanager.containerinstance, - com.azure.resourcemanager.containerregistry, - com.azure.resourcemanager.containerservice, - com.azure.resourcemanager.cosmos, - com.azure.resourcemanager.dns, - com.azure.resourcemanager.eventhubs, - com.azure.resourcemanager.keyvault, - com.azure.resourcemanager.monitor, - com.azure.resourcemanager.msi, - com.azure.resourcemanager.network, - com.azure.resourcemanager.privatedns, - com.azure.resourcemanager.redis, - com.azure.resourcemanager.search, - com.azure.resourcemanager.servicebus, - com.azure.resourcemanager.sql, - com.azure.resourcemanager.storage, - com.azure.resourcemanager.trafficmanager; + exports com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation + to com.azure.resourcemanager.appplatform, com.azure.resourcemanager.appservice, + com.azure.resourcemanager.authorization, com.azure.resourcemanager.cdn, com.azure.resourcemanager.compute, + com.azure.resourcemanager.containerinstance, com.azure.resourcemanager.containerregistry, + com.azure.resourcemanager.containerservice, com.azure.resourcemanager.cosmos, com.azure.resourcemanager.dns, + com.azure.resourcemanager.eventhubs, com.azure.resourcemanager.keyvault, com.azure.resourcemanager.monitor, + com.azure.resourcemanager.msi, com.azure.resourcemanager.network, com.azure.resourcemanager.privatedns, + com.azure.resourcemanager.redis, com.azure.resourcemanager.search, com.azure.resourcemanager.servicebus, + com.azure.resourcemanager.sql, com.azure.resourcemanager.storage, com.azure.resourcemanager.trafficmanager; + exports com.azure.resourcemanager.resources.fluentcore.arm.implementation to com.azure.resourcemanager.appplatform, + com.azure.resourcemanager.appservice, com.azure.resourcemanager.authorization, com.azure.resourcemanager.cdn, + com.azure.resourcemanager.compute, com.azure.resourcemanager.containerinstance, + com.azure.resourcemanager.containerregistry, com.azure.resourcemanager.containerservice, + com.azure.resourcemanager.cosmos, com.azure.resourcemanager.dns, com.azure.resourcemanager.eventhubs, + com.azure.resourcemanager.keyvault, com.azure.resourcemanager.monitor, com.azure.resourcemanager.msi, + com.azure.resourcemanager.network, com.azure.resourcemanager.privatedns, com.azure.resourcemanager.redis, + com.azure.resourcemanager.search, com.azure.resourcemanager.servicebus, com.azure.resourcemanager.sql, + com.azure.resourcemanager.storage, com.azure.resourcemanager.trafficmanager, com.azure.resourcemanager; + exports com.azure.resourcemanager.resources.fluentcore.arm.models.implementation + to com.azure.resourcemanager.appplatform, com.azure.resourcemanager.appservice, + com.azure.resourcemanager.authorization, com.azure.resourcemanager.cdn, com.azure.resourcemanager.compute, + com.azure.resourcemanager.containerinstance, com.azure.resourcemanager.containerregistry, + com.azure.resourcemanager.containerservice, com.azure.resourcemanager.cosmos, com.azure.resourcemanager.dns, + com.azure.resourcemanager.eventhubs, com.azure.resourcemanager.keyvault, com.azure.resourcemanager.monitor, + com.azure.resourcemanager.msi, com.azure.resourcemanager.network, com.azure.resourcemanager.privatedns, + com.azure.resourcemanager.redis, com.azure.resourcemanager.search, com.azure.resourcemanager.servicebus, + com.azure.resourcemanager.sql, com.azure.resourcemanager.storage, com.azure.resourcemanager.trafficmanager; + exports com.azure.resourcemanager.resources.fluentcore.model.implementation + to com.azure.resourcemanager.appplatform, com.azure.resourcemanager.appservice, + com.azure.resourcemanager.authorization, com.azure.resourcemanager.cdn, com.azure.resourcemanager.compute, + com.azure.resourcemanager.containerinstance, com.azure.resourcemanager.containerregistry, + com.azure.resourcemanager.containerservice, com.azure.resourcemanager.cosmos, com.azure.resourcemanager.dns, + com.azure.resourcemanager.eventhubs, com.azure.resourcemanager.keyvault, com.azure.resourcemanager.monitor, + com.azure.resourcemanager.msi, com.azure.resourcemanager.network, com.azure.resourcemanager.privatedns, + com.azure.resourcemanager.redis, com.azure.resourcemanager.search, com.azure.resourcemanager.servicebus, + com.azure.resourcemanager.sql, com.azure.resourcemanager.storage, com.azure.resourcemanager.trafficmanager; // open packages specifically for azure core opens com.azure.resourcemanager.resources.fluent.models to com.azure.core; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DataBoundariesTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DataBoundariesTests.java index 35b919284f0d4..696a3ddef7e20 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DataBoundariesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DataBoundariesTests.java @@ -13,8 +13,8 @@ public class DataBoundariesTests extends ResourceManagementTest { @Test public void testDataBoundaries() { - DataBoundaryDefinitionInner dataBoundaryDefinition = resourceClient.dataBoundaryClient().getDataBoundaries() - .getTenant(DefaultName.DEFAULT); + DataBoundaryDefinitionInner dataBoundaryDefinition + = resourceClient.dataBoundaryClient().getDataBoundaries().getTenant(DefaultName.DEFAULT); Assertions.assertEquals(DataBoundary.GLOBAL, dataBoundaryDefinition.properties().dataBoundary()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java index f93b7d84e99cd..ea0ba50130496 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java @@ -27,8 +27,10 @@ public class DeploymentStacksTests extends ResourceManagementTest { private String rgName; private static final Region REGION = Region.US_WEST3; - private static final String TEMPLATE_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; - private static final String PARAMETERS_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; + private static final String TEMPLATE_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; + private static final String PARAMETERS_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; private static final String CONTENT_VERSION = "1.0.0.0"; @Override @@ -37,9 +39,7 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile testId = generateRandomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; - resourceGroups.define(rgName) - .withRegion(REGION) - .create(); + resourceGroups.define(rgName).withRegion(REGION).create(); } @Override @@ -51,32 +51,27 @@ protected void cleanUpResources() { public void testDeploymentStacks() { final String dpName = "dpA" + testId; - DeploymentStackInner deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() - .createOrUpdateAtResourceGroup(rgName, dpName, - new DeploymentStackInner() - .withTags(Collections.singletonMap("usage", "test")) - .withTemplateLink( - new DeploymentStacksTemplateLink() - .withUri(TEMPLATE_URI) - .withContentVersion(CONTENT_VERSION)) - .withParametersLink( - new DeploymentStacksParametersLink() - .withUri(PARAMETERS_URI) - .withContentVersion(CONTENT_VERSION)) - .withActionOnUnmanage( - new ActionOnUnmanage() - .withResources(DeploymentStacksDeleteDetachEnum.DELETE) - .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) - .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) - .withDenySettings(new DenySettings() - .withMode(DenySettingsMode.NONE))); + DeploymentStackInner deploymentStack = resourceClient.deploymentStackClient() + .getDeploymentStacks() + .createOrUpdateAtResourceGroup(rgName, dpName, new DeploymentStackInner() + .withTags(Collections.singletonMap("usage", "test")) + .withTemplateLink( + new DeploymentStacksTemplateLink().withUri(TEMPLATE_URI).withContentVersion(CONTENT_VERSION)) + .withParametersLink( + new DeploymentStacksParametersLink().withUri(PARAMETERS_URI).withContentVersion(CONTENT_VERSION)) + .withActionOnUnmanage(new ActionOnUnmanage().withResources(DeploymentStacksDeleteDetachEnum.DELETE) + .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) + .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) + .withDenySettings(new DenySettings().withMode(DenySettingsMode.NONE))); Assertions.assertEquals(dpName, deploymentStack.name()); - Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); + Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, + deploymentStack.actionOnUnmanage().resources()); - deploymentStack = resourceClient.deploymentStackClient().getDeploymentStacks() - .getByResourceGroup(rgName, dpName); + deploymentStack + = resourceClient.deploymentStackClient().getDeploymentStacks().getByResourceGroup(rgName, dpName); Assertions.assertEquals(dpName, deploymentStack.name()); - Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, deploymentStack.actionOnUnmanage().resources()); + Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, + deploymentStack.actionOnUnmanage().resources()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java index f42b64e15f681..8a20530711baa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java @@ -47,11 +47,16 @@ public class DeploymentsTests extends ResourceManagementTest { private String testId; private String rgName; - private static final String TEMPLATE_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; - private static final String BLANK_TEMPLATE_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/100-blank-template/azuredeploy.json"; - private static final String PARAMETERS_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; - private static final String UPDATE_TEMPLATE = "{\"$schema\":\"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\",\"contentVersion\":\"1.0.0.0\",\"parameters\":{\"vnetName\":{\"type\":\"string\",\"defaultValue\":\"VNet2\",\"metadata\":{\"description\":\"VNet name\"}},\"vnetAddressPrefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.0.0/16\",\"metadata\":{\"description\":\"Address prefix\"}},\"subnet1Prefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.0.0/24\",\"metadata\":{\"description\":\"Subnet 1 Prefix\"}},\"subnet1Name\":{\"type\":\"string\",\"defaultValue\":\"Subnet1\",\"metadata\":{\"description\":\"Subnet 1 Name\"}},\"subnet2Prefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.1.0/24\",\"metadata\":{\"description\":\"Subnet 2 Prefix\"}},\"subnet2Name\":{\"type\":\"string\",\"defaultValue\":\"Subnet222\",\"metadata\":{\"description\":\"Subnet 2 Name\"}}},\"variables\":{\"apiVersion\":\"2015-06-15\"},\"resources\":[{\"apiVersion\":\"[variables('apiVersion')]\",\"type\":\"Microsoft.Network/virtualNetworks\",\"name\":\"[parameters('vnetName')]\",\"location\":\"[resourceGroup().location]\",\"properties\":{\"addressSpace\":{\"addressPrefixes\":[\"[parameters('vnetAddressPrefix')]\"]},\"subnets\":[{\"name\":\"[parameters('subnet1Name')]\",\"properties\":{\"addressPrefix\":\"[parameters('subnet1Prefix')]\"}},{\"name\":\"[parameters('subnet2Name')]\",\"properties\":{\"addressPrefix\":\"[parameters('subnet2Prefix')]\"}}]}}]}"; - private static final String UPDATE_PARAMETERS = "{\"vnetAddressPrefix\":{\"value\":\"10.0.0.0/16\"},\"subnet1Name\":{\"value\":\"Subnet1\"},\"subnet1Prefix\":{\"value\":\"10.0.0.0/24\"}}"; + private static final String TEMPLATE_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; + private static final String BLANK_TEMPLATE_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/100-blank-template/azuredeploy.json"; + private static final String PARAMETERS_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; + private static final String UPDATE_TEMPLATE + = "{\"$schema\":\"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\",\"contentVersion\":\"1.0.0.0\",\"parameters\":{\"vnetName\":{\"type\":\"string\",\"defaultValue\":\"VNet2\",\"metadata\":{\"description\":\"VNet name\"}},\"vnetAddressPrefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.0.0/16\",\"metadata\":{\"description\":\"Address prefix\"}},\"subnet1Prefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.0.0/24\",\"metadata\":{\"description\":\"Subnet 1 Prefix\"}},\"subnet1Name\":{\"type\":\"string\",\"defaultValue\":\"Subnet1\",\"metadata\":{\"description\":\"Subnet 1 Name\"}},\"subnet2Prefix\":{\"type\":\"string\",\"defaultValue\":\"10.0.1.0/24\",\"metadata\":{\"description\":\"Subnet 2 Prefix\"}},\"subnet2Name\":{\"type\":\"string\",\"defaultValue\":\"Subnet222\",\"metadata\":{\"description\":\"Subnet 2 Name\"}}},\"variables\":{\"apiVersion\":\"2015-06-15\"},\"resources\":[{\"apiVersion\":\"[variables('apiVersion')]\",\"type\":\"Microsoft.Network/virtualNetworks\",\"name\":\"[parameters('vnetName')]\",\"location\":\"[resourceGroup().location]\",\"properties\":{\"addressSpace\":{\"addressPrefixes\":[\"[parameters('vnetAddressPrefix')]\"]},\"subnets\":[{\"name\":\"[parameters('subnet1Name')]\",\"properties\":{\"addressPrefix\":\"[parameters('subnet1Prefix')]\"}},{\"name\":\"[parameters('subnet2Name')]\",\"properties\":{\"addressPrefix\":\"[parameters('subnet2Prefix')]\"}}]}}]}"; + private static final String UPDATE_PARAMETERS + = "{\"vnetAddressPrefix\":{\"value\":\"10.0.0.0/16\"},\"subnet1Name\":{\"value\":\"Subnet1\"},\"subnet1Prefix\":{\"value\":\"10.0.0.0/24\"}}"; private static final String CONTENT_VERSION = "1.0.0.0"; private static final String NETWORK_API_VERSION = "2020-11-01"; @@ -61,9 +66,7 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile testId = generateRandomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; - resourceGroup = resourceGroups.define(rgName) - .withRegion(Region.US_SOUTH_CENTRAL) - .create(); + resourceGroup = resourceGroups.define(rgName).withRegion(Region.US_SOUTH_CENTRAL).create(); } @Override @@ -99,7 +102,8 @@ public void canDeployVirtualNetwork() throws Exception { Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); - GenericResource generic = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); + GenericResource generic = resourceClient.genericResources() + .get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); Assertions.assertNotNull(generic); // Export Assertions.assertNotNull(deployment.exportTemplate().templateAsJson()); @@ -110,7 +114,8 @@ public void canDeployVirtualNetwork() throws Exception { Assertions.assertEquals(3, TestUtilities.getSize(operations)); DeploymentOperation op = deployment.deploymentOperations().getById(operations.iterator().next().operationId()); Assertions.assertNotNull(op); - resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); + resourceClient.genericResources() + .delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); } @Test @@ -149,7 +154,8 @@ public void canPostDeploymentWhatIfOnResourceGroup() throws Exception { Assertions.assertEquals("Succeeded", result.status()); Assertions.assertEquals(1, result.changes().size()); - resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); + resourceClient.genericResources() + .delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); } @Test @@ -189,7 +195,8 @@ public void canPostDeploymentWhatIfOnSubscription() throws Exception { Assertions.assertEquals("Succeeded", result.status()); Assertions.assertEquals(0, result.changes().size()); - resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); + resourceClient.genericResources() + .delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION); } @Test @@ -211,7 +218,8 @@ public void canCancelVirtualNetworkDeployment() throws Exception { deployment.cancel(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals("Canceled", deployment.provisioningState()); - Assertions.assertFalse(resourceClient.genericResources().checkExistence(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION)); + Assertions.assertFalse(resourceClient.genericResources() + .checkExistence(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", NETWORK_API_VERSION)); } @Test @@ -243,9 +251,11 @@ public void canUpdateVirtualNetworkDeployment() throws Exception { deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(DeploymentMode.INCREMENTAL, deployment.mode()); Assertions.assertEquals("Succeeded", deployment.provisioningState()); - GenericResource genericVnet = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", NETWORK_API_VERSION); + GenericResource genericVnet = resourceClient.genericResources() + .get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", NETWORK_API_VERSION); Assertions.assertNotNull(genericVnet); - resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", NETWORK_API_VERSION); + resourceClient.genericResources() + .delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", NETWORK_API_VERSION); } finally { resourceClient.deployments().deleteByResourceGroup(rgName, dp); } @@ -277,9 +287,8 @@ public void canDeployVirtualNetworkSyncPoll() throws Exception { PollResponse pollResponse = acceptedDeployment.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); - delayInMills = pollResponse.getRetryAfter() == null - ? defaultDelayInMillis - : pollResponse.getRetryAfter().toMillis(); + delayInMills + = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); Deployment deployment = acceptedDeployment.getFinalResult(); @@ -308,7 +317,8 @@ public void canDeployVirtualNetworkSyncPoll() throws Exception { public void canDeployVirtualNetworkSyncPollWithFailure() throws Exception { final long defaultDelayInMillis = 10 * 1000; - final String templateJson = "{ \"$schema\": \"https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#\", \"contentVersion\": \"1.0.0.0\", \"resources\": [ { \"type\": \"Microsoft.Storage/storageAccounts\", \"apiVersion\": \"2019-04-01\", \"name\": \"satestnameconflict\", \"location\": \"eastus\", \"sku\": { \"name\": \"Standard_LRS\" }, \"kind\": \"StorageV2\", \"properties\": { \"supportsHttpsTrafficOnly\": true } } ] }"; + final String templateJson + = "{ \"$schema\": \"https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#\", \"contentVersion\": \"1.0.0.0\", \"resources\": [ { \"type\": \"Microsoft.Storage/storageAccounts\", \"apiVersion\": \"2019-04-01\", \"name\": \"satestnameconflict\", \"location\": \"eastus\", \"sku\": { \"name\": \"Standard_LRS\" }, \"kind\": \"StorageV2\", \"properties\": { \"supportsHttpsTrafficOnly\": true } } ] }"; final String dp = "dpE" + testId; // Begin create @@ -331,9 +341,8 @@ public void canDeployVirtualNetworkSyncPollWithFailure() throws Exception { PollResponse pollResponse = acceptedDeployment.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); - delayInMills = pollResponse.getRetryAfter() == null - ? defaultDelayInMillis - : pollResponse.getRetryAfter().toMillis(); + delayInMills + = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); Deployment deployment = acceptedDeployment.getFinalResult(); @@ -386,13 +395,14 @@ public void canDeployVirtualNetworkSyncPollWithFailure() throws Exception { deployment = resourceClient.deployments().getByResourceGroup(newRgName, dp2); Assertions.assertEquals("Failed", deployment.provisioningState()); PagedIterable operations = deployment.deploymentOperations().list(); - Optional failedOperation = operations.stream() - .filter(o -> "Failed".equalsIgnoreCase(o.provisioningState())).findFirst(); + Optional failedOperation + = operations.stream().filter(o -> "Failed".equalsIgnoreCase(o.provisioningState())).findFirst(); Assertions.assertTrue(failedOperation.isPresent()); Assertions.assertEquals("Conflict", failedOperation.get().statusCode()); // check poll result again, should stay failed - Assertions.assertEquals(LongRunningOperationStatus.FAILED, acceptedDeployment.getSyncPoller().poll().getStatus()); + Assertions.assertEquals(LongRunningOperationStatus.FAILED, + acceptedDeployment.getSyncPoller().poll().getStatus()); exceptionOnFinalResult = false; try { deployment = acceptedDeployment.getFinalResult(); @@ -426,11 +436,12 @@ public void canGetErrorWhenDeploymentFail() throws Exception { .create(); } catch (ManagementException deploymentException) { // verify ManagementException - Assertions.assertTrue(deploymentException.getValue().getDetails().stream() + Assertions.assertTrue(deploymentException.getValue() + .getDetails() + .stream() .anyMatch(detail -> detail.getMessage().contains("Subnet2"))); - Deployment failedDeployment = resourceClient.deployments() - .getByResourceGroup(rgName, dpName); + Deployment failedDeployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); deploymentError = failedDeployment.error(); // verify deployment operations @@ -441,8 +452,8 @@ public void canGetErrorWhenDeploymentFail() throws Exception { } // verify Deployment.error() Assertions.assertNotNull(deploymentError); - Assertions.assertTrue(deploymentError.getDetails().stream() - .anyMatch(detail -> detail.getMessage().contains("Subnet2"))); + Assertions.assertTrue( + deploymentError.getDetails().stream().anyMatch(detail -> detail.getMessage().contains("Subnet2"))); } @Test @@ -454,8 +465,7 @@ public void canDeployVirtualNetworkWithContext() { try { String correlationRequestId = generateRandomUuid(); LOGGER.log(LogLevel.VERBOSE, () -> "x-ms-correlation-request-id: " + correlationRequestId); - Context context = new Context( - AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, + Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders().set("x-ms-correlation-request-id", correlationRequestId)); // with context @@ -485,7 +495,8 @@ public void canDeployVirtualNetworkWithContext() { .withMode(DeploymentMode.COMPLETE) .create(); - Assertions.assertEquals(correlationRequestId, deployment1.getActivationResponse().getValue().innerModel().properties().correlationId()); + Assertions.assertEquals(correlationRequestId, + deployment1.getActivationResponse().getValue().innerModel().properties().correlationId()); Assertions.assertEquals(correlationRequestId, deployment2.innerModel().properties().correlationId()); Assertions.assertNotEquals(correlationRequestId, deployment3.innerModel().properties().correlationId()); } finally { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/FeaturesTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/FeaturesTests.java index 7688d8d736392..9d9f49f120dc7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/FeaturesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/FeaturesTests.java @@ -20,7 +20,7 @@ public void canListAndRegisterFeature() { features.stream() .filter(f -> "NotRegistered".equals(f.state())) .findFirst() - .ifPresent(feature -> resourceClient.features() - .register(feature.resourceProviderName(), feature.featureName())); + .ifPresent( + feature -> resourceClient.features().register(feature.resourceProviderName(), feature.featureName())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/GenericResourcesTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/GenericResourcesTests.java index 367e44b059751..916c4bf0dd30a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/GenericResourcesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/GenericResourcesTests.java @@ -53,12 +53,8 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile super.initializeClients(httpPipeline, profile); resourceGroups = resourceClient.resourceGroups(); genericResources = resourceClient.genericResources(); - resourceGroups.define(rgName) - .withRegion(Region.US_EAST) - .create(); - resourceGroups.define(newRgName) - .withRegion(Region.US_SOUTH_CENTRAL) - .create(); + resourceGroups.define(rgName).withRegion(Region.US_EAST).create(); + resourceGroups.define(newRgName).withRegion(Region.US_SOUTH_CENTRAL).create(); } @Override @@ -72,14 +68,15 @@ public void canCreateUpdateMoveResource() throws Exception { final String resourceName = "rs" + testId; // Create GenericResource resource = genericResources.define(resourceName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withResourceType("sites") - .withProviderNamespace("Microsoft.Web") - .withoutPlan() - .withParentResourcePath("") - .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", Object.class, SerializerEncoding.JSON)) - .create(); + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withResourceType("sites") + .withProviderNamespace("Microsoft.Web") + .withoutPlan() + .withParentResourcePath("") + .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", + Object.class, SerializerEncoding.JSON)) + .create(); //List PagedIterable resourceList = genericResources.listByResourceGroup(rgName); boolean found = false; @@ -92,19 +89,24 @@ public void canCreateUpdateMoveResource() throws Exception { } Assertions.assertTrue(found); // Get - Assertions.assertNotNull(genericResources.get(rgName, resource.resourceProviderNamespace(), resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); + Assertions.assertNotNull(genericResources.get(rgName, resource.resourceProviderNamespace(), + resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); // Move genericResources.moveResources(rgName, resourceGroups.getByName(newRgName), Arrays.asList(resource.id())); - Assertions.assertFalse(genericResources.checkExistence(rgName, resource.resourceProviderNamespace(), resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); - resource = genericResources.get(newRgName, resource.resourceProviderNamespace(), resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion()); + Assertions.assertFalse(genericResources.checkExistence(rgName, resource.resourceProviderNamespace(), + resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); + resource = genericResources.get(newRgName, resource.resourceProviderNamespace(), resource.parentResourcePath(), + resource.resourceType(), resource.name(), resource.apiVersion()); Assertions.assertNotNull(resource); // Update resource.update() - .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Dynamic\"}", Object.class, SerializerEncoding.JSON)) - .apply(); + .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Dynamic\"}", + Object.class, SerializerEncoding.JSON)) + .apply(); // Delete genericResources.deleteById(resource.id()); - Assertions.assertFalse(genericResources.checkExistence(newRgName, resource.resourceProviderNamespace(), resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); + Assertions.assertFalse(genericResources.checkExistence(newRgName, resource.resourceProviderNamespace(), + resource.parentResourcePath(), resource.resourceType(), resource.name(), resource.apiVersion())); Assertions.assertFalse(genericResources.checkExistenceById(resource.id())); } @@ -139,7 +141,8 @@ public void canValidateMoveResources() throws Exception { // validate fail as name conflict Assertions.assertThrows(ManagementException.class, () -> { - genericResources.validateMoveResources(rgName, targetResourceGroup, Collections.singletonList(resource.id())); + genericResources.validateMoveResources(rgName, targetResourceGroup, + Collections.singletonList(resource.id())); }); final String resourceName3 = "rs2" + testId; @@ -153,7 +156,8 @@ public void canValidateMoveResources() throws Exception { // validate fail as managed identity does not support move Assertions.assertThrows(ManagementException.class, () -> { - genericResources.validateMoveResources(rgName, targetResourceGroup, Collections.singletonList(resource3.id())); + genericResources.validateMoveResources(rgName, targetResourceGroup, + Collections.singletonList(resource3.id())); }); } @@ -170,7 +174,8 @@ public void canCreateDeleteResourceSyncPoll() throws Exception { .withProviderNamespace("Microsoft.Web") .withoutPlan() .withParentResourcePath("") - .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", Object.class, SerializerEncoding.JSON)) + .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", + Object.class, SerializerEncoding.JSON)) .beginCreate(); LongRunningOperationStatus pollStatus = acceptedResource.getActivationResponse().getStatus(); @@ -182,18 +187,18 @@ public void canCreateDeleteResourceSyncPoll() throws Exception { PollResponse pollResponse = acceptedResource.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); - delayInMills = pollResponse.getRetryAfter() == null - ? defaultDelayInMillis - : pollResponse.getRetryAfter().toMillis(); + delayInMills + = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); GenericResource resource = acceptedResource.getFinalResult(); Assertions.assertNotNull(resource.id()); Assertions.assertEquals(resourceName, ResourceUtils.nameFromResourceId(resource.id())); - PagedIterable resources = - genericResources.manager().serviceClient().getResources() - .listByResourceGroup(rgName, null, "provisioningState", null, Context.NONE); + PagedIterable resources = genericResources.manager() + .serviceClient() + .getResources() + .listByResourceGroup(rgName, null, "provisioningState", null, Context.NONE); Optional resourceOpt = resources.stream().filter(r -> resourceName.equals(r.name())).findFirst(); Assertions.assertTrue(resourceOpt.isPresent()); @@ -211,18 +216,22 @@ public void canCreateUpdateKindSkuIdentity() throws Exception { final String resourceName = "rs" + testId; final String apiVersion = "2021-01-01"; - GenericResource storageResource = resourceClient.genericResources().define(resourceName) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withResourceType("storageAccounts") - .withProviderNamespace("Microsoft.Storage") - .withoutPlan() - .withKind("Storage") - .withSku(new Sku().withName("Standard_LRS")) - .withIdentity(new Identity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)) - .withProperties(serializerAdapter.deserialize("{\"minimumTlsVersion\": \"TLS1_2\", \"supportsHttpsTrafficOnly\": true}", Object.class, SerializerEncoding.JSON)) - .withApiVersion(apiVersion) - .create(); + GenericResource storageResource + = resourceClient.genericResources() + .define(resourceName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withResourceType("storageAccounts") + .withProviderNamespace("Microsoft.Storage") + .withoutPlan() + .withKind("Storage") + .withSku(new Sku().withName("Standard_LRS")) + .withIdentity(new Identity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)) + .withProperties(serializerAdapter.deserialize( + "{\"minimumTlsVersion\": \"TLS1_2\", \"supportsHttpsTrafficOnly\": true}", Object.class, + SerializerEncoding.JSON)) + .withApiVersion(apiVersion) + .create(); Assertions.assertEquals("Storage", storageResource.kind()); Assertions.assertEquals("Standard_LRS", storageResource.sku().name()); Assertions.assertNotNull(storageResource.identity()); @@ -230,18 +239,11 @@ public void canCreateUpdateKindSkuIdentity() throws Exception { Assertions.assertNotNull(storageResource.identity().principalId()); Assertions.assertNotNull(storageResource.identity().tenantId()); - storageResource.update() - .withKind("StorageV2") - .withoutIdentity() - .withApiVersion(apiVersion) - .apply(); + storageResource.update().withKind("StorageV2").withoutIdentity().withApiVersion(apiVersion).apply(); Assertions.assertEquals("StorageV2", storageResource.kind()); Assertions.assertEquals(ResourceIdentityType.NONE, storageResource.identity().type()); - storageResource.update() - .withSku(new Sku().withName("Standard_RAGRS")) - .withApiVersion(apiVersion) - .apply(); + storageResource.update().withSku(new Sku().withName("Standard_RAGRS")).withApiVersion(apiVersion).apply(); Assertions.assertEquals("Standard_RAGRS", storageResource.sku().name()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/HttpPipelineProviderTest.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/HttpPipelineProviderTest.java index db2f5dafa5e2e..5de5232dd2377 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/HttpPipelineProviderTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/HttpPipelineProviderTest.java @@ -35,7 +35,8 @@ public class HttpPipelineProviderTest { static class BeforeRetryPolicy implements HttpPipelinePolicy { @Override - public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + public Mono process(HttpPipelineCallContext httpPipelineCallContext, + HttpPipelineNextPolicy httpPipelineNextPolicy) { return httpPipelineNextPolicy.process(); } @@ -48,7 +49,8 @@ public HttpPipelinePosition getPipelinePosition() { static class AfterRetryPolicy implements HttpPipelinePolicy { @Override - public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + public Mono process(HttpPipelineCallContext httpPipelineCallContext, + HttpPipelineNextPolicy httpPipelineNextPolicy) { return httpPipelineNextPolicy.process(); } } @@ -56,18 +58,15 @@ public Mono process(HttpPipelineCallContext httpPipelineCallContex @Test public void addPolicyTest() { //provide before and after retry policy - HttpPipeline pipeline = HttpPipelineProvider.buildHttpPipeline( - Mockito.mock(TokenCredential.class), - new AzureProfile(new AzureEnvironment(new HashMap<>())), - new String[0], new HttpLogOptions(), - new Configuration(), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - new ArrayList() {{ - this.add(new AfterRetryPolicy()); - this.add(new BeforeRetryPolicy()); - }}, - new MockHttpClient() - ); + HttpPipeline pipeline = HttpPipelineProvider.buildHttpPipeline(Mockito.mock(TokenCredential.class), + new AzureProfile(new AzureEnvironment(new HashMap<>())), new String[0], new HttpLogOptions(), + new Configuration(), new RetryPolicy("Retry-After", ChronoUnit.SECONDS), + new ArrayList() { + { + this.add(new AfterRetryPolicy()); + this.add(new BeforeRetryPolicy()); + } + }, new MockHttpClient()); int retryIndex = findRetryPolicyIndex(pipeline); int beforeRetryIndex = findBeforeRetryIndex(pipeline); int afterRetryIndex = findAfterRetryIndex(pipeline); @@ -79,18 +78,14 @@ public void addPolicyTest() { Assertions.assertTrue(afterRetryIndex > retryIndex, "afterRetryIndex <= retryIndex"); //only provide after - pipeline = HttpPipelineProvider.buildHttpPipeline( - Mockito.mock(TokenCredential.class), - new AzureProfile(new AzureEnvironment(new HashMap<>())), - new String[0], - new HttpLogOptions(), - new Configuration(), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - new ArrayList() {{ - this.add(new AfterRetryPolicy()); - }}, - new MockHttpClient() - ); + pipeline = HttpPipelineProvider.buildHttpPipeline(Mockito.mock(TokenCredential.class), + new AzureProfile(new AzureEnvironment(new HashMap<>())), new String[0], new HttpLogOptions(), + new Configuration(), new RetryPolicy("Retry-After", ChronoUnit.SECONDS), + new ArrayList() { + { + this.add(new AfterRetryPolicy()); + } + }, new MockHttpClient()); retryIndex = findRetryPolicyIndex(pipeline); beforeRetryIndex = findBeforeRetryIndex(pipeline); afterRetryIndex = findAfterRetryIndex(pipeline); @@ -101,18 +96,14 @@ public void addPolicyTest() { Assertions.assertTrue(afterRetryIndex > retryIndex, "afterRetryIndex <= retryIndex"); //only provide before - pipeline = HttpPipelineProvider.buildHttpPipeline( - Mockito.mock(TokenCredential.class), - new AzureProfile(new AzureEnvironment(new HashMap<>())), - new String[0], - new HttpLogOptions(), - new Configuration(), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - new ArrayList() {{ - this.add(new BeforeRetryPolicy()); - }}, - new MockHttpClient() - ); + pipeline = HttpPipelineProvider.buildHttpPipeline(Mockito.mock(TokenCredential.class), + new AzureProfile(new AzureEnvironment(new HashMap<>())), new String[0], new HttpLogOptions(), + new Configuration(), new RetryPolicy("Retry-After", ChronoUnit.SECONDS), + new ArrayList() { + { + this.add(new BeforeRetryPolicy()); + } + }, new MockHttpClient()); retryIndex = findRetryPolicyIndex(pipeline); beforeRetryIndex = findBeforeRetryIndex(pipeline); afterRetryIndex = findAfterRetryIndex(pipeline); @@ -123,16 +114,9 @@ public void addPolicyTest() { Assertions.assertTrue(beforeRetryIndex < retryIndex, "beforeRetryIndex >= retryIndex"); //provide none - pipeline = HttpPipelineProvider.buildHttpPipeline( - Mockito.mock(TokenCredential.class), - new AzureProfile(new AzureEnvironment(new HashMap<>())), - new String[0], - new HttpLogOptions(), - new Configuration(), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - null, - new MockHttpClient() - ); + pipeline = HttpPipelineProvider.buildHttpPipeline(Mockito.mock(TokenCredential.class), + new AzureProfile(new AzureEnvironment(new HashMap<>())), new String[0], new HttpLogOptions(), + new Configuration(), new RetryPolicy("Retry-After", ChronoUnit.SECONDS), null, new MockHttpClient()); } private int findRetryPolicyIndex(HttpPipeline pipeline) { @@ -147,7 +131,6 @@ private int findAfterRetryIndex(HttpPipeline pipeline) { return findPolicyIndex(pipeline, AfterRetryPolicy.class); } - private int findPolicyIndex(HttpPipeline pipeline, Class policyClazz) { int policyCount = pipeline.getPolicyCount(); for (int i = 0; i < policyCount; i++) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/LocksTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/LocksTests.java index 7d7921089333e..59ae1fb2ab61d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/LocksTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/LocksTests.java @@ -19,11 +19,11 @@ public void canCreateLock() { String rgName = generateRandomResourceName("rgloc", 15); String lockName = generateRandomResourceName("lock", 15); - ResourceGroup resourceGroup = resourceClient.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + ResourceGroup resourceGroup + = resourceClient.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); - ManagementLock lock = resourceClient.managementLocks().define(lockName) + ManagementLock lock = resourceClient.managementLocks() + .define(lockName) .withLockedResourceGroup(resourceGroup) .withLevel(LockLevel.CAN_NOT_DELETE) .create(); @@ -49,11 +49,11 @@ public void canCreateUpdateLock() { String rgName = generateRandomResourceName("rgloc", 15); String lockName = generateRandomResourceName("lock", 15); - ResourceGroup resourceGroup = resourceClient.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + ResourceGroup resourceGroup + = resourceClient.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); - ManagementLock lock = resourceClient.managementLocks().define(lockName) + ManagementLock lock = resourceClient.managementLocks() + .define(lockName) .withLockedResourceGroup(resourceGroup) .withLevel(LockLevel.CAN_NOT_DELETE) .create(); @@ -72,10 +72,7 @@ public void canCreateUpdateLock() { } Assertions.assertNotNull(foundLock); - foundLock.update() - .withLockedResourceGroup(rgName) - .withLevel(LockLevel.READ_ONLY) - .apply(); + foundLock.update().withLockedResourceGroup(rgName).withLevel(LockLevel.READ_ONLY).apply(); ManagementLock updatedLock = resourceClient.managementLocks().getByResourceGroup(rgName, lockName); Assertions.assertNotNull(updatedLock); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/PolicyTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/PolicyTests.java index f4ee5ae542fd9..ca5b1d5dd086d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/PolicyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/PolicyTests.java @@ -26,8 +26,10 @@ import java.util.Map; public class PolicyTests extends ResourceManagementTest { - private String policyRule = "{\"if\":{\"not\":{\"field\":\"location\",\"in\":[\"southcentralus\",\"westeurope\"]}},\"then\":{\"effect\":\"deny\"}}"; - private String policyRule2 = "{\"if\":{\"not\":{\"field\":\"name\",\"like\":\"[concat(parameters('prefix'),'*',parameters('suffix'))]\"}},\"then\":{\"effect\":\"deny\"}}"; + private String policyRule + = "{\"if\":{\"not\":{\"field\":\"location\",\"in\":[\"southcentralus\",\"westeurope\"]}},\"then\":{\"effect\":\"deny\"}}"; + private String policyRule2 + = "{\"if\":{\"not\":{\"field\":\"name\",\"like\":\"[concat(parameters('prefix'),'*',parameters('suffix'))]\"}},\"then\":{\"effect\":\"deny\"}}"; private final SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); @Override @@ -47,14 +49,15 @@ public void canCRUDPolicyDefinition() throws Exception { metadata.put("category", "Compute"); // Create - PolicyDefinition definition = resourceClient.policyDefinitions().define(policyName) - .withPolicyRuleJson(policyRule) - .withPolicyType(PolicyType.CUSTOM) - .withDisplayName(displayName) - .withDescription("This is my policy") - .withMode("All") - .withMetadata(metadata) - .create(); + PolicyDefinition definition = resourceClient.policyDefinitions() + .define(policyName) + .withPolicyRuleJson(policyRule) + .withPolicyType(PolicyType.CUSTOM) + .withDisplayName(displayName) + .withDescription("This is my policy") + .withMode("All") + .withMetadata(metadata) + .create(); Assertions.assertEquals(policyName, definition.name()); Assertions.assertEquals(PolicyType.CUSTOM, definition.policyType()); Assertions.assertEquals(displayName, definition.displayName()); @@ -102,21 +105,21 @@ public void canCRUDPolicyAssignment() throws Exception { String resourceName = generateRandomResourceName("webassignment", 15); try { // Create definition - PolicyDefinition definition = resourceClient.policyDefinitions().define(policyName) - .withPolicyRuleJson(policyRule) - .withPolicyType(PolicyType.CUSTOM) - .withDisplayName(displayName) - .withDescription("This is my policy") - .create(); + PolicyDefinition definition = resourceClient.policyDefinitions() + .define(policyName) + .withPolicyRuleJson(policyRule) + .withPolicyType(PolicyType.CUSTOM) + .withDisplayName(displayName) + .withDescription("This is my policy") + .create(); // Create assignment - ResourceGroup group = resourceClient.resourceGroups().define(rgName) - .withRegion(Region.UK_WEST) - .create(); - PolicyAssignment assignment1 = resourceClient.policyAssignments().define(assignmentName1) - .forResourceGroup(group) - .withPolicyDefinition(definition) - .withDisplayName("My Assignment") - .create(); + ResourceGroup group = resourceClient.resourceGroups().define(rgName).withRegion(Region.UK_WEST).create(); + PolicyAssignment assignment1 = resourceClient.policyAssignments() + .define(assignmentName1) + .forResourceGroup(group) + .withPolicyDefinition(definition) + .withDisplayName("My Assignment") + .create(); Assertions.assertNotNull(assignment1); Assertions.assertEquals("My Assignment", assignment1.displayName()); @@ -126,27 +129,31 @@ public void canCRUDPolicyAssignment() throws Exception { Assertions.assertEquals(EnforcementMode.DEFAULT, assignment1.enforcementMode()); Assertions.assertEquals(0, assignment1.parameters().size()); - GenericResource resource = resourceClient.genericResources().define(resourceName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(group) - .withResourceType("sites") - .withProviderNamespace("Microsoft.Web") - .withoutPlan() - .withApiVersion("2020-12-01") - .withParentResourcePath("") - .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", Object.class, SerializerEncoding.JSON)) - .create(); - - PolicyAssignment assignment2 = resourceClient.policyAssignments().define(assignmentName2) - .forResource(resource) - .withPolicyDefinition(definition) - .withDisplayName("My Assignment 2") - .create(); + GenericResource resource = resourceClient.genericResources() + .define(resourceName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(group) + .withResourceType("sites") + .withProviderNamespace("Microsoft.Web") + .withoutPlan() + .withApiVersion("2020-12-01") + .withParentResourcePath("") + .withProperties(serializerAdapter.deserialize("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}", + Object.class, SerializerEncoding.JSON)) + .create(); + + PolicyAssignment assignment2 = resourceClient.policyAssignments() + .define(assignmentName2) + .forResource(resource) + .withPolicyDefinition(definition) + .withDisplayName("My Assignment 2") + .create(); Assertions.assertNotNull(assignment2); Assertions.assertEquals("My Assignment 2", assignment2.displayName()); - PagedIterable assignments = resourceClient.policyAssignments().listByResourceGroup(rgName); + PagedIterable assignments + = resourceClient.policyAssignments().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.getSize(assignments) >= 2); boolean foundAssignment1 = false; @@ -162,15 +169,18 @@ public void canCRUDPolicyAssignment() throws Exception { Assertions.assertTrue(foundAssignment2); // definition and assignment with parameters - PolicyDefinition definition2 = resourceClient.policyDefinitions().define(policyName) + PolicyDefinition definition2 = resourceClient.policyDefinitions() + .define(policyName) .withPolicyRuleJson(policyRule2) .withPolicyType(PolicyType.CUSTOM) .withParameter("prefix", ParameterType.STRING, "dept") - .withParameter("suffix", new ParameterDefinitionsValue().withType(ParameterType.STRING).withDefaultValue("-US")) + .withParameter("suffix", + new ParameterDefinitionsValue().withType(ParameterType.STRING).withDefaultValue("-US")) .withDisplayName(displayName) .withDescription("Test policy") .create(); - PolicyAssignment assignment3 = resourceClient.policyAssignments().define(assignmentName3) + PolicyAssignment assignment3 = resourceClient.policyAssignments() + .define(assignmentName3) .forResourceGroup(group) .withPolicyDefinition(definition2) .withExcludedScope(resource.id()) diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java index 66eda20dc0590..9914dcab68569 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java @@ -35,7 +35,9 @@ public void canUnregisterAndRegisterProvider() { Assertions.assertFalse(resourceTypes.isEmpty()); Assertions.assertNotNull(provider); if ("Registered".equals(provider.registrationState())) { - Assertions.fail(String.format("Provider '%s' already registered, please test with a provider that not currently registered.", providerNamespace)); + Assertions.fail(String.format( + "Provider '%s' already registered, please test with a provider that not currently registered.", + providerNamespace)); } // register diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceGroupsTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceGroupsTests.java index 1ee8b144a4721..9cb76bd01f196 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceGroupsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceGroupsTests.java @@ -26,10 +26,10 @@ public void canCreateResourceGroup() throws Exception { Region region = Region.US_SOUTH_CENTRAL; // Create resourceGroups.define(rgName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withTag("department", "finance") - .withTag("tagname", "tagvalue") - .create(); + .withRegion(Region.US_SOUTH_CENTRAL) + .withTag("department", "finance") + .withTag("tagname", "tagvalue") + .create(); // List ResourceGroup groupResult = null; for (ResourceGroup rg : resourceGroups.listByTag("department", "finance")) { @@ -51,9 +51,7 @@ public void canCreateResourceGroup() throws Exception { Assertions.assertNotNull(getGroup); Assertions.assertEquals(rgName, getGroup.name()); // Update - ResourceGroup updatedGroup = getGroup.update() - .withTag("tag1", "value1") - .apply(); + ResourceGroup updatedGroup = getGroup.update().withTag("tag1", "value1").apply(); Assertions.assertEquals("value1", updatedGroup.tags().get("tag1")); Assertions.assertTrue(region.name().equalsIgnoreCase(getGroup.regionName())); // Delete diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceIdTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceIdTests.java index 4c82d8d6ea4fb..d1fbaa7a87f3b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceIdTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceIdTests.java @@ -16,10 +16,10 @@ */ public class ResourceIdTests { - @Test public void resourceIdForTopLevelResourceWorksFine() { - ResourceId resourceId = ResourceId.fromString("/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something"); + ResourceId resourceId = ResourceId.fromString( + "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something"); Assertions.assertEquals(resourceId.name(), "something"); Assertions.assertEquals(resourceId.subscriptionId(), "9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef"); @@ -32,7 +32,8 @@ public void resourceIdForTopLevelResourceWorksFine() { @Test public void resourceIdForChildLevelResourceWorksFine() { - ResourceId resourceId = ResourceId.fromString("/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something/someChildType/childName"); + ResourceId resourceId = ResourceId.fromString( + "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something/someChildType/childName"); Assertions.assertEquals(resourceId.name(), "childName"); Assertions.assertEquals(resourceId.subscriptionId(), "9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef"); @@ -52,21 +53,24 @@ public void resourceIdForChildLevelResourceWorksFine() { @Test public void resourceIdForGrandChildLevelResourceWorksFine() { - ResourceId resourceId = ResourceId.fromString("/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something/someChildType/childName/grandChildType/grandChild"); + ResourceId resourceId = ResourceId.fromString( + "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/resourceGroupName/providers/Microsoft.Network/applicationGateways/something/someChildType/childName/grandChildType/grandChild"); Assertions.assertEquals(resourceId.name(), "grandChild"); Assertions.assertEquals(resourceId.subscriptionId(), "9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef"); Assertions.assertEquals(resourceId.resourceGroupName(), "resourceGroupName"); Assertions.assertEquals(resourceId.providerNamespace(), "Microsoft.Network"); Assertions.assertEquals(resourceId.resourceType(), "grandChildType"); - Assertions.assertEquals(resourceId.fullResourceType(), "Microsoft.Network/applicationGateways/someChildType/grandChildType"); + Assertions.assertEquals(resourceId.fullResourceType(), + "Microsoft.Network/applicationGateways/someChildType/grandChildType"); Assertions.assertNotNull(resourceId.parent()); Assertions.assertEquals(resourceId.parent().name(), "childName"); Assertions.assertEquals(resourceId.parent().subscriptionId(), "9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef"); Assertions.assertEquals(resourceId.parent().resourceGroupName(), "resourceGroupName"); Assertions.assertEquals(resourceId.parent().providerNamespace(), "Microsoft.Network"); Assertions.assertEquals(resourceId.parent().resourceType(), "someChildType"); - Assertions.assertEquals(resourceId.parent().fullResourceType(), "Microsoft.Network/applicationGateways/someChildType"); + Assertions.assertEquals(resourceId.parent().fullResourceType(), + "Microsoft.Network/applicationGateways/someChildType"); Assertions.assertNotNull(resourceId.parent().parent()); Assertions.assertEquals(resourceId.parent().parent().name(), "something"); Assertions.assertEquals(resourceId.parent().parent().subscriptionId(), "9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef"); @@ -74,16 +78,20 @@ public void resourceIdForGrandChildLevelResourceWorksFine() { Assertions.assertEquals(resourceId.parent().parent().name(), "something"); Assertions.assertEquals(resourceId.parent().parent().providerNamespace(), "Microsoft.Network"); Assertions.assertEquals(resourceId.parent().parent().resourceType(), "applicationGateways"); - Assertions.assertEquals(resourceId.parent().parent().fullResourceType(), "Microsoft.Network/applicationGateways"); + Assertions.assertEquals(resourceId.parent().parent().fullResourceType(), + "Microsoft.Network/applicationGateways"); } @Test public void encodeResourceIdTest() throws URISyntaxException { // white spaces are not allowed to appear in URI - String resourceId = "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/%20my_resourcegroup/providers/Microsoft.Network/applicationGateways/my application gateway/someChildType/request routing,rule+/grandChildType/grandChild"; - Assertions.assertThrows(URISyntaxException.class, () -> new URI(String.format("http://localhost:3000%s", resourceId))); + String resourceId + = "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/%20my_resourcegroup/providers/Microsoft.Network/applicationGateways/my application gateway/someChildType/request routing,rule+/grandChildType/grandChild"; + Assertions.assertThrows(URISyntaxException.class, + () -> new URI(String.format("http://localhost:3000%s", resourceId))); - String expectedEncodedResourceId = "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/%20my_resourcegroup/providers/Microsoft.Network/applicationGateways/my%20application%20gateway/someChildType/request%20routing,rule+/grandChildType/grandChild"; + String expectedEncodedResourceId + = "/subscriptions/9657ab5d-4a4a-4fd2-ae7a-4cd9fbd030ef/resourceGroups/%20my_resourcegroup/providers/Microsoft.Network/applicationGateways/my%20application%20gateway/someChildType/request%20routing,rule+/grandChildType/grandChild"; new URI(String.format("http://localhost:3000%s", expectedEncodedResourceId)); Assertions.assertEquals(expectedEncodedResourceId, ResourceUtils.encodeResourceId(resourceId)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceManagementTest.java index e6b3cf8477fc5..3cef7ba7459ca 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ResourceManagementTest.java @@ -25,21 +25,10 @@ class ResourceManagementTest extends ResourceManagerTestProxyTestBase { protected ResourceManager resourceClient; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/TagsTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/TagsTests.java index 85b7f3ab3a2f4..a1a20ec04ed3d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/TagsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/TagsTests.java @@ -17,16 +17,20 @@ public class TagsTests extends ResourceManagementTest { @Test public void canUpdateTag() throws Exception { // assume there is a resource - ResourceGroup resource = resourceClient.resourceGroups().list().stream() + ResourceGroup resource = resourceClient.resourceGroups() + .list() + .stream() .filter(resourceGroup -> "Succeeded".equalsIgnoreCase(resourceGroup.provisioningState())) - .findFirst().get(); + .findFirst() + .get(); Map originalTags = resource.tags(); if (originalTags == null) { originalTags = new HashMap<>(); } - TagResource updatedTags = resourceClient.tagOperations().updateTags(resource, new TypeSerializationTests.Map1<>("tag.1", "value.1")); + TagResource updatedTags = resourceClient.tagOperations() + .updateTags(resource, new TypeSerializationTests.Map1<>("tag.1", "value.1")); Assertions.assertNotNull(updatedTags.tags()); Assertions.assertEquals(1, updatedTags.tags().size()); Assertions.assertTrue(updatedTags.tags().containsKey("tag.1")); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ChickenImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ChickenImpl.java index 51329580a6022..991085f999d4f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ChickenImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ChickenImpl.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.resources.childresource; - import reactor.core.publisher.Flux; class ChickenImpl { @@ -38,7 +37,6 @@ ChickenImpl withoutPullet(String name) { Flux applyAsync() { final ChickenImpl self = this; - return this.pullets.commitAsync() - .flatMap(p -> Flux.just(self)); + return this.pullets.commitAsync().flatMap(p -> Flux.just(self)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ExternalChildResourceTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ExternalChildResourceTests.java index 0cff565d01673..249e4f9b2a657 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ExternalChildResourceTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/ExternalChildResourceTests.java @@ -31,42 +31,34 @@ public void noCommitIfNoChange() throws InterruptedException { // In the unit test cases we call it directly as we testing external child resource here. // pullets.commitAsync() - .subscribe( - pullet -> Assertions.assertTrue(false, "nothing to commit onNext should not be invoked"), + .subscribe(pullet -> Assertions.assertTrue(false, "nothing to commit onNext should not be invoked"), throwable -> { monitor.countDown(); Assertions.assertTrue(false, "nothing to commit onError should not be invoked"); - }, - () -> monitor.countDown() - ); + }, () -> monitor.countDown()); monitor.await(); } @Test public void shouldCommitCreateUpdateAndDelete() throws InterruptedException { ChickenImpl chicken = new ChickenImpl(); // Parent resource - chicken - .defineNewPullet("alice") - .withAge(1) - .attach() - .updatePullet("Clover") - .withAge(2) - .parent() - .withoutPullet("Pinky"); + chicken.defineNewPullet("alice") + .withAge(1) + .attach() + .updatePullet("Clover") + .withAge(2) + .parent() + .withoutPullet("Pinky"); final List changedPuppets = new ArrayList<>(); final CountDownLatch monitor = new CountDownLatch(1); PulletsImpl pullets = chicken.pullets(); - pullets.commitAsync().subscribe( - pullet -> changedPuppets.add(pullet), - throwable -> { - monitor.countDown(); - Assertions.assertTrue(false, "onError should not be invoked"); - }, - () -> monitor.countDown() - ); + pullets.commitAsync().subscribe(pullet -> changedPuppets.add(pullet), throwable -> { + monitor.countDown(); + Assertions.assertTrue(false, "onError should not be invoked"); + }, () -> monitor.countDown()); monitor.await(); Assertions.assertTrue(changedPuppets.size() == 3); @@ -78,43 +70,37 @@ public void shouldCommitCreateUpdateAndDelete() throws InterruptedException { @Test public void shouldEmitErrorAfterAllSuccessfulCommit() throws InterruptedException { ChickenImpl chicken = new ChickenImpl(); // Parent resource - chicken - .defineNewPullet("alice") - .withAge(1) - .withFailFlag(PulletImpl.FailFlag.OnCreate) - .attach() - .updatePullet("Clover") - .withAge(2) - .parent() - .updatePullet("Goldilocks") - .withAge(2) - .withFailFlag(PulletImpl.FailFlag.OnUpdate) - .parent() - .withoutPullet("Pinky"); + chicken.defineNewPullet("alice") + .withAge(1) + .withFailFlag(PulletImpl.FailFlag.OnCreate) + .attach() + .updatePullet("Clover") + .withAge(2) + .parent() + .updatePullet("Goldilocks") + .withAge(2) + .withFailFlag(PulletImpl.FailFlag.OnUpdate) + .parent() + .withoutPullet("Pinky"); final List changedPuppets = new ArrayList<>(); final List throwables = new ArrayList<>(); final CountDownLatch monitor = new CountDownLatch(1); PulletsImpl pullets = chicken.pullets(); - pullets.commitAsync() - .subscribe( - pullet -> changedPuppets.add(pullet), - throwable -> { - try { - Throwable[] exception = throwable.getSuppressed(); - Assertions.assertNotNull(exception); - for (Throwable innerThrowable : exception) { - throwables.add(innerThrowable); - } - } finally { - monitor.countDown(); - } - }, - () -> { - monitor.countDown(); - Assertions.assertTrue(false, "onCompleted should not be invoked"); + pullets.commitAsync().subscribe(pullet -> changedPuppets.add(pullet), throwable -> { + try { + Throwable[] exception = throwable.getSuppressed(); + Assertions.assertNotNull(exception); + for (Throwable innerThrowable : exception) { + throwables.add(innerThrowable); } - ); + } finally { + monitor.countDown(); + } + }, () -> { + monitor.countDown(); + Assertions.assertTrue(false, "onCompleted should not be invoked"); + }); monitor.await(); Assertions.assertTrue(throwables.size() == 2); @@ -124,26 +110,20 @@ public void shouldEmitErrorAfterAllSuccessfulCommit() throws InterruptedExceptio @Test public void canStreamAccumulatedResult() throws InterruptedException { ChickenImpl chicken = new ChickenImpl(); - chicken - .defineNewPullet("alice") - .withAge(1) - .attach() - .updatePullet("Clover") - .withAge(2) - .attach() - .withoutPullet("Pinky"); + chicken.defineNewPullet("alice") + .withAge(1) + .attach() + .updatePullet("Clover") + .withAge(2) + .attach() + .withoutPullet("Pinky"); PulletsImpl pullets = chicken.pullets(); final CountDownLatch monitor = new CountDownLatch(1); - pullets.commitAndGetAllAsync() - .subscribe(lets -> Assertions.assertTrue(lets.size() == 3), - throwable -> { - monitor.countDown(); - Assertions.assertTrue(false, "onError should not be invoked"); - }, - () -> monitor.countDown() - ); - + pullets.commitAndGetAllAsync().subscribe(lets -> Assertions.assertTrue(lets.size() == 3), throwable -> { + monitor.countDown(); + Assertions.assertTrue(false, "onError should not be invoked"); + }, () -> monitor.countDown()); monitor.await(); } @@ -153,15 +133,15 @@ public void canCrossReferenceChildren() throws Exception { SchoolsImpl schools = new SchoolsImpl(); Flux items = schools.define("redmondSchool") - .withAddress("sc-address") - .defineTeacher("maria") - .withSubject("Maths") - .attach() - .defineStudent("bob") - .withAge(10) - .withTeacher("maria") // Refer another creatable external child resource with key 'maria' in the parent - .attach() - .createAsync(); + .withAddress("sc-address") + .defineTeacher("maria") + .withSubject("Maths") + .attach() + .defineStudent("bob") + .withAge(10) + .withTeacher("maria") // Refer another creatable external child resource with key 'maria' in the parent + .attach() + .createAsync(); final SchoolsImpl.SchoolImpl[] foundSchool = new SchoolsImpl.SchoolImpl[1]; final SchoolsImpl.TeacherImpl[] foundTeacher = new SchoolsImpl.TeacherImpl[1]; @@ -192,19 +172,17 @@ public void canCrossReferenceChildren() throws Exception { public void canCreateChildrenIndependently() throws Exception { SchoolsImpl schools = new SchoolsImpl(); - Creatable creatableTeacher = schools.independentTeachers() - .define("john") - .withSubject("physics"); + Creatable creatableTeacher + = schools.independentTeachers().define("john").withSubject("physics"); - SchoolsImpl.StudentImpl creatableStudent = schools.independentStudents() - .define("nit") - .withAge(15) - .withTeacher(creatableTeacher); + SchoolsImpl.StudentImpl creatableStudent + = schools.independentStudents().define("nit").withAge(15).withTeacher(creatableTeacher); final SchoolsImpl.TeacherImpl[] foundTeacher = new SchoolsImpl.TeacherImpl[1]; final SchoolsImpl.StudentImpl[] foundStudent = new SchoolsImpl.StudentImpl[1]; - creatableStudent.taskGroup().invokeAsync(creatableStudent.taskGroup().newInvocationContext()) + creatableStudent.taskGroup() + .invokeAsync(creatableStudent.taskGroup().newInvocationContext()) .doOnNext(indexable -> { if (indexable instanceof SchoolsImpl.TeacherImpl) { foundTeacher[0] = (SchoolsImpl.TeacherImpl) indexable; @@ -212,7 +190,8 @@ public void canCreateChildrenIndependently() throws Exception { if (indexable instanceof SchoolsImpl.StudentImpl) { foundStudent[0] = (SchoolsImpl.StudentImpl) indexable; } - }).blockLast(); + }) + .blockLast(); Assertions.assertNotNull(foundTeacher[0]); Assertions.assertNotNull(foundStudent[0]); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/PulletImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/PulletImpl.java index c7be7bbfb4b13..4dde1e454e8d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/PulletImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/PulletImpl.java @@ -7,8 +7,7 @@ import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; -class PulletImpl extends ExternalChildResourceImpl - implements Pullet { +class PulletImpl extends ExternalChildResourceImpl implements Pullet { Integer age; private FailFlag failFlag = FailFlag.None; @@ -42,9 +41,7 @@ public Mono createResourceAsync() { } Pullet self = this; - return Mono - .just(self) - .subscribeOn(Schedulers.boundedElastic()); + return Mono.just(self).subscribeOn(Schedulers.boundedElastic()); } @Override @@ -59,9 +56,7 @@ public Mono updateResourceAsync() { } Pullet self = this; - return Mono - .just(self) - .subscribeOn(Schedulers.boundedElastic()); + return Mono.just(self).subscribeOn(Schedulers.boundedElastic()); } @Override @@ -89,9 +84,6 @@ public String id() { } enum FailFlag { - None, - OnCreate, - OnUpdate, - OnDelete + None, OnCreate, OnUpdate, OnDelete } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/SchoolsImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/SchoolsImpl.java index 8fc562062035b..c7feb4e9d3cf2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/SchoolsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/childresource/SchoolsImpl.java @@ -127,11 +127,10 @@ public boolean isHot() { @Override public Mono invokeAsync(TaskGroup.InvocationContext context) { - return Mono.just(this) - .map(indexable -> { - isInvoked = true; - return indexable; - }); + return Mono.just(this).map(indexable -> { + isInvoked = true; + return indexable; + }); } @Override @@ -153,9 +152,8 @@ public SchoolImpl withStudent(StudentImpl student) { /** * Type representing an instance of Teacher. */ - class TeacherImpl - extends ExternalChildResourceImpl - implements TaskGroup.HasTaskGroup, Creatable { + class TeacherImpl extends ExternalChildResourceImpl + implements TaskGroup.HasTaskGroup, Creatable { private boolean isInvoked; @@ -178,11 +176,10 @@ public boolean isInvoked() { @Override public Mono createResourceAsync() { - return Mono.just(this) - .map(teacher -> { - isInvoked = true; - return teacher; - }); + return Mono.just(this).map(teacher -> { + isInvoked = true; + return teacher; + }); } @Override @@ -208,7 +205,8 @@ public SchoolImpl attach() { /** * Type representing Teacher collection where a teacher entries can be created as part of parent School. */ - class InlineTeachersImpl extends ExternalChildResourcesCachedImpl { + class InlineTeachersImpl + extends ExternalChildResourcesCachedImpl { protected InlineTeachersImpl(SchoolImpl parent, TaskGroup parentTaskGroup, String childResourceName) { super(parent, parentTaskGroup, childResourceName); @@ -256,9 +254,8 @@ public TeacherImpl define(String name) { /** * Type representing an instance of Student. */ - class StudentImpl - extends ExternalChildResourceImpl - implements TaskGroup.HasTaskGroup, Creatable { + class StudentImpl extends ExternalChildResourceImpl + implements TaskGroup.HasTaskGroup, Creatable { private String teacherName; private boolean isInvoked; @@ -338,7 +335,8 @@ public SchoolImpl attach() { /** * Type representing Student collection where a student entries can be created as part of parent School. */ - class InlineStudentsImpl extends ExternalChildResourcesCachedImpl { + class InlineStudentsImpl + extends ExternalChildResourcesCachedImpl { protected InlineStudentsImpl(SchoolImpl parent, TaskGroup parentTaskGroup, String childResourceName) { super(parent, parentTaskGroup, childResourceName); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/core/TestResourceProviderRegistration.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/core/TestResourceProviderRegistration.java index 31b9840001180..b7e5a243e6f0e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/core/TestResourceProviderRegistration.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/core/TestResourceProviderRegistration.java @@ -12,7 +12,8 @@ public class TestResourceProviderRegistration { @Test public void testManuallyUnregisteredRp() { - String error = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription is not registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}"; + String error + = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription is not registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}"; Matcher matcher = Pattern.compile(".*'(.*)'").matcher(error); matcher.find(); Assertions.assertEquals("Microsoft.Devices", matcher.group(1)); @@ -20,7 +21,8 @@ public void testManuallyUnregisteredRp() { @Test public void testRpInNewSubscription() { - String error = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}"; + String error + = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}"; Matcher matcher = Pattern.compile(".*'(.*)'").matcher(error); matcher.find(); Assertions.assertEquals("Microsoft.Devices", matcher.group(1)); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java index 0185c2be1335c..6f9ff25f353a6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java @@ -29,8 +29,7 @@ public class AzureConfigurableTests { @Test public void testRetryOptions() throws NoSuchFieldException, IllegalAccessException { // RetryOptions should take effect - ResourceManager resourceManager = ResourceManager - .configure() + ResourceManager resourceManager = ResourceManager.configure() .withRetryOptions(new RetryOptions(new FixedDelayOptions(3, Duration.ofSeconds(1)))) .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) @@ -40,8 +39,7 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti validateRetryPolicy(httpPipeline, FixedDelay.class); // Default is RetryPolicy with ExponentialBackoff - resourceManager = ResourceManager - .configure() + resourceManager = ResourceManager.configure() .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) .withSubscription(Mockito.anyString()); @@ -49,8 +47,7 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti httpPipeline = resourceManager.genericResources().manager().httpPipeline(); validateRetryPolicy(httpPipeline, ExponentialBackoff.class); - resourceManager = ResourceManager - .configure() + resourceManager = ResourceManager.configure() .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) .withSubscription(Mockito.anyString()); @@ -59,7 +56,8 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti validateRetryPolicy(httpPipeline, ExponentialBackoff.class); } - private static void validateRetryPolicy(HttpPipeline httpPipeline, Class retryStrategyClass) throws NoSuchFieldException, IllegalAccessException { + private static void validateRetryPolicy(HttpPipeline httpPipeline, Class retryStrategyClass) + throws NoSuchFieldException, IllegalAccessException { Assertions.assertNotNull(httpPipeline); Field pipelinePoliciesField = HttpPipeline.class.getDeclaredField("pipelinePolicies"); @@ -72,7 +70,8 @@ private static void validateRetryPolicy(HttpPipeline httpPipeline, Class retr } } - private static void validateRetryPolicy(RetryPolicy retryPolicy, Class retryStrategyClass) throws NoSuchFieldException, IllegalAccessException { + private static void validateRetryPolicy(RetryPolicy retryPolicy, Class retryStrategyClass) + throws NoSuchFieldException, IllegalAccessException { Assertions.assertNotNull(retryPolicy); Field retryStrategyField = RetryPolicy.class.getDeclaredField("retryStrategy"); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClientTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClientTests.java index 6d3bc012996cf..eafcb537ccee3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClientTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureServiceClientTests.java @@ -22,7 +22,7 @@ private class AzureServiceClientImpl extends AzureServiceClient { } protected AzureServiceClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - AzureEnvironment environment) { + AzureEnvironment environment) { super(httpPipeline, serializerAdapter, environment); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java index e2d2e643964bb..669263033efd0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java @@ -28,9 +28,7 @@ public BreadSliceImpl(String name) { @Override public Mono executeWorkAsync() { LOGGER.log(LogLevel.VERBOSE, () -> "Bread(" + this.name + ")::executeWorkAsync() [Getting slice from store]"); - return Mono.just(this) - .delayElement(Duration.ofMillis(250)) - .map(breadSlice -> breadSlice); + return Mono.just(this).delayElement(Duration.ofMillis(250)).map(breadSlice -> breadSlice); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java index 4df71ac7a2c57..e9eb8254e347f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java @@ -66,7 +66,6 @@ public void testTerminateOnInProgressTaskCompletion() { PancakeImpl pancakeL = new PancakeImpl("L", 250); pancakeL.withInstantPancake(pancakeP); - PancakeImpl pancakeB = new PancakeImpl("B", 4000, true); // Task B wait for 4000 ms then emit error pancakeB.withInstantPancake(pancakeA); PancakeImpl pancakeC = new PancakeImpl("C", 250); @@ -108,7 +107,7 @@ public void testTerminateOnInProgressTaskCompletion() { TaskGroup pancakeFtg = pancakeF.taskGroup(); TaskGroup.InvocationContext context = pancakeFtg.newInvocationContext() - .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); + .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; LOGGER.log(LogLevel.VERBOSE, () -> "map.onNext: " + pancake.name()); @@ -179,7 +178,6 @@ public void testTerminateOnHittingLcaTask() { PastaImpl pastaL = new PastaImpl("L", 250); pastaL.withInstantPasta(pastaP); - PastaImpl pastaB = new PastaImpl("B", 4000, true); // Task B wait for 4000 ms then emit error pastaB.withInstantPasta(pastaA); PastaImpl pastaC = new PastaImpl("C", 250); @@ -226,7 +224,7 @@ public void testTerminateOnHittingLcaTask() { TaskGroup pastaFtg = pastaF.taskGroup(); TaskGroup.InvocationContext context = pastaFtg.newInvocationContext() - .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_HITTING_LCA_TASK); + .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_HITTING_LCA_TASK); IPasta rootPasta = pastaFtg.invokeAsync(context).map(indexable -> { IPasta pasta = (IPasta) indexable; @@ -295,7 +293,6 @@ public void testCompositeError() { PancakeImpl pancakeL = new PancakeImpl("L", 250); pancakeL.withInstantPancake(pancakeP); - PancakeImpl pancakeB = new PancakeImpl("B", 3500, true); // Task B wait for 3500 ms then emit error pancakeB.withInstantPancake(pancakeA); PancakeImpl pancakeC = new PancakeImpl("C", 250); @@ -316,7 +313,6 @@ public void testCompositeError() { pancakeF.withInstantPancake(pancakeE); pancakeF.withInstantPancake(pancakeH); - pancakeA.withDelayedPancake(pancakeJ); pancakeA.withDelayedPancake(pancakeK); @@ -341,7 +337,7 @@ public void testCompositeError() { TaskGroup pancakeFtg = pancakeF.taskGroup(); TaskGroup.InvocationContext context = pancakeFtg.newInvocationContext() - .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); + .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; @@ -410,7 +406,6 @@ public void testErrorOnRoot() { PancakeImpl pancakeL = new PancakeImpl("L", 250); pancakeL.withInstantPancake(pancakeP); - PancakeImpl pancakeB = new PancakeImpl("B", 250); pancakeB.withInstantPancake(pancakeA); PancakeImpl pancakeC = new PancakeImpl("C", 250); @@ -460,7 +455,7 @@ public void testErrorOnRoot() { TaskGroup pancakeFtg = pancakeF.taskGroup(); TaskGroup.InvocationContext context = pancakeFtg.newInvocationContext() - .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); + .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; seen.add(pancake.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGFinalizeTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGFinalizeTests.java index df5f7ee20c012..5839a0f92f59c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGFinalizeTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGFinalizeTests.java @@ -67,8 +67,8 @@ public void testWithoutFinalize() { Assertions.assertEquals(nodeA.dependencyKeys().size(), 0); Assertions.assertEquals(nodeA.dependentKeys().size(), 2); for (String dependentKey : nodeA.dependentKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) - || dependentKey.equalsIgnoreCase(pizzaC.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) || dependentKey.equalsIgnoreCase(pizzaC.key())); } // Level 0 - "I" Assertions.assertEquals(pizzaI.taskGroup().getNodes().size(), 1); @@ -95,8 +95,8 @@ public void testWithoutFinalize() { } Assertions.assertEquals(nodeB.dependentKeys().size(), 2); for (String dependentKey : nodeB.dependentKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) - || dependentKey.equalsIgnoreCase(pizzaE.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) || dependentKey.equalsIgnoreCase(pizzaE.key())); } // Level 1 - "C" Assertions.assertEquals(pizzaC.taskGroup().getNodes().size(), 2); @@ -172,8 +172,8 @@ public void testWithoutFinalize() { Assertions.assertNotNull(nodeE); Assertions.assertEquals(nodeE.dependencyKeys().size(), 2); for (String dependentKey : nodeE.dependencyKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) - || dependentKey.equalsIgnoreCase(pizzaG.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) || dependentKey.equalsIgnoreCase(pizzaG.key())); } Assertions.assertEquals(nodeE.dependentKeys().size(), 1); for (String dependentKey : nodeE.dependentKeys()) { @@ -199,8 +199,8 @@ public void testWithoutFinalize() { Assertions.assertEquals(nodeF.dependencyKeys().size(), 3); for (String dependentKey : nodeF.dependencyKeys()) { Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) - || dependentKey.equalsIgnoreCase(pizzaE.key()) - || dependentKey.equalsIgnoreCase(pizzaH.key())); + || dependentKey.equalsIgnoreCase(pizzaE.key()) + || dependentKey.equalsIgnoreCase(pizzaH.key())); } Assertions.assertEquals(nodeF.dependentKeys().size(), 0); } @@ -363,8 +363,8 @@ public void testFinalize() { Assertions.assertNotNull(nodeJ); Assertions.assertEquals(nodeJ.dependencyKeys().size(), 2); for (String dependentKey : nodeJ.dependencyKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaM.key()) - || dependentKey.equalsIgnoreCase(pizzaN.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaM.key()) || dependentKey.equalsIgnoreCase(pizzaN.key())); } Assertions.assertEquals(nodeJ.dependentKeys().size(), 1); for (String dependentKey : nodeJ.dependentKeys()) { @@ -411,13 +411,13 @@ public void testFinalize() { Assertions.assertNotNull(nodeA); Assertions.assertEquals(nodeA.dependencyKeys().size(), 2); for (String dependentKey : nodeA.dependencyKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaJ.key()) - || dependentKey.equalsIgnoreCase(pizzaK.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaJ.key()) || dependentKey.equalsIgnoreCase(pizzaK.key())); } Assertions.assertEquals(nodeA.dependentKeys().size(), 2); for (String dependentKey : nodeA.dependentKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) - || dependentKey.equalsIgnoreCase(pizzaC.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) || dependentKey.equalsIgnoreCase(pizzaC.key())); } // ---------------------------------------------------------------------------------- // LEVEL - 3 @@ -438,8 +438,8 @@ public void testFinalize() { } Assertions.assertEquals(nodeB.dependentKeys().size(), 2); for (String dependentKey : nodeB.dependentKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) - || dependentKey.equalsIgnoreCase(pizzaE.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) || dependentKey.equalsIgnoreCase(pizzaE.key())); } // ---------------------------------------------------------------------------------- // LEVEL - 4 @@ -479,8 +479,8 @@ public void testFinalize() { Assertions.assertNotNull(nodeG); Assertions.assertEquals(nodeG.dependencyKeys().size(), 2); for (String dependentKey : nodeG.dependencyKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaC.key()) - || dependentKey.equalsIgnoreCase(pizzaL.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaC.key()) || dependentKey.equalsIgnoreCase(pizzaL.key())); } Assertions.assertEquals(nodeG.dependentKeys().size(), 1); for (String dependentKey : nodeG.dependentKeys()) { @@ -507,8 +507,8 @@ public void testFinalize() { Assertions.assertNotNull(nodeE); Assertions.assertEquals(nodeE.dependencyKeys().size(), 2); for (String dependentKey : nodeE.dependencyKeys()) { - Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) - || dependentKey.equalsIgnoreCase(pizzaG.key())); + Assertions + .assertTrue(dependentKey.equalsIgnoreCase(pizzaB.key()) || dependentKey.equalsIgnoreCase(pizzaG.key())); } Assertions.assertEquals(nodeE.dependentKeys().size(), 1); for (String dependentKey : nodeE.dependentKeys()) { @@ -540,8 +540,8 @@ public void testFinalize() { Assertions.assertEquals(nodeF.dependencyKeys().size(), 3); for (String dependentKey : nodeF.dependencyKeys()) { Assertions.assertTrue(dependentKey.equalsIgnoreCase(pizzaD.key()) - || dependentKey.equalsIgnoreCase(pizzaE.key()) - || dependentKey.equalsIgnoreCase(pizzaH.key())); + || dependentKey.equalsIgnoreCase(pizzaE.key()) + || dependentKey.equalsIgnoreCase(pizzaH.key())); } Assertions.assertEquals(nodeF.dependentKeys().size(), 0); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTest.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTest.java index fb7e10915e020..093da5a12d92c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTest.java @@ -23,9 +23,13 @@ public void testDAGraphGetNext() { * |-------->[H]-------------------->[I] */ List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); + expectedOrder.add("A"); + expectedOrder.add("I"); + expectedOrder.add("B"); + expectedOrder.add("C"); + expectedOrder.add("H"); + expectedOrder.add("D"); + expectedOrder.add("G"); expectedOrder.add("E"); expectedOrder.add("F"); @@ -51,7 +55,6 @@ public void testDAGraphGetNext() { ItemHolder nodeD = new ItemHolder("D", "dataD"); nodeD.addDependency(nodeB.key()); - ItemHolder nodeF = new ItemHolder("F", "dataF"); nodeF.addDependency(nodeD.key()); nodeF.addDependency(nodeE.key()); @@ -93,9 +96,13 @@ public void testGraphMerge() { * |-------->[H]-------------------->[I] */ List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); + expectedOrder.add("A"); + expectedOrder.add("I"); + expectedOrder.add("B"); + expectedOrder.add("C"); + expectedOrder.add("H"); + expectedOrder.add("D"); + expectedOrder.add("G"); expectedOrder.add("E"); expectedOrder.add("F"); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java index ba6710befa369..5609b6db69354 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java @@ -26,9 +26,13 @@ public void testDAGraphGetNext() { * |-------->[H]-------------------->[I] */ List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); // Level 0 - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); // Level 1 - expectedOrder.add("D"); expectedOrder.add("G"); // Level 2 + expectedOrder.add("A"); + expectedOrder.add("I"); // Level 0 + expectedOrder.add("B"); + expectedOrder.add("C"); + expectedOrder.add("H"); // Level 1 + expectedOrder.add("D"); + expectedOrder.add("G"); // Level 2 expectedOrder.add("E"); // Level 3 expectedOrder.add("F"); // Level 4 @@ -54,7 +58,6 @@ public void testDAGraphGetNext() { ItemHolder nodeD = new ItemHolder("D", "dataD"); nodeD.addDependency(nodeB.key()); - ItemHolder nodeF = new ItemHolder("F", "dataF"); nodeF.addDependency(nodeD.key()); nodeF.addDependency(nodeE.key()); @@ -96,9 +99,13 @@ public void testGraphDependency() { * |-------->[H]-------------------->[I] */ List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); // Level 0 - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); // Level 1 - expectedOrder.add("D"); expectedOrder.add("G"); // Level 2 + expectedOrder.add("A"); + expectedOrder.add("I"); // Level 0 + expectedOrder.add("B"); + expectedOrder.add("C"); + expectedOrder.add("H"); // Level 1 + expectedOrder.add("D"); + expectedOrder.add("G"); // Level 2 expectedOrder.add("E"); // Level 3 expectedOrder.add("F"); // Level 4 @@ -294,79 +301,78 @@ public void testGraphNodeTableBubblingUp() { * |-----------------[F] (graph4Root1) */ - //====================================================== // Validate nodeTables (graph1Root) ItemHolder nodeAWithG1 = graph1Root.getNode("A"); Assertions.assertEquals(1, nodeAWithG1.owner().nodeTable.size()); - assertExactMatch(nodeAWithG1.owner().nodeTable.keySet(), new String[] {"A"}); + assertExactMatch(nodeAWithG1.owner().nodeTable.keySet(), new String[] { "A" }); ItemHolder nodeBWithG1 = graph1Root.getNode("B"); Assertions.assertEquals(2, nodeBWithG1.owner().nodeTable.size()); - assertExactMatch(nodeBWithG1.owner().nodeTable.keySet(), new String[] {"A", "B"}); + assertExactMatch(nodeBWithG1.owner().nodeTable.keySet(), new String[] { "A", "B" }); ItemHolder nodeCWithG1 = graph1Root.getNode("C"); Assertions.assertEquals(3, nodeCWithG1.owner().nodeTable.size()); - assertExactMatch(nodeCWithG1.owner().nodeTable.keySet(), new String[] {"A", "B", "C"}); + assertExactMatch(nodeCWithG1.owner().nodeTable.keySet(), new String[] { "A", "B", "C" }); //====================================================== // Validate nodeTables (graph4Root1) ItemHolder nodeAWithG41 = graph4Root1.getNode("A"); Assertions.assertEquals(1, nodeAWithG41.owner().nodeTable.size()); - assertExactMatch(nodeAWithG41.owner().nodeTable.keySet(), new String[] {"A"}); + assertExactMatch(nodeAWithG41.owner().nodeTable.keySet(), new String[] { "A" }); ItemHolder nodeBWithG41 = graph4Root1.getNode("B"); Assertions.assertEquals(2, nodeBWithG41.owner().nodeTable.size()); - assertExactMatch(nodeBWithG41.owner().nodeTable.keySet(), new String[] {"A", "B"}); + assertExactMatch(nodeBWithG41.owner().nodeTable.keySet(), new String[] { "A", "B" }); ItemHolder nodeCWithG41 = graph4Root1.getNode("C"); Assertions.assertEquals(3, nodeCWithG41.owner().nodeTable.size()); - assertExactMatch(nodeCWithG41.owner().nodeTable.keySet(), new String[] {"A", "B", "C"}); + assertExactMatch(nodeCWithG41.owner().nodeTable.keySet(), new String[] { "A", "B", "C" }); ItemHolder nodeGWithG41 = graph4Root1.getNode("G"); Assertions.assertEquals(1, nodeGWithG41.owner().nodeTable.size()); - assertExactMatch(nodeGWithG41.owner().nodeTable.keySet(), new String[] {"G"}); + assertExactMatch(nodeGWithG41.owner().nodeTable.keySet(), new String[] { "G" }); ItemHolder nodeDWithG41 = graph4Root1.getNode("D"); Assertions.assertEquals(2, nodeDWithG41.owner().nodeTable.size()); - assertExactMatch(nodeDWithG41.owner().nodeTable.keySet(), new String[] {"D", "G"}); + assertExactMatch(nodeDWithG41.owner().nodeTable.keySet(), new String[] { "D", "G" }); ItemHolder nodeEWithG41 = graph4Root1.getNode("E"); Assertions.assertEquals(3, nodeEWithG41.owner().nodeTable.size()); - assertExactMatch(nodeEWithG41.owner().nodeTable.keySet(), new String[] {"E", "D", "G"}); + assertExactMatch(nodeEWithG41.owner().nodeTable.keySet(), new String[] { "E", "D", "G" }); ItemHolder nodeFWithG41 = graph4Root1.getNode("F"); Assertions.assertEquals(7, nodeFWithG41.owner().nodeTable.size()); - assertExactMatch(nodeFWithG41.owner().nodeTable.keySet(), new String[] {"E", "F", "D", "G", "A", "B", "C"}); + assertExactMatch(nodeFWithG41.owner().nodeTable.keySet(), new String[] { "E", "F", "D", "G", "A", "B", "C" }); //====================================================== // Validate nodeTables (graph4Root2) ItemHolder nodeAWithG42 = graph4Root2.getNode("A"); Assertions.assertEquals(1, nodeAWithG42.owner().nodeTable.size()); - assertExactMatch(nodeAWithG42.owner().nodeTable.keySet(), new String[] {"A"}); + assertExactMatch(nodeAWithG42.owner().nodeTable.keySet(), new String[] { "A" }); ItemHolder nodeBWithG42 = graph4Root2.getNode("B"); Assertions.assertEquals(2, nodeBWithG42.owner().nodeTable.size()); - assertExactMatch(nodeBWithG42.owner().nodeTable.keySet(), new String[] {"A", "B"}); + assertExactMatch(nodeBWithG42.owner().nodeTable.keySet(), new String[] { "A", "B" }); ItemHolder nodeCWithG42 = graph4Root2.getNode("C"); Assertions.assertEquals(3, nodeCWithG42.owner().nodeTable.size()); - assertExactMatch(nodeCWithG42.owner().nodeTable.keySet(), new String[] {"A", "B", "C"}); + assertExactMatch(nodeCWithG42.owner().nodeTable.keySet(), new String[] { "A", "B", "C" }); ItemHolder nodeIWithG42 = graph4Root2.getNode("I"); Assertions.assertEquals(1, nodeIWithG42.owner().nodeTable.size()); - assertExactMatch(nodeIWithG42.owner().nodeTable.keySet(), new String[] {"I"}); + assertExactMatch(nodeIWithG42.owner().nodeTable.keySet(), new String[] { "I" }); ItemHolder nodeHWithG42 = graph4Root2.getNode("H"); Assertions.assertEquals(2, nodeHWithG42.owner().nodeTable.size()); - assertExactMatch(nodeHWithG42.owner().nodeTable.keySet(), new String[] {"I", "H"}); + assertExactMatch(nodeHWithG42.owner().nodeTable.keySet(), new String[] { "I", "H" }); ItemHolder nodeJWithG42 = graph4Root2.getNode("J"); Assertions.assertEquals(6, nodeJWithG42.owner().nodeTable.size()); - assertExactMatch(nodeJWithG42.owner().nodeTable.keySet(), new String[] {"I", "H", "J", "A", "B", "C"}); + assertExactMatch(nodeJWithG42.owner().nodeTable.keySet(), new String[] { "I", "H", "J", "A", "B", "C" }); // System.out.println(combinedGraphRoot.nodeTable.keySet()); @@ -385,12 +391,10 @@ public void testGraphNodeTableBubblingUp() { DAGraph graphL = createGraph("L"); DAGraph graphM = createGraph("M"); - graphL.addDependencyGraph(graphK); graphM.addDependencyGraph(graphL); graphM.addDependencyGraph(graphK); - // Add a non-root node in this graph as dependency of a non-root node in the first graph. // graphA.addDependencyGraph(graphL); @@ -425,39 +429,40 @@ public void testGraphNodeTableBubblingUp() { ItemHolder nodeKWithG41 = graph4Root1.getNode("K"); Assertions.assertEquals(1, nodeKWithG41.owner().nodeTable.size()); - assertExactMatch(nodeKWithG41.owner().nodeTable.keySet(), new String[] {"K"}); + assertExactMatch(nodeKWithG41.owner().nodeTable.keySet(), new String[] { "K" }); ItemHolder nodeLWithG41 = graph4Root1.getNode("L"); Assertions.assertEquals(2, nodeLWithG41.owner().nodeTable.size()); - assertExactMatch(nodeLWithG41.owner().nodeTable.keySet(), new String[] {"K", "L"}); + assertExactMatch(nodeLWithG41.owner().nodeTable.keySet(), new String[] { "K", "L" }); ItemHolder nodeAWithG41Updated = graph4Root1.getNode("A"); Assertions.assertEquals(3, nodeAWithG41Updated.owner().nodeTable.size()); - assertExactMatch(nodeAWithG41Updated.owner().nodeTable.keySet(), new String[] {"K", "L", "A"}); + assertExactMatch(nodeAWithG41Updated.owner().nodeTable.keySet(), new String[] { "K", "L", "A" }); ItemHolder nodeBWithG41Updated = graph4Root1.getNode("B"); Assertions.assertEquals(4, nodeBWithG41Updated.owner().nodeTable.size()); - assertExactMatch(nodeBWithG41Updated.owner().nodeTable.keySet(), new String[] {"K", "L", "A", "B"}); + assertExactMatch(nodeBWithG41Updated.owner().nodeTable.keySet(), new String[] { "K", "L", "A", "B" }); ItemHolder nodeCWithG41Updated = graph4Root1.getNode("C"); Assertions.assertEquals(5, nodeCWithG41Updated.owner().nodeTable.size()); - assertExactMatch(nodeCWithG41Updated.owner().nodeTable.keySet(), new String[] {"K", "L", "A", "B", "C"}); + assertExactMatch(nodeCWithG41Updated.owner().nodeTable.keySet(), new String[] { "K", "L", "A", "B", "C" }); ItemHolder nodeFWithG41Updated = graph4Root1.getNode("F"); Assertions.assertEquals(9, nodeFWithG41Updated.owner().nodeTable.size()); - assertExactMatch(nodeFWithG41Updated.owner().nodeTable.keySet(), new String[] {"K", "L", "A", "B", "C", "F", "E", "D", "G"}); + assertExactMatch(nodeFWithG41Updated.owner().nodeTable.keySet(), + new String[] { "K", "L", "A", "B", "C", "F", "E", "D", "G" }); ItemHolder nodeGWithG41NoUpdate = graph4Root1.getNode("G"); Assertions.assertEquals(1, nodeGWithG41NoUpdate.owner().nodeTable.size()); - assertExactMatch(nodeGWithG41NoUpdate.owner().nodeTable.keySet(), new String[] {"G"}); + assertExactMatch(nodeGWithG41NoUpdate.owner().nodeTable.keySet(), new String[] { "G" }); ItemHolder nodeDWithG41NoUpdate = graph4Root1.getNode("D"); Assertions.assertEquals(2, nodeDWithG41NoUpdate.owner().nodeTable.size()); - assertExactMatch(nodeDWithG41NoUpdate.owner().nodeTable.keySet(), new String[] {"D", "G"}); + assertExactMatch(nodeDWithG41NoUpdate.owner().nodeTable.keySet(), new String[] { "D", "G" }); ItemHolder nodeEWithG41NoUpdate = graph4Root1.getNode("E"); Assertions.assertEquals(3, nodeEWithG41NoUpdate.owner().nodeTable.size()); - assertExactMatch(nodeEWithG41NoUpdate.owner().nodeTable.keySet(), new String[] {"E", "D", "G"}); + assertExactMatch(nodeEWithG41NoUpdate.owner().nodeTable.keySet(), new String[] { "E", "D", "G" }); } private DAGraph createGraph(String resourceName) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ExecutableWithCreatableTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ExecutableWithCreatableTests.java index 3dc3fbfce5daa..9357b50cbfbdc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ExecutableWithCreatableTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ExecutableWithCreatableTests.java @@ -10,16 +10,14 @@ public class ExecutableWithCreatableTests { public void testExecutableWithExecutableDependency() { BreadSliceImpl breadFetcher1 = new BreadSliceImpl("BreadSlice1"); BreadSliceImpl breadFetcher2 = new BreadSliceImpl("BreadSlice2"); - breadFetcher1.withAnotherSliceFromStore(breadFetcher2) - .execute(); + breadFetcher1.withAnotherSliceFromStore(breadFetcher2).execute(); } @Test public void testExecutableWithCreatableDependency() { BreadSliceImpl breadFetcher = new BreadSliceImpl("BreadSlice"); OrderImpl order = new OrderImpl("OrderForSlice", new OrderInner()); - breadFetcher.withNewOrder(order) - .execute(); + breadFetcher.withNewOrder(order).execute(); } @Test @@ -28,7 +26,6 @@ public void testCreatableWithExecutableDependency() { BreadSliceImpl breadFetcher = new BreadSliceImpl("SliceForSandwich"); OrderImpl order = new OrderImpl("OrderForSlice", new OrderInner()); breadFetcher.withNewOrder(order); - sandwich.withBreadSliceFromStore(breadFetcher) - .create(); + sandwich.withBreadSliceFromStore(breadFetcher).create(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IBreadSlice.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IBreadSlice.java index d2ba48f10fbbe..f501945c93792 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IBreadSlice.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IBreadSlice.java @@ -12,5 +12,6 @@ */ public interface IBreadSlice extends Indexable, Executable { IBreadSlice withAnotherSliceFromStore(Executable breadFetcher); + IBreadSlice withNewOrder(Creatable order); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPanCake.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPanCake.java index 05b5c3b2c41ee..d413d74f6a600 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPanCake.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPanCake.java @@ -11,6 +11,6 @@ */ interface IPancake extends Indexable, Creatable { IPancake withInstantPancake(Creatable anotherPancake); + IPancake withDelayedPancake(Creatable anotherPancake); } - diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPasta.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPasta.java index b4063b7b4182d..620f0d6e6722e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPasta.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPasta.java @@ -11,6 +11,6 @@ */ interface IPasta extends Indexable, Creatable { IPasta withInstantPasta(Creatable anotherPasta); + IPasta withDelayedPasta(Creatable anotherPasta); } - diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPizza.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPizza.java index f69f626bfc6cc..167a4e53d0ffb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPizza.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/IPizza.java @@ -11,6 +11,6 @@ */ interface IPizza extends Indexable, Creatable { IPizza withInstantPizza(Creatable anotherPizza); + IPizza withDelayedPizza(Creatable anotherPizza); } - diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/InvokeRootTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/InvokeRootTests.java index 98d1dc86bd6a9..018946607289e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/InvokeRootTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/InvokeRootTests.java @@ -21,17 +21,16 @@ public void testIgnoreCachedResultOnRootWithNoProxy() { final HashMap seen = new HashMap<>(); - taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(2, seen.size()); Assertions.assertTrue(seen.containsKey("A")); @@ -39,23 +38,21 @@ public void testIgnoreCachedResultOnRootWithNoProxy() { Assertions.assertEquals(1, (long) seen.get("A")); Assertions.assertEquals(1, (long) seen.get("B")); - Assertions.assertEquals(1, taskItem1.getCallCount()); Assertions.assertEquals(1, taskItem2.getCallCount()); seen.clear(); - taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(2, seen.size()); Assertions.assertTrue(seen.containsKey("A")); @@ -63,7 +60,6 @@ public void testIgnoreCachedResultOnRootWithNoProxy() { Assertions.assertEquals(1, (long) seen.get("A")); Assertions.assertEquals(1, (long) seen.get("B")); - Assertions.assertEquals(2, taskItem1.getCallCount()); Assertions.assertEquals(1, taskItem2.getCallCount()); } @@ -79,17 +75,16 @@ public void testIgnoreCachedResultOnRootWithProxy() { final HashMap seen = new HashMap<>(); - taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(3, seen.size()); // X, Y, Z @@ -106,17 +101,16 @@ public void testIgnoreCachedResultOnRootWithProxy() { seen.clear(); - taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem1.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(3, seen.size()); @@ -149,17 +143,16 @@ public void testIgnoreCachedResultOnRootWithProxyWithDescendantProxy() { final HashMap seen = new HashMap<>(); - taskItem4.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem4.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(5, seen.size()); @@ -183,17 +176,16 @@ public void testIgnoreCachedResultOnRootWithProxyWithDescendantProxy() { seen.clear(); - taskItem4.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()) - .map(item -> { - SupportCountingAndHasName c = (SupportCountingAndHasName) item; - if (seen.containsKey(c.name())) { - Integer a = seen.get(c.name()) + 1; - seen.put(c.name(), a); - } else { - seen.put(c.name(), 1); - } - return item; - }).blockLast(); + taskItem4.taskGroup().invokeAsync(taskItem1.taskGroup().newInvocationContext()).map(item -> { + SupportCountingAndHasName c = (SupportCountingAndHasName) item; + if (seen.containsKey(c.name())) { + Integer a = seen.get(c.name()) + 1; + seen.put(c.name(), a); + } else { + seen.put(c.name(), 1); + } + return item; + }).blockLast(); Assertions.assertEquals(5, seen.size()); @@ -237,11 +229,10 @@ public int getCallCount() { @Override protected Mono invokeTaskAsync(TaskGroup.InvocationContext context) { - return Mono.just(this) - .map(r -> { - callCount++; - return r; - }); + return Mono.just(this).map(r -> { + callCount++; + return r; + }); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java index d4ac227fff7cb..8d584fe02a30d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java @@ -13,9 +13,7 @@ /** * Implementation of {@link IOrder} */ -public class OrderImpl - extends CreatableUpdatableImpl - implements IOrder { +public class OrderImpl extends CreatableUpdatableImpl implements IOrder { private static final ClientLogger LOGGER = new ClientLogger(OrderImpl.class); /** @@ -31,9 +29,7 @@ protected OrderImpl(String name, OrderInner innerObject) { @Override public Mono createResourceAsync() { LOGGER.log(LogLevel.VERBOSE, () -> "Order(" + this.name() + ")::createResourceAsync() [Creating order]"); - return Mono.just(this) - .delayElement(Duration.ofMillis(250)) - .map(sandwich -> sandwich); + return Mono.just(this).delayElement(Duration.ofMillis(250)).map(sandwich -> sandwich); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java index 743ff9dac62b9..c952ff64998e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java @@ -18,9 +18,7 @@ /** * Implementation of {@link IPancake} */ -class PancakeImpl - extends CreatableUpdatableImpl - implements IPancake { +class PancakeImpl extends CreatableUpdatableImpl implements IPancake { private static final ClientLogger LOGGER = new ClientLogger(PancakeImpl.class); final List> delayedPancakes; @@ -70,7 +68,8 @@ public PancakeImpl withDelayedPancake(Creatable pancake) { @Override public void beforeGroupCreateOrUpdate() { - Assertions.assertFalse(this.prepareCalled, "PancakeImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); + Assertions.assertFalse(this.prepareCalled, + "PancakeImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); prepareCalled = true; int oldCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); for (Creatable pancake : this.delayedPancakes) { @@ -86,13 +85,13 @@ public Mono createResourceAsync() { if (this.errorToThrow == null) { LOGGER.log(LogLevel.VERBOSE, () -> "Pancake(" + this.name() + ")::createResourceAsync() 'onNext()'"); return Mono.just(this) - .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) - .map(pancake -> pancake); + .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) + .map(pancake -> pancake); } else { LOGGER.log(LogLevel.VERBOSE, () -> "Pancake(" + this.name() + ")::createResourceAsync() 'onError()'"); return Mono.just(this) - .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) - .flatMap(pancake -> toErrorMono(errorToThrow)); + .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) + .flatMap(pancake -> toErrorMono(errorToThrow)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java index f38f7f9ebd70c..496f056cf6900 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java @@ -18,9 +18,7 @@ /** * Implementation of {@link IPasta} */ -class PastaImpl - extends CreatableUpdatableImpl - implements IPasta { +class PastaImpl extends CreatableUpdatableImpl implements IPasta { private static final ClientLogger LOGGER = new ClientLogger(PastaImpl.class); final List> delayedPastas; @@ -68,10 +66,10 @@ public PastaImpl withDelayedPasta(Creatable pasta) { return this; } - @Override public void beforeGroupCreateOrUpdate() { - Assertions.assertFalse(this.prepareCalled, "PastaImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); + Assertions.assertFalse(this.prepareCalled, + "PastaImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); prepareCalled = true; int oldCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); for (Creatable pancake : this.delayedPastas) { @@ -86,14 +84,12 @@ public void beforeGroupCreateOrUpdate() { public Mono createResourceAsync() { if (this.errorToThrow == null) { LOGGER.log(LogLevel.VERBOSE, () -> "Pasta(" + this.name() + ")::createResourceAsync() 'onNext()'"); - return Mono.just(this) - .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) - .map(pasta -> pasta); + return Mono.just(this).delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)).map(pasta -> pasta); } else { LOGGER.log(LogLevel.VERBOSE, () -> "Pasta(" + this.name() + ")::createResourceAsync() 'onError()'"); return Mono.just(this) - .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) - .flatMap(pasta -> toErrorObservable(errorToThrow)); + .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) + .flatMap(pasta -> toErrorObservable(errorToThrow)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java index dc72b43c093f2..6ea6a1fd6e057 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java @@ -18,9 +18,7 @@ /** * Implementation of {@link IPizza} */ -class PizzaImpl - extends CreatableUpdatableImpl - implements IPizza { +class PizzaImpl extends CreatableUpdatableImpl implements IPizza { private static final ClientLogger LOGGER = new ClientLogger(PizzaImpl.class); final List> delayedPizzas; @@ -58,7 +56,8 @@ public PizzaImpl withDelayedPizza(Creatable pizza) { @Override public void beforeGroupCreateOrUpdate() { - Assertions.assertFalse(this.prepareCalled, "PizzaImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); + Assertions.assertFalse(this.prepareCalled, + "PizzaImpl::beforeGroupCreateOrUpdate() should not be called multiple times"); prepareCalled = true; int oldCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); for (Creatable pizza : this.delayedPizzas) { @@ -72,9 +71,7 @@ public void beforeGroupCreateOrUpdate() { @Override public Mono createResourceAsync() { LOGGER.log(LogLevel.VERBOSE, () -> "Pizza(" + this.name() + ")::createResourceAsync()"); - return Mono.just(this) - .delayElement(Duration.ofMillis(250)) - .map(pizza -> pizza); + return Mono.just(this).delayElement(Duration.ofMillis(250)).map(pizza -> pizza); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java index 58fd15b5786ec..4c8de4d6eedf9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java @@ -41,19 +41,15 @@ public void testSampleTaskGroupSanity() { * ------->D------------- */ final List groupItems = new ArrayList<>(); - TaskGroup group = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - groupItems); + TaskGroup group = createSampleTaskGroup("A", "B", "C", "D", "E", "F", groupItems); // Invocation of group should invoke all the tasks // - group.invokeAsync(group.newInvocationContext()) - .subscribe(value -> { - StringIndexable stringIndexable = toStringIndexable(value); - Assertions.assertTrue(groupItems.contains(stringIndexable.str())); - groupItems.remove(stringIndexable.str()); - }); + group.invokeAsync(group.newInvocationContext()).subscribe(value -> { + StringIndexable stringIndexable = toStringIndexable(value); + Assertions.assertTrue(groupItems.contains(stringIndexable.str())); + groupItems.remove(stringIndexable.str()); + }); Assertions.assertEquals(0, groupItems.size()); @@ -61,29 +57,29 @@ public void testSampleTaskGroupSanity() { // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { })); Set seen = new HashSet<>(); // Test invocation order for group // group.prepareForEnumeration(); for (TaskGroupEntry entry = group.getNext(); entry != null; entry = group.getNext()) { -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -95,8 +91,8 @@ public void testSampleTaskGroupSanity() { Assertions.assertEquals(6, seen.size()); // 1 groups with 6 nodes Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", "E", "F"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); } @@ -119,10 +115,7 @@ public void testTaskGroupInvocationShouldNotInvokeDependentTaskGroup() { * ------->D------------- */ final List group1Items = new ArrayList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -140,10 +133,7 @@ public void testTaskGroupInvocationShouldNotInvokeDependentTaskGroup() { * ------->J------------- */ final List group2Items = new ArrayList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Expand group-2 by adding group-1 as it's dependency // @@ -175,12 +165,11 @@ public void testTaskGroupInvocationShouldNotInvokeDependentTaskGroup() { // Invocation of group-1 should not invoke group-2 // - group1.invokeAsync(group1.newInvocationContext()) - .subscribe(value -> { - StringIndexable stringIndexable = toStringIndexable(value); - Assertions.assertTrue(group1Items.contains(stringIndexable.str())); - group1Items.remove(stringIndexable.str()); - }); + group1.invokeAsync(group1.newInvocationContext()).subscribe(value -> { + StringIndexable stringIndexable = toStringIndexable(value); + Assertions.assertTrue(group1Items.contains(stringIndexable.str())); + group1Items.remove(stringIndexable.str()); + }); Assertions.assertEquals(0, group1Items.size()); @@ -188,29 +177,29 @@ public void testTaskGroupInvocationShouldNotInvokeDependentTaskGroup() { // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { })); Set seen = new HashSet<>(); // Test invocation order for group-1 // group1.prepareForEnumeration(); for (TaskGroupEntry entry = group1.getNext(); entry != null; entry = group1.getNext()) { -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -222,8 +211,8 @@ public void testTaskGroupInvocationShouldNotInvokeDependentTaskGroup() { Assertions.assertEquals(6, seen.size()); // 1 groups with 6 nodes Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", "E", "F"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); } @@ -246,10 +235,7 @@ public void testTaskGroupInvocationShouldInvokeDependencyTaskGroup() { * ------->D------------- */ final List group1Items = new ArrayList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -267,10 +253,7 @@ public void testTaskGroupInvocationShouldInvokeDependencyTaskGroup() { * ------->J------------- */ final List group2Items = new ArrayList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Expand group-2 by adding it as group-1's dependent // @@ -304,54 +287,52 @@ public void testTaskGroupInvocationShouldInvokeDependencyTaskGroup() { // Invocation of group-2 should invoke group-2 and group-1 // - group2.invokeAsync(group2.newInvocationContext()) - .subscribe(value -> { - StringIndexable stringIndexable = toStringIndexable(value); - Assertions.assertTrue(group2Items.contains(stringIndexable.str())); - group2Items.remove(stringIndexable.str()); - }); + group2.invokeAsync(group2.newInvocationContext()).subscribe(value -> { + StringIndexable stringIndexable = toStringIndexable(value); + Assertions.assertTrue(group2Items.contains(stringIndexable.str())); + group2Items.remove(stringIndexable.str()); + }); Assertions.assertEquals(0, group2Items.size()); - Map> shouldNotSee = new HashMap<>(); // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { })); // NotSeen entries for nodes in Group-2 // shouldNotSee.put("G", new HashSet()); - shouldNotSee.get("G").addAll(Arrays.asList(new String[]{"H", "I", "J", "K", "L"})); + shouldNotSee.get("G").addAll(Arrays.asList(new String[] { "H", "I", "J", "K", "L" })); shouldNotSee.put("H", new HashSet()); - shouldNotSee.get("H").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("H").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("I", new HashSet()); - shouldNotSee.get("I").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("I").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("J", new HashSet()); - shouldNotSee.get("J").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("J").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("K", new HashSet()); - shouldNotSee.get("K").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("K").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("L", new HashSet()); - shouldNotSee.get("L").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("L").addAll(Arrays.asList(new String[] { })); Set seen = new HashSet<>(); // Test invocation order for group-2 @@ -360,7 +341,7 @@ public void testTaskGroupInvocationShouldInvokeDependencyTaskGroup() { for (TaskGroupEntry entry = group2.getNext(); entry != null; entry = group2.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -372,8 +353,9 @@ public void testTaskGroupInvocationShouldInvokeDependencyTaskGroup() { Assertions.assertEquals(12, seen.size()); // 2 groups each with 6 nodes Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee + .addAll(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); } @@ -396,10 +378,7 @@ public void testTaskGroupInvocationShouldInvokePostRunDependentTaskGroup() { * ------->D------------- */ final LinkedList group1Items = new LinkedList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -417,10 +396,7 @@ public void testTaskGroupInvocationShouldInvokePostRunDependentTaskGroup() { * ------->J------------- */ final LinkedList group2Items = new LinkedList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Add group-2 as group-1's "post run" dependent // @@ -457,70 +433,66 @@ public void testTaskGroupInvocationShouldInvokePostRunDependentTaskGroup() { // Invocation of group-1 should run group-1 and it's "post run" dependent group-2 // - group1.invokeAsync(group1.newInvocationContext()) - .subscribe( - value -> { - StringIndexable stringIndexable = toStringIndexable(value); - Assertions.assertTrue(group1Items.contains(stringIndexable.str())); - group1Items.remove(stringIndexable.str()); - }, throwable -> { - } - ); + group1.invokeAsync(group1.newInvocationContext()).subscribe(value -> { + StringIndexable stringIndexable = toStringIndexable(value); + Assertions.assertTrue(group1Items.contains(stringIndexable.str())); + group1Items.remove(stringIndexable.str()); + }, throwable -> { + }); Assertions.assertEquals(0, group1Items.size()); Map> shouldNotSee = new HashMap<>(); // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F", "proxy-F"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F", "proxy-F" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F", "proxy-F"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F", "proxy-F" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F", "proxy-F"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F", "proxy-F" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{"proxy-F"})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { "proxy-F" })); // NotSeen entries for nodes in Group-2 // shouldNotSee.put("G", new HashSet()); - shouldNotSee.get("G").addAll(Arrays.asList(new String[]{"H", "I", "J", "K", "L", "proxy-F"})); + shouldNotSee.get("G").addAll(Arrays.asList(new String[] { "H", "I", "J", "K", "L", "proxy-F" })); shouldNotSee.put("H", new HashSet()); - shouldNotSee.get("H").addAll(Arrays.asList(new String[]{"L", "proxy-F"})); + shouldNotSee.get("H").addAll(Arrays.asList(new String[] { "L", "proxy-F" })); shouldNotSee.put("I", new HashSet()); - shouldNotSee.get("I").addAll(Arrays.asList(new String[]{"K", "L", "proxy-F"})); + shouldNotSee.get("I").addAll(Arrays.asList(new String[] { "K", "L", "proxy-F" })); shouldNotSee.put("J", new HashSet()); - shouldNotSee.get("J").addAll(Arrays.asList(new String[]{"K", "L", "proxy-F"})); + shouldNotSee.get("J").addAll(Arrays.asList(new String[] { "K", "L", "proxy-F" })); shouldNotSee.put("K", new HashSet()); - shouldNotSee.get("K").addAll(Arrays.asList(new String[]{"L", "proxy-F"})); + shouldNotSee.get("K").addAll(Arrays.asList(new String[] { "L", "proxy-F" })); shouldNotSee.put("L", new HashSet()); - shouldNotSee.get("L").addAll(Arrays.asList(new String[]{"proxy-F"})); + shouldNotSee.get("L").addAll(Arrays.asList(new String[] { "proxy-F" })); // NotSeen entries for proxies shouldNotSee.put("proxy-F", new HashSet()); - shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[] { })); Set seen = new HashSet<>(); // Test invocation order for "group-1 proxy" // group1.proxyTaskGroupWrapper.taskGroup().prepareForEnumeration(); - for (TaskGroupEntry entry = group1.proxyTaskGroupWrapper.taskGroup().getNext(); - entry != null; - entry = group1.proxyTaskGroupWrapper.taskGroup().getNext()) { + for (TaskGroupEntry entry = group1.proxyTaskGroupWrapper.taskGroup().getNext(); entry != null; + entry = group1.proxyTaskGroupWrapper.taskGroup().getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -532,17 +504,14 @@ public void testTaskGroupInvocationShouldInvokePostRunDependentTaskGroup() { Assertions.assertEquals(13, seen.size()); // 2 groups each with 6 nodes + 1 proxy (proxy-F) Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "G", "H", - "I", "J", "K", "L", - "proxy-F"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll( + Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "proxy-F" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); - group1.invokeAsync(group1.newInvocationContext()) - .subscribe(indexable -> LOGGER.log(LogLevel.VERBOSE, indexable::key)); + .subscribe(indexable -> LOGGER.log(LogLevel.VERBOSE, indexable::key)); } @Test @@ -563,10 +532,7 @@ public void testPostRunTaskGroupInvocationShouldInvokeDependencyTaskGroup() { * ------->D------------- */ final LinkedList group1Items = new LinkedList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -584,10 +550,7 @@ public void testPostRunTaskGroupInvocationShouldInvokeDependencyTaskGroup() { * ------->J------------- */ final List group2Items = new ArrayList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Add group-2 as group-1's "post run" dependent // @@ -624,56 +587,55 @@ public void testPostRunTaskGroupInvocationShouldInvokeDependencyTaskGroup() { // Invocation of group-2 should run group-2 and group-1 // - group2.invokeAsync(group2.newInvocationContext()) - .subscribe(value -> { - StringIndexable stringIndexable = toStringIndexable(value); - Assertions.assertTrue(group2Items.contains(stringIndexable.str())); - group2Items.remove(stringIndexable.str()); - }); + group2.invokeAsync(group2.newInvocationContext()).subscribe(value -> { + StringIndexable stringIndexable = toStringIndexable(value); + Assertions.assertTrue(group2Items.contains(stringIndexable.str())); + group2Items.remove(stringIndexable.str()); + }); Assertions.assertEquals(0, group2Items.size()); Map> shouldNotSee = new HashMap<>(); // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F", "proxy-F"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F", "proxy-F" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F", "proxy-F"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F", "proxy-F" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F", "proxy-F"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F", "proxy-F" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{"proxy-F"})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { "proxy-F" })); // NotSeen entries for nodes in Group-2 // shouldNotSee.put("G", new HashSet()); - shouldNotSee.get("G").addAll(Arrays.asList(new String[]{"H", "I", "J", "K", "L", "proxy-F"})); + shouldNotSee.get("G").addAll(Arrays.asList(new String[] { "H", "I", "J", "K", "L", "proxy-F" })); shouldNotSee.put("H", new HashSet()); - shouldNotSee.get("H").addAll(Arrays.asList(new String[]{"L", "proxy-F"})); + shouldNotSee.get("H").addAll(Arrays.asList(new String[] { "L", "proxy-F" })); shouldNotSee.put("I", new HashSet()); - shouldNotSee.get("I").addAll(Arrays.asList(new String[]{"K", "L", "proxy-F"})); + shouldNotSee.get("I").addAll(Arrays.asList(new String[] { "K", "L", "proxy-F" })); shouldNotSee.put("J", new HashSet()); - shouldNotSee.get("J").addAll(Arrays.asList(new String[]{"K", "L", "proxy-F"})); + shouldNotSee.get("J").addAll(Arrays.asList(new String[] { "K", "L", "proxy-F" })); shouldNotSee.put("K", new HashSet()); - shouldNotSee.get("K").addAll(Arrays.asList(new String[]{"L", "proxy-F"})); + shouldNotSee.get("K").addAll(Arrays.asList(new String[] { "L", "proxy-F" })); shouldNotSee.put("L", new HashSet()); - shouldNotSee.get("L").addAll(Arrays.asList(new String[]{"proxy-F"})); + shouldNotSee.get("L").addAll(Arrays.asList(new String[] { "proxy-F" })); // NotSeen entries for proxies shouldNotSee.put("proxy-F", new HashSet()); - shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[] { })); Set seen = new HashSet<>(); // Test invocation order for "group-2 proxy" @@ -682,7 +644,7 @@ public void testPostRunTaskGroupInvocationShouldInvokeDependencyTaskGroup() { for (TaskGroupEntry entry = group2.getNext(); entry != null; entry = group2.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -694,10 +656,9 @@ public void testPostRunTaskGroupInvocationShouldInvokeDependencyTaskGroup() { Assertions.assertEquals(12, seen.size()); // 2 groups each with 6 nodes no proxy Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "G", "H", - "I", "J", "K", "L"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee + .addAll(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); } @@ -720,10 +681,7 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { * ------->D------------- */ final LinkedList group1Items = new LinkedList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -741,10 +699,7 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { * ------->J------------- */ final List group2Items = new ArrayList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Make group-2 as group-1's parent by adding group-1 as group-2's dependency. // @@ -796,10 +751,7 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { */ final LinkedList group3Items = new LinkedList<>(); - final TaskGroup group3 = createSampleTaskGroup("M", "N", - "O", "P", - "Q", "R", - group3Items); + final TaskGroup group3 = createSampleTaskGroup("M", "N", "O", "P", "Q", "R", group3Items); // Make group-3 as group-1's 'post-run" dependent. This activate proxy group, should do parent re-assignment // i.e. the parent "group-2" of "group-1" will become parent of "group-1's proxy". @@ -846,63 +798,63 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { Map> shouldNotSee = new HashMap<>(); // NotSeen entries for group-1 shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F", "proxy-F", "L"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F", "proxy-F", "L" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F", "proxy-F", "L"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F", "proxy-F", "L" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F", "L"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F", "L" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F", "L"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F", "L" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F", "proxy-F", "L"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F", "proxy-F", "L" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{"proxy-F", "L"})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { "proxy-F", "L" })); // NotSeen entries for nodes in Group-3 // shouldNotSee.put("M", new HashSet()); - shouldNotSee.get("M").addAll(Arrays.asList(new String[]{"N", "O", "P", "Q", "R", "proxy-F", "L"})); + shouldNotSee.get("M").addAll(Arrays.asList(new String[] { "N", "O", "P", "Q", "R", "proxy-F", "L" })); shouldNotSee.put("N", new HashSet()); - shouldNotSee.get("N").addAll(Arrays.asList(new String[]{"R", "proxy-F", "L"})); + shouldNotSee.get("N").addAll(Arrays.asList(new String[] { "R", "proxy-F", "L" })); shouldNotSee.put("O", new HashSet()); - shouldNotSee.get("O").addAll(Arrays.asList(new String[]{"Q", "R", "L"})); + shouldNotSee.get("O").addAll(Arrays.asList(new String[] { "Q", "R", "L" })); shouldNotSee.put("P", new HashSet()); - shouldNotSee.get("P").addAll(Arrays.asList(new String[]{"Q", "R", "proxy-F", "L"})); + shouldNotSee.get("P").addAll(Arrays.asList(new String[] { "Q", "R", "proxy-F", "L" })); shouldNotSee.put("Q", new HashSet()); - shouldNotSee.get("Q").addAll(Arrays.asList(new String[]{"R", "proxy-F", "L"})); + shouldNotSee.get("Q").addAll(Arrays.asList(new String[] { "R", "proxy-F", "L" })); shouldNotSee.put("R", new HashSet()); - shouldNotSee.get("R").addAll(Arrays.asList(new String[]{"proxy-F", "L"})); + shouldNotSee.get("R").addAll(Arrays.asList(new String[] { "proxy-F", "L" })); // NotSeen entries for nodes in Group-2 // shouldNotSee.put("G", new HashSet()); - shouldNotSee.get("G").addAll(Arrays.asList(new String[]{"H", "I", "J", "K", "L"})); + shouldNotSee.get("G").addAll(Arrays.asList(new String[] { "H", "I", "J", "K", "L" })); shouldNotSee.put("H", new HashSet()); - shouldNotSee.get("H").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("H").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("I", new HashSet()); - shouldNotSee.get("I").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("I").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("J", new HashSet()); - shouldNotSee.get("J").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("J").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("K", new HashSet()); - shouldNotSee.get("K").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("K").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("L", new HashSet()); - shouldNotSee.get("L").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("L").addAll(Arrays.asList(new String[] { })); // NotSeen entries for proxies shouldNotSee.put("proxy-F", new HashSet()); - shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[] { "L" })); Set seen = new HashSet<>(); // Test invocation order for "group-2" @@ -911,7 +863,7 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { for (TaskGroupEntry entry = group2.getNext(); entry != null; entry = group2.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -923,12 +875,27 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { Assertions.assertEquals(19, seen.size()); // 3 groups each with 6 nodes + one proxy (proxy-F) Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "G", "H", - "I", "J", "K", "L", - "M", "N", "O", "P", - "Q", "proxy-F", "R"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "proxy-F", + "R" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); @@ -940,7 +907,7 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { for (TaskGroupEntry entry = group1Proxy.getNext(); entry != null; entry = group1Proxy.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -952,10 +919,8 @@ public void testParentReassignmentUponProxyTaskGroupActivation() { Assertions.assertEquals(13, seen.size()); // 2 groups each with 6 nodes + one proxy (proxy-F) expectedToSee.clear(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "M", "N", - "O", "P", "Q", "proxy-F", - "R"})); + expectedToSee.addAll( + Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F", "M", "N", "O", "P", "Q", "proxy-F", "R" })); } @Test @@ -976,10 +941,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { * ------->D------------- */ final LinkedList group1Items = new LinkedList<>(); - final TaskGroup group1 = createSampleTaskGroup("A", "B", - "C", "D", - "E", "F", - group1Items); + final TaskGroup group1 = createSampleTaskGroup("A", "B", "C", "D", "E", "F", group1Items); // Prepare group-2 // @@ -997,10 +959,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { * ------->J------------- */ final List group2Items = new ArrayList<>(); - final TaskGroup group2 = createSampleTaskGroup("G", "H", - "I", "J", - "K", "L", - group2Items); + final TaskGroup group2 = createSampleTaskGroup("G", "H", "I", "J", "K", "L", group2Items); // Make group-2 as group-1's parent by adding group-1 as group-2's dependency. // @@ -1052,10 +1011,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { */ final LinkedList group3Items = new LinkedList<>(); - final TaskGroup group3 = createSampleTaskGroup("M", "N", - "O", "P", - "Q", "R", - group3Items); + final TaskGroup group3 = createSampleTaskGroup("M", "N", "O", "P", "Q", "R", group3Items); // Make group-3 (Root-R) as group-1's (Root-F) 'post-run" dependent. This activate "group-1 proxy group", // should do parent re-assignment i.e. the parent "group-2" of "group-1" will become parent of "group-1's proxy". @@ -1099,7 +1055,6 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { Assertions.assertEquals(1, group1.proxyTaskGroupWrapper.taskGroup().parentDAGs.size()); Assertions.assertTrue(group1.proxyTaskGroupWrapper.taskGroup().parentDAGs.contains(group2)); - // Prepare group-4 // /** @@ -1117,10 +1072,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { */ final LinkedList group4Items = new LinkedList<>(); - final TaskGroup group4 = createSampleTaskGroup("S", "T", - "U", "V", - "W", "X", - group4Items); + final TaskGroup group4 = createSampleTaskGroup("S", "T", "U", "V", "W", "X", group4Items); // Prepare group-5 // @@ -1139,10 +1091,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { */ final LinkedList group5Items = new LinkedList<>(); - final TaskGroup group5 = createSampleTaskGroup("1", "2", - "3", "4", - "5", "6", - group5Items); + final TaskGroup group5 = createSampleTaskGroup("1", "2", "3", "4", "5", "6", group5Items); // Make group-5 as group-4's 'post-run" dependent. This activates "group-4 proxy group". @@ -1239,105 +1188,107 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { // NotSeen entries for nodes in Group-1 // shouldNotSee.put("A", new HashSet()); - shouldNotSee.get("A").addAll(Arrays.asList(new String[]{"B", "C", "D", "E", "F", "proxy-F", "L"})); + shouldNotSee.get("A").addAll(Arrays.asList(new String[] { "B", "C", "D", "E", "F", "proxy-F", "L" })); shouldNotSee.put("B", new HashSet()); - shouldNotSee.get("B").addAll(Arrays.asList(new String[]{"F", "proxy-F", "L"})); + shouldNotSee.get("B").addAll(Arrays.asList(new String[] { "F", "proxy-F", "L" })); shouldNotSee.put("C", new HashSet()); - shouldNotSee.get("C").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F", "L"})); + shouldNotSee.get("C").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F", "L" })); shouldNotSee.put("D", new HashSet()); - shouldNotSee.get("D").addAll(Arrays.asList(new String[]{"E", "F", "proxy-F", "L"})); + shouldNotSee.get("D").addAll(Arrays.asList(new String[] { "E", "F", "proxy-F", "L" })); shouldNotSee.put("E", new HashSet()); - shouldNotSee.get("E").addAll(Arrays.asList(new String[]{"F", "proxy-F", "L"})); + shouldNotSee.get("E").addAll(Arrays.asList(new String[] { "F", "proxy-F", "L" })); shouldNotSee.put("F", new HashSet()); - shouldNotSee.get("F").addAll(Arrays.asList(new String[]{"proxy-F", "L"})); + shouldNotSee.get("F").addAll(Arrays.asList(new String[] { "proxy-F", "L" })); // NotSeen entries for nodes in Group-3 // shouldNotSee.put("M", new HashSet()); - shouldNotSee.get("M").addAll(Arrays.asList(new String[]{"N", "O", "P", "Q", "R", "proxy-F", "L"})); + shouldNotSee.get("M").addAll(Arrays.asList(new String[] { "N", "O", "P", "Q", "R", "proxy-F", "L" })); shouldNotSee.put("N", new HashSet()); - shouldNotSee.get("N").addAll(Arrays.asList(new String[]{"R", "proxy-F", "L"})); + shouldNotSee.get("N").addAll(Arrays.asList(new String[] { "R", "proxy-F", "L" })); shouldNotSee.put("O", new HashSet()); - shouldNotSee.get("O").addAll(Arrays.asList(new String[]{"Q", "R", "L"})); + shouldNotSee.get("O").addAll(Arrays.asList(new String[] { "Q", "R", "L" })); shouldNotSee.put("P", new HashSet()); - shouldNotSee.get("P").addAll(Arrays.asList(new String[]{"Q", "R", "proxy-F", "L"})); + shouldNotSee.get("P").addAll(Arrays.asList(new String[] { "Q", "R", "proxy-F", "L" })); shouldNotSee.put("Q", new HashSet()); - shouldNotSee.get("Q").addAll(Arrays.asList(new String[]{"R", "proxy-F", "L"})); + shouldNotSee.get("Q").addAll(Arrays.asList(new String[] { "R", "proxy-F", "L" })); shouldNotSee.put("R", new HashSet()); - shouldNotSee.get("R").addAll(Arrays.asList(new String[]{"proxy-F", "L"})); + shouldNotSee.get("R").addAll(Arrays.asList(new String[] { "proxy-F", "L" })); // NotSeen entries for nodes in Group-4 // shouldNotSee.put("S", new HashSet()); - shouldNotSee.get("S").addAll(Arrays.asList(new String[]{"T", "U", "V", "W", "X", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("S") + .addAll(Arrays.asList(new String[] { "T", "U", "V", "W", "X", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("T", new HashSet()); - shouldNotSee.get("T").addAll(Arrays.asList(new String[]{"X", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("T").addAll(Arrays.asList(new String[] { "X", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("U", new HashSet()); - shouldNotSee.get("U").addAll(Arrays.asList(new String[]{"W", "X", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("U").addAll(Arrays.asList(new String[] { "W", "X", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("V", new HashSet()); - shouldNotSee.get("V").addAll(Arrays.asList(new String[]{"W", "X", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("V").addAll(Arrays.asList(new String[] { "W", "X", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("W", new HashSet()); - shouldNotSee.get("W").addAll(Arrays.asList(new String[]{"X", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("W").addAll(Arrays.asList(new String[] { "X", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("X", new HashSet()); - shouldNotSee.get("X").addAll(Arrays.asList(new String[]{"proxy-X", "proxy-F", "L"})); + shouldNotSee.get("X").addAll(Arrays.asList(new String[] { "proxy-X", "proxy-F", "L" })); // NotSeen entries for nodes in Group-5 // shouldNotSee.put("1", new HashSet()); - shouldNotSee.get("1").addAll(Arrays.asList(new String[]{"2", "3", "4", "5", "6", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("1") + .addAll(Arrays.asList(new String[] { "2", "3", "4", "5", "6", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("2", new HashSet()); - shouldNotSee.get("2").addAll(Arrays.asList(new String[]{"6", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("2").addAll(Arrays.asList(new String[] { "6", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("3", new HashSet()); - shouldNotSee.get("3").addAll(Arrays.asList(new String[]{"5", "6", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("3").addAll(Arrays.asList(new String[] { "5", "6", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("4", new HashSet()); - shouldNotSee.get("4").addAll(Arrays.asList(new String[]{"5", "6", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("4").addAll(Arrays.asList(new String[] { "5", "6", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("5", new HashSet()); - shouldNotSee.get("5").addAll(Arrays.asList(new String[]{"6", "proxy-X", "proxy-F", "L"})); + shouldNotSee.get("5").addAll(Arrays.asList(new String[] { "6", "proxy-X", "proxy-F", "L" })); shouldNotSee.put("6", new HashSet()); - shouldNotSee.get("6").addAll(Arrays.asList(new String[]{"proxy-X", "proxy-F", "L"})); + shouldNotSee.get("6").addAll(Arrays.asList(new String[] { "proxy-X", "proxy-F", "L" })); // NotSeen entries for nodes in Group-2 // shouldNotSee.put("G", new HashSet()); - shouldNotSee.get("G").addAll(Arrays.asList(new String[]{"H", "I", "J", "K", "L"})); + shouldNotSee.get("G").addAll(Arrays.asList(new String[] { "H", "I", "J", "K", "L" })); shouldNotSee.put("H", new HashSet()); - shouldNotSee.get("H").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("H").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("I", new HashSet()); - shouldNotSee.get("I").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("I").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("J", new HashSet()); - shouldNotSee.get("J").addAll(Arrays.asList(new String[]{"K", "L"})); + shouldNotSee.get("J").addAll(Arrays.asList(new String[] { "K", "L" })); shouldNotSee.put("K", new HashSet()); - shouldNotSee.get("K").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("K").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("L", new HashSet()); - shouldNotSee.get("L").addAll(Arrays.asList(new String[]{})); + shouldNotSee.get("L").addAll(Arrays.asList(new String[] { })); // NotSeen entries for proxies shouldNotSee.put("proxy-F", new HashSet()); - shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[]{"L"})); + shouldNotSee.get("proxy-F").addAll(Arrays.asList(new String[] { "L" })); shouldNotSee.put("proxy-X", new HashSet()); - shouldNotSee.get("proxy-X").addAll(Arrays.asList(new String[]{"proxy-F", "L"})); + shouldNotSee.get("proxy-X").addAll(Arrays.asList(new String[] { "proxy-F", "L" })); // Test invocation order for group-1 (which gets delegated to group-1's proxy) // @@ -1348,7 +1299,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { for (TaskGroupEntry entry = group1Proxy.getNext(); entry != null; entry = group1Proxy.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -1360,14 +1311,34 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { Assertions.assertEquals(26, seen.size()); // 4 groups each with 6 nodes + two proxy (proxy-F and proxy-X) Set expectedToSee = new HashSet<>(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "M", "N", - "O", "P", "Q", "R", - "S", "T", "U", "V", - "W", "X", "proxy-X", - "1", "proxy-F", "2", - "3", "4", "5", "6"})); -// Sets.SetView diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { + "A", + "B", + "C", + "D", + "E", + "F", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "proxy-X", + "1", + "proxy-F", + "2", + "3", + "4", + "5", + "6" })); + // Sets.SetView diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); @@ -1380,7 +1351,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { for (TaskGroupEntry entry = group4Proxy.getNext(); entry != null; entry = group4Proxy.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -1392,13 +1363,28 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { Assertions.assertEquals(19, seen.size()); // 3 groups each with 6 nodes + one proxy expectedToSee.clear(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "S", "T", - "U", "V", "W", "X", - "proxy-X", "1", "2", - "3", "4", "5", "6"})); - -// diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { + "A", + "B", + "C", + "D", + "E", + "F", + "S", + "T", + "U", + "V", + "W", + "X", + "proxy-X", + "1", + "2", + "3", + "4", + "5", + "6" })); + + // diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); @@ -1410,7 +1396,7 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { for (TaskGroupEntry entry = group2.getNext(); entry != null; entry = group2.getNext()) { Assertions.assertTrue(shouldNotSee.containsKey(entry.key())); Assertions.assertFalse(seen.contains(entry.key())); -// Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); + // Sets.SetView common = Sets.intersection(shouldNotSee.get(entry.key()), seen); Set common = shouldNotSee.get(entry.key()); common.retainAll(seen); if (common.size() > 0) { @@ -1421,16 +1407,41 @@ public void testParentProxyReassignmentUponProxyTaskGroupActivation() { } expectedToSee.clear(); - expectedToSee.addAll(Arrays.asList(new String[]{"A", "B", "C", "D", - "E", "F", "G", "H", - "I", "J", "K", "L", - "M", "N", "O", "P", - "Q", "R", "S", "T", - "U", "V", "W", "X", - "proxy-X", "1", "proxy-F", "2", "3", - "4", "5", "6"})); - -// diff = Sets.difference(seen, expectedToSee); + expectedToSee.addAll(Arrays.asList(new String[] { + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "proxy-X", + "1", + "proxy-F", + "2", + "3", + "4", + "5", + "6" })); + + // diff = Sets.difference(seen, expectedToSee); seen.removeAll(expectedToSee); Assertions.assertEquals(0, seen.size()); } @@ -1484,17 +1495,15 @@ protected Mono invokeTaskAsync(TaskGroup.InvocationContext context) { CountDownLatch down = new CountDownLatch(1); itiC.taskGroup() .invokeAsync(itiC.taskGroup().newInvocationContext()) - .subscribe( - indexable -> seen.add(indexable.key()), - throwable -> down.countDown(), - () -> down.countDown()); + .subscribe(indexable -> seen.add(indexable.key()), throwable -> down.countDown(), () -> down.countDown()); down.await(); - boolean b1 = seen.equals(new ArrayList<>(Arrays.asList(new String[]{"A", "C", "B", "C"}))); - boolean b2 = seen.equals(new ArrayList<>(Arrays.asList(new String[]{"C", "A", "B", "C"}))); + boolean b1 = seen.equals(new ArrayList<>(Arrays.asList(new String[] { "A", "C", "B", "C" }))); + boolean b2 = seen.equals(new ArrayList<>(Arrays.asList(new String[] { "C", "A", "B", "C" }))); if (!b1 && !b2) { - Assertions.assertTrue(false, "Emission order should be either [A, C, B, C] or [C, A, B, C] but got " + seen); + Assertions.assertTrue(false, + "Emission order should be either [A, C, B, C] or [C, A, B, C] but got " + seen); } Assertions.assertEquals(beforeGroupInvokeCntB[0], 1); @@ -1549,26 +1558,20 @@ protected Mono invokeTaskAsync(TaskGroup.InvocationContext context) { seen.clear(); itiF.taskGroup() .invokeAsync(itiC.taskGroup().newInvocationContext()) - .subscribe(indexable -> seen.add(indexable.key()), - throwable -> monitor.countDown(), + .subscribe(indexable -> seen.add(indexable.key()), throwable -> monitor.countDown(), () -> monitor.countDown()); monitor.await(); - b1 = seen.equals(new ArrayList<>(Arrays.asList(new String[]{"E", "D", "E", "F"}))); + b1 = seen.equals(new ArrayList<>(Arrays.asList(new String[] { "E", "D", "E", "F" }))); Assertions.assertTrue(b1, "Emission order should be [E, D, E, F] but got " + seen); Assertions.assertEquals(beforeGroupInvokeCntE[0], 1); Assertions.assertEquals(beforeGroupInvokeCntF[0], 1); } - private TaskGroup createSampleTaskGroup(String vertex1, - String vertex2, - String vertex3, - String vertex4, - String vertex5, - String vertex6, - List verticesNames) { + private TaskGroup createSampleTaskGroup(String vertex1, String vertex2, String vertex3, String vertex4, + String vertex5, String vertex6, List verticesNames) { verticesNames.add(vertex6); verticesNames.add(vertex5); verticesNames.add(vertex4); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java index 419086bfe47cd..25bf05aabfce3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java @@ -14,9 +14,7 @@ /** * Implementation of {@link ISandwich} */ -public class SandwichImpl - extends CreatableUpdatableImpl - implements ISandwich { +public class SandwichImpl extends CreatableUpdatableImpl implements ISandwich { private static final ClientLogger LOGGER = new ClientLogger(SandwichImpl.class); /** @@ -29,7 +27,6 @@ protected SandwichImpl(String name, SandwichInner innerObject) { super(name, name, innerObject); } - @Override public ISandwich withBreadSliceFromStore(Executable breadFetcher) { this.addDependency(breadFetcher); @@ -39,9 +36,7 @@ public ISandwich withBreadSliceFromStore(Executable breadFetcher) { @Override public Mono createResourceAsync() { LOGGER.log(LogLevel.VERBOSE, () -> "Sandwich(" + this.name() + ")::createResourceAsync() [Creating sandwich]"); - return Mono.just(this) - .delayElement(Duration.ofMillis(250)) - .map(sandwich -> sandwich); + return Mono.just(this).delayElement(Duration.ofMillis(250)).map(sandwich -> sandwich); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/BatchDeletionImplTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/BatchDeletionImplTests.java index 0041ddad73744..2fbee4b338601 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/BatchDeletionImplTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/BatchDeletionImplTests.java @@ -21,35 +21,41 @@ public class BatchDeletionImplTests { @Test public void testBatchDeletion() { - BiFunction> mockDeleteByGroupAndNameAsync = - (rgName, name) -> name.startsWith("invalid") ? Mono.error(new ManagementException("fail on " + name, null)) : Mono.empty(); + BiFunction> mockDeleteByGroupAndNameAsync + = (rgName, name) -> name.startsWith("invalid") + ? Mono.error(new ManagementException("fail on " + name, null)) + : Mono.empty(); // 1 error List names = Arrays.asList("valid1", "invalid2", "valid3", "valid4", "valid5"); List ids = names.stream() - .map(name -> "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg1/providers/Microsoft.Compute/disks/" + name) + .map( + name -> "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg1/providers/Microsoft.Compute/disks/" + + name) .collect(Collectors.toList()); Map resultIds = new ConcurrentHashMap<>(); Flux fluxIds = BatchDeletionImpl.deleteByIdsAsync(ids, mockDeleteByGroupAndNameAsync); Assertions.assertThrows(ManagementException.class, () -> { - fluxIds.doOnNext(id -> resultIds.put(id, id)) - .onErrorMap(e -> e) - .blockLast(); + fluxIds.doOnNext(id -> resultIds.put(id, id)).onErrorMap(e -> e).blockLast(); }); Assertions.assertEquals(4, resultIds.size()); } @Test public void testBatchDeletionMultipleException() { - BiFunction> mockDeleteByGroupAndNameAsync = - (rgName, name) -> name.startsWith("invalid") ? Mono.error(new ManagementException("fail on " + name, null)) : Mono.empty(); + BiFunction> mockDeleteByGroupAndNameAsync + = (rgName, name) -> name.startsWith("invalid") + ? Mono.error(new ManagementException("fail on " + name, null)) + : Mono.empty(); // more than 1 errors List names = Arrays.asList("valid1", "invalid2", "valid3", "invalid4", "valid5"); List ids = names.stream() - .map(name -> "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg1/providers/Microsoft.Compute/disks/" + name) + .map( + name -> "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg1/providers/Microsoft.Compute/disks/" + + name) .collect(Collectors.toList()); Map resultIds = new ConcurrentHashMap<>(); @@ -57,9 +63,7 @@ public void testBatchDeletionMultipleException() { // reactor.core.Exceptions.CompositeException Assertions.assertThrows(ManagementException.class, () -> { - fluxIds.doOnNext(id -> resultIds.put(id, id)) - .onErrorMap(e -> e) - .blockLast(); + fluxIds.doOnNext(id -> resultIds.put(id, id)).onErrorMap(e -> e).blockLast(); }); Assertions.assertEquals(3, resultIds.size()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverterTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverterTests.java index 7eda2b26605cd..ce460056f3a62 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverterTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/PagedConverterTests.java @@ -88,7 +88,8 @@ public void testMapPageIterator() { @Test public void testFlatMapPage() { PagedFlux pagedFlux = mockPagedFlux("base", 0, 10, 4); - PagedFlux convertedPagedFlux = PagedConverter.flatMapPage(pagedFlux, item -> Flux.just(item, item + "#")); + PagedFlux convertedPagedFlux + = PagedConverter.flatMapPage(pagedFlux, item -> Flux.just(item, item + "#")); StepVerifier.create(convertedPagedFlux.byPage()) .expectSubscription() .expectNextMatches(p -> p.getValue().size() == 8 @@ -105,7 +106,8 @@ public void testFlatMapPage() { @Test public void testMergePagedFlux() { PagedFlux pagedFlux = mockPagedFlux("base", 0, 3, 2); - PagedFlux mergedPagedFlux = PagedConverter.mergePagedFlux(pagedFlux, item -> mockPagedFlux(item + "sub", 0, 10, 4)); + PagedFlux mergedPagedFlux + = PagedConverter.mergePagedFlux(pagedFlux, item -> mockPagedFlux(item + "sub", 0, 10, 4)); StepVerifier.create(mergedPagedFlux.byPage()) .expectSubscription() .expectNextMatches(p -> p.getValue().size() == 4 @@ -183,7 +185,8 @@ public void testMapPageOnePage() { public void testFlatMapPageOnePage() { AtomicInteger pageCount = new AtomicInteger(0); PagedFlux pagedFlux = mockPagedFlux("base", 0, 10, 4, pageCount); - PagedFlux convertedPagedFlux = PagedConverter.flatMapPage(pagedFlux, item -> Flux.just(item, item + "#")); + PagedFlux convertedPagedFlux + = PagedConverter.flatMapPage(pagedFlux, item -> Flux.just(item, item + "#")); PagedIterable pagedIterable = new PagedIterable<>(convertedPagedFlux); pagedIterable.stream().findFirst().get(); @@ -197,7 +200,8 @@ public void testMergePagedFluxOnePage() { AtomicInteger pageCountRoot = new AtomicInteger(0); AtomicInteger pageCount = new AtomicInteger(0); PagedFlux pagedFlux = mockPagedFlux("base", 0, 3, 2, pageCountRoot); - PagedFlux mergedPagedFlux = PagedConverter.mergePagedFlux(pagedFlux, item -> mockPagedFlux(item + "sub", 0, 10, 4, pageCount)); + PagedFlux mergedPagedFlux + = PagedConverter.mergePagedFlux(pagedFlux, item -> mockPagedFlux(item + "sub", 0, 10, 4, pageCount)); PagedIterable pagedIterable = new PagedIterable<>(mergedPagedFlux); pagedIterable.stream().findFirst().get(); @@ -207,17 +211,17 @@ public void testMergePagedFluxOnePage() { } private static PagedFlux mockEmptyPagedFlux() { - PagedResponseBase emptyPage = new PagedResponseBase<>(null, 200, null, - Collections.emptyList(), null, null); - return new PagedFlux<>(() -> Mono.just(emptyPage), - continuationToken -> Mono.empty()); + PagedResponseBase emptyPage + = new PagedResponseBase<>(null, 200, null, Collections.emptyList(), null, null); + return new PagedFlux<>(() -> Mono.just(emptyPage), continuationToken -> Mono.empty()); } private static PagedFlux mockPagedFlux(String prefix, int startInclusive, int stopExclusive, int pageSize) { return mockPagedFlux(prefix, startInclusive, stopExclusive, pageSize, new AtomicInteger(0)); } - private static PagedFlux mockPagedFlux(String prefix, int startInclusive, int stopExclusive, int pageSize, AtomicInteger pageCount) { + private static PagedFlux mockPagedFlux(String prefix, int startInclusive, int stopExclusive, int pageSize, + AtomicInteger pageCount) { Iterator iterator = IntStream.range(startInclusive, stopExclusive).iterator(); Map> pages = new HashMap<>(); String currentContinuationToken = prefix; @@ -234,8 +238,7 @@ private static PagedFlux mockPagedFlux(String prefix, int startInclusive } String newContinuationToken = iterator.hasNext() ? prefix + possibleNext : null; - PagedResponse page = new PagedResponseBase<>(null, 200, null, - items, newContinuationToken, null); + PagedResponse page = new PagedResponseBase<>(null, 200, null, items, newContinuationToken, null); pages.put(currentContinuationToken, page); currentContinuationToken = newContinuationToken; } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfoTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfoTests.java index 2e10f96a46232..0871202f1dd30 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfoTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceManagerThrottlingInfoTests.java @@ -14,8 +14,7 @@ public class ResourceManagerThrottlingInfoTests { @Test public void canCalculateThrottlingInfo() { String resourceHeaderValue = "Microsoft.Compute/PutVM3Min;237,Microsoft.Compute/PutVM30Min;1197"; - HttpHeaders headers = new HttpHeaders() - .set("x-ms-ratelimit-remaining-subscription-writes", "1193") + HttpHeaders headers = new HttpHeaders().set("x-ms-ratelimit-remaining-subscription-writes", "1193") .set("x-ms-ratelimit-remaining-resource", resourceHeaderValue); ResourceManagerThrottlingInfo info = ResourceManagerThrottlingInfo.fromHeaders(headers); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceUtilsTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceUtilsTests.java index 2941b25201071..22d99a50dfd98 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceUtilsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/utils/ResourceUtilsTests.java @@ -11,36 +11,50 @@ public class ResourceUtilsTests { @Test public void canExtractGroupFromId() throws Exception { - Assertions.assertEquals("foo", ResourceUtils.groupFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); - Assertions.assertEquals("foo", ResourceUtils.groupFromResourceId("subscriptions/123/resourcegroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("foo", ResourceUtils + .groupFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("foo", ResourceUtils + .groupFromResourceId("subscriptions/123/resourcegroups/foo/providers/Microsoft.Bar/bars/bar1")); Assertions.assertNull(ResourceUtils.groupFromResourceId(null)); } @Test public void canExtractResourceProviderFromResourceId() { - Assertions.assertEquals("Microsoft.Bar", ResourceUtils.resourceProviderFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("Microsoft.Bar", ResourceUtils + .resourceProviderFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); Assertions.assertNull(ResourceUtils.resourceProviderFromResourceId(null)); } @Test public void canExtractParentPathFromId() throws Exception { - Assertions.assertEquals("/subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1", ResourceUtils.parentResourceIdFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1/bazs/baz1")); - Assertions.assertNull(ResourceUtils.parentResourceIdFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("/subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1", + ResourceUtils.parentResourceIdFromResourceId( + "subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1/bazs/baz1")); + Assertions.assertNull(ResourceUtils + .parentResourceIdFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); } @Test public void canExtractRelativePathFromId() throws Exception { - Assertions.assertEquals("bars/bar1", ResourceUtils.relativePathFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); - Assertions.assertEquals("", ResourceUtils.parentRelativePathFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); - Assertions.assertEquals("bars/bar1/providers/provider1", ResourceUtils.relativePathFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1/providers/provider1")); - Assertions.assertEquals("providers/provider1/bars/bar1", ResourceUtils.relativePathFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/providers/provider1/bars/bar1")); + Assertions.assertEquals("bars/bar1", ResourceUtils + .relativePathFromResourceId("subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("", ResourceUtils.parentRelativePathFromResourceId( + "subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1")); + Assertions.assertEquals("bars/bar1/providers/provider1", ResourceUtils.relativePathFromResourceId( + "subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/bars/bar1/providers/provider1")); + Assertions.assertEquals("providers/provider1/bars/bar1", ResourceUtils.relativePathFromResourceId( + "subscriptions/123/resourceGroups/foo/providers/Microsoft.Bar/providers/provider1/bars/bar1")); } @Test public void canGetDefaultScopeFromUrl() throws Exception { - Assertions.assertEquals("https://graph.windows.net/.default", ResourceManagerUtils.getDefaultScopeFromUrl("https://graph.windows.net/random", AzureEnvironment.AZURE)); - Assertions.assertEquals("https://vault.azure.net/.default", ResourceManagerUtils.getDefaultScopeFromUrl("https://random.vault.azure.net/random", AzureEnvironment.AZURE)); - Assertions.assertEquals("https://api.applicationinsights.io/.default", ResourceManagerUtils.getDefaultScopeFromUrl("https://api.applicationinsights.io/random", AzureEnvironment.AZURE)); - Assertions.assertEquals("https://api.loganalytics.io/.default", ResourceManagerUtils.getDefaultScopeFromUrl("https://api.loganalytics.io/random", AzureEnvironment.AZURE)); + Assertions.assertEquals("https://graph.windows.net/.default", + ResourceManagerUtils.getDefaultScopeFromUrl("https://graph.windows.net/random", AzureEnvironment.AZURE)); + Assertions.assertEquals("https://vault.azure.net/.default", ResourceManagerUtils + .getDefaultScopeFromUrl("https://random.vault.azure.net/random", AzureEnvironment.AZURE)); + Assertions.assertEquals("https://api.applicationinsights.io/.default", ResourceManagerUtils + .getDefaultScopeFromUrl("https://api.applicationinsights.io/random", AzureEnvironment.AZURE)); + Assertions.assertEquals("https://api.loganalytics.io/.default", + ResourceManagerUtils.getDefaultScopeFromUrl("https://api.loganalytics.io/random", AzureEnvironment.AZURE)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/implementation/TypeSerializationTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/implementation/TypeSerializationTests.java index c494ae7d26fac..fb4620a900268 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/implementation/TypeSerializationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/implementation/TypeSerializationTests.java @@ -27,10 +27,10 @@ public class TypeSerializationTests { - private static final SerializerAdapter SERIALIZER_ADAPTER = - SerializerFactory.createDefaultManagementSerializerAdapter(); - private static final TypeReference> TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER = - new TypeReference>() { + private static final SerializerAdapter SERIALIZER_ADAPTER + = SerializerFactory.createDefaultManagementSerializerAdapter(); + private static final TypeReference> TYPE_REFERENCE_MAP_DEPLOYMENT_PARAMETER + = new TypeReference>() { }; public static final class Map1 extends AbstractMap { @@ -98,8 +98,7 @@ public boolean equals(Object o) { public void testTagsPatchResourceSerialization() throws Exception { Map tags = new Map1<>("tag.1", "value.1"); - TagsPatchResource tagsPatchResource = new TagsPatchResource() - .withOperation(TagsPatchOperation.REPLACE) + TagsPatchResource tagsPatchResource = new TagsPatchResource().withOperation(TagsPatchOperation.REPLACE) .withProperties(new Tags().withTags(tags)); SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); @@ -109,7 +108,8 @@ public void testTagsPatchResourceSerialization() throws Exception { @Test public void testDeploymentSerialization() throws Exception { - final String templateJson = "{ \"/subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/\": {} }"; + final String templateJson + = "{ \"/subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/\": {} }"; final String parametersJson = "{\"id1\": {\"value\": \"myParameterType\"}}"; DeploymentImpl deployment = new DeploymentImpl(new DeploymentExtendedInner(), "", null); @@ -118,19 +118,20 @@ public void testDeploymentSerialization() throws Exception { deployment.withParameters(parametersJson); SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - String deploymentJson = serializerAdapter.serialize(createRequestFromInner(deployment), SerializerEncoding.JSON); + String deploymentJson + = serializerAdapter.serialize(createRequestFromInner(deployment), SerializerEncoding.JSON); Assertions.assertTrue(deploymentJson.contains("Microsoft.ManagedIdentity")); Assertions.assertTrue(deploymentJson.contains("myParameterType")); } - private static DeploymentInner createRequestFromInner(DeploymentImpl deployment) throws NoSuchFieldException, IllegalAccessException { + private static DeploymentInner createRequestFromInner(DeploymentImpl deployment) + throws NoSuchFieldException, IllegalAccessException { Field field = DeploymentImpl.class.getDeclaredField("deploymentCreateUpdateParameters"); field.setAccessible(true); DeploymentInner implInner = (DeploymentInner) field.get(deployment); - DeploymentInner inner = new DeploymentInner() - .withProperties(new DeploymentProperties()); + DeploymentInner inner = new DeploymentInner().withProperties(new DeploymentProperties()); inner.properties().withMode(deployment.mode()); inner.properties().withTemplate(implInner.properties().template()); inner.properties().withTemplateLink(deployment.templateLink()); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml index f0b608e21790f..b0131c70c23cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml @@ -41,6 +41,7 @@ com.azure.core.*: com.azure.resourcemanager.*.samples + false diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index 386bcbad3c0a3..6c1a0bb96b9d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -67,7 +67,8 @@ * - Assign custom domain to gateway endpoint */ public class ManageSpringCloud { - private static final String PIGGYMETRICS_TAR_GZ_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; + private static final String PIGGYMETRICS_TAR_GZ_URL + = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** @@ -77,25 +78,25 @@ public class ManageSpringCloud { * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ - public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException { + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) + throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException { final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); - final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); + final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); final Region region = Region.US_EAST; final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); try { - azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); //============================================================ // Create a spring cloud service with 3 apps: gateway, auth-service, account-service System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); - SpringService service = azureResourceManager.springServices().define(serviceName) + SpringService service = azureResourceManager.springServices() + .define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); @@ -109,7 +110,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); - OutputStream outputStream = new FileOutputStream(gzFile)) { + OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); @@ -119,11 +120,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create spring cloud app: gateway System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); - SpringApp gateway = service.apps().define("gateway") + SpringApp gateway = service.apps() + .define("gateway") .defineActiveDeployment("default") - .withSourceCodeTarGzFile(gzFile) - .withTargetModule("gateway") - .attach() + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("gateway") + .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); @@ -135,11 +137,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create spring cloud app: auth-service System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); - SpringApp authService = service.apps().define("auth-service") + SpringApp authService = service.apps() + .define("auth-service") .defineActiveDeployment("default") - .withSourceCodeTarGzFile(gzFile) - .withTargetModule("auth-service") - .attach() + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("auth-service") + .attach() .create(); System.out.println("Created spring cloud service auth-service"); @@ -149,11 +152,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create spring cloud app: account-service System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); - SpringApp accountService = service.apps().define("account-service") + SpringApp accountService = service.apps() + .define("account-service") .defineActiveDeployment("default") - .withSourceCodeTarGzFile(gzFile) - .withTargetModule("account-service") - .attach() + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("account-service") + .attach() .create(); System.out.println("Created spring cloud service account-service"); @@ -164,20 +168,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); @@ -188,9 +193,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); - dnsZone.update() - .withCNameRecordSet("ssl", gateway.fqdn()) - .apply(); + dnsZone.update().withCNameRecordSet("ssl", gateway.fqdn()).apply(); // Please use a trusted certificate for actual use System.out.printf("Generate a self-signed certificate for ssl.%s %n", domainName); @@ -198,59 +201,55 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin String cerPassword = Utils.password(); String cerPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".cer"; String pfxPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".pfx"; - Utils.createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); + Utils.createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, + "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); String alias = Collections.list(store.aliases()).get(0); - String thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); + String thumbprint = DatatypeConverter + .printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); - System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); - Vault vault = azureResourceManager.vaults().define(vaultName) + System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, + SPRING_CLOUD_SERVICE_PRINCIPAL); + Vault vault = azureResourceManager.vaults() + .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowSecretAllPermissions() - .allowCertificateAllPermissions() - .attach() + .forServicePrincipal(clientId) + .allowSecretAllPermissions() + .allowCertificateAllPermissions() + .attach() .defineAccessPolicy() - .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) - .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) - .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) - .attach() + .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) + .attach() .create(); System.out.printf("Created key vault %s%n", vault.name()); Utils.print(vault); // upload certificate - CertificateClient certificateClient = new CertificateClientBuilder() - .vaultUrl(vault.vaultUri()) + CertificateClient certificateClient = new CertificateClientBuilder().vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( - new ImportCertificateOptions(certName, certificate) - .setPassword(cerPassword) - .setEnabled(true) - ); + new ImportCertificateOptions(certName, certificate).setPassword(cerPassword).setEnabled(true)); //============================================================ // Update Certificate and Custom Domain for Spring Cloud System.out.println("Updating Spring Cloud Service with certificate ..."); - service.update() - .withCertificate(certName, vault.vaultUri(), certName) - .apply(); + service.update().withCertificate(certName, vault.vaultUri(), certName).apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); - gateway.update() - .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) - .apply(); + gateway.update().withCustomDomain(String.format("ssl.%s", domainName), thumbprint).apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); @@ -281,8 +280,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -290,7 +288,8 @@ public static void main(String[] args) { // Print selected subscription System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); - runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); + runSample(azureResourceManager, + Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); @@ -300,7 +299,8 @@ public static void main(String[] args) { public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); - try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { + try (TarArchiveInputStream inputStream + = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { @@ -336,19 +336,17 @@ private static byte[] readAllBytes(InputStream inputStream) throws IOException { } private static void allowAllSSL() throws NoSuchAlgorithmException, KeyManagementException { - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } - }; + } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java index 711b982aa23d5..e8c6bd3621f74 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java @@ -33,25 +33,24 @@ public final class ManageFunctionAppBasic { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); - final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); - final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); + final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); try { - //============================================================ // Create a function app with a new app service plan System.out.println("Creating function app " + app1Name + " in resource group " + rg1Name + "..."); FunctionApp app1 = azureResourceManager.functionApps() - .define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rg1Name) - .create(); + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rg1Name) + .create(); System.out.println("Created function app " + app1.name()); Utils.print(app1); @@ -62,11 +61,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another function app " + app2Name + " in resource group " + rg1Name + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); FunctionApp app2 = azureResourceManager.functionApps() - .define(app2Name) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rg1Name) - .withNewAppServicePlan(PricingTier.BASIC_B1) - .create(); + .define(app2Name) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rg1Name) + .withNewAppServicePlan(PricingTier.BASIC_B1) + .create(); System.out.println("Created function app " + app2.name()); Utils.print(app2); @@ -77,10 +76,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another function app " + app3Name + " in resource group " + rg2Name + "..."); FunctionApp app3 = azureResourceManager.functionApps() - .define(app3Name) - .withExistingAppServicePlan(plan) - .withNewResourceGroup(rg2Name) - .create(); + .define(app3Name) + .withExistingAppServicePlan(plan) + .withNewResourceGroup(rg2Name) + .create(); System.out.println("Created function app " + app3.name()); Utils.print(app3); @@ -158,11 +157,10 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() - .withLogLevel(HttpLogDetailLevel.BASIC) - .authenticate(credential, profile) - .withDefaultSubscription(); + AzureResourceManager azureResourceManager = AzureResourceManager.configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java index 6cb7c432a0f4f..a687cf2f78e98 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java @@ -25,7 +25,6 @@ import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; - /** * Azure App Service basic sample for managing function apps. * - Create a function app under the same new app service plan: @@ -42,34 +41,37 @@ public final class ManageFunctionAppLogs { */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { // New resources - final String suffix = ".azurewebsites.net"; - final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String appUrl = appName + suffix; - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String appUrl = appName + suffix; + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { - //============================================================ // Create a function app with a new app service plan System.out.println("Creating function app " + appName + " in resource group " + rgName + "..."); - FunctionApp app = azureResourceManager.functionApps().define(appName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .defineDiagnosticLogsConfiguration() - .withApplicationLogging() - .withLogLevel(LogLevel.VERBOSE) - .withApplicationLogsStoredOnFileSystem() - .attach() - .withFtpsState(FtpsState.ALL_ALLOWED) - .create(); + FunctionApp app = azureResourceManager.functionApps() + .define(appName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .defineDiagnosticLogsConfiguration() + .withApplicationLogging() + .withLogLevel(LogLevel.VERBOSE) + .withApplicationLogsStoredOnFileSystem() + .attach() + .withFtpsState(FtpsState.ALL_ALLOWED) + .create(); System.out.println("Created function app " + app.name()); Utils.print(app); - app.manager().resourceManager().genericResources().define("ftp") + app.manager() + .resourceManager() + .genericResources() + .define("ftp") .withRegion(app.regionName()) .withExistingResourceGroup(app.resourceGroupName()) .withResourceType("basicPublishingCredentialsPolicies") @@ -85,9 +87,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Deploying a function app to " + appName + " through FTP..."); - Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "host.json", ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/host.json")); - Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "square/function.json", ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/square/function.json")); - Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "square/index.js", ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/square/index.js")); + Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "host.json", + ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/host.json")); + Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "square/function.json", + ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/square/function.json")); + Utils.uploadFileForFunctionViaFtp(app.getPublishingProfile(), "square/index.js", + ManageFunctionAppLogs.class.getResourceAsStream("/square-function-app/square/index.js")); // sync triggers app.syncTriggers(); @@ -108,7 +113,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw String line = readLine(stream); StopWatch stopWatch = new StopWatch(); stopWatch.start(); - new Thread(() -> { + new Thread(() -> { Utils.sendPostRequest("http://" + appUrl + "/api/square", "625"); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); Utils.sendPostRequest("http://" + appUrl + "/api/square", "725"); @@ -124,7 +129,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Listen to logs asynchronously until 3 requests are completed - new Thread(() -> { + new Thread(() -> { ResourceManagerUtils.sleep(Duration.ofSeconds(5)); System.out.println("Starting hitting"); Utils.sendPostRequest("http://" + appUrl + "/api/square", "625"); @@ -167,6 +172,7 @@ protected void hookOnError(Throwable throwable) { } } } + /** * Main entry point. * @param args the parameters @@ -182,8 +188,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java index 95b966ac3ea89..a5f1423558146 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java @@ -39,11 +39,11 @@ public final class ManageFunctionAppWithDomainSsl { */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); - final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; - final String certPassword = Utils.password(); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String certPassword = Utils.password(); try { //============================================================ @@ -51,10 +51,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating function app " + app1Name + "..."); - FunctionApp app1 = azureResourceManager.functionApps().define(app1Name) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .create(); + FunctionApp app1 = azureResourceManager.functionApps() + .define(app1Name) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .create(); System.out.println("Created function app " + app1.name()); Utils.print(app1); @@ -63,10 +64,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Create a second function app with the same app service plan System.out.println("Creating another function app " + app2Name + "..."); - FunctionApp app2 = azureResourceManager.functionApps().define(app2Name) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .create(); + FunctionApp app2 = azureResourceManager.functionApps() + .define(app2Name) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Created function app " + app2.name()); Utils.print(app2); @@ -76,47 +78,52 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) - .withExistingResourceGroup(rgName) - .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(false) - .create(); + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); //============================================================ // Bind domain to function app 1 - System.out.println("Binding http://" + app1Name + "." + domainName + " to function app " + app1Name + "..."); + System.out + .println("Binding http://" + app1Name + "." + domainName + " to function app " + app1Name + "..."); app1 = app1.update() - .defineHostnameBinding() - .withAzureManagedDomain(domain) - .withSubDomain(app1Name) - .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) - .attach() - .apply(); - - System.out.println("Finished binding http://" + app1Name + "." + domainName + " to function app " + app1Name); + .defineHostnameBinding() + .withAzureManagedDomain(domain) + .withSubDomain(app1Name) + .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) + .attach() + .apply(); + + System.out + .println("Finished binding http://" + app1Name + "." + domainName + " to function app " + app1Name); Utils.print(app1); //============================================================ // Create a self-singed SSL certificate - String pfxPath = ManageFunctionAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; - String cerPath = ManageFunctionAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + String pfxPath + = ManageFunctionAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath + = ManageFunctionAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; System.out.println("Creating a self-signed certificate " + pfxPath + "..."); @@ -127,32 +134,36 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Bind domain to function app 2 and turn on wild card SSL for both - System.out.println("Binding https://" + app1Name + "." + domainName + " to function app " + app1Name + "..."); + System.out + .println("Binding https://" + app1Name + "." + domainName + " to function app " + app1Name + "..."); app1 = app1.update() - .withManagedHostnameBindings(domain, app1Name) - .defineSslBinding() - .forHostname(app1Name + "." + domainName) - .withPfxCertificateToUpload(new File(pfxPath), certPassword) - .withSniBasedSsl() - .attach() - .apply(); - - System.out.println("Finished binding http://" + app1Name + "." + domainName + " to function app " + app1Name); + .withManagedHostnameBindings(domain, app1Name) + .defineSslBinding() + .forHostname(app1Name + "." + domainName) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .apply(); + + System.out + .println("Finished binding http://" + app1Name + "." + domainName + " to function app " + app1Name); Utils.print(app1); - System.out.println("Binding https://" + app2Name + "." + domainName + " to function app " + app2Name + "..."); + System.out + .println("Binding https://" + app2Name + "." + domainName + " to function app " + app2Name + "..."); app2 = app2.update() - .withManagedHostnameBindings(domain, app2Name) - .defineSslBinding() - .forHostname(app2Name + "." + domainName) - .withPfxCertificateToUpload(new File(pfxPath), certPassword) - .withSniBasedSsl() - .attach() - .apply(); - - System.out.println("Finished binding http://" + app2Name + "." + domainName + " to function app " + app2Name); + .withManagedHostnameBindings(domain, app2Name) + .defineSslBinding() + .forHostname(app2Name + "." + domainName) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .apply(); + + System.out + .println("Finished binding http://" + app2Name + "." + domainName + " to function app " + app2Name); Utils.print(app2); return true; @@ -168,13 +179,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } } + /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { - try { //============================================================= @@ -185,8 +196,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java index 94457e7c7016f..d20598f74decd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java @@ -28,7 +28,8 @@ */ public class ManageLinuxFunctionAppSourceControl { - private static final String FUNCTION_APP_PACKAGE_URL = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; + private static final String FUNCTION_APP_PACKAGE_URL + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/resources/java-functions.zip"; private static final long TIMEOUT_IN_SECONDS = 5 * 60; /** @@ -37,15 +38,15 @@ public class ManageLinuxFunctionAppSourceControl { * @return true if sample runs successfully */ public static boolean runSample(AzureResourceManager azureResourceManager) { - final String suffix = ".azurewebsites.net"; - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app1Url = app1Name + suffix; - final String app2Url = app2Name + suffix; - final String plan1Name = Utils.randomResourceName(azureResourceManager, "plan1-", 20); - final String plan2Name = Utils.randomResourceName(azureResourceManager, "plan2-", 20); - final String storage1Name = Utils.randomResourceName(azureResourceManager, "storage1", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app1Url = app1Name + suffix; + final String app2Url = app2Name + suffix; + final String plan1Name = Utils.randomResourceName(azureResourceManager, "plan1-", 20); + final String plan2Name = Utils.randomResourceName(azureResourceManager, "plan2-", 20); + final String storage1Name = Utils.randomResourceName(azureResourceManager, "storage1", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { @@ -54,15 +55,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating function app " + app1Name + " in resource group " + rgName + "..."); - FunctionApp app1 = azureResourceManager.functionApps().define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewLinuxAppServicePlan(plan1Name, PricingTier.STANDARD_S1) - .withBuiltInImage(FunctionRuntimeStack.JAVA_8) - .withNewStorageAccount(storage1Name, StorageAccountSkuType.STANDARD_LRS) - .withHttpsOnly(true) - .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) - .create(); + FunctionApp app1 = azureResourceManager.functionApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewLinuxAppServicePlan(plan1Name, PricingTier.STANDARD_S1) + .withBuiltInImage(FunctionRuntimeStack.JAVA_8) + .withNewStorageAccount(storage1Name, StorageAccountSkuType.STANDARD_LRS) + .withHttpsOnly(true) + .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) + .create(); System.out.println("Created function app " + app1.name()); Utils.print(app1); @@ -85,21 +87,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Response is " + Utils.sendGetRequest("https://" + app1UrlFunction)); // response would be "Hello, ..." - //============================================================ // Create a function app with a new consumption plan, configure as run from a package System.out.println("Creating function app " + app2Name + " in resource group " + rgName + "..."); - FunctionApp app2 = azureResourceManager.functionApps().define(app2Name) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewLinuxConsumptionPlan(plan2Name) - .withBuiltInImage(FunctionRuntimeStack.JAVA_8) - .withExistingStorageAccount(azureResourceManager.storageAccounts().getByResourceGroup(rgName, storage1Name)) - .withHttpsOnly(true) - .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) - .create(); + FunctionApp app2 = azureResourceManager.functionApps() + .define(app2Name) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewLinuxConsumptionPlan(plan2Name) + .withBuiltInImage(FunctionRuntimeStack.JAVA_8) + .withExistingStorageAccount( + azureResourceManager.storageAccounts().getByResourceGroup(rgName, storage1Name)) + .withHttpsOnly(true) + .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) + .create(); System.out.println("Created function app " + app2.name()); Utils.print(app2); @@ -151,8 +154,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java index 7a95a9a7cf626..ecd96a9efd7f6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java @@ -37,27 +37,26 @@ public final class ManageLinuxWebAppBasic { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); - final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); - final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); + final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); try { - //============================================================ // Create a web app with a new app service plan System.out.println("Creating web app " + app1Name + " in resource group " + rg1Name + "..."); WebApp app1 = azureResourceManager.webApps() - .define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rg1Name) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) - .create(); + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rg1Name) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -68,11 +67,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app2Name + " in resource group " + rg1Name + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); WebApp app2 = azureResourceManager.webApps() - .define(app2Name) - .withExistingLinuxPlan(plan) - .withExistingResourceGroup(rg1Name) - .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) - .create(); + .define(app2Name) + .withExistingLinuxPlan(plan) + .withExistingResourceGroup(rg1Name) + .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) + .create(); System.out.println("Created web app " + app2.name()); Utils.print(app2); @@ -83,11 +82,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app3Name + " in resource group " + rg2Name + "..."); WebApp app3 = azureResourceManager.webApps() - .define(app3Name) - .withExistingLinuxPlan(plan) - .withNewResourceGroup(rg2Name) - .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) - .create(); + .define(app3Name) + .withExistingLinuxPlan(plan) + .withNewResourceGroup(rg2Name) + .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) + .create(); System.out.println("Created web app " + app3.name()); Utils.print(app3); @@ -111,9 +110,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Configure app 3 to have Java 8 enabled System.out.println("Adding Java support to web app " + app3Name + "..."); app3.update() - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .apply(); + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .apply(); System.out.println("Java supported on web app " + app3Name + "..."); //============================================================= @@ -174,8 +173,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java index 2bc6bbf608ad5..008f82c991c8d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java @@ -47,15 +47,16 @@ public final class ManageLinuxWebAppCosmosDbByMsi { * @param clientId the client ID * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azure, String clientId) throws IOException, InterruptedException { + public static boolean runSample(AzureResourceManager azure, String clientId) + throws IOException, InterruptedException { // New resources - final Region region = Region.US_WEST; - final String acrName = Utils.randomResourceName(azure, "acr", 20); - final String appName = Utils.randomResourceName(azure, "webapp1-", 20); - final String password = Utils.password(); - final String rgName = Utils.randomResourceName(azure, "rg1NEMV_", 24); - final String vaultName = Utils.randomResourceName(azure, "vault", 20); - final String cosmosName = Utils.randomResourceName(azure, "cosmosdb", 20); + final Region region = Region.US_WEST; + final String acrName = Utils.randomResourceName(azure, "acr", 20); + final String appName = Utils.randomResourceName(azure, "webapp1-", 20); + final String password = Utils.password(); + final String rgName = Utils.randomResourceName(azure, "rg1NEMV_", 24); + final String vaultName = Utils.randomResourceName(azure, "vault", 20); + final String cosmosName = Utils.randomResourceName(azure, "cosmosdb", 20); String servicePrincipalClientId = clientId; // replace with a real service principal client id @@ -64,12 +65,13 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts().define(cosmosName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withDataModelSql() - .withStrongConsistency() - .create(); + CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts() + .define(cosmosName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDataModelSql() + .withStrongConsistency() + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); @@ -77,12 +79,13 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr //============================================================ // Create a service principal - ServicePrincipal servicePrincipal = azure.accessManagement().servicePrincipals() - .define(appName) - .withNewApplication() - .definePasswordCredential("password") - .attach() - .create(); + ServicePrincipal servicePrincipal = azure.accessManagement() + .servicePrincipals() + .define(appName) + .withNewApplication() + .definePasswordCredential("password") + .attach() + .create(); //============================================================= // If service principal client id and secret are not set via the local variables, attempt to read the service @@ -95,7 +98,9 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); - if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + if (envSecondaryServicePrincipal == null + || !envSecondaryServicePrincipal.isEmpty() + || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } @@ -107,33 +112,30 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr // Create a key vault Vault vault = azure.vaults() - .define(vaultName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(servicePrincipalClientId) - .allowSecretAllPermissions() - .attach() - .defineAccessPolicy() - .forServicePrincipal(servicePrincipal) - .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) - .attach() - .create(); - -// SdkContext.sleep(10000); + .define(vaultName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(servicePrincipalClientId) + .allowSecretAllPermissions() + .attach() + .defineAccessPolicy() + .forServicePrincipal(servicePrincipal) + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) + .attach() + .create(); + + // SdkContext.sleep(10000); //============================================================ // Store Cosmos DB credentials in Key Vault - vault.secrets().define("azure-documentdb-uri") - .withValue(cosmosDBAccount.documentEndpoint()) - .create(); - vault.secrets().define("azure-documentdb-key") + vault.secrets().define("azure-documentdb-uri").withValue(cosmosDBAccount.documentEndpoint()).create(); + vault.secrets() + .define("azure-documentdb-key") .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) .create(); - vault.secrets().define("azure-documentdb-database") - .withValue("tododb") - .create(); + vault.secrets().define("azure-documentdb-database").withValue("tododb").create(); //============================================================= // Create an Azure Container Registry to store and manage private Docker container images @@ -142,23 +144,26 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr long t1 = System.currentTimeMillis(); - Registry azureRegistry = azure.containerRegistries().define(acrName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withBasicSku() - .withRegistryNameAsAdminUser() - .create(); + Registry azureRegistry = azure.containerRegistries() + .define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); long t2 = System.currentTimeMillis(); - System.out.println("Created Azure Container Registry: (took " + ((t2 - t1) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println( + "Created Azure Container Registry: (took " + ((t2 - t1) / 1000) + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + DockerClient dockerClient + = DockerUtils.createDockerClient(azure, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); String imageName = "tomcat:7.0-slim"; String privateRepoUrl = azureRegistry.loginServerUrl() + "/todoapp"; @@ -170,8 +175,7 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr String imageId = dockerClient.inspectImageCmd(imageName).exec().getId(); dockerClient.tagImageCmd(imageId, privateRepoUrl, "latest").exec(); - dockerClient.pushImageCmd(privateRepoUrl) - .exec(new PushImageResultCallback()).awaitCompletion(); + dockerClient.pushImageCmd(privateRepoUrl).exec(new PushImageResultCallback()).awaitCompletion(); //============================================================ // Create a web app with a new app service plan @@ -179,16 +183,16 @@ public static boolean runSample(AzureResourceManager azure, String clientId) thr System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); WebApp app1 = azure.webApps() - .define(appName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withPrivateRegistryImage(privateRepoUrl, azureRegistry.loginServerUrl()) - .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) - .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) - .withAppSetting("AZURE_KEYVAULT_CLIENT_ID", servicePrincipal.applicationId()) - .withAppSetting("AZURE_KEYVAULT_CLIENT_KEY", password) - .create(); + .define(appName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withPrivateRegistryImage(privateRepoUrl, azureRegistry.loginServerUrl()) + .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) + .withAppSetting("AZURE_KEYVAULT_CLIENT_ID", servicePrincipal.applicationId()) + .withAppSetting("AZURE_KEYVAULT_CLIENT_KEY", password) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -222,8 +226,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java index 1594bc31cf8c6..5e3a9613b9b00 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java @@ -48,18 +48,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw try { - //============================================================ // Create a sql server System.out.println("Creating SQL server " + sqlServerName + "..."); - SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(admin) - .withAdministratorPassword(password) - .create(); + SqlServer server = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(admin) + .withAdministratorPassword(password) + .create(); System.out.println("Created SQL server " + server.name()); @@ -77,20 +77,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + appName + "..."); - WebApp app = azureResourceManager.webApps().define(appName) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withBuiltInImage(RuntimeStack.PHP_7_2) - .defineSourceControl() - .withPublicGitRepository("https://github.com/ProjectNami/projectnami") - .withBranch("master") - .attach() - .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) - .withAppSetting("ProjectNami.DBName", db.name()) - .withAppSetting("ProjectNami.DBUser", admin) - .withAppSetting("ProjectNami.DBPass", password) - .create(); + WebApp app = azureResourceManager.webApps() + .define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.PHP_7_2) + .defineSourceControl() + .withPublicGitRepository("https://github.com/ProjectNami/projectnami") + .withBranch("master") + .attach() + .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) + .withAppSetting("ProjectNami.DBName", db.name()) + .withAppSetting("ProjectNami.DBUser", admin) + .withAppSetting("ProjectNami.DBPass", password) + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); @@ -110,7 +111,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw Utils.print(server); System.out.println("Your WordPress app is ready."); - System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); + System.out + .println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); System.in.read(); return true; @@ -143,8 +145,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java index a78db8be5581c..eb2953d984f9c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java @@ -36,7 +36,6 @@ import java.time.OffsetDateTime; import java.util.Collections; - /** * Azure App Service basic sample for managing web apps. * - Create a storage account and upload a couple blobs @@ -53,12 +52,12 @@ public final class ManageLinuxWebAppStorageAccountConnection { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String suffix = ".azurewebsites.net"; - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app1Url = app1Name + suffix; - final String storageName = Utils.randomResourceName(azureResourceManager, "jsdkstore", 20); - final String containerName = Utils.randomResourceName(azureResourceManager, "jcontainer", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app1Url = app1Name + suffix; + final String storageName = Utils.randomResourceName(azureResourceManager, "jsdkstore", 20); + final String containerName = Utils.randomResourceName(azureResourceManager, "jcontainer", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { @@ -67,15 +66,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating storage account " + storageName + "..."); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", - storageAccount.name(), accountKey); + storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); @@ -84,9 +84,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Uploading 2 blobs to container " + containerName + "..."); - BlobContainerClient container = setUpStorageAccount(connectionString, containerName, storageAccount.manager().httpPipeline().getHttpClient()); - uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); - uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); + BlobContainerClient container = setUpStorageAccount(connectionString, containerName, + storageAccount.manager().httpPipeline().getHttpClient()); + uploadFileToContainer(container, "helloworld.war", + ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); + uploadFileToContainer(container, "install_apache.sh", + ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); @@ -96,20 +99,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating web app " + app1Name + "..."); // note: the env variable will not work in linux since dot is not allowed in env variable name - WebApp app1 = azureResourceManager.webApps().define(app1Name) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) - .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) - .withAppSetting("storage.containerName", containerName) - .withFtpsState(FtpsState.ALL_ALLOWED) - .create(); + WebApp app1 = azureResourceManager.webApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) + .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) + .withAppSetting("storage.containerName", containerName) + .withFtpsState(FtpsState.ALL_ALLOWED) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); - app1.manager().resourceManager().genericResources().define("ftp") + app1.manager() + .resourceManager() + .genericResources() + .define("ftp") .withRegion(app1.regionName()) .withExistingResourceGroup(app1.resourceGroupName()) .withResourceType("basicPublishingCredentialsPolicies") @@ -126,7 +133,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); - Utils.uploadFileViaFtp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); + Utils.uploadFileViaFtp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", + ManageLinuxWebAppStorageAccountConnection.class + .getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); @@ -151,6 +160,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -167,8 +177,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -183,28 +192,27 @@ public static void main(String[] args) { } } - private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName, HttpClient httpClient) { - BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() - .connectionString(connectionString) - .containerName(containerName) - .httpClient(httpClient) - .buildClient(); + private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName, + HttpClient httpClient) { + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().connectionString(connectionString) + .containerName(containerName) + .httpClient(httpClient) + .buildClient(); blobContainerClient.create(); - BlobSignedIdentifier identifier = new BlobSignedIdentifier() - .setId("webapp") - .setAccessPolicy(new BlobAccessPolicy() - .setStartsOn(OffsetDateTime.now()) - .setExpiresOn(OffsetDateTime.now().plusDays(7)) - .setPermissions("rl")); + BlobSignedIdentifier identifier = new BlobSignedIdentifier().setId("webapp") + .setAccessPolicy(new BlobAccessPolicy().setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } - private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { + private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, + String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java index 503f313a6e43d..9c4413b2e66a7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java @@ -49,7 +49,8 @@ public class ManageLinuxWebAppWithContainerRegistry { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, InterruptedException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); final String appName = Utils.randomResourceName(azureResourceManager, "webapp", 20); @@ -67,41 +68,44 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw Date t1 = new Date(); - Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withBasicSku() - .withRegistryNameAsAdminUser() - .create(); + Registry azureRegistry = azureResourceManager.containerRegistries() + .define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); - //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + DockerClient dockerClient + = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR dockerClient.pullImageCmd(dockerImageName) - .withTag(dockerImageTag) - .withAuthConfig(new AuthConfig()) - .exec(new PullImageResultCallback()) - .awaitCompletion(); + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) + .exec(new PullImageResultCallback()) + .awaitCompletion(); System.out.println("List local Docker images:"); List images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } - CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + CreateContainerResponse dockerContainerInstance + = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) .withName(dockerContainerName) .exec(); @@ -111,19 +115,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl) - .withTag("latest").exec(); + .withTag("latest") + .exec(); // We can now remove the temporary container instance - dockerClient.removeContainerCmd(dockerContainerInstance.getId()) - .withForce(true) - .exec(); + dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry dockerClient.pushImageCmd(privateRepoUrl) - .withAuthConfig(dockerClient.authConfig()) - .exec(new PushImageResultCallback()).awaitSuccess(); + .withAuthConfig(dockerClient.authConfig()) + .exec(new PushImageResultCallback()) + .awaitSuccess(); // Remove the temp image from the local Docker host try { @@ -137,14 +141,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); - WebApp app = azureResourceManager.webApps().define(appName) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withPrivateRegistryImage(privateRepoUrl + ":latest", "http://" + azureRegistry.loginServerUrl()) - .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) - .withAppSetting("PORT", "8080") - .create(); + WebApp app = azureResourceManager.webApps() + .define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withPrivateRegistryImage(privateRepoUrl + ":latest", "http://" + azureRegistry.loginServerUrl()) + .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withAppSetting("PORT", "8080") + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); @@ -185,8 +190,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java index 1b6278ba7d3c5..150c287f83f61 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java @@ -42,11 +42,11 @@ public final class ManageLinuxWebAppWithDomainSsl { */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); - final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; - final String certPassword = Utils.password(); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String certPassword = Utils.password(); try { //============================================================ @@ -54,12 +54,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + app1Name + "..."); - WebApp app1 = azureResourceManager.webApps().define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewLinuxPlan(PricingTier.STANDARD_S1) - .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) - .create(); + WebApp app1 = azureResourceManager.webApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -69,11 +70,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating another web app " + app2Name + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); - WebApp app2 = azureResourceManager.webApps().define(app2Name) - .withExistingLinuxPlan(plan) - .withExistingResourceGroup(rgName) - .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) - .create(); + WebApp app2 = azureResourceManager.webApps() + .define(app2Name) + .withExistingLinuxPlan(plan) + .withExistingResourceGroup(rgName) + .withBuiltInImage(RuntimeStack.NODEJS_10_LTS) + .create(); System.out.println("Created web app " + app2.name()); Utils.print(app2); @@ -83,23 +85,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) - .withExistingResourceGroup(rgName) - .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(false) - .create(); + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); @@ -109,12 +112,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding http://" + app1Name + "." + domainName + " to web app " + app1Name + "..."); app1 = app1.update() - .defineHostnameBinding() - .withAzureManagedDomain(domain) - .withSubDomain(app1Name) - .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) - .attach() - .apply(); + .defineHostnameBinding() + .withAzureManagedDomain(domain) + .withSubDomain(app1Name) + .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) + .attach() + .apply(); System.out.println("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name); Utils.print(app1); @@ -122,8 +125,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Create a self-singed SSL certificate - String pfxPath = ManageLinuxWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; - String cerPath = ManageLinuxWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + String pfxPath + = ManageLinuxWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath + = ManageLinuxWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; System.out.println("Creating a self-signed certificate " + pfxPath + "..."); @@ -137,13 +142,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding https://" + app1Name + "." + domainName + " to web app " + app1Name + "..."); app1 = app1.update() - .withManagedHostnameBindings(domain, app1Name) - .defineSslBinding() - .forHostname(app1Name + "." + domainName) - .withPfxCertificateToUpload(new File(pfxPath), certPassword) - .withSniBasedSsl() - .attach() - .apply(); + .withManagedHostnameBindings(domain, app1Name) + .defineSslBinding() + .forHostname(app1Name + "." + domainName) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .apply(); System.out.println("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name); Utils.print(app1); @@ -151,13 +156,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding https://" + app2Name + "." + domainName + " to web app " + app2Name + "..."); app2 = app2.update() - .withManagedHostnameBindings(domain, app2Name) - .defineSslBinding() - .forHostname(app2Name + "." + domainName) - .withExistingCertificate(app1.hostnameSslStates().get(app1Name + "." + domainName).thumbprint()) - .withSniBasedSsl() - .attach() - .apply(); + .withManagedHostnameBindings(domain, app2Name) + .defineSslBinding() + .forHostname(app2Name + "." + domainName) + .withExistingCertificate(app1.hostnameSslStates().get(app1Name + "." + domainName).thumbprint()) + .withSniBasedSsl() + .attach() + .apply(); System.out.println("Finished binding http://" + app2Name + "." + domainName + " to web app " + app2Name); Utils.print(app2); @@ -175,13 +180,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } } + /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { - try { //============================================================= @@ -192,8 +197,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java index f8d6baada38cc..a26ad95c9e5ca 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java @@ -75,11 +75,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Purchasing a domain " + domainName + "..."); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); - domain = azureResourceManager.appServiceDomains().define(domainName) + domain = azureResourceManager.appServiceDomains() + .define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") @@ -102,8 +101,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Create a self-singed SSL certificate - pfxPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; - String cerPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + pfxPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + + ".pfx"; + String cerPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + + domainName + ".cer"; System.out.println("Creating a self-signed certificate " + pfxPath + "..."); @@ -172,7 +173,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); - TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) + TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles() + .define(tmName) .withExistingResourceGroup(rgName) .withLeafDomainLabel(tmName) .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) @@ -198,27 +200,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Scaling up app service plan " + plan1Name + "..."); - plan1.update() - .withCapacity(plan1.capacity() * 2) - .apply(); + plan1.update().withCapacity(plan1.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan1Name); Utils.print(plan1); System.out.println("Scaling up app service plan " + plan2Name + "..."); - plan2.update() - .withCapacity(plan2.capacity() * 2) - .apply(); + plan2.update().withCapacity(plan2.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan2Name); Utils.print(plan2); System.out.println("Scaling up app service plan " + plan3Name + "..."); - plan3.update() - .withCapacity(plan3.capacity() * 2) - .apply(); + plan3.update().withCapacity(plan3.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan3Name); Utils.print(plan3); @@ -238,30 +234,32 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } private static AppServicePlan createAppServicePlan(String name, Region region) { - return azureResourceManager.appServicePlans().define(name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withPricingTier(PricingTier.STANDARD_S2) - .withOperatingSystem(OperatingSystem.LINUX) - .create(); + return azureResourceManager.appServicePlans() + .define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.STANDARD_S2) + .withOperatingSystem(OperatingSystem.LINUX) + .create(); } - private static final String WEB_APP_PACKAGE_URL = - "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/helloworld.zip"; + private static final String WEB_APP_PACKAGE_URL + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/helloworld.zip"; private static WebApp createWebApp(String name, AppServicePlan plan) { - return azureResourceManager.webApps().define(name) - .withExistingLinuxPlan(plan) - .withExistingResourceGroup(rgName) - .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) - .withManagedHostnameBindings(domain, name) - .defineSslBinding() - .forHostname(name + "." + domain.name()) - .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) - .withSniBasedSsl() - .attach() - .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", WEB_APP_PACKAGE_URL) - .create(); + return azureResourceManager.webApps() + .define(name) + .withExistingLinuxPlan(plan) + .withExistingResourceGroup(rgName) + .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) + .withManagedHostnameBindings(domain, name) + .defineSslBinding() + .forHostname(name + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) + .withSniBasedSsl() + .attach() + .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", WEB_APP_PACKAGE_URL) + .create(); } /** @@ -278,8 +276,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java index 270cbe41582aa..c36e7f16c3db0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java @@ -36,26 +36,25 @@ public final class ManageWebAppBasic { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); - final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); - final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); + final String rg1Name = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String rg2Name = Utils.randomResourceName(azureResourceManager, "rg2NEMV_", 24); try { - //============================================================ // Create a web app with a new app service plan System.out.println("Creating web app " + app1Name + " in resource group " + rg1Name + "..."); WebApp app1 = azureResourceManager.webApps() - .define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rg1Name) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .create(); + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rg1Name) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -66,10 +65,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app2Name + " in resource group " + rg1Name + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); WebApp app2 = azureResourceManager.webApps() - .define(app2Name) - .withExistingWindowsPlan(plan) - .withExistingResourceGroup(rg1Name) - .create(); + .define(app2Name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rg1Name) + .create(); System.out.println("Created web app " + app2.name()); Utils.print(app2); @@ -80,10 +79,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app3Name + " in resource group " + rg2Name + "..."); WebApp app3 = azureResourceManager.webApps() - .define(app3Name) - .withExistingWindowsPlan(plan) - .withNewResourceGroup(rg2Name) - .create(); + .define(app3Name) + .withExistingWindowsPlan(plan) + .withNewResourceGroup(rg2Name) + .create(); System.out.println("Created web app " + app3.name()); Utils.print(app3); @@ -107,9 +106,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Configure app 3 to have Java 8 enabled System.out.println("Adding Java support to web app " + app3Name + "..."); app3.update() - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .apply(); + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .apply(); System.out.println("Java supported on web app " + app3Name + "..."); //============================================================= @@ -170,8 +169,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java index 4f16e822919a7..bdee3ceff9f19 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java @@ -49,19 +49,20 @@ public final class ManageWebAppCosmosDbByMsi { */ public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException { // New resources - final Region region = Region.US_WEST; - final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); - final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 20); - final String cosmosName = Utils.randomResourceName(azureResourceManager, "cosmosdb", 20); - final String appUrl = appName + ".azurewebsites.net"; + final Region region = Region.US_WEST; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 20); + final String cosmosName = Utils.randomResourceName(azureResourceManager, "cosmosdb", 20); + final String appUrl = appName + ".azurewebsites.net"; try { //============================================================ // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) @@ -86,7 +87,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Allow the sample to store secret in the Key Vault - azureResourceManager.accessManagement().roleAssignments().define(UUID.randomUUID().toString()) + azureResourceManager.accessManagement() + .roleAssignments() + .define(UUID.randomUUID().toString()) .forServicePrincipal(clientId) .withBuiltInRole(BuiltInRole.KEY_VAULT_SECRETS_OFFICER) .withScope(vault.id()) @@ -98,15 +101,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Store Cosmos DB credentials in Key Vault - vault.secrets().define("azure-documentdb-uri") - .withValue(cosmosDBAccount.documentEndpoint()) - .create(); - vault.secrets().define("azure-documentdb-key") + vault.secrets().define("azure-documentdb-uri").withValue(cosmosDBAccount.documentEndpoint()).create(); + vault.secrets() + .define("azure-documentdb-key") .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) .create(); - vault.secrets().define("azure-documentdb-database") - .withValue("tododb") - .create(); + vault.secrets().define("azure-documentdb-database").withValue("tododb").create(); //============================================================ // Create a web app with a new app service plan @@ -134,7 +134,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Deploying a spring boot app to " + appName + " through OneDeploy..."); - try (InputStream is = ManageWebAppCosmosDbByMsi.class.getResourceAsStream("/todo-app-java-on-azure-1.0-SNAPSHOT.jar")) { + try (InputStream is + = ManageWebAppCosmosDbByMsi.class.getResourceAsStream("/todo-app-java-on-azure-1.0-SNAPSHOT.jar")) { byte[] buff = new byte[8192]; int bytesRead; ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -189,8 +190,7 @@ public static void main(String[] args) { .build(); final Configuration configuration = Configuration.getGlobalConfiguration(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java index 20a4f2e38d7a4..56096f0aa7814 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java @@ -44,26 +44,27 @@ public final class ManageWebAppCosmosDbThroughKeyVault { */ public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) { // New resources - final Region region = Region.US_WEST; - final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); - final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 20); - final String cosmosName = Utils.randomResourceName(azureResourceManager, "cosmosdb", 20); - final String appUrl = appName + ".azurewebsites.net"; + final Region region = Region.US_WEST; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 20); + final String cosmosName = Utils.randomResourceName(azureResourceManager, "cosmosdb", 20); + final String appUrl = appName + ".azurewebsites.net"; try { //============================================================ // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) - .withEventualConsistency() - .withWriteReplication(Region.US_EAST) - .withReadReplication(Region.US_CENTRAL) - .create(); + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(cosmosName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) + .withEventualConsistency() + .withWriteReplication(Region.US_EAST) + .withReadReplication(Region.US_CENTRAL) + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); @@ -72,32 +73,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create a key vault Vault vault = azureResourceManager.vaults() - .define(vaultName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowSecretAllPermissions() - .attach() - .create(); + .define(vaultName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(clientId) + .allowSecretAllPermissions() + .attach() + .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); //============================================================ // Store Cosmos DB credentials in Key Vault + vault.secrets().define("azure-documentdb-uri").withValue(cosmosDBAccount.documentEndpoint()).create(); vault.secrets() - .define("azure-documentdb-uri") - .withValue(cosmosDBAccount.documentEndpoint()) - .create(); - vault.secrets() - .define("azure-documentdb-key") - .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) - .create(); - vault.secrets() - .define("azure-documentdb-database") - .withValue("tododb") - .create(); + .define("azure-documentdb-key") + .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) + .create(); + vault.secrets().define("azure-documentdb-database").withValue("tododb").create(); //============================================================ // Create a web app with a new app service plan @@ -105,21 +100,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); WebApp app = azureResourceManager.webApps() - .define(appName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_5_NEWEST) - .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) - .withSystemAssignedManagedServiceIdentity() - .withFtpsState(FtpsState.ALL_ALLOWED) - .create(); + .define(appName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_5_NEWEST) + .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) + .withSystemAssignedManagedServiceIdentity() + .withFtpsState(FtpsState.ALL_ALLOWED) + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); - app.manager().resourceManager().genericResources().define("ftp") + app.manager() + .resourceManager() + .genericResources() + .define("ftp") .withRegion(app.regionName()) .withExistingResourceGroup(app.resourceGroupName()) .withResourceType("basicPublishingCredentialsPolicies") @@ -134,19 +132,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Update vault to allow the web app to access vault.update() - .defineAccessPolicy() - .forObjectId(app.systemAssignedManagedServiceIdentityPrincipalId()) - .allowSecretAllPermissions() - .attach() - .apply(); + .defineAccessPolicy() + .forObjectId(app.systemAssignedManagedServiceIdentityPrincipalId()) + .allowSecretAllPermissions() + .attach() + .apply(); //============================================================ // Deploy to app through FTP System.out.println("Deploying a spring boot app to " + appName + " through FTP..."); - Utils.uploadFileViaFtp(app.getPublishingProfile(), "ROOT.jar", ManageWebAppCosmosDbThroughKeyVault.class.getResourceAsStream("/todo-app-java-on-azure-1.0-SNAPSHOT.jar")); - Utils.uploadFileViaFtp(app.getPublishingProfile(), "web.config", ManageWebAppCosmosDbThroughKeyVault.class.getResourceAsStream("/web.config")); + Utils.uploadFileViaFtp(app.getPublishingProfile(), "ROOT.jar", ManageWebAppCosmosDbThroughKeyVault.class + .getResourceAsStream("/todo-app-java-on-azure-1.0-SNAPSHOT.jar")); + Utils.uploadFileViaFtp(app.getPublishingProfile(), "web.config", + ManageWebAppCosmosDbThroughKeyVault.class.getResourceAsStream("/web.config")); System.out.println("Deployment to web app " + app.name() + " completed"); Utils.print(app); @@ -158,7 +158,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("CURLing " + appUrl); System.out.println(Utils.sendGetRequest("http://" + appUrl)); - return true; } finally { try { @@ -189,8 +188,7 @@ public static void main(String[] args) { .build(); final Configuration configuration = Configuration.getGlobalConfiguration(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java index 611e212793c09..734c86f4194cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java @@ -26,7 +26,6 @@ import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; - /** * Azure App Service basic sample for managing web app logs. * - Create a function app under the same new app service plan: @@ -56,22 +55,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); - final WebApp app = azureResourceManager.webApps().define(appName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .defineDiagnosticLogsConfiguration() - .withWebServerLogging() - .withWebServerLogsStoredOnFileSystem() - .attach() - .defineDiagnosticLogsConfiguration() - .withApplicationLogging() - .withLogLevel(LogLevel.VERBOSE) - .withApplicationLogsStoredOnFileSystem() - .attach() - .create(); + final WebApp app = azureResourceManager.webApps() + .define(appName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .defineDiagnosticLogsConfiguration() + .withWebServerLogging() + .withWebServerLogsStoredOnFileSystem() + .attach() + .defineDiagnosticLogsConfiguration() + .withApplicationLogging() + .withLogLevel(LogLevel.VERBOSE) + .withApplicationLogsStoredOnFileSystem() + .attach() + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); @@ -94,9 +94,10 @@ public void run() { System.out.println("Deploying coffeeshop.war to " + appName + " through web deploy..."); app.deploy() - .withPackageUri("https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/coffeeshop.zip") - .withExistingDeploymentsDeleted(false) - .execute(); + .withPackageUri( + "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/coffeeshop.zip") + .withExistingDeploymentsDeleted(false) + .execute(); System.out.println("Deployments to web app " + app.name() + " completed"); Utils.print(app); @@ -182,8 +183,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java index 8bb29e7053d97..a30105cbe95c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java @@ -37,17 +37,15 @@ public final class ManageWebAppSlots { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 24); - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); - final String slotName = "staging"; + final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 24); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); + final String slotName = "staging"; try { - azureResourceManager.resourceGroups().define(resourceGroupName) - .withRegion(Region.US_EAST) - .create(); + azureResourceManager.resourceGroups().define(resourceGroupName).withRegion(Region.US_EAST).create(); //============================================================ // Create 3 web apps with 3 new app service plans in different regions @@ -56,7 +54,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { WebApp app2 = createWebApp(azureResourceManager, app2Name, Region.EUROPE_WEST, resourceGroupName); WebApp app3 = createWebApp(azureResourceManager, app3Name, Region.ASIA_EAST, resourceGroupName); - //============================================================ // Create a deployment slot under each web app with auto swap @@ -89,6 +86,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -105,8 +103,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -122,23 +119,24 @@ public static void main(String[] args) { } } - private static WebApp createWebApp(AzureResourceManager azureResourceManager, String appName, Region region, String resourceGroupName) { + private static WebApp createWebApp(AzureResourceManager azureResourceManager, String appName, Region region, + String resourceGroupName) { final String appUrl = appName + SUFFIX; System.out.println("Creating web app " + appName + " with master branch..."); WebApp app = azureResourceManager.webApps() - .define(appName) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") - .withBranch("master") - .attach() - .create(); + .define(appName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") + .withBranch("master") + .attach() + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); @@ -152,10 +150,10 @@ private static DeploymentSlot createSlot(String slotName, WebApp app) { System.out.println("Creating a slot " + slotName + " with auto swap turned on..."); DeploymentSlot slot = app.deploymentSlots() - .define(slotName) - .withConfigurationFromParent() - .withAutoSwapSlotName("production") - .create(); + .define(slotName) + .withConfigurationFromParent() + .withAutoSwapSlotName("production") + .create(); System.out.println("Created slot " + slot.name()); Utils.print(slot); @@ -168,11 +166,11 @@ private static void deployToStaging(DeploymentSlot slot) { System.out.println("Deploying staging branch to slot " + slot.name() + "..."); slot.update() - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") - .withBranch("staging") - .attach() - .apply(); + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") + .withBranch("staging") + .attach() + .apply(); System.out.println("Deployed staging branch to slot " + slot.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java index a1b0be7a913a9..b53dfef2a624c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java @@ -36,29 +36,29 @@ public final class ManageWebAppSqlConnection { */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { // New resources - final String suffix = ".azurewebsites.net"; - final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String appUrl = appName + suffix; - final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); - final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); - final String admin = "jsdkadmin"; - final String password = Utils.password(); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String appUrl = appName + suffix; + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); + final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); + final String admin = "jsdkadmin"; + final String password = Utils.password(); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { - //============================================================ // Create a sql server System.out.println("Creating SQL server " + sqlServerName + "..."); - SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(admin) - .withAdministratorPassword(password) - .create(); + SqlServer server = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(admin) + .withAdministratorPassword(password) + .create(); System.out.println("Created SQL server " + server.name()); @@ -76,20 +76,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + appName + "..."); - WebApp app = azureResourceManager.webApps().define(appName) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withPhpVersion(PhpVersion.PHP5_6) - .defineSourceControl() - .withPublicGitRepository("https://github.com/ProjectNami/projectnami") - .withBranch("master") - .attach() - .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) - .withAppSetting("ProjectNami.DBName", db.name()) - .withAppSetting("ProjectNami.DBUser", admin) - .withAppSetting("ProjectNami.DBPass", password) - .create(); + WebApp app = azureResourceManager.webApps() + .define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withPhpVersion(PhpVersion.PHP5_6) + .defineSourceControl() + .withPublicGitRepository("https://github.com/ProjectNami/projectnami") + .withBranch("master") + .attach() + .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) + .withAppSetting("ProjectNami.DBName", db.name()) + .withAppSetting("ProjectNami.DBUser", admin) + .withAppSetting("ProjectNami.DBPass", password) + .create(); System.out.println("Created web app " + app.name()); Utils.print(app); @@ -109,7 +110,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw Utils.print(server); System.out.println("Your WordPress app is ready."); - System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); + System.out + .println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); System.in.read(); return true; @@ -125,6 +127,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } } + /** * Main entry point. * @param args the parameters @@ -140,8 +143,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java index 9647f8062963b..47d5217332174 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java @@ -37,7 +37,6 @@ import java.time.OffsetDateTime; import java.util.Collections; - /** * Azure App Service basic sample for managing web apps. * - Create a storage account and upload a couple blobs @@ -54,12 +53,12 @@ public final class ManageWebAppStorageAccountConnection { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String suffix = ".azurewebsites.net"; - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app1Url = app1Name + suffix; - final String storageName = Utils.randomResourceName(azureResourceManager, "jsdkstore", 20); - final String containerName = Utils.randomResourceName(azureResourceManager, "jcontainer", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app1Url = app1Name + suffix; + final String storageName = Utils.randomResourceName(azureResourceManager, "jsdkstore", 20); + final String containerName = Utils.randomResourceName(azureResourceManager, "jcontainer", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { @@ -68,15 +67,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating storage account " + storageName + "..."); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", - storageAccount.name(), accountKey); + storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); @@ -85,9 +85,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Uploading 2 blobs to container " + containerName + "..."); - BlobContainerClient container = setUpStorageAccount(connectionString, containerName, storageAccount.manager().httpPipeline().getHttpClient()); - uploadFileToContainer(container, "helloworld.war", ManageWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); - uploadFileToContainer(container, "install_apache.sh", ManageWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); + BlobContainerClient container = setUpStorageAccount(connectionString, containerName, + storageAccount.manager().httpPipeline().getHttpClient()); + uploadFileToContainer(container, "helloworld.war", + ManageWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); + uploadFileToContainer(container, "install_apache.sh", + ManageWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); @@ -96,21 +99,25 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating web app " + app1Name + "..."); - WebApp app1 = azureResourceManager.webApps().define(app1Name) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) - .withAppSetting("storage.containerName", containerName) - .withFtpsState(FtpsState.ALL_ALLOWED) - .create(); + WebApp app1 = azureResourceManager.webApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) + .withAppSetting("storage.containerName", containerName) + .withFtpsState(FtpsState.ALL_ALLOWED) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); - app1.manager().resourceManager().genericResources().define("ftp") + app1.manager() + .resourceManager() + .genericResources() + .define("ftp") .withRegion(app1.regionName()) .withExistingResourceGroup(app1.resourceGroupName()) .withResourceType("basicPublishingCredentialsPolicies") @@ -127,7 +134,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); - Utils.uploadFileViaFtp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); + Utils.uploadFileViaFtp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", + ManageWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); @@ -152,6 +160,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -168,8 +177,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -184,28 +192,27 @@ public static void main(String[] args) { } } - private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName, HttpClient httpClient) { - BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() - .connectionString(connectionString) - .containerName(containerName) - .httpClient(httpClient) - .buildClient(); + private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName, + HttpClient httpClient) { + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().connectionString(connectionString) + .containerName(containerName) + .httpClient(httpClient) + .buildClient(); blobContainerClient.create(); - BlobSignedIdentifier identifier = new BlobSignedIdentifier() - .setId("webapp") - .setAccessPolicy(new BlobAccessPolicy() - .setStartsOn(OffsetDateTime.now()) - .setExpiresOn(OffsetDateTime.now().plusDays(7)) - .setPermissions("rl")); + BlobSignedIdentifier identifier = new BlobSignedIdentifier().setId("webapp") + .setAccessPolicy(new BlobAccessPolicy().setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } - private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { + private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, + String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java index e4da35b9f5473..2c4b55ef1e971 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java @@ -37,32 +37,32 @@ public final class ManageWebAppWithAuthentication { */ public static boolean runSample(AzureResourceManager azureResourceManager) { // New resources - final String suffix = ".azurewebsites.net"; - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); - final String app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); - final String app1Url = app1Name + suffix; - final String app2Url = app2Name + suffix; - final String app3Url = app3Name + suffix; - final String app4Url = app4Name + suffix; - final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + final String suffix = ".azurewebsites.net"; + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); + final String app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); + final String app1Url = app1Name + suffix; + final String app2Url = app2Name + suffix; + final String app3Url = app3Name + suffix; + final String app4Url = app4Name + suffix; + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { - //============================================================ // Create a web app with a new app service plan System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "..."); - WebApp app1 = azureResourceManager.webApps().define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .create(); + WebApp app1 = azureResourceManager.webApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -80,11 +80,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating web app " + app1Name + " to use active directory login..."); app1.update() - .defineAuthentication() - .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.AZURE_ACTIVE_DIRECTORY) - .withActiveDirectory(applicationId, "https://sts.windows.net/" + tenantId) - .attach() - .apply(); + .defineAuthentication() + .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.AZURE_ACTIVE_DIRECTORY) + .withActiveDirectory(applicationId, "https://sts.windows.net/" + tenantId) + .attach() + .apply(); System.out.println("Added active directory login to " + app1.name()); Utils.print(app1); @@ -94,12 +94,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); - WebApp app2 = azureResourceManager.webApps().define(app2Name) - .withExistingWindowsPlan(plan) - .withExistingResourceGroup(rgName) - .withJavaVersion(JavaVersion.JAVA_8_NEWEST) - .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) - .create(); + WebApp app2 = azureResourceManager.webApps() + .define(app2Name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rgName) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .create(); System.out.println("Created web app " + app2.name()); Utils.print(app2); @@ -116,11 +117,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating web app " + app2Name + " to use Facebook login..."); app2.update() - .defineAuthentication() - .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK) - .withFacebook(fbAppId, fbAppSecret) - .attach() - .apply(); + .defineAuthentication() + .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK) + .withFacebook(fbAppId, fbAppSecret) + .attach() + .apply(); System.out.println("Added Facebook login to " + app2.name()); Utils.print(app2); @@ -129,14 +130,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a 3rd web app with a public GitHub repo in Azure-Samples System.out.println("Creating another web app " + app3Name + "..."); - WebApp app3 = azureResourceManager.webApps().define(app3Name) - .withExistingWindowsPlan(plan) - .withNewResourceGroup(rgName) - .defineSourceControl() - .withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started") - .withBranch("master") - .attach() - .create(); + WebApp app3 = azureResourceManager.webApps() + .define(app3Name) + .withExistingWindowsPlan(plan) + .withNewResourceGroup(rgName) + .defineSourceControl() + .withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started") + .withBranch("master") + .attach() + .create(); System.out.println("Created web app " + app3.name()); Utils.print(app3); @@ -153,11 +155,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating web app " + app3Name + " to use Google login..."); app3.update() - .defineAuthentication() - .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.GOOGLE) - .withGoogle(gClientId, gClientSecret) - .attach() - .apply(); + .defineAuthentication() + .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.GOOGLE) + .withGoogle(gClientId, gClientSecret) + .attach() + .apply(); System.out.println("Added Google login to " + app3.name()); Utils.print(app3); @@ -167,10 +169,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another web app " + app4Name + "..."); WebApp app4 = azureResourceManager.webApps() - .define(app4Name) - .withExistingWindowsPlan(plan) - .withExistingResourceGroup(rgName) - .create(); + .define(app4Name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Created web app " + app4.name()); Utils.print(app4); @@ -187,11 +189,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating web app " + app3Name + " to use Microsoft login..."); app4.update() - .defineAuthentication() - .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.MICROSOFT_ACCOUNT) - .withMicrosoft(clientId, clientSecret) - .attach() - .apply(); + .defineAuthentication() + .withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.MICROSOFT_ACCOUNT) + .withMicrosoft(clientId, clientSecret) + .attach() + .apply(); System.out.println("Added Microsoft login to " + app4.name()); Utils.print(app4); @@ -209,6 +211,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -224,8 +227,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java index d60972ed3e075..d66ba6715704b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java @@ -41,11 +41,11 @@ public final class ManageWebAppWithDomainSsl { */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { // New resources - final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); - final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; - final String certPassword = Utils.password(); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String certPassword = Utils.password(); try { //============================================================ @@ -53,11 +53,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating web app " + app1Name + "..."); - WebApp app1 = azureResourceManager.webApps().define(app1Name) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.STANDARD_S1) - .create(); + WebApp app1 = azureResourceManager.webApps() + .define(app1Name) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); @@ -67,10 +68,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating another web app " + app2Name + "..."); AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); - WebApp app2 = azureResourceManager.webApps().define(app2Name) - .withExistingWindowsPlan(plan) - .withExistingResourceGroup(rgName) - .create(); + WebApp app2 = azureResourceManager.webApps() + .define(app2Name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Created web app " + app2.name()); Utils.print(app2); @@ -80,23 +82,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) - .withExistingResourceGroup(rgName) - .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(false) - .create(); + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); @@ -106,12 +109,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding http://" + app1Name + "." + domainName + " to web app " + app1Name + "..."); app1 = app1.update() - .defineHostnameBinding() - .withAzureManagedDomain(domain) - .withSubDomain(app1Name) - .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) - .attach() - .apply(); + .defineHostnameBinding() + .withAzureManagedDomain(domain) + .withSubDomain(app1Name) + .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) + .attach() + .apply(); System.out.println("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name); Utils.print(app1); @@ -119,8 +122,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Create a self-singed SSL certificate - String pfxPath = ManageWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; - String cerPath = ManageWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + String pfxPath + = ManageWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath + = ManageWebAppWithDomainSsl.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; System.out.println("Creating a self-signed certificate " + pfxPath + "..."); @@ -134,13 +139,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding https://" + app1Name + "." + domainName + " to web app " + app1Name + "..."); app1 = app1.update() - .withManagedHostnameBindings(domain, app1Name) - .defineSslBinding() - .forHostname(app1Name + "." + domainName) - .withPfxCertificateToUpload(new File(pfxPath), certPassword) - .withSniBasedSsl() - .attach() - .apply(); + .withManagedHostnameBindings(domain, app1Name) + .defineSslBinding() + .forHostname(app1Name + "." + domainName) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .apply(); System.out.println("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name); Utils.print(app1); @@ -148,13 +153,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Binding https://" + app2Name + "." + domainName + " to web app " + app2Name + "..."); app2 = app2.update() - .withManagedHostnameBindings(domain, app2Name) - .defineSslBinding() - .forHostname(app2Name + "." + domainName) - .withExistingCertificate(app1.hostnameSslStates().get(app1Name + "." + domainName).thumbprint()) - .withSniBasedSsl() - .attach() - .apply(); + .withManagedHostnameBindings(domain, app2Name) + .defineSslBinding() + .forHostname(app2Name + "." + domainName) + .withExistingCertificate(app1.hostnameSslStates().get(app1Name + "." + domainName).thumbprint()) + .withSniBasedSsl() + .attach() + .apply(); System.out.println("Finished binding http://" + app2Name + "." + domainName + " to web app " + app2Name); Utils.print(app2); @@ -172,6 +177,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } } + /** * Main entry point. * @param args the parameters @@ -188,8 +194,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java index 2eac627fcd8f4..96b63d6b7ed1c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java @@ -74,11 +74,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Purchasing a domain " + domainName + "..."); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); - domain = azureResourceManager.appServiceDomains().define(domainName) + domain = azureResourceManager.appServiceDomains() + .define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") @@ -102,7 +101,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Create a self-singed SSL certificate pfxPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; - String cerPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + String cerPath + = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; System.out.println("Creating a self-signed certificate " + pfxPath + "..."); @@ -171,7 +171,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); - TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) + TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles() + .define(tmName) .withExistingResourceGroup(rgName) .withLeafDomainLabel(tmName) .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) @@ -197,27 +198,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Scaling up app service plan " + plan1Name + "..."); - plan1.update() - .withCapacity(plan1.capacity() * 2) - .apply(); + plan1.update().withCapacity(plan1.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan1Name); Utils.print(plan1); System.out.println("Scaling up app service plan " + plan2Name + "..."); - plan2.update() - .withCapacity(plan2.capacity() * 2) - .apply(); + plan2.update().withCapacity(plan2.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan2Name); Utils.print(plan2); System.out.println("Scaling up app service plan " + plan3Name + "..."); - plan3.update() - .withCapacity(plan3.capacity() * 2) - .apply(); + plan3.update().withCapacity(plan3.capacity() * 2).apply(); System.out.println("Scaled up app service plan " + plan3Name); Utils.print(plan3); @@ -237,29 +232,31 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } private static AppServicePlan createAppServicePlan(String name, Region region) { - return azureResourceManager.appServicePlans().define(name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withPricingTier(PricingTier.STANDARD_S1) - .withOperatingSystem(OperatingSystem.WINDOWS) - .create(); + return azureResourceManager.appServicePlans() + .define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.STANDARD_S1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); } private static WebApp createWebApp(String name, AppServicePlan plan) { - return azureResourceManager.webApps().define(name) - .withExistingWindowsPlan(plan) - .withExistingResourceGroup(rgName) - .withManagedHostnameBindings(domain, name) - .defineSslBinding() - .forHostname(name + "." + domain.name()) - .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) - .withSniBasedSsl() - .attach() - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") - .withBranch("master") - .attach() - .create(); + return azureResourceManager.webApps() + .define(name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rgName) + .withManagedHostnameBindings(domain, name) + .defineSslBinding() + .forHostname(name + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) + .withSniBasedSsl() + .attach() + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); } /** @@ -276,8 +273,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java index 4b66261401458..1a73621313154 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java @@ -41,15 +41,16 @@ public final class ManageServicePrincipalCredentials { * @param profile the profile the sample is running in * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager, AzureProfile profile) throws IOException { - final String spName = Utils.randomResourceName(azureResourceManager, "sp", 20); - final String appName = Utils.randomResourceName(azureResourceManager, "app", 20); - final String passwordName1 = Utils.randomResourceName(azureResourceManager, "password", 20); + public static boolean runSample(AzureResourceManager azureResourceManager, AzureProfile profile) + throws IOException { + final String spName = Utils.randomResourceName(azureResourceManager, "sp", 20); + final String appName = Utils.randomResourceName(azureResourceManager, "app", 20); + final String passwordName1 = Utils.randomResourceName(azureResourceManager, "password", 20); final PasswordHolder passwordHolder1 = new PasswordHolder(); - final String passwordName2 = Utils.randomResourceName(azureResourceManager, "password", 20); + final String passwordName2 = Utils.randomResourceName(azureResourceManager, "password", 20); final PasswordHolder passwordHolder2 = new PasswordHolder(); - final String certName1 = Utils.randomResourceName(azureResourceManager, "cert", 20); - final String raName = Utils.randomUuid(azureResourceManager); + final String certName1 = Utils.randomResourceName(azureResourceManager, "cert", 20); + final String raName = Utils.randomUuid(azureResourceManager); String servicePrincipalId = ""; try { // ============================================================ @@ -57,21 +58,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Creating an Active Directory service principal " + spName + "..."); - ServicePrincipal servicePrincipal = azureResourceManager.accessManagement().servicePrincipals() - .define(spName) - .withNewApplication() - .definePasswordCredential(passwordName1) - .withPasswordConsumer(passwordHolder1) - .attach() - .definePasswordCredential(passwordName2) - .withPasswordConsumer(passwordHolder2) - .attach() - .defineCertificateCredential(certName1) - .withAsymmetricX509Certificate() - .withPublicKey(ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer"))) - .withDuration(Duration.ofDays(1)) - .attach() - .create(); + ServicePrincipal servicePrincipal = azureResourceManager.accessManagement() + .servicePrincipals() + .define(spName) + .withNewApplication() + .definePasswordCredential(passwordName1) + .withPasswordConsumer(passwordHolder1) + .attach() + .definePasswordCredential(passwordName2) + .withPasswordConsumer(passwordHolder2) + .attach() + .defineCertificateCredential(certName1) + .withAsymmetricX509Certificate() + .withPublicKey( + ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer"))) + .withDuration(Duration.ofDays(1)) + .attach() + .create(); System.out.println("Created service principal " + spName + "."); Utils.print(servicePrincipal); @@ -84,12 +87,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure ResourceManagerUtils.sleep(Duration.ofSeconds(15)); - RoleAssignment roleAssignment = azureResourceManager.accessManagement().roleAssignments() - .define(raName) - .forServicePrincipal(servicePrincipal) - .withBuiltInRole(BuiltInRole.CONTRIBUTOR) - .withSubscriptionScope(profile.getSubscriptionId()) - .create(); + RoleAssignment roleAssignment = azureResourceManager.accessManagement() + .roleAssignments() + .define(raName) + .forServicePrincipal(servicePrincipal) + .withBuiltInRole(BuiltInRole.CONTRIBUTOR) + .withSubscriptionScope(profile.getSubscriptionId()) + .create(); System.out.println("Created role assignment " + raName + "."); Utils.print(roleAssignment); @@ -99,12 +103,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Verifying password credential " + passwordName1 + " is valid..."); - TokenCredential testCredential = new ClientSecretCredentialBuilder() - .tenantId(azureResourceManager.tenantId()) - .clientId(servicePrincipal.applicationId()) - .clientSecret(passwordHolder1.password) - .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) - .build(); + TokenCredential testCredential + = new ClientSecretCredentialBuilder().tenantId(azureResourceManager.tenantId()) + .clientId(servicePrincipal.applicationId()) + .clientSecret(passwordHolder1.password) + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); try { AzureResourceManager.authenticate(testCredential, profile).withDefaultSubscription(); @@ -115,8 +119,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Verifying password credential " + passwordName2 + " is valid..."); - testCredential = new ClientSecretCredentialBuilder() - .tenantId(azureResourceManager.tenantId()) + testCredential = new ClientSecretCredentialBuilder().tenantId(azureResourceManager.tenantId()) .clientId(servicePrincipal.applicationId()) .clientSecret(passwordHolder2.password) .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) @@ -131,8 +134,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Verifying certificate credential " + certName1 + " is valid..."); - testCredential = new ClientCertificateCredentialBuilder() - .tenantId(azureResourceManager.tenantId()) + testCredential = new ClientCertificateCredentialBuilder().tenantId(azureResourceManager.tenantId()) .clientId(servicePrincipal.applicationId()) .pfxCertificate(ManageServicePrincipalCredentials.class.getResource("/myTest.pfx").toString(), "Abc123") .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) @@ -149,9 +151,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure // Revoke access of the 1st password credential System.out.println("Revoking access for password credential " + passwordName1 + "..."); - servicePrincipal.update() - .withoutCredential(passwordName1) - .apply(); + servicePrincipal.update().withoutCredential(passwordName1).apply(); ResourceManagerUtils.sleep(Duration.ofSeconds(15)); @@ -162,8 +162,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Verifying password credential " + passwordName1 + " is revoked..."); - testCredential = new ClientSecretCredentialBuilder() - .tenantId(azureResourceManager.tenantId()) + testCredential = new ClientSecretCredentialBuilder().tenantId(azureResourceManager.tenantId()) .clientId(servicePrincipal.applicationId()) .clientSecret(passwordHolder1.password) .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) @@ -190,22 +189,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Verifying password credential " + passwordName2 + " has no access to subscription..."); - testCredential = new ClientSecretCredentialBuilder() - .tenantId(azureResourceManager.tenantId()) + testCredential = new ClientSecretCredentialBuilder().tenantId(azureResourceManager.tenantId()) .clientId(servicePrincipal.applicationId()) .clientSecret(passwordHolder2.password) .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); try { - AzureResourceManager.authenticate(testCredential, profile).withDefaultSubscription() - .resourceGroups().list(); + AzureResourceManager.authenticate(testCredential, profile) + .withDefaultSubscription() + .resourceGroups() + .list(); System.out.println("Failed to verify " + passwordName2 + " has no access to subscription."); } catch (Exception e) { System.out.println("Verified " + passwordName2 + " has no access to subscription."); } - return true; } finally { try { @@ -239,8 +238,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java index 867b5d4d7f08c..9f7273c9ef2b4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java @@ -56,11 +56,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure System.out.println("Creating an AD user " + userName + "..."); - ActiveDirectoryUser user = azureResourceManager.accessManagement().activeDirectoryUsers() - .define(userName) - .withEmailAlias(userEmail) - .withPassword(Utils.password()) - .create(); + ActiveDirectoryUser user = azureResourceManager.accessManagement() + .activeDirectoryUsers() + .define(userName) + .withEmailAlias(userEmail) + .withPassword(Utils.password()) + .create(); System.out.println("Created AD user " + userName); Utils.print(user); @@ -68,12 +69,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure // ============================================================ // Assign role to AD user - RoleAssignment roleAssignment1 = azureResourceManager.accessManagement().roleAssignments() - .define(raName1) - .forUser(user) - .withBuiltInRole(BuiltInRole.READER) - .withSubscriptionScope(profile.getSubscriptionId()) - .create(); + RoleAssignment roleAssignment1 = azureResourceManager.accessManagement() + .roleAssignments() + .define(raName1) + .forUser(user) + .withBuiltInRole(BuiltInRole.READER) + .withSubscriptionScope(profile.getSubscriptionId()) + .create(); System.out.println("Created Role Assignment:"); Utils.print(roleAssignment1); @@ -86,16 +88,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure // ============================================================ // Get role by scope and role name - RoleDefinition roleDefinition = azureResourceManager.accessManagement().roleDefinitions() - .getByScopeAndRoleName("subscriptions/" + profile.getSubscriptionId(), "Contributor"); + RoleDefinition roleDefinition = azureResourceManager.accessManagement() + .roleDefinitions() + .getByScopeAndRoleName("subscriptions/" + profile.getSubscriptionId(), "Contributor"); Utils.print(roleDefinition); // ============================================================ // Create Service Principal - ServicePrincipal sp = azureResourceManager.accessManagement().servicePrincipals().define(spName) - .withNewApplication() - .create(); + ServicePrincipal sp = azureResourceManager.accessManagement() + .servicePrincipals() + .define(spName) + .withNewApplication() + .create(); // wait till service principal created and propagated ResourceManagerUtils.sleep(Duration.ofSeconds(15)); System.out.println("Created Service Principal:"); @@ -105,12 +110,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure // ============================================================ // Assign role to Service Principal - RoleAssignment roleAssignment2 = azureResourceManager.accessManagement().roleAssignments() - .define(raName2) - .forServicePrincipal(sp) - .withBuiltInRole(BuiltInRole.CONTRIBUTOR) - .withSubscriptionScope(profile.getSubscriptionId()) - .create(); + RoleAssignment roleAssignment2 = azureResourceManager.accessManagement() + .roleAssignments() + .define(raName2) + .forServicePrincipal(sp) + .withBuiltInRole(BuiltInRole.CONTRIBUTOR) + .withSubscriptionScope(profile.getSubscriptionId()) + .create(); System.out.println("Created Role Assignment:"); Utils.print(roleAssignment2); @@ -118,29 +124,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure // Create Active Directory groups System.out.println("Creating Active Directory group " + groupName1 + "..."); - ActiveDirectoryGroup group1 = azureResourceManager.accessManagement().activeDirectoryGroups() - .define(groupName1) - .withEmailAlias(groupEmail1) - .create(); + ActiveDirectoryGroup group1 = azureResourceManager.accessManagement() + .activeDirectoryGroups() + .define(groupName1) + .withEmailAlias(groupEmail1) + .create(); System.out.println("Created Active Directory group " + groupName1); Utils.print(group1); System.out.println("Creating Active Directory group " + groupName2 + "..."); - ActiveDirectoryGroup group2 = azureResourceManager.accessManagement().activeDirectoryGroups() - .define(groupName2) - .withEmailAlias(groupEmail2) - .create(); + ActiveDirectoryGroup group2 = azureResourceManager.accessManagement() + .activeDirectoryGroups() + .define(groupName2) + .withEmailAlias(groupEmail2) + .create(); System.out.println("Created Active Directory group " + groupName2); Utils.print(group2); System.out.println("Adding group members to group " + groupName2 + "..."); - group2.update() - .withMember(user) - .withMember(sp) - .withMember(group1) - .apply(); + group2.update().withMember(user).withMember(sp).withMember(group1).apply(); System.out.println("Group members added to group " + groupName2); Utils.print(group2); @@ -168,8 +172,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java index 3cd42d6abcf54..612b8f08596c4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java @@ -51,9 +51,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { try { // ============================================================ // Create a resource group for holding all the created resources - azureResourceManager.resourceGroups().define(resourceGroupName) - .withRegion(Region.US_CENTRAL) - .create(); + azureResourceManager.resourceGroups().define(resourceGroupName).withRegion(Region.US_CENTRAL).create(); // ============================================================ // Create 8 websites @@ -85,7 +83,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create CDN Profile definition object that will let us do a for loop // to define all 8 endpoints and then parallelize their creation - CdnProfile.DefinitionStages.WithStandardCreate profileDefinition = azureResourceManager.cdnProfiles().define(cdnProfileName) + CdnProfile.DefinitionStages.WithStandardCreate profileDefinition = azureResourceManager.cdnProfiles() + .define(cdnProfileName) .withRegion(Region.US_CENTRAL) .withExistingResourceGroup(resourceGroupName) .withStandardVerizonSku(); @@ -137,11 +136,9 @@ public static void main(String[] args) { // Authenticate final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); - final TokenCredential credential = new DefaultAzureCredentialBuilder() - .build(); + final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -156,7 +153,8 @@ public static void main(String[] args) { } } - private static WebApp createWebApp(String appName, Region region, AzureResourceManager azureResourceManager, String resourceGroupName) { + private static WebApp createWebApp(String appName, Region region, AzureResourceManager azureResourceManager, + String resourceGroupName) { final String appUrl = appName + SUFFIX; System.out.println("Creating web app " + appName + " with master branch..."); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java index 082146f6ac332..2634c53c59c63 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java @@ -45,28 +45,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { String customDomain = cnameRecordName + "." + domainName; try { - azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); //============================================================ // Purchase a domain System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); @@ -76,25 +75,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create root DNS zone System.out.println("Creating root DNS zone " + domainName + "..."); - DnsZone dnsZone = azureResourceManager.dnsZones().define(domainName) - .withExistingResourceGroup(rgName) - .create(); + DnsZone dnsZone + = azureResourceManager.dnsZones().define(domainName).withExistingResourceGroup(rgName).create(); System.out.println("Created root DNS zone " + dnsZone.name()); //============================================================ // Create CNAME DNS record System.out.println("Creating CNAME DNS record " + cnameRecordName + "..."); - dnsZone.update() - .withCNameRecordSet(cnameRecordName, cdnEndpointName + ".azureedge.net") - .apply(); + dnsZone.update().withCNameRecordSet(cnameRecordName, cdnEndpointName + ".azureedge.net").apply(); System.out.println("Created CNAME DNS record"); //============================================================ // Create CDN profile System.out.println("Creating CDN profile " + cdnProfileName + "..."); - CdnProfile cdnProfile = azureResourceManager.cdnProfiles().define(cdnProfileName) + CdnProfile cdnProfile = azureResourceManager.cdnProfiles() + .define(cdnProfileName) .withRegion(region) .withExistingResourceGroup(rgName) .withStandardMicrosoftSku() @@ -107,10 +104,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating CDN endpoint " + cdnEndpointName + "..."); cdnProfile.update() .defineNewEndpoint(cdnEndpointName) - .withOrigin("origin1", "www.someDomain.net") - .withHttpAllowed(true) - .withHttpsAllowed(true) - .attach() + .withOrigin("origin1", "www.someDomain.net") + .withHttpAllowed(true) + .withHttpsAllowed(true) + .attach() .apply(); Map cdnEndpoints = cdnProfile.endpoints(); @@ -121,11 +118,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Associate the custom domain with CDN endpoint System.out.println("Associating the custom domain with CDN endpoint " + cdnEndpoint.name()); - cdnProfile.update() - .updateEndpoint(cdnEndpointName) - .withCustomDomain(customDomain) - .parent() - .apply(); + cdnProfile.update().updateEndpoint(cdnEndpointName).withCustomDomain(customDomain).parent().apply(); cdnEndpoints = cdnProfile.endpoints(); cdnEndpoint = cdnEndpoints.get(cdnEndpointName); System.out.println("Associated the custom domain with CDN endpoint " + cdnEndpoint.name()); @@ -160,11 +153,9 @@ public static void main(String[] args) { // Authenticate final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); - final TokenCredential credential = new DefaultAzureCredentialBuilder() - .build(); + final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java index 9468f23ff5e40..1a858af28a799 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java @@ -57,7 +57,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") @@ -94,7 +95,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create incremental Snapshot from the OS managed disk - System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); + System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", + osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") @@ -107,11 +109,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Copy snapshots to the new region - System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); - Snapshot osSnapshotNewRegion = azureResourceManager - .snapshots() + Snapshot osSnapshotNewRegion = azureResourceManager.snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) @@ -131,7 +131,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { - System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); + System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", + dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") @@ -146,8 +147,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); - Snapshot dataSnapshotNewRegion = azureResourceManager - .snapshots() + Snapshot dataSnapshotNewRegion = azureResourceManager.snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) @@ -171,7 +171,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); - Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) + Disk newOSDisk = azureResourceManager.disks() + .define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) @@ -188,7 +189,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); - Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) + Disk dataDisk = azureResourceManager.disks() + .define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() @@ -206,7 +208,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using specialized OS and data disks"); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") @@ -263,8 +266,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java index 99a22d44ef16d..416cf0fae439b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java @@ -42,26 +42,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating an un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(100) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(100) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created a Linux VM with un-managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -112,8 +113,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java index 25368e324ee75..76fe3f13366f0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java @@ -43,7 +43,8 @@ public final class CreateMultipleVirtualMachinesAndBatchQueryStatus { * @param resourceGraphManager instance of the azure graph client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager, ResourceGraphManager resourceGraphManager) { + public static boolean runSample(AzureResourceManager azureResourceManager, + ResourceGraphManager resourceGraphManager) { final Integer desiredVMCount = 6; final Region region = Region.US_EAST; final String rgName = Utils.randomResourceName(azureResourceManager, "rg-", 15); @@ -56,52 +57,54 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Resou System.out.println("Creating Network: " + networkName); Network primaryNetwork = azureResourceManager.networks() - .define(networkName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("10.0.0.0/16") - .withSubnet(subNetName, "10.0.1.0/24") - .create(); + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("10.0.0.0/16") + .withSubnet(subNetName, "10.0.1.0/24") + .create(); System.out.println("Batch creating Virtual Machines"); for (int i = 0; i < desiredVMCount; i++) { azureResourceManager.virtualMachines() - .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(primaryNetwork) - .withSubnet(subNetName) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) - .withSsh(Utils.sshPublicKey()) - .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .beginCreate(); + .define(Utils.randomResourceName(azureResourceManager, "javascvm", 15)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(primaryNetwork) + .withSubnet(subNetName) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername(Utils.randomResourceName(azureResourceManager, "tirekicker", 15)) + .withSsh(Utils.sshPublicKey()) + .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .beginCreate(); } System.out.println("Use Azure Resource Graph to query the count number for each [provisioningState]."); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("resources ") - .append("| where (resourceGroup =~ ('").append(rgName).append("')) ") - .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") - .append("| where (name contains 'javascvm') ") - .append("| extend provisioningState = case(") - .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") - .append("properties['provisioningState'] =~ 'Accepted','Accepted',") - .append("properties['provisioningState'] =~ 'Running','Running',") - .append("properties['provisioningState'] =~ 'Ready','Ready',") - .append("properties['provisioningState'] =~ 'Creating','Creating',") - .append("properties['provisioningState'] =~ 'Created','Created',") - .append("properties['provisioningState'] =~ 'Deleting','Deleting',") - .append("properties['provisioningState'] =~ 'Deleted','Deleted',") - .append("properties['provisioningState'] =~ 'Canceled','Canceled',") - .append("properties['provisioningState'] =~ 'Failed','Failed',") - .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") - .append("properties['provisioningState'] =~ 'Updating','Updating',") - .append("properties['provisioningState']) ") - .append("| summarize count=count() by provisioningState"); + .append("| where (resourceGroup =~ ('") + .append(rgName) + .append("')) ") + .append("| where (type =~ ('microsoft.compute/virtualmachines')) ") + .append("| where (name contains 'javascvm') ") + .append("| extend provisioningState = case(") + .append("properties['provisioningState'] =~ 'NotSpecified','NotSpecified',") + .append("properties['provisioningState'] =~ 'Accepted','Accepted',") + .append("properties['provisioningState'] =~ 'Running','Running',") + .append("properties['provisioningState'] =~ 'Ready','Ready',") + .append("properties['provisioningState'] =~ 'Creating','Creating',") + .append("properties['provisioningState'] =~ 'Created','Created',") + .append("properties['provisioningState'] =~ 'Deleting','Deleting',") + .append("properties['provisioningState'] =~ 'Deleted','Deleted',") + .append("properties['provisioningState'] =~ 'Canceled','Canceled',") + .append("properties['provisioningState'] =~ 'Failed','Failed',") + .append("properties['provisioningState'] =~ 'Succeeded','Succeeded',") + .append("properties['provisioningState'] =~ 'Updating','Updating',") + .append("properties['provisioningState']) ") + .append("| summarize count=count() by provisioningState"); while (succeededTotal < desiredVMCount) { Integer creatingTotal = 0; @@ -111,38 +114,48 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Resou succeededTotal = 0; QueryResponse queryResponse = resourceGraphManager.resourceProviders() - .resources(new QueryRequest() - .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) - .withQuery(queryBuilder.toString()) - .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); - - List totalResultList = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference>() {}); + .resources(new QueryRequest() + .withSubscriptions(Collections.singletonList(azureResourceManager.subscriptionId())) + .withQuery(queryBuilder.toString()) + .withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY))); + + List totalResultList + = new ObjectMapper().convertValue(queryResponse.data(), new TypeReference>() { + }); for (TotalResult totalResult : totalResultList) { switch (totalResult.getProvisioningState()) { case "Creating": creatingTotal = totalResult.getCount(); break; + case "Succeeded": succeededTotal = totalResult.getCount(); break; + case "Updating": updatingTotal = totalResult.getCount(); break; + case "Failed": failedTotal = totalResult.getCount(); break; + default: otherTotal += totalResult.getCount(); break; } } - System.out.println(new StringBuilder() - .append("\n\tThe total number of Creating : ").append(creatingTotal) - .append("\n\tThe total number of Updating : ").append(updatingTotal) - .append("\n\tThe total number of Failed : ").append(failedTotal) - .append("\n\tThe total number of Succeeded : ").append(succeededTotal) - .append("\n\tThe total number of Other Status : ").append(otherTotal)); + System.out.println(new StringBuilder().append("\n\tThe total number of Creating : ") + .append(creatingTotal) + .append("\n\tThe total number of Updating : ") + .append(updatingTotal) + .append("\n\tThe total number of Failed : ") + .append(failedTotal) + .append("\n\tThe total number of Succeeded : ") + .append(succeededTotal) + .append("\n\tThe total number of Other Status : ") + .append(otherTotal)); if (failedTotal > 0) { break; @@ -172,19 +185,17 @@ public static void main(String[] args) { // Authenticate final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() - .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) - .build(); + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() - .withLogLevel(HttpLogDetailLevel.BASIC) - .authenticate(credential, profile) - .withDefaultSubscription(); + AzureResourceManager azureResourceManager = AzureResourceManager.configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); - ResourceGraphManager resourceGraphManager = ResourceGraphManager - .configure() - .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) - .authenticate(credential, profile); + ResourceGraphManager resourceGraphManager = ResourceGraphManager.configure() + .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) + .authenticate(credential, profile); // Print selected subscription System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); @@ -196,7 +207,8 @@ public static void main(String[] args) { } } - private CreateMultipleVirtualMachinesAndBatchQueryStatus() {} + private CreateMultipleVirtualMachinesAndBatchQueryStatus() { + } private static class TotalResult { private String provisioningState; diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java index d845e180dc62d..0b0bdd282dba4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java @@ -63,17 +63,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withRegion(region) .withNewResourceGroup(rgName) .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowKeyPermissions(KeyPermissions.CREATE) - .attach() + .forServicePrincipal(clientId) + .allowKeyPermissions(KeyPermissions.CREATE) + .attach() .withPurgeProtectionEnabled() .create(); - Key vaultKey = vault.keys() - .define(keyName) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key vaultKey = vault.keys().define(keyName).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); //============================================================= // Create disk encryption set @@ -94,9 +90,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin vault.update() .defineAccessPolicy() - .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .apply(); //============================================================= @@ -127,9 +123,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin linuxVM.deallocate(); Disk lun1 = azureResourceManager.disks().getById(linuxVM.dataDisks().get(1).id()); - lun1.update() - .withDiskEncryptionSet(des.id(), EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY) - .apply(); + lun1.update().withDiskEncryptionSet(des.id(), EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY).apply(); linuxVM.start(); linuxVM.refresh(); System.out.println("Converted encryption of data disk lun2 to customer-managed keys: "); @@ -138,7 +132,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================= // Create a new disk encrypted using customer-managed key - Disk lun2 = azureResourceManager.disks().define(diskLun3Name) + Disk lun2 = azureResourceManager.disks() + .define(diskLun3Name) .withRegion(region) .withExistingResourceGroup(rgName) .withData() @@ -149,9 +144,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================= // Attach the disk to the vm as lun2 - linuxVM.update() - .withExistingDataDisk(lun2, 2, CachingTypes.READ_WRITE) - .apply(); + linuxVM.update().withExistingDataDisk(lun2, 2, CachingTypes.READ_WRITE).apply(); System.out.println("Updated virtual machine with 2 data disks all encrypted using customer-managed key"); Utils.print(linuxVM); return true; @@ -183,8 +176,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java index a64c23ff38b74..0cdffa181fde6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java @@ -56,7 +56,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST2; - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String apacheInstallCommand = "bash install_apache.sh"; List apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); @@ -68,38 +69,39 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(100) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .defineUnmanagedDataDisk("disk-3") - .withNewVhd(60) - .withLun(3) - .attach() - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", apacheInstallScriptUris) - .withPublicSetting("commandToExecute", apacheInstallCommand) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(100) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .defineUnmanagedDataDisk("disk-3") + .withNewVhd(60) + .withLun(3) + .attach() + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", apacheInstallScriptUris) + .withPublicSetting("commandToExecute", apacheInstallCommand) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) + .create(); System.out.println("Created a Linux VM with un-managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -129,24 +131,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating virtual machine custom image from un-managed disk VHDs: " + linuxVM.id()); VirtualMachineCustomImage virtualMachineCustomImage = azureResourceManager.virtualMachineCustomImages() - .define(customImageName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED) - .defineDataDiskImage() - .withLun(linuxVM.unmanagedDataDisks().get(1).lun()) - .fromVhd(linuxVM.unmanagedDataDisks().get(1).vhdUri()) - .attach() - .defineDataDiskImage() - .withLun(linuxVM.unmanagedDataDisks().get(2).lun()) - .fromVhd(linuxVM.unmanagedDataDisks().get(2).vhdUri()) - .attach() - .defineDataDiskImage() - .withLun(linuxVM.unmanagedDataDisks().get(3).lun()) - .fromVhd(linuxVM.unmanagedDataDisks().get(3).vhdUri()) - .withDiskCaching(CachingTypes.READ_ONLY) - .attach() - .create(); + .define(customImageName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED) + .defineDataDiskImage() + .withLun(linuxVM.unmanagedDataDisks().get(1).lun()) + .fromVhd(linuxVM.unmanagedDataDisks().get(1).vhdUri()) + .attach() + .defineDataDiskImage() + .withLun(linuxVM.unmanagedDataDisks().get(2).lun()) + .fromVhd(linuxVM.unmanagedDataDisks().get(2).vhdUri()) + .attach() + .defineDataDiskImage() + .withLun(linuxVM.unmanagedDataDisks().get(3).lun()) + .fromVhd(linuxVM.unmanagedDataDisks().get(3).vhdUri()) + .withDiskCaching(CachingTypes.READ_ONLY) + .attach() + .create(); System.out.println("Created custom image"); @@ -157,17 +159,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using custom image: " + virtualMachineCustomImage.id()); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.STANDARD_B2S) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.STANDARD_B2S) + .create(); System.out.println("Created Linux VM"); Utils.print(linuxVM2); @@ -176,21 +179,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create another Linux VM using custom image and configure the data disks from image and // add another data disk - VirtualMachine linuxVM3 = azureResourceManager.virtualMachines().define(linuxVMName3) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withNewDataDiskFromImage(1, 200, CachingTypes.READ_WRITE) - .withNewDataDiskFromImage(2, 100, CachingTypes.READ_ONLY) - .withNewDataDiskFromImage(3, 100, CachingTypes.READ_WRITE) - .withNewDataDisk(50) - .withSize(VirtualMachineSizeTypes.STANDARD_B2S) - .create(); + VirtualMachine linuxVM3 = azureResourceManager.virtualMachines() + .define(linuxVMName3) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withNewDataDiskFromImage(1, 200, CachingTypes.READ_WRITE) + .withNewDataDiskFromImage(2, 100, CachingTypes.READ_ONLY) + .withNewDataDiskFromImage(3, 100, CachingTypes.READ_WRITE) + .withNewDataDisk(50) + .withSize(VirtualMachineSizeTypes.STANDARD_B2S) + .create(); Utils.print(linuxVM3); @@ -255,8 +259,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -279,11 +282,12 @@ public static void main(String[] args) { protected static void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { System.out.println("Trying to de-provision"); - virtualMachine.manager().serviceClient().getVirtualMachines().beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); + virtualMachine.manager() + .serviceClient() + .getVirtualMachines() + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunShellScript") + .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); // wait as above command will not return as sync ResourceManagerUtils.sleep(Duration.ofMinutes(1)); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java index 222ca5ee16b7a..e2db335ed88b4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java @@ -54,7 +54,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST2; - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String apacheInstallCommand = "bash install_apache.sh"; List apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); @@ -66,34 +67,35 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(100) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", apacheInstallScriptUris) - .withPublicSetting("commandToExecute", apacheInstallCommand) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(100) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", apacheInstallScriptUris) + .withPublicSetting("commandToExecute", apacheInstallCommand) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created a Linux VM with un-managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -123,11 +125,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Capturing VM as custom image: " + linuxVM.id()); VirtualMachineCustomImage virtualMachineCustomImage = azureResourceManager.virtualMachineCustomImages() - .define(customImageName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .fromVirtualMachine(linuxVM) - .create(); + .define(customImageName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .fromVirtualMachine(linuxVM) + .create(); System.out.println("Captured VM: " + linuxVM.id()); @@ -138,17 +140,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using custom image - " + virtualMachineCustomImage.id()); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) + .create(); Utils.print(linuxVM2); @@ -156,22 +159,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create another Linux VM using custom image and configure the data disks from image and // add another data disk - System.out.println("Creating another Linux VM with additional data disks using custom image - " + virtualMachineCustomImage.id()); - - VirtualMachine linuxVM3 = azureResourceManager.virtualMachines().define(linuxVMName3) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withNewDataDiskFromImage(1, 200, CachingTypes.READ_WRITE) // TODO: Naming needs to be finalized - .withNewDataDiskFromImage(2, 100, CachingTypes.READ_ONLY) - .withNewDataDisk(50) - .withSize(VirtualMachineSizeTypes.STANDARD_B2S) - .create(); + System.out.println("Creating another Linux VM with additional data disks using custom image - " + + virtualMachineCustomImage.id()); + + VirtualMachine linuxVM3 = azureResourceManager.virtualMachines() + .define(linuxVMName3) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withNewDataDiskFromImage(1, 200, CachingTypes.READ_WRITE) // TODO: Naming needs to be finalized + .withNewDataDiskFromImage(2, 100, CachingTypes.READ_ONLY) + .withNewDataDisk(50) + .withSize(VirtualMachineSizeTypes.STANDARD_B2S) + .create(); Utils.print(linuxVM3); @@ -182,7 +187,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { linuxVM3.deallocate(); - //============================================================= // Get the readonly SAS URI to the OS and data disks System.out.println("Getting OS and data disks SAS Uris"); @@ -237,8 +241,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -256,11 +259,12 @@ public static void main(String[] args) { protected static void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { System.out.println("Trying to de-provision"); - virtualMachine.manager().serviceClient().getVirtualMachines().beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); + virtualMachine.manager() + .serviceClient() + .getVirtualMachines() + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunShellScript") + .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); // wait as above command will not return as sync ResourceManagerUtils.sleep(Duration.ofMinutes(1)); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java index 8533af6d46b39..a383d543c877f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java @@ -52,7 +52,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST2; - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String apacheInstallCommand = "bash install_apache.sh"; List apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); @@ -64,27 +65,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", apacheInstallScriptUris) - .withPublicSetting("commandToExecute", apacheInstallCommand) - .attach() - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", apacheInstallScriptUris) + .withPublicSetting("commandToExecute", apacheInstallCommand) + .attach() + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -109,13 +111,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create Snapshot from the OS managed disk - System.out.println(String.format("Creating managed snapshot from the managed disk (holding specialized OS): %s ", osDisk.id())); + System.out.println(String + .format("Creating managed snapshot from the managed disk (holding specialized OS): %s ", osDisk.id())); - Snapshot osSnapshot = azureResourceManager.snapshots().define(managedOSSnapshotName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromDisk(osDisk) - .create(); + Snapshot osSnapshot = azureResourceManager.snapshots() + .define(managedOSSnapshotName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromDisk(osDisk) + .create(); System.out.println("Created managed snapshot holding OS: " + osSnapshot.id()); // ResourceManagerUtils.print(osSnapshot); TODO @@ -126,14 +130,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { - System.out.println(String.format("Creating managed snapshot from the managed disk (holding data): %s ", dataDisk.id())); - - Snapshot dataSnapshot = azureResourceManager.snapshots().define(managedDataDiskSnapshotPrefix + "-" + i) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withDataFromDisk(dataDisk) - .withSku(SnapshotSkuType.STANDARD_LRS) - .create(); + System.out.println(String.format("Creating managed snapshot from the managed disk (holding data): %s ", + dataDisk.id())); + + Snapshot dataSnapshot = azureResourceManager.snapshots() + .define(managedDataDiskSnapshotPrefix + "-" + i) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withDataFromDisk(dataDisk) + .withSku(SnapshotSkuType.STANDARD_LRS) + .create(); dataSnapshots.add(dataSnapshot); System.out.println("Created managed snapshot holding data: " + dataSnapshot.id()); @@ -144,14 +150,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create Managed disk from the specialized OS snapshot - System.out.println(String.format("Creating managed disk from the snapshot holding OS: %s ", osSnapshot.id())); + System.out + .println(String.format("Creating managed disk from the snapshot holding OS: %s ", osSnapshot.id())); - Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromSnapshot(osSnapshot) - .withSizeInGB(100) - .create(); + Disk newOSDisk = azureResourceManager.disks() + .define(managedNewOSDiskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromSnapshot(osSnapshot) + .withSizeInGB(100) + .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); // ResourceManagerUtils.print(osDisk); TODO @@ -162,14 +170,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { - System.out.println(String.format("Creating managed disk from the Data snapshot: %s ", dataSnapshot.id())); - - Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .fromSnapshot(dataSnapshot) - .create(); + System.out + .println(String.format("Creating managed disk from the Data snapshot: %s ", dataSnapshot.id())); + + Disk dataDisk = azureResourceManager.disks() + .define(managedNewDataDiskNamePrefix + "-" + i) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .fromSnapshot(dataSnapshot) + .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); @@ -183,17 +193,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using specialized OS and data disks"); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) - .withExistingDataDisk(newDataDisks.get(0)) - .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) + .withExistingDataDisk(newDataDisks.get(0)) + .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); Utils.print(linuxVM2); @@ -267,8 +278,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java index cd8322707ae4d..567ad0ec9275b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java @@ -49,7 +49,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String apacheInstallCommand = "bash install_apache.sh"; List apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); @@ -59,35 +60,36 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a un-managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(50) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", apacheInstallScriptUris) - .withPublicSetting("commandToExecute", apacheInstallCommand) - .attach() - .withNewStorageAccount(storageAccountName) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(50) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", apacheInstallScriptUris) + .withPublicSetting("commandToExecute", apacheInstallCommand) + .attach() + .withNewStorageAccount(storageAccountName) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Created a Linux VM with un-managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -111,15 +113,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create Managed disk from the specialized OS VHD - System.out.println(String.format("Creating managed disk from the specialized OS VHD: %s ", specializedOSVhdUri)); + System.out + .println(String.format("Creating managed disk from the specialized OS VHD: %s ", specializedOSVhdUri)); - Disk osDisk = azureResourceManager.disks().define(managedOSDiskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromVhd(specializedOSVhdUri) - .withStorageAccountName(storageAccountName) - .withSizeInGB(100) - .create(); + Disk osDisk = azureResourceManager.disks() + .define(managedOSDiskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromVhd(specializedOSVhdUri) + .withStorageAccountName(storageAccountName) + .withSizeInGB(100) + .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); // ResourceManagerUtils.print(osDisk); TODO @@ -132,15 +136,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { for (String dataVhdUri : dataVhdUris) { System.out.println(String.format("Creating managed disk from the Data VHD: %s ", dataVhdUri)); - Disk dataDisk = azureResourceManager.disks().define(managedDataDiskNamePrefix + "-" + i) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .fromVhd(dataVhdUri) - .withStorageAccountName(storageAccountName) - .withSizeInGB(150) - .withSku(DiskSkuTypes.STANDARD_LRS) - .create(); + Disk dataDisk = azureResourceManager.disks() + .define(managedDataDiskNamePrefix + "-" + i) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .fromVhd(dataVhdUri) + .withStorageAccountName(storageAccountName) + .withSizeInGB(150) + .withSku(DiskSkuTypes.STANDARD_LRS) + .create(); dataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); @@ -153,17 +158,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using specialized OS and data disks"); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSDisk(osDisk, OperatingSystemTypes.LINUX) - .withExistingDataDisk(dataDisks.get(0)) - .withExistingDataDisk(dataDisks.get(1), 1, CachingTypes.READ_WRITE) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSDisk(osDisk, OperatingSystemTypes.LINUX) + .withExistingDataDisk(dataDisks.get(0)) + .withExistingDataDisk(dataDisks.get(1), 1, CachingTypes.READ_WRITE) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Utils.print(linuxVM2); @@ -177,10 +183,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating VM by detaching the data disks"); - linuxVM2.update() - .withoutDataDisk(0) - .withoutDataDisk(1) - .apply(); + linuxVM2.update().withoutDataDisk(0).withoutDataDisk(1).apply(); Utils.print(linuxVM2); @@ -221,8 +224,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java index 2dd2f67ffd4af..ea0005c10fa1d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java @@ -50,20 +50,13 @@ public static boolean runSample(AzureResourceManager azure) { ResourceGroup resourceGroup = null; ResourceGroup newResourceGroup = null; try { - resourceGroup = azure.resourceGroups() - .define(rgName) - .withRegion(region) - .create(); - newResourceGroup = azure.resourceGroups() - .define(newRgName) - .withRegion(newRegion) - .create(); + resourceGroup = azure.resourceGroups().define(rgName).withRegion(region).create(); + newResourceGroup = azure.resourceGroups().define(newRgName).withRegion(newRegion).create(); //============================================================= // Create a managed virtual machine with TrustedLaunch from PIR image with two empty data disks final String trustedVmName = Utils.randomResourceName(azure, "vm", 15); - VirtualMachine trustedVMFromPirImage = azure - .virtualMachines() + VirtualMachine trustedVMFromPirImage = azure.virtualMachines() .define(trustedVmName) .withRegion(resourceGroup.region()) .withExistingResourceGroup(resourceGroup) @@ -100,8 +93,7 @@ public static boolean runSample(AzureResourceManager azure) { //============================================================= // Create a gallery to hold gallery images final String galleryName = Utils.randomResourceName(azure, "jsim", 15); - Gallery gallery = azure - .galleries() + Gallery gallery = azure.galleries() .define(galleryName) .withRegion(Region.US_WEST_CENTRAL) .withExistingResourceGroup(resourceGroup) @@ -111,8 +103,7 @@ public static boolean runSample(AzureResourceManager azure) { //============================================================= // Create a gallery image in the gallery with hypervisor generation 2 and with TrustedLaunch feature final String galleryImageName = "SampleImages"; - GalleryImage galleryImage = azure - .galleryImages() + GalleryImage galleryImage = azure.galleryImages() .define(galleryImageName) .withExistingGallery(gallery) .withLocation(resourceGroup.region()) @@ -125,8 +116,7 @@ public static boolean runSample(AzureResourceManager azure) { //============================================================= // Create a gallery image version from the virtual machine custom image final String versionName = "0.0.1"; - GalleryImageVersion imageVersion = azure - .galleryImageVersions() + GalleryImageVersion imageVersion = azure.galleryImageVersions() .define(versionName) .withExistingImage(resourceGroup.name(), gallery.name(), galleryImage.name()) .withLocation(resourceGroup.region()) @@ -137,24 +127,22 @@ public static boolean runSample(AzureResourceManager azure) { //============================================================= // Create a virtual machine with TrustedLaunch from the gallery image version final String vmFromImageName = Utils.randomResourceName(azure, "tlvm", 15); - VirtualMachine trustedVMFromGalleryImage = - azure - .virtualMachines() - .define(vmFromImageName) - .withRegion(newRegion) - .withExistingResourceGroup(newResourceGroup) - .withNewPrimaryNetwork("10.0.1.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedWindowsGalleryImageVersion(imageVersion.id()) - .withAdminUsername("jvuser") - .withAdminPassword(Utils.password()) - .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) - // gallery images with 'TrustedLaunch` feature can only create VMs with 'TrustedLaunch' feature - .withTrustedLaunch() - .withSecureBoot() - .withVTpm() - .create(); + VirtualMachine trustedVMFromGalleryImage = azure.virtualMachines() + .define(vmFromImageName) + .withRegion(newRegion) + .withExistingResourceGroup(newResourceGroup) + .withNewPrimaryNetwork("10.0.1.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedWindowsGalleryImageVersion(imageVersion.id()) + .withAdminUsername("jvuser") + .withAdminPassword(Utils.password()) + .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) + // gallery images with 'TrustedLaunch` feature can only create VMs with 'TrustedLaunch' feature + .withTrustedLaunch() + .withSecureBoot() + .withVTpm() + .create(); Utils.print(trustedVMFromGalleryImage); return true; @@ -177,14 +165,10 @@ private static void prepareWindowsVMForGeneralization(VirtualMachine virtualMach virtualMachine.manager() .serviceClient() .getVirtualMachines() - .beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunPowerShellScript") - .withScript(Arrays.asList( - "Remove-Item 'C:\\Windows\\Panther' -Recurse", - "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /mode:vm /shutdown" - ))) + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunPowerShellScript") + .withScript(Arrays.asList("Remove-Item 'C:\\Windows\\Panther' -Recurse", + "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /mode:vm /shutdown"))) .waitForCompletion(); System.out.println("De-provision finished"); } @@ -203,8 +187,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java index 07b60d35ec744..514225b40c079 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java @@ -67,9 +67,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { try { // Create one resource group for everything for easier cleanup later System.out.println(String.format("Creating the resource group (`%s`)...", resourceGroupName)); - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(resourceGroupName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(resourceGroupName).withRegion(region).create(); System.out.println("Resource group created."); // ===================================================================== @@ -96,33 +95,37 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Define a network for each VM String networkName = Utils.randomResourceName(azureResourceManager, "net", 14); - Creatable networkDefinition = azureResourceManager.networks().define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0." + i + ".0/29"); // Make the address space unique + Creatable networkDefinition = azureResourceManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0." + i + ".0/29"); // Make the address space unique relatedDefinitions.add(networkDefinition); // Define a PIP for each VM String pipName = Utils.randomResourceName(azureResourceManager, "pip", 14); - Creatable pipDefinition = azureResourceManager.publicIpAddresses().define(pipName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable pipDefinition = azureResourceManager.publicIpAddresses() + .define(pipName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); relatedDefinitions.add(pipDefinition); // Define a NIC for each VM String nicName = Utils.randomResourceName(azureResourceManager, "nic", 14); - Creatable nicDefinition = azureResourceManager.networkInterfaces().define(nicName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipDefinition); + Creatable nicDefinition = azureResourceManager.networkInterfaces() + .define(nicName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipDefinition); // Define an availability set for each VM String availabilitySetName = Utils.randomResourceName(azureResourceManager, "as", 14); - Creatable availabilitySetDefinition = azureResourceManager.availabilitySets().define(availabilitySetName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable availabilitySetDefinition = azureResourceManager.availabilitySets() + .define(availabilitySetName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); relatedDefinitions.add(availabilitySetDefinition); String vmName = Utils.randomResourceName(azureResourceManager, "vm", 14); @@ -136,15 +139,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { userName = "tester"; } - Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetworkInterface(nicDefinition) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withRootPassword(Utils.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availabilitySetDefinition); + Creatable vmDefinition = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetworkInterface(nicDefinition) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withRootPassword(Utils.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availabilitySetDefinition); // Keep track of all the related resource definitions based on the VM definition vmNonNicResourceDefinitions.put(vmDefinition.key(), relatedDefinitions); @@ -156,8 +160,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Start the parallel creation of everything asynchronously // System.out.println("Creating the virtual machines and related required resources in parallel..."); - azureResourceManager - .virtualMachines() + azureResourceManager.virtualMachines() .createAsync(new ArrayList<>(vmDefinitions.values())) .map(virtualMachine -> { @@ -186,8 +189,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creation completed."); // Show any errors - for (Throwable error: errors) { - System.out.println("ERROR: Creation of virtual machines has been stopped due to a failure to create a resource.\n"); + for (Throwable error : errors) { + System.out.println( + "ERROR: Creation of virtual machines has been stopped due to a failure to create a resource.\n"); if (error instanceof ManagementException) { ManagementException ce = (ManagementException) error; System.out.println("Cloud Exception: " + ce.getMessage()); @@ -220,7 +224,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { String createdResourceId = createdResourceIds.get(resource.key()); if (createdResourceId != null) { // Prepare the deletion of each related resource (treating it as a generic resource) as a multi-threaded Observable - deleteObservables.add(azureResourceManager.genericResources().deleteByIdAsync(createdResourceId)); + deleteObservables + .add(azureResourceManager.genericResources().deleteByIdAsync(createdResourceId)); } } } @@ -231,20 +236,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Number of failed/cleaned up VM creations: " + vmNonNicResourceDefinitions.size()); // Verifications - final int actualVMCount = Utils.getSize(azureResourceManager.virtualMachines().listByResourceGroup(resourceGroupName)); + final int actualVMCount + = Utils.getSize(azureResourceManager.virtualMachines().listByResourceGroup(resourceGroupName)); System.out.println("Number of successful VMs: " + actualVMCount); - final int actualNicCount = Utils.getSize(azureResourceManager.networkInterfaces().listByResourceGroup(resourceGroupName)); - System.out.println(String.format("Remaining network interfaces (should be %d): %d", actualVMCount, actualNicCount)); + final int actualNicCount + = Utils.getSize(azureResourceManager.networkInterfaces().listByResourceGroup(resourceGroupName)); + System.out.println( + String.format("Remaining network interfaces (should be %d): %d", actualVMCount, actualNicCount)); - final int actualNetworkCount = Utils.getSize(azureResourceManager.networks().listByResourceGroup(resourceGroupName)); - System.out.println(String.format("Remaining virtual networks (should be %d): %d", actualVMCount, actualNetworkCount)); + final int actualNetworkCount + = Utils.getSize(azureResourceManager.networks().listByResourceGroup(resourceGroupName)); + System.out.println( + String.format("Remaining virtual networks (should be %d): %d", actualVMCount, actualNetworkCount)); - final int actualPipCount = Utils.getSize(azureResourceManager.publicIpAddresses().listByResourceGroup(resourceGroupName)); - System.out.println(String.format("Remaining public IP addresses (should be %d): %d", actualVMCount, actualPipCount)); + final int actualPipCount + = Utils.getSize(azureResourceManager.publicIpAddresses().listByResourceGroup(resourceGroupName)); + System.out.println( + String.format("Remaining public IP addresses (should be %d): %d", actualVMCount, actualPipCount)); - final int actualAvailabilitySetCount = Utils.getSize(azureResourceManager.availabilitySets().listByResourceGroup(resourceGroupName)); - System.out.println(String.format("Remaining availability sets (should be %d): %d", actualVMCount, actualAvailabilitySetCount)); + final int actualAvailabilitySetCount + = Utils.getSize(azureResourceManager.availabilitySets().listByResourceGroup(resourceGroupName)); + System.out.println(String.format("Remaining availability sets (should be %d): %d", actualVMCount, + actualAvailabilitySetCount)); return true; } finally { @@ -274,8 +288,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java index 0c48ca0a4d8da..5c923cd2606af 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java @@ -69,13 +69,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create a resource group (Where all resources gets created) // - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); System.out.println("Created a new resource group - " + resourceGroup.id()); -// List publicIpCreatableKeys = new ArrayList<>(); + // List publicIpCreatableKeys = new ArrayList<>(); // Prepare a batch of Creatable definitions // List> creatableVirtualMachines = new ArrayList<>(); @@ -89,18 +88,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Prepare Creatable Network definition (Where all the virtual machines get added to) // String networkName = Utils.randomResourceName(azureResourceManager, "vnetCOPD-", 20); - Creatable networkCreatable = azureResourceManager.networks().define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("172.16.0.0/16"); + Creatable networkCreatable = azureResourceManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("172.16.0.0/16"); //============================================================= // Create 1 storage creatable per region (For storing VMs disk) // String storageAccountName = Utils.randomResourceName(azureResourceManager, "stgcopd", 20); - Creatable storageAccountCreatable = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable storageAccountCreatable = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); String linuxVMNamePrefix = Utils.randomResourceName(azureResourceManager, "vm-", 15); for (int i = 1; i <= vmCount; i++) { @@ -109,32 +110,31 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create 1 public IP address creatable // Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses() - .define(String.format("%s-%d", linuxVMNamePrefix, i)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(Utils.randomResourceName(azureResourceManager, "pip", 10)); + .define(String.format("%s-%d", linuxVMNamePrefix, i)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(Utils.randomResourceName(azureResourceManager, "pip", 10)); -// publicIpCreatableKeys.add(publicIPAddressCreatable.key()); + // publicIpCreatableKeys.add(publicIPAddressCreatable.key()); //============================================================= // Create 1 virtual machine creatable Creatable virtualMachineCreatable = azureResourceManager.virtualMachines() - .define(String.format("%s-%d", linuxVMNamePrefix, i)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(storageAccountCreatable); + .define(String.format("%s-%d", linuxVMNamePrefix, i)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(storageAccountCreatable); creatableVirtualMachines.add(virtualMachineCreatable); } } - //============================================================= // Create !! @@ -142,7 +142,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating the virtual machines"); stopwatch.start(); - CreatedResources virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines); + CreatedResources virtualMachines + = azureResourceManager.virtualMachines().create(creatableVirtualMachines); stopwatch.stop(); System.out.println("Created virtual machines"); @@ -151,49 +152,50 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println(virtualMachine.id()); } - System.out.println("Virtual Machines created: (took " + (stopwatch.getTime() / 1000) + " seconds to create) == " + virtualMachines.size() + " == virtual machines"); - -// List publicIpResourceIds = new ArrayList<>(); -// for (String publicIpCreatableKey : publicIpCreatableKeys) { -// PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKey); -// publicIpResourceIds.add(pip.id()); -// } -// -// //============================================================= -// // Create 1 Traffic Manager Profile -// // -// String trafficManagerName = azure.internalContext().randomResourceName("tra", 15); -// TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName) -// .withExistingResourceGroup(resourceGroup) -// .withLeafDomainLabel(trafficManagerName) -// .withPerformanceBasedRouting(); -// -// int endpointPriority = 1; -// TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null; -// for (String publicIpResourceId : publicIpResourceIds) { -// String endpointName = String.format("azendpoint-%d", endpointPriority); -// if (endpointPriority == 1) { -// profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName) -// .toResourceId(publicIpResourceId) -// .withRoutingPriority(endpointPriority) -// .attach(); -// } else { -// profileWithCreate = profileWithCreate.defineAzureTargetEndpoint(endpointName) -// .toResourceId(publicIpResourceId) -// .withRoutingPriority(endpointPriority) -// .attach(); -// } -// endpointPriority++; -// } -// -// System.out.println("Creating a traffic manager profile for the VMs"); -// stopwatch.reset(); -// stopwatch.start(); -// -// TrafficManagerProfile trafficManagerProfile = profileWithCreate.create(); -// -// stopwatch.stop(); -// System.out.println("Created a traffic manager profile (took " + (stopwatch.getTime() / 1000) + " seconds to create): " + trafficManagerProfile.id()); + System.out.println("Virtual Machines created: (took " + (stopwatch.getTime() / 1000) + + " seconds to create) == " + virtualMachines.size() + " == virtual machines"); + + // List publicIpResourceIds = new ArrayList<>(); + // for (String publicIpCreatableKey : publicIpCreatableKeys) { + // PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKey); + // publicIpResourceIds.add(pip.id()); + // } + // + // //============================================================= + // // Create 1 Traffic Manager Profile + // // + // String trafficManagerName = azure.internalContext().randomResourceName("tra", 15); + // TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName) + // .withExistingResourceGroup(resourceGroup) + // .withLeafDomainLabel(trafficManagerName) + // .withPerformanceBasedRouting(); + // + // int endpointPriority = 1; + // TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null; + // for (String publicIpResourceId : publicIpResourceIds) { + // String endpointName = String.format("azendpoint-%d", endpointPriority); + // if (endpointPriority == 1) { + // profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName) + // .toResourceId(publicIpResourceId) + // .withRoutingPriority(endpointPriority) + // .attach(); + // } else { + // profileWithCreate = profileWithCreate.defineAzureTargetEndpoint(endpointName) + // .toResourceId(publicIpResourceId) + // .withRoutingPriority(endpointPriority) + // .attach(); + // } + // endpointPriority++; + // } + // + // System.out.println("Creating a traffic manager profile for the VMs"); + // stopwatch.reset(); + // stopwatch.start(); + // + // TrafficManagerProfile trafficManagerProfile = profileWithCreate.create(); + // + // stopwatch.stop(); + // System.out.println("Created a traffic manager profile (took " + (stopwatch.getTime() / 1000) + " seconds to create): " + trafficManagerProfile.id()); return true; } finally { @@ -209,6 +211,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } + /** * Main entry point. * @param args the parameters @@ -224,8 +227,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java index 950bfd74a2200..4b2441c682d5c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java @@ -53,7 +53,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String apacheInstallCommand = "bash install_apache.sh"; List apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); @@ -64,26 +65,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(Region.US_WEST2) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", apacheInstallScriptUris) - .withPublicSetting("commandToExecute", apacheInstallCommand) - .attach() - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(Region.US_WEST2) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", apacheInstallScriptUris) + .withPublicSetting("commandToExecute", apacheInstallCommand) + .attach() + .create(); System.out.println("Created a Linux VM: " + linuxVM.id()); Utils.print(linuxVM); @@ -121,17 +123,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM using captured image - " + capturedImageUri); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) - .withRegion(Region.US_WEST2) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withStoredLinuxImage(capturedImageUri) // Note: A Generalized Image can also be an uploaded VHD prepared from an on-premise generalized VM. - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVMName2) + .withRegion(Region.US_WEST2) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withStoredLinuxImage(capturedImageUri) // Note: A Generalized Image can also be an uploaded VHD prepared from an on-premise generalized VM. + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); Utils.print(linuxVM2); @@ -148,19 +151,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create a Linux VM using 'specialized VHD' of previous VM - System.out.println("Creating a new Linux VM by attaching OS Disk vhd - " - + specializedVhd - + " of deleted VM"); + System.out + .println("Creating a new Linux VM by attaching OS Disk vhd - " + specializedVhd + " of deleted VM"); - VirtualMachine linuxVM3 = azureResourceManager.virtualMachines().define(linuxVMName3) - .withRegion(Region.US_WEST2) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.LINUX) // New user credentials cannot be specified - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) // when attaching a specialized VHD - .create(); + VirtualMachine linuxVM3 = azureResourceManager.virtualMachines() + .define(linuxVMName3) + .withRegion(Region.US_WEST2) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.LINUX) // New user credentials cannot be specified + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) // when attaching a specialized VHD + .create(); Utils.print(linuxVM3); return true; @@ -178,6 +181,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } + /** * Main entry point. * @param args the parameters @@ -192,8 +196,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -222,7 +225,8 @@ private static String extractCapturedImageUri(String capturedResultJson) { JsonNode resourcesNode = rootNode.path("resources"); if (resourcesNode instanceof MissingNode) { - throw new IllegalArgumentException("Expected 'resources' node not found in the capture result -" + capturedResultJson); + throw new IllegalArgumentException( + "Expected 'resources' node not found in the capture result -" + capturedResultJson); } String imageUri = null; @@ -246,7 +250,8 @@ private static String extractCapturedImageUri(String capturedResultJson) { } if (imageUri == null) { - throw new IllegalArgumentException("Could not locate image uri under expected section in the capture result -" + capturedResultJson); + throw new IllegalArgumentException( + "Could not locate image uri under expected section in the capture result -" + capturedResultJson); } return imageUri; } @@ -254,11 +259,12 @@ private static String extractCapturedImageUri(String capturedResultJson) { protected static void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { System.out.println("Trying to de-provision"); - virtualMachine.manager().serviceClient().getVirtualMachines().beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); + virtualMachine.manager() + .serviceClient() + .getVirtualMachines() + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunShellScript") + .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); // wait as above command will not return as sync ResourceManagerUtils.sleep(Duration.ofMinutes(1)); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java index 65782d58f9363..4e4b453f8ce1e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java @@ -55,22 +55,25 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } else if (sku.resourceType().equals(ComputeResourceType.SNAPSHOTS)) { size = sku.diskSkuType().toString(); } - System.out.println(String.format(format, sku.name(), sku.resourceType(), size, regionZoneToString(sku.zones()))); + System.out + .println(String.format(format, sku.name(), sku.resourceType(), size, regionZoneToString(sku.zones()))); } //================================================================= // List compute SKUs for a specific compute resource type (VirtualMachines) in a region // - System.out.println("Listing compute SKUs for a specific compute resource type (VirtualMachines) in a region (US East2)"); + System.out.println( + "Listing compute SKUs for a specific compute resource type (VirtualMachines) in a region (US East2)"); format = "%-22s %-22s %s"; System.out.println(String.format(format, "Name", "Size", "Regions [zones]")); System.out.println("============================================================================"); skus = azureResourceManager.computeSkus() - .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.VIRTUALMACHINES); + .listByRegionAndResourceType(Region.US_EAST2, ComputeResourceType.VIRTUALMACHINES); for (ComputeSku sku : skus) { - final String line = String.format(format, sku.name(), sku.virtualMachineSizeType(), regionZoneToString(sku.zones())); + final String line + = String.format(format, sku.name(), sku.virtualMachineSizeType(), regionZoneToString(sku.zones())); System.out.println(line); } @@ -83,8 +86,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println(String.format(format, "Name", "Size", "Regions [zones]")); System.out.println("============================================================================"); - skus = azureResourceManager.computeSkus() - .listByResourceType(ComputeResourceType.DISKS); + skus = azureResourceManager.computeSkus().listByResourceType(ComputeResourceType.DISKS); for (ComputeSku sku : skus) { final String line = String.format(format, sku.name(), sku.diskSkuType(), regionZoneToString(sku.zones())); System.out.println(line); @@ -98,7 +100,7 @@ private static String regionZoneToString(Map> re for (Map.Entry> regionZones : regionZonesMap.entrySet()) { builder.append(regionZones.getKey().toString()); builder.append(" [ "); - for (AvailabilityZoneId zone :regionZones.getValue()) { + for (AvailabilityZoneId zone : regionZones.getValue()) { builder.append(zone).append(" "); } builder.append("] "); @@ -121,8 +123,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java index 60924f047dc27..c5ad7ea5a7473 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java @@ -37,16 +37,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions // by browsing through extension image publishers, types, and versions - PagedIterable publishers = azureResourceManager - .virtualMachineImages() - .publishers() - .listByRegion(region); + PagedIterable publishers + = azureResourceManager.virtualMachineImages().publishers().listByRegion(region); VirtualMachinePublisher chosenPublisher; - System.out.println("US East data center: printing list of \n" - + "a) Publishers and\n" - + "b) virtual machine extension images published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions"); + System.out.println("US East data center: printing list of \n" + "a) Publishers and\n" + + "b) virtual machine extension images published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions"); System.out.println("======================================================="); System.out.println("\n"); @@ -55,7 +52,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Publisher - " + publisher.name()); if (publisher.name().equalsIgnoreCase("Microsoft.OSTCExtensions") - || publisher.name().equalsIgnoreCase("Microsoft.Azure.Extensions")) { + || publisher.name().equalsIgnoreCase("Microsoft.Azure.Extensions")) { chosenPublisher = publisher; System.out.print("\n\n"); @@ -65,11 +62,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Printing entries as publisher/type/version"); for (VirtualMachineExtensionImageType imageType : chosenPublisher.extensionTypes().list()) { - for (VirtualMachineExtensionImageVersion version: imageType.versions().list()) { + for (VirtualMachineExtensionImageVersion version : imageType.versions().list()) { VirtualMachineExtensionImage image = version.getImage(); - System.out.println("Image - " + chosenPublisher.name() + "/" - + image.typeName() + "/" - + image.versionName()); + System.out.println( + "Image - " + chosenPublisher.name() + "/" + image.typeName() + "/" + image.versionName()); } } @@ -95,8 +91,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java index d9f3daa0f5106..bef83ade4274c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java @@ -37,16 +37,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // published by Canonical, Red Hat and SUSE // by browsing through locations, publishers, offers, SKUs and images - PagedIterable publishers = azureResourceManager - .virtualMachineImages() - .publishers() - .listByRegion(region); + PagedIterable publishers + = azureResourceManager.virtualMachineImages().publishers().listByRegion(region); VirtualMachinePublisher chosenPublisher; - System.out.println("US East data center: printing list of \n" - + "a) Publishers and\n" - + "b) Images published by Canonical, Red Hat and Suse"); + System.out.println("US East data center: printing list of \n" + "a) Publishers and\n" + + "b) Images published by Canonical, Red Hat and Suse"); System.out.println("======================================================="); System.out.println("\n"); @@ -55,8 +52,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Publisher - " + publisher.name()); if (publisher.name().equalsIgnoreCase("Canonical") - || publisher.name().equalsIgnoreCase("Suse") - || publisher.name().equalsIgnoreCase("RedHat")) { + || publisher.name().equalsIgnoreCase("Suse") + || publisher.name().equalsIgnoreCase("RedHat")) { chosenPublisher = publisher; System.out.print("\n\n"); @@ -66,11 +63,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Printing entries as publisher/offer/sku/image.version()"); for (VirtualMachineOffer offer : chosenPublisher.offers().list()) { - for (VirtualMachineSku sku: offer.skus().list()) { + for (VirtualMachineSku sku : offer.skus().list()) { for (VirtualMachineImage image : sku.images().list()) { - System.out.println("Image - " + chosenPublisher.name() + "/" - + offer.name() + "/" - + sku.name() + "/" + image.version()); + System.out.println("Image - " + chosenPublisher.name() + "/" + offer.name() + "/" + + sku.name() + "/" + image.version()); } } @@ -98,8 +94,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java index cbdd1be68b752..04798ed228b7a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java @@ -58,15 +58,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating an availability set"); - AvailabilitySet availSet1 = azureResourceManager.availabilitySets().define(availSetName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withFaultDomainCount(2) - .withUpdateDomainCount(4) - .withSku(AvailabilitySetSkuTypes.ALIGNED) - .withTag("cluster", "Windowslinux") - .withTag("tag1", "tag1val") - .create(); + AvailabilitySet availSet1 = azureResourceManager.availabilitySets() + .define(availSetName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withFaultDomainCount(2) + .withUpdateDomainCount(4) + .withSku(AvailabilitySetSkuTypes.ALIGNED) + .withTag("cluster", "Windowslinux") + .withTag("tag1", "tag1val") + .create(); System.out.println("Created first availability set: " + availSet1.id()); Utils.print(availSet1); @@ -74,83 +75,78 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Define a virtual network for the VMs in this availability set - Creatable networkDefinition = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28"); - + Creatable networkDefinition = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28"); //============================================================= // Create a Windows VM in the new availability set System.out.println("Creating a Windows VM in the availability set"); - VirtualMachine vm1 = azureResourceManager.virtualMachines().define(vm1Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withExistingAvailabilitySet(availSet1) - .create(); - + VirtualMachine vm1 = azureResourceManager.virtualMachines() + .define(vm1Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withExistingAvailabilitySet(availSet1) + .create(); System.out.println("Created first VM:" + vm1.id()); Utils.print(vm1); - //============================================================= // Create a Linux VM in the same availability set System.out.println("Creating a Linux VM in the availability set"); - VirtualMachine vm2 = azureResourceManager.virtualMachines().define(vm2Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withExistingAvailabilitySet(availSet1) - .create(); + VirtualMachine vm2 = azureResourceManager.virtualMachines() + .define(vm2Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withExistingAvailabilitySet(availSet1) + .create(); System.out.println("Created second VM: " + vm2.id()); Utils.print(vm2); - //============================================================= // Update - Tag the availability set - availSet1 = availSet1.update() - .withTag("server1", "nginx") - .withTag("server2", "iis") - .withoutTag("tag1") - .apply(); + availSet1 + = availSet1.update().withTag("server1", "nginx").withTag("server2", "iis").withoutTag("tag1").apply(); System.out.println("Tagged availability set: " + availSet1.id()); - //============================================================= // Create another availability set System.out.println("Creating an availability set"); - AvailabilitySet availSet2 = azureResourceManager.availabilitySets().define(availSetName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .create(); + AvailabilitySet availSet2 = azureResourceManager.availabilitySets() + .define(availSetName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Created second availability set: " + availSet2.id()); Utils.print(availSet2); - //============================================================= // List availability sets @@ -158,11 +154,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Printing list of availability sets ======="); - for (AvailabilitySet availabilitySet : azureResourceManager.availabilitySets().listByResourceGroup(resourceGroupName)) { + for (AvailabilitySet availabilitySet : azureResourceManager.availabilitySets() + .listByResourceGroup(resourceGroupName)) { Utils.print(availabilitySet); } - //============================================================= // Delete an availability set @@ -201,8 +197,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java index 48d0209b03a62..087b848615a3d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java @@ -68,17 +68,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withRegion(region) .withNewResourceGroup(rgName) .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowKeyPermissions(KeyPermissions.CREATE) - .attach() + .forServicePrincipal(clientId) + .allowKeyPermissions(KeyPermissions.CREATE) + .attach() .withPurgeProtectionEnabled() .create(); - Key k1 = kv1.keys() - .define(k1Name) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key k1 = kv1.keys().define(k1Name).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); //============================================================= // Create a disk encryption set, des1, with key vault kv1, key k1 and encryption type @@ -100,9 +96,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin kv1.update() .defineAccessPolicy() - .forObjectId(des1.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(des1.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .apply(); //============================================================= @@ -116,7 +112,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withPurgeProtectionEnabled() .create(); - azureResourceManager.accessManagement().roleAssignments().define(rbacName) + azureResourceManager.accessManagement() + .roleAssignments() + .define(rbacName) .forServicePrincipal(clientId) .withBuiltInRole(BuiltInRole.KEY_VAULT_ADMINISTRATOR) .withResourceScope(kv2) @@ -124,11 +122,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // wait for propagation time ResourceManagerUtils.sleep(Duration.ofMinutes(1)); - Key k2 = kv2.keys() - .define(k2Name) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key k2 = kv2.keys().define(k2Name).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); //============================================================= // Create a new disk encryption set des2 with key vault kv2, key k2, encryption type @@ -194,8 +188,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java index 0de1cbb0a45c3..7cdd51abb7c06 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java @@ -61,20 +61,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVM1Name = Utils.randomResourceName(azureResourceManager, "vm" + "-", 18); final String linuxVM1Pip = Utils.randomResourceName(azureResourceManager, "pip" + "-", 18); VirtualMachine linuxVM1 = azureResourceManager.virtualMachines() - .define(linuxVM1Name) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(linuxVM1Pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withNewDataDisk(50) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); - - System.out.println("Created VM [with an implicit Managed OS disk and explicit Managed data disk]: " + linuxVM1.id()); + .define(linuxVM1Name) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(linuxVM1Pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withNewDataDisk(50) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); + + System.out.println( + "Created VM [with an implicit Managed OS disk and explicit Managed data disk]: " + linuxVM1.id()); // Creation is simplified with implicit creation of managed disks without specifying all the disk details. You will notice that you do not require storage accounts // ::== Update the VM @@ -84,21 +85,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String vmScaleSetName = Utils.randomResourceName(azureResourceManager, "vmss" + "-", 18); VirtualMachineScaleSet vmScaleSet = azureResourceManager.virtualMachineScaleSets() - .define(vmScaleSetName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D5_V2) - .withExistingPrimaryNetworkSubnet(prepareNetwork(azureResourceManager, region, rgName), "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(prepareLoadBalancer(azureResourceManager, region, rgName)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tirekicker") - .withSsh(sshPublicKey) - .withNewDataDisk(50) - .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) - .withNewDataDisk(50, 2, CachingTypes.READ_ONLY) - .withCapacity(3) - .create(); + .define(vmScaleSetName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D5_V2) + .withExistingPrimaryNetworkSubnet(prepareNetwork(azureResourceManager, region, rgName), "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer( + prepareLoadBalancer(azureResourceManager, region, rgName)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tirekicker") + .withSsh(sshPublicKey) + .withNewDataDisk(50) + .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) + .withNewDataDisk(50, 2, CachingTypes.READ_ONLY) + .withCapacity(3) + .create(); System.out.println("Created VMSS [with implicit managed OS disks and explicit managed data disks]"); System.out.println("Created VMSS [with implicit managed OS disks and explicit managed data disks]"); @@ -110,12 +112,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating empty data disk [to attach to a VM]"); final String diskName = Utils.randomResourceName(azureResourceManager, "dsk" + "-", 18); - Disk dataDisk = azureResourceManager.disks().define(diskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(50) - .create(); + Disk dataDisk = azureResourceManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(50) + .create(); System.out.println("Created empty data disk [to attach to a VM]"); @@ -123,22 +126,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVM2Name = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); final String linuxVM2Pip = Utils.randomResourceName(azureResourceManager, "pip" + "-", 18); - VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVM2Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(linuxVM2Pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - // Begin: Managed data disks - .withNewDataDisk(50) - .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) - .withExistingDataDisk(dataDisk) - // End: Managed data disks - .withSize(VirtualMachineSizeTypes.STANDARD_B2S) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVM2Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(linuxVM2Pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + // Begin: Managed data disks + .withNewDataDisk(50) + .withNewDataDisk(50, 1, CachingTypes.READ_WRITE) + .withExistingDataDisk(dataDisk) + // End: Managed data disks + .withSize(VirtualMachineSizeTypes.STANDARD_B2S) + .create(); System.out.println("Created VM [with new managed data disks and disk attached]"); @@ -146,10 +150,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating VM [by detaching a disk and adding empty disk]"); - linuxVM2.update() - .withoutDataDisk(2) - .withNewDataDisk(200) - .apply(); + linuxVM2.update().withoutDataDisk(2).withNewDataDisk(200).apply(); System.out.println("Updated VM [by detaching a disk and adding empty disk]"); @@ -157,7 +158,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Preparing specialized virtual machine with un-managed disk"); - final VirtualMachine linuxVM = prepareSpecializedUnmanagedVirtualMachine(azureResourceManager, region, rgName); + final VirtualMachine linuxVM + = prepareSpecializedUnmanagedVirtualMachine(azureResourceManager, region, rgName); System.out.println("Prepared specialized virtual machine with un-managed disk"); @@ -165,28 +167,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String customImageName = Utils.randomResourceName(azureResourceManager, "cimg" + "-", 10); VirtualMachineCustomImage virtualMachineCustomImage = azureResourceManager.virtualMachineCustomImages() - .define(customImageName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .fromVirtualMachine(linuxVM) // from a deallocated and generalized VM - .create(); + .define(customImageName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .fromVirtualMachine(linuxVM) // from a deallocated and generalized VM + .create(); System.out.println("Created custom image from specialized virtual machine"); System.out.println("Creating VM [from custom image]"); final String linuxVM3Name = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); - VirtualMachine linuxVM3 = azureResourceManager.virtualMachines().define(linuxVM3Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM3 = azureResourceManager.virtualMachines() + .define(linuxVM3Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withGeneralizedLinuxCustomImage(virtualMachineCustomImage.id()) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created VM [from custom image]: " + linuxVM3.id()); @@ -199,15 +202,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating VM [by attaching un-managed disk]"); - VirtualMachine linuxVM4 = azureResourceManager.virtualMachines().define(linuxVMName4) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.LINUX) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM4 = azureResourceManager.virtualMachines() + .define(linuxVMName4) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.LINUX) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created VM [by attaching un-managed disk]: " + linuxVM4.id()); @@ -215,7 +219,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Preparing specialized virtual machine with managed disks"); - final VirtualMachine linuxVM5 = prepareSpecializedManagedVirtualMachine(azureResourceManager, region, rgName); + final VirtualMachine linuxVM5 + = prepareSpecializedManagedVirtualMachine(azureResourceManager, region, rgName); Disk osDisk = azureResourceManager.disks().getById(linuxVM5.osDiskId()); List dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM5.dataDisks().values()) { @@ -233,11 +238,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a managed snapshot for an OS disk final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "snp" + "-", 10); - Snapshot osSnapshot = azureResourceManager.snapshots().define(managedOSSnapshotName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromDisk(osDisk) - .create(); + Snapshot osSnapshot = azureResourceManager.snapshots() + .define(managedOSSnapshotName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromDisk(osDisk) + .create(); System.out.println("Created snapshot [from managed OS disk]"); @@ -245,12 +251,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a managed disk from the managed snapshot for the OS disk final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "dsk" + "-", 10); - Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLinuxFromSnapshot(osSnapshot) - .withSizeInGB(50) - .create(); + Disk newOSDisk = azureResourceManager.disks() + .define(managedNewOSDiskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLinuxFromSnapshot(osSnapshot) + .withSizeInGB(50) + .create(); System.out.println("Created managed OS disk [from snapshot]"); @@ -258,12 +265,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a managed snapshot for a data disk final String managedDataDiskSnapshotName = Utils.randomResourceName(azureResourceManager, "dsk" + "-", 10); - Snapshot dataSnapshot = azureResourceManager.snapshots().define(managedDataDiskSnapshotName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withDataFromDisk(dataDisks.get(0)) - .withSku(SnapshotSkuType.STANDARD_LRS) - .create(); + Snapshot dataSnapshot = azureResourceManager.snapshots() + .define(managedDataDiskSnapshotName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withDataFromDisk(dataDisks.get(0)) + .withSku(SnapshotSkuType.STANDARD_LRS) + .create(); System.out.println("Created managed data snapshot [from managed data disk]"); @@ -271,28 +279,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a managed disk from the managed snapshot for the data disk final String managedNewDataDiskName = Utils.randomResourceName(azureResourceManager, "dsk" + "-", 10); - Disk newDataDisk = azureResourceManager.disks().define(managedNewDataDiskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .fromSnapshot(dataSnapshot) - .create(); + Disk newDataDisk = azureResourceManager.disks() + .define(managedNewDataDiskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .fromSnapshot(dataSnapshot) + .create(); System.out.println("Created managed data disk [from managed snapshot]"); System.out.println("Creating VM [with specialized OS managed disk]"); final String linuxVM6Name = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); - VirtualMachine linuxVM6 = azureResourceManager.virtualMachines().define(linuxVM6Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) - .withExistingDataDisk(newDataDisk) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM6 = azureResourceManager.virtualMachines() + .define(linuxVM6Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) + .withExistingDataDisk(newDataDisk) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created VM [with specialized OS managed disk]: " + linuxVM6.id()); @@ -302,19 +312,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVM7Name = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); final String linuxVM7Pip = Utils.randomResourceName(azureResourceManager, "pip" + "-", 18); - VirtualMachine linuxVM7 = azureResourceManager.virtualMachines().define(linuxVM7Name) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(linuxVM7Pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tirekicker") - .withSsh(sshPublicKey) - .withUnmanagedDisks() // uses storage accounts - .withNewUnmanagedDataDisk(50) - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM7 = azureResourceManager.virtualMachines() + .define(linuxVM7Name) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(linuxVM7Pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tirekicker") + .withSsh(sshPublicKey) + .withUnmanagedDisks() // uses storage accounts + .withNewUnmanagedDataDisk(50) + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created VM [with un-managed disk for migration]"); @@ -360,8 +371,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -376,32 +386,34 @@ public static void main(String[] args) { } } - private static VirtualMachine prepareSpecializedUnmanagedVirtualMachine(AzureResourceManager azureResourceManager, Region region, String rgName) { + private static VirtualMachine prepareSpecializedUnmanagedVirtualMachine(AzureResourceManager azureResourceManager, + Region region, String rgName) { final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip" + "-", 20); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIpDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .defineUnmanagedDataDisk("disk-1") - .withNewVhd(100) - .withLun(1) - .attach() - .defineUnmanagedDataDisk("disk-2") - .withNewVhd(50) - .withLun(2) - .attach() - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIpDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .defineUnmanagedDataDisk("disk-1") + .withNewVhd(100) + .withLun(1) + .attach() + .defineUnmanagedDataDisk("disk-2") + .withNewVhd(50) + .withLun(2) + .attach() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); // De-provision the virtual machine deprovisionAgentInLinuxVM(linuxVM); @@ -414,25 +426,27 @@ private static VirtualMachine prepareSpecializedUnmanagedVirtualMachine(AzureRes return linuxVM; } - private static VirtualMachine prepareSpecializedManagedVirtualMachine(AzureResourceManager azureResourceManager, Region region, String rgName) { + private static VirtualMachine prepareSpecializedManagedVirtualMachine(AzureResourceManager azureResourceManager, + Region region, String rgName) { final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "vm" + "-", 10); final String publicIPDnsLabel = Utils.randomResourceName(azureResourceManager, "pip" + "-", 20); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withNewDataDisk(100) - .withNewDataDisk(200) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withNewDataDisk(100) + .withNewDataDisk(200) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); // De-provision the virtual machine deprovisionAgentInLinuxVM(linuxVM); @@ -453,11 +467,12 @@ private static VirtualMachine prepareSpecializedManagedVirtualMachine(AzureResou protected static void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { System.out.println("Trying to de-provision"); - virtualMachine.manager().serviceClient().getVirtualMachines().beginRunCommand( - virtualMachine.resourceGroupName(), virtualMachine.name(), - new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); + virtualMachine.manager() + .serviceClient() + .getVirtualMachines() + .beginRunCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), + new RunCommandInput().withCommandId("RunShellScript") + .withScript(Collections.singletonList("sudo waagent -deprovision+user --force"))); // wait as above command will not return as sync ResourceManagerUtils.sleep(Duration.ofMinutes(1)); @@ -466,18 +481,20 @@ protected static void deprovisionAgentInLinuxVM(VirtualMachine virtualMachine) { private static Network prepareNetwork(AzureResourceManager azureResourceManager, Region region, String rgName) { final String vnetName = Utils.randomResourceName(azureResourceManager, "vnet", 24); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("subnet1") - .withAddressPrefix("172.16.1.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("subnet1") + .withAddressPrefix("172.16.1.0/24") + .attach() + .create(); return network; } - private static LoadBalancer prepareLoadBalancer(AzureResourceManager azureResourceManager, Region region, String rgName) { + private static LoadBalancer prepareLoadBalancer(AzureResourceManager azureResourceManager, Region region, + String rgName) { final String loadBalancerName1 = Utils.randomResourceName(azureResourceManager, "intlb" + "-", 18); final String frontendName = loadBalancerName1 + "-FE1"; final String backendPoolName1 = loadBalancerName1 + "-BAP1"; @@ -490,58 +507,60 @@ private static LoadBalancer prepareLoadBalancer(AzureResourceManager azureResour final String natPool60XXto23 = "natPool60XXto23"; final String publicIpName = "pip-" + loadBalancerName1; - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(publicIpName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName) - .create(); - LoadBalancer loadBalancer = azureResourceManager.loadBalancers().define(loadBalancerName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - // Add nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatPool(natPool50XXto22) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPool60XXto23) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - // Explicitly define a frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) - .attach() - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(publicIpName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName) + .create(); + LoadBalancer loadBalancer = azureResourceManager.loadBalancers() + .define(loadBalancerName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + // Add nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatPool(natPool50XXto22) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPool60XXto23) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + // Explicitly define a frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) + .attach() + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) + .attach() + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + + .create(); return loadBalancer; } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java index eb9b67fdf44be..9f097e6922a54 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java @@ -53,7 +53,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_EAST; - final String installScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/create_resources_with_msi.sh"; + final String installScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/create_resources_with_msi.sh"; String installCommand = "bash create_resources_with_msi.sh {stgName} {rgName} {location}"; List fileUris = new ArrayList<>(); fileUris.add(installScript); @@ -68,30 +69,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a AAD security group"); activeDirectoryGroup = azureResourceManager.accessManagement() - .activeDirectoryGroups() - .define(groupName) - .withEmailAlias(groupName) - .create(); + .activeDirectoryGroups() + .define(groupName) + .withEmailAlias(groupName) + .create(); //============================================================= // Assign AAD security group Contributor role at a resource group - ResourceGroup resourceGroup = azureResourceManager.resourceGroups() - .define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); ResourceManagerUtils.sleep(Duration.ofSeconds(45)); System.out.println("Assigning AAD security group Contributor role to the resource group"); azureResourceManager.accessManagement() - .roleAssignments() - .define(roleAssignmentName) - .forGroup(activeDirectoryGroup) - .withBuiltInRole(BuiltInRole.CONTRIBUTOR) - .withResourceGroupScope(resourceGroup) - .create(); + .roleAssignments() + .define(roleAssignmentName) + .forGroup(activeDirectoryGroup) + .withBuiltInRole(BuiltInRole.CONTRIBUTOR) + .withResourceGroupScope(resourceGroup) + .create(); System.out.println("Assigned AAD security group Contributor role to the resource group"); @@ -101,19 +100,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM with MSI enabled"); VirtualMachine virtualMachine = azureResourceManager.virtualMachines() - .define(linuxVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipName) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .create(); + .define(linuxVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .create(); System.out.println("Created virtual machine with MSI enabled"); Utils.print(virtualMachine); @@ -124,8 +123,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Adding virtual machine MSI service principal to the AAD group"); activeDirectoryGroup.update() - .withMember(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) - .apply(); + .withMember(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) + .apply(); System.out.println("Added virtual machine MSI service principal to the AAD group"); @@ -137,30 +136,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // final String stgName = Utils.randomResourceName(azureResourceManager, "st44", 15); installCommand = installCommand.replace("{stgName}", stgName) - .replace("{rgName}", rgName) - .replace("{location}", region.name()); + .replace("{rgName}", rgName) + .replace("{location}", region.name()); // Update the VM by installing custom script extension. // System.out.println("Installing custom script extension to configure az cli in the virtual machine"); System.out.println("az cli will use MSI credentials to create storage account"); - virtualMachine - .update() - .defineNewExtension("az-create-storage-account") - .withPublisher("Microsoft.Azure.Extensions") - .withType("CustomScript") - .withVersion("2.1") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .apply(); + virtualMachine.update() + .defineNewExtension("az-create-storage-account") + .withPublisher("Microsoft.Azure.Extensions") + .withType("CustomScript") + .withVersion("2.1") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .apply(); // Retrieve the storage account created by az cli using MSI credentials // - StorageAccount storageAccount = azureResourceManager.storageAccounts() - .getByResourceGroup(rgName, stgName); + StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(rgName, stgName); System.out.println("Storage account created by az cli using MSI credential"); Utils.print(storageAccount); @@ -169,7 +166,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { try { if (activeDirectoryGroup != null) { System.out.println("Deleting AAD Group: " + activeDirectoryGroup.name()); - azureResourceManager.accessManagement().activeDirectoryGroups() + azureResourceManager.accessManagement() + .activeDirectoryGroups() .deleteById(activeDirectoryGroup.id()); } } catch (Exception e) { @@ -200,8 +198,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java index eda27a4e600a4..d6e04bfc6c97b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java @@ -33,7 +33,9 @@ * - Login using created service principle and verify it can assign/remove identity #1, but not #2 */ public final class ManageScaleSetUserAssignedMSIFromServicePrincipal { - private static final ClientLogger LOGGER = new ClientLogger(ManageScaleSetUserAssignedMSIFromServicePrincipal.class); + private static final ClientLogger LOGGER + = new ClientLogger(ManageScaleSetUserAssignedMSIFromServicePrincipal.class); + /** * Main function which runs the actual sample. * @@ -63,76 +65,73 @@ public static boolean runSample(AzureResourceManager.Authenticated authenticated // ============================================================ // Create Virtual Machine Scale Set Network network = azureResourceManager.networks() - .define("vmssvnet") - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + .define("vmssvnet") + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); VirtualMachineScaleSet virtualMachineScaleSet1 = azureResourceManager.virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withoutPrimaryInternetFacingLoadBalancer() - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .create(); + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withoutPrimaryInternetFacingLoadBalancer() + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .create(); // ============================================================ // Create a managed service identity #1 and create a service principal. Configure the service principal to have 2 permissions, to update the scale set and assign the managed service identity #1 to the scale set - servicePrincipal = authenticated.servicePrincipals().define(spName1) - .withNewApplication() - .definePasswordCredential("sppass") - .attach() - .withNewRole(BuiltInRole.CONTRIBUTOR, resourceGroupId(virtualMachineScaleSet1.id())) - .create(); - - Identity identity1 = azureResourceManager.identities().define(identityName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - .create(); - - servicePrincipal.update() - .withNewRole(BuiltInRole.MANAGED_IDENTITY_OPERATOR, identity1.id()) - .apply(); + servicePrincipal = authenticated.servicePrincipals() + .define(spName1) + .withNewApplication() + .definePasswordCredential("sppass") + .attach() + .withNewRole(BuiltInRole.CONTRIBUTOR, resourceGroupId(virtualMachineScaleSet1.id())) + .create(); + + Identity identity1 = azureResourceManager.identities() + .define(identityName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); + + servicePrincipal.update().withNewRole(BuiltInRole.MANAGED_IDENTITY_OPERATOR, identity1.id()).apply(); // ============================================================ // Create a managed service identity #2 - Identity identity2 = azureResourceManager.identities().define(identityName2) - .withRegion(region) - .withNewResourceGroup(rgName + "2") - .create(); + Identity identity2 = azureResourceManager.identities() + .define(identityName2) + .withRegion(region) + .withNewResourceGroup(rgName + "2") + .create(); // ============================================================ // Login using created service principle and verify it can assign/remove identity #1, but not #2 - ClientSecretCredential credential = new ClientSecretCredentialBuilder() - .clientId(servicePrincipal.applicationId()) - .tenantId(servicePrincipal.manager().tenantId()) - .clientSecret("\"StrongPass!12\"") - .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) - .build(); + ClientSecretCredential credential + = new ClientSecretCredentialBuilder().clientId(servicePrincipal.applicationId()) + .tenantId(servicePrincipal.manager().tenantId()) + .clientSecret("\"StrongPass!12\"") + .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) + .build(); AzureProfile profile = new AzureProfile(null, subscription, AzureEnvironment.AZURE); ComputeManager computeManager1 = ComputeManager.authenticate(credential, profile); - VirtualMachineScaleSet vmss = computeManager1.virtualMachineScaleSets().getById(virtualMachineScaleSet1.id()); + VirtualMachineScaleSet vmss + = computeManager1.virtualMachineScaleSets().getById(virtualMachineScaleSet1.id()); - vmss.update() - .withExistingUserAssignedManagedServiceIdentity(identity1) - .apply(); + vmss.update().withExistingUserAssignedManagedServiceIdentity(identity1).apply(); // verify that cannot assign user identity #2 as service principal does not have permissions try { - vmss.update() - .withExistingUserAssignedManagedServiceIdentity(identity2) - .apply(); - throw LOGGER.logExceptionAsError( - new RuntimeException("Should not be able to assign identity #2 as service principal does not have permissions") - ); + vmss.update().withExistingUserAssignedManagedServiceIdentity(identity2).apply(); + throw LOGGER.logExceptionAsError(new RuntimeException( + "Should not be able to assign identity #2 as service principal does not have permissions")); } catch (ManagementException ex) { ex.printStackTrace(); } @@ -148,7 +147,9 @@ public static boolean runSample(AzureResourceManager.Authenticated authenticated } } try { - authenticated.activeDirectoryApplications().deleteById(authenticated.activeDirectoryApplications().getByName(servicePrincipal.applicationId()).id()); + authenticated.activeDirectoryApplications() + .deleteById( + authenticated.activeDirectoryApplications().getByName(servicePrincipal.applicationId()).id()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); @@ -162,8 +163,7 @@ public static boolean runSample(AzureResourceManager.Authenticated authenticated */ private static String resourceGroupId(String id) { final ResourceId resourceId = ResourceId.fromString(id); - return String.format("/subscriptions/%s/resourceGroups/%s", - resourceId.subscriptionId(), + return String.format("/subscriptions/%s/resourceGroups/%s", resourceId.subscriptionId(), resourceId.resourceGroupName()); } @@ -181,8 +181,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager.Authenticated authenticated = AzureResourceManager - .configure() + AzureResourceManager.Authenticated authenticated = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java index 861dc5e65b44f..a3c943554398d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java @@ -44,7 +44,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_EAST; - final String installScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/create_resources_with_msi.sh"; + final String installScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/create_resources_with_msi.sh"; String installCommand = "bash create_resources_with_msi.sh {stgName} {rgName} {location}"; List fileUris = new ArrayList<>(); fileUris.add(installScript); @@ -56,20 +57,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM with MSI enabled"); VirtualMachine virtualMachine = azureResourceManager.virtualMachines() - .define(linuxVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipName) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withOSDiskCaching(CachingTypes.READ_WRITE) - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .create(); + .define(linuxVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withOSDiskCaching(CachingTypes.READ_WRITE) + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .create(); System.out.println("Created virtual machine with MSI enabled"); Utils.print(virtualMachine); @@ -78,30 +79,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // final String stgName = Utils.randomResourceName(azureResourceManager, "st44", 15); installCommand = installCommand.replace("{stgName}", stgName) - .replace("{rgName}", rgName) - .replace("{location}", region.name()); + .replace("{rgName}", rgName) + .replace("{location}", region.name()); // Update the VM by installing custom script extension. // System.out.println("Installing custom script extension to configure az cli in the virtual machine"); System.out.println("az cli will use MSI credentials to create storage account"); - virtualMachine - .update() - .defineNewExtension("az-create-storage-account") - .withPublisher("Microsoft.Azure.Extensions") - .withType("CustomScript") - .withVersion("2.1") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .apply(); + virtualMachine.update() + .defineNewExtension("az-create-storage-account") + .withPublisher("Microsoft.Azure.Extensions") + .withType("CustomScript") + .withVersion("2.1") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .apply(); // Retrieve the storage account created by az cli using MSI credentials // - StorageAccount storageAccount = azureResourceManager.storageAccounts() - .getByResourceGroup(rgName, stgName); + StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(rgName, stgName); System.out.println("Storage account created by az cli using MSI credential"); Utils.print(storageAccount); @@ -132,8 +131,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java index 6a77245988f05..23bf55f5e8727 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java @@ -56,19 +56,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================================================ // Create a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group - System.out.println("Creating a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group"); + System.out.println( + "Creating a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group"); - ResourceGroup resourceGroup1 = azureResourceManager.resourceGroups() - .define(rgName1) - .withRegion(region) - .create(); + ResourceGroup resourceGroup1 + = azureResourceManager.resourceGroups().define(rgName1).withRegion(region).create(); Identity identity = azureResourceManager.identities() - .define(identityName) - .withRegion(region) - .withNewResourceGroup(rgName2) - .withAccessTo(resourceGroup1.id(), BuiltInRole.CONTRIBUTOR) - .create(); + .define(identityName) + .withRegion(region) + .withNewResourceGroup(rgName2) + .withAccessTo(resourceGroup1.id(), BuiltInRole.CONTRIBUTOR) + .create(); System.out.println("Created Resource Group and User Assigned MSI"); @@ -81,7 +80,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // The script to install Java8, Maven3 and Git on a virtual machine using Azure Custom Script Extension // - final String javaMvnGitInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_jva_mvn_git.sh"; + final String javaMvnGitInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_jva_mvn_git.sh"; final String invokeScriptCommand = "bash install_jva_mvn_git.sh"; List fileUris = new ArrayList<>(); fileUris.add(javaMvnGitInstallScript); @@ -89,26 +89,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Linux VM with MSI associated and install Java8, Maven and Git"); VirtualMachine virtualMachine = azureResourceManager.virtualMachines() - .define(linuxVMName) - .withRegion(region) - .withExistingResourceGroup(rgName2) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipName) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withExistingUserAssignedManagedServiceIdentity(identity) - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", invokeScriptCommand) - .attach() - .create(); + .define(linuxVMName) + .withRegion(region) + .withExistingResourceGroup(rgName2) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withExistingUserAssignedManagedServiceIdentity(identity) + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", invokeScriptCommand) + .attach() + .create(); System.out.println("Created Linux VM"); @@ -117,12 +117,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Run Java application in the MSI enabled Linux VM which uses MSI credentials to manage Azure resource - System.out.println("Running a Java application in the MSI enabled VM which creates another virtual machine"); + System.out + .println("Running a Java application in the MSI enabled VM which creates another virtual machine"); List commands = new ArrayList<>(); - commands.add("git clone https://github.com/Azure-Samples/compute-java-manage-vm-from-vm-with-msi-credentials.git"); + commands.add( + "git clone https://github.com/Azure-Samples/compute-java-manage-vm-from-vm-with-msi-credentials.git"); commands.add("cd compute-java-manage-vm-from-vm-with-msi-credentials"); - commands.add(String.format("mvn clean compile exec:java -Dexec.args='%s %s %s false'", azureResourceManager.subscriptionId(), resourceGroup1.name(), identity.clientId())); + commands.add(String.format("mvn clean compile exec:java -Dexec.args='%s %s %s false'", + azureResourceManager.subscriptionId(), resourceGroup1.name(), identity.clientId())); RunCommandResult commandResult = runCommandOnVM(azureResourceManager, virtualMachine, commands); @@ -139,7 +142,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Retrieving the virtual machine created from the MSI enabled Linux VM"); - PagedIterable virtualMachines = azureResourceManager.virtualMachines().listByResourceGroup(resourceGroup1.name()); + PagedIterable virtualMachines + = azureResourceManager.virtualMachines().listByResourceGroup(resourceGroup1.name()); for (VirtualMachine vm : virtualMachines) { Utils.print(vm); } @@ -159,12 +163,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } - private static RunCommandResult runCommandOnVM(AzureResourceManager azureResourceManager, VirtualMachine virtualMachine, List commands) { - RunCommandInput runParams = new RunCommandInput() - .withCommandId("RunShellScript") - .withScript(commands); + private static RunCommandResult runCommandOnVM(AzureResourceManager azureResourceManager, + VirtualMachine virtualMachine, List commands) { + RunCommandInput runParams = new RunCommandInput().withCommandId("RunShellScript").withScript(commands); - return azureResourceManager.virtualMachines().runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams); + return azureResourceManager.virtualMachines() + .runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams); } /** @@ -181,8 +185,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java index d58161203971d..c0d264b076cfa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java @@ -57,81 +57,71 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Prepare a creatable data disk for VM // - Creatable dataDiskCreatable = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100); + Creatable dataDiskCreatable = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100); // Create a data disk to attach to VM // Disk dataDisk = azureResourceManager.disks() - .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withNewResourceGroup(rgName) - .withData() - .withSizeInGB(50) - .create(); + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withNewResourceGroup(rgName) + .withData() + .withSizeInGB(50) + .create(); System.out.println("Creating a Windows VM"); Date t1 = new Date(); VirtualMachine windowsVM = azureResourceManager.virtualMachines() - .define(windowsVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withNewDataDisk(10) - .withNewDataDisk(dataDiskCreatable) - .withExistingDataDisk(dataDisk) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + .define(windowsVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withNewDataDisk(10) + .withNewDataDisk(dataDiskCreatable) + .withExistingDataDisk(dataDisk) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t2 = new Date(); - System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id()); + System.out + .println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id()); // Print virtual machine details Utils.print(windowsVM); - //============================================================= // Update - Tag the virtual machine - windowsVM.update() - .withTag("who-rocks", "java") - .withTag("where", "on azure") - .apply(); + windowsVM.update().withTag("who-rocks", "java").withTag("where", "on azure").apply(); System.out.println("Tagged VM: " + windowsVM.id()); - //============================================================= // Update - Add data disk - windowsVM.update() - .withNewDataDisk(10) - .apply(); - + windowsVM.update().withNewDataDisk(10).apply(); System.out.println("Added a data disk to VM" + windowsVM.id()); Utils.print(windowsVM); - //============================================================= // Update - detach data disk - windowsVM.update() - .withoutDataDisk(0) - .apply(); + windowsVM.update().withoutDataDisk(0).apply(); System.out.println("Detached data disk at lun 0 from VM " + windowsVM.id()); - //============================================================= // Restart the virtual machine @@ -141,7 +131,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Restarted VM: " + windowsVM.id() + "; state = " + windowsVM.powerState()); - //============================================================= // Stop (powerOff) the virtual machine @@ -154,25 +143,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Get the network where Windows VM is hosted Network network = windowsVM.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); - //============================================================= // Create a Linux VM in the same virtual network System.out.println("Creating a Linux VM in the network"); VirtualMachine linuxVM = azureResourceManager.virtualMachines() - .define(linuxVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + .define(linuxVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Created a Linux VM (in the same virtual network): " + linuxVM.id()); Utils.print(linuxVM); @@ -184,7 +172,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Printing list of VMs ======="); - for (VirtualMachine virtualMachine : azureResourceManager.virtualMachines().listByResourceGroup(resourceGroupName)) { + for (VirtualMachine virtualMachine : azureResourceManager.virtualMachines() + .listByResourceGroup(resourceGroupName)) { Utils.print(virtualMachine); } @@ -225,8 +214,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java index d899b9c90eca3..081f8cb689e90 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java @@ -64,83 +64,77 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) // final Date t1 = new Date(); - final Creatable dataDiskCreatable = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100); + final Creatable dataDiskCreatable = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100); // Create a data disk to attach to VM // - Mono dataDiskMono = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withNewResourceGroup(rgName) - .withData() - .withSizeInGB(50) - .createAsync(); + Mono dataDiskMono = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withNewResourceGroup(rgName) + .withData() + .withSizeInGB(50) + .createAsync(); final Map createdVms = new TreeMap<>(); - Mono networkMono = azureResourceManager.networks().define(Utils.randomResourceName(azureResourceManager, "network", 20)) + Mono networkMono = azureResourceManager.networks() + .define(Utils.randomResourceName(azureResourceManager, "network", 20)) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .createAsync(); - Mono.zip(dataDiskMono, networkMono) - .flatMapMany( - tuple -> Flux.merge( - Mono.defer(() -> { - System.out.println("Creating a Windows VM"); - return azureResourceManager.virtualMachines().define(windowsVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(tuple.getT2()) - .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withNewDataDisk(10) - .withNewDataDisk(dataDiskCreatable) - .withExistingDataDisk(tuple.getT1()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .createAsync(); - }), - Mono.defer(() -> { - System.out.println("Creating a Linux VM in the same network"); - return azureResourceManager.virtualMachines().define(linuxVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(tuple.getT2()) - .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .createAsync(); - }) - ) - ).doOnNext( - virtualMachine -> { - Date t2 = new Date(); - if (isWindowsVM(virtualMachine)) { - createdVms.put(windowsVmKey, virtualMachine); - System.out.println("Created Windows VM: " - + virtualMachine.id()); - } else { - createdVms.put(linuxVmKey, virtualMachine); - System.out.println("Created a Linux VM (in the same virtual network): " - + virtualMachine.id()); - } - System.out.println("Virtual machine creation took " - + ((t2.getTime() - t1.getTime()) / 1000) - + " seconds"); + Mono.zip(dataDiskMono, networkMono).flatMapMany(tuple -> Flux.merge(Mono.defer(() -> { + System.out.println("Creating a Windows VM"); + return azureResourceManager.virtualMachines() + .define(windowsVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(tuple.getT2()) + .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withNewDataDisk(10) + .withNewDataDisk(dataDiskCreatable) + .withExistingDataDisk(tuple.getT1()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .createAsync(); + }), Mono.defer(() -> { + System.out.println("Creating a Linux VM in the same network"); + return azureResourceManager.virtualMachines() + .define(linuxVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(tuple.getT2()) + .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .createAsync(); + }))).doOnNext(virtualMachine -> { + Date t2 = new Date(); + if (isWindowsVM(virtualMachine)) { + createdVms.put(windowsVmKey, virtualMachine); + System.out.println("Created Windows VM: " + virtualMachine.id()); + } else { + createdVms.put(linuxVmKey, virtualMachine); + System.out.println("Created a Linux VM (in the same virtual network): " + virtualMachine.id()); } - ).blockLast(); + System.out + .println("Virtual machine creation took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds"); + }).blockLast(); final VirtualMachine windowsVM = createdVms.get(windowsVmKey); final VirtualMachine linuxVM = createdVms.get(linuxVmKey); @@ -150,43 +144,36 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) // - Tag the virtual machine on Linux VM Mono updateLinuxVMChain = linuxVM.update() - .withTag("who-rocks-on-linux", "java") - .withTag("where", "on azure") - .applyAsync() - .map(virtualMachine -> { - System.out.println("Tagged Linux VM: " + virtualMachine.id()); - return virtualMachine; - }); + .withTag("who-rocks-on-linux", "java") + .withTag("where", "on azure") + .applyAsync() + .map(virtualMachine -> { + System.out.println("Tagged Linux VM: " + virtualMachine.id()); + return virtualMachine; + }); // - Add a data disk on Windows VM. - Mono updateWindowsVMChain = windowsVM.update() - .withNewDataDisk(200) - .applyAsync(); + Mono updateWindowsVMChain = windowsVM.update().withNewDataDisk(200).applyAsync(); - Flux.merge(updateLinuxVMChain, updateWindowsVMChain) - .last().block(); + Flux.merge(updateLinuxVMChain, updateWindowsVMChain).last().block(); //============================================================= // List virtual machines and print details - azureResourceManager.virtualMachines().listByResourceGroupAsync(rgName) - .map(virtualMachine -> { - System.out.println("Retrieved details for VM: " + virtualMachine.id()); - return virtualMachine; - }).last().block(); + azureResourceManager.virtualMachines().listByResourceGroupAsync(rgName).map(virtualMachine -> { + System.out.println("Retrieved details for VM: " + virtualMachine.id()); + return virtualMachine; + }).last().block(); //============================================================= // Delete the virtual machines in parallel - Flux.merge( - azureResourceManager.virtualMachines().deleteByIdAsync(windowsVM.id()), - azureResourceManager.virtualMachines().deleteByIdAsync(linuxVM.id())) - .singleOrEmpty().block(); + Flux.merge(azureResourceManager.virtualMachines().deleteByIdAsync(windowsVM.id()), + azureResourceManager.virtualMachines().deleteByIdAsync(linuxVM.id())).singleOrEmpty().block(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); - azureResourceManager.resourceGroups().deleteByNameAsync(rgName) - .block(); + azureResourceManager.resourceGroups().deleteByNameAsync(rgName).block(); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); @@ -202,6 +189,7 @@ private static boolean isWindowsVM(VirtualMachine vm) { } return false; } + /** * Main entry point. * @param args the parameters @@ -217,8 +205,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java index e75414c44e38e..8e06a6c62ead6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java @@ -60,7 +60,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxCustomScriptExtensionTypeName = "CustomScriptForLinux"; final String linuxCustomScriptExtensionVersionName = "1.4"; - final String mySqlLinuxInstallScript = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/4397e808d07df60ff3cdfd1ae40999f0130eb1b3/mysql-standalone-server-ubuntu/scripts/install_mysql_server_5.6.sh"; + final String mySqlLinuxInstallScript + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/4397e808d07df60ff3cdfd1ae40999f0130eb1b3/mysql-standalone-server-ubuntu/scripts/install_mysql_server_5.6.sh"; final String installMySQLLinuxCommand = "bash install_mysql_server_5.6.sh Abc.123x("; final List linuxScriptFileUris = new ArrayList<>(); linuxScriptFileUris.add(mySqlLinuxInstallScript); @@ -70,7 +71,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String windowsCustomScriptExtensionTypeName = "CustomScriptExtension"; final String windowsCustomScriptExtensionVersionName = "1.7"; - final String mySqlWindowsInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/installMySQL.ps1"; + final String mySqlWindowsInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/installMySQL.ps1"; final String installMySQLWindowsCommand = "powershell.exe -ExecutionPolicy Unrestricted -File installMySQL.ps1"; final List windowsScriptFileUris = new ArrayList<>(); windowsScriptFileUris.add(mySqlWindowsInstallScript); @@ -98,24 +100,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String windowsVMAccessExtensionVersionName = "2.4"; try { - //============================================================= // Create a Linux VM with root (sudo) user System.out.println("Creating a Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipDnsLabelLinuxVM) - // mysql-server-5.6 not available for Ubuntu 16 and 18 - .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.4-LTS") - .withRootUsername(firstLinuxUserName) - .withRootPassword(firstLinuxUserPassword) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipDnsLabelLinuxVM) + // mysql-server-5.6 not available for Ubuntu 16 and 18 + .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.4-LTS") + .withRootUsername(firstLinuxUserName) + .withRootPassword(firstLinuxUserPassword) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Created a Linux VM with" + linuxVM.id()); Utils.print(linuxVM); @@ -124,15 +126,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Add a second sudo user to Linux VM using VMAccess extension linuxVM.update() - .defineNewExtension(linuxVMAccessExtensionName) - .withPublisher(linuxVMAccessExtensionPublisherName) - .withType(linuxVMAccessExtensionTypeName) - .withVersion(linuxVMAccessExtensionVersionName) - .withProtectedSetting("username", secondLinuxUserName) - .withProtectedSetting("password", secondLinuxUserPassword) - .withProtectedSetting("expiration", secondLinuxUserExpiration) - .attach() - .apply(); + .defineNewExtension(linuxVMAccessExtensionName) + .withPublisher(linuxVMAccessExtensionPublisherName) + .withType(linuxVMAccessExtensionTypeName) + .withVersion(linuxVMAccessExtensionVersionName) + .withProtectedSetting("username", secondLinuxUserName) + .withProtectedSetting("password", secondLinuxUserPassword) + .withProtectedSetting("expiration", secondLinuxUserExpiration) + .attach() + .apply(); System.out.println("Added a second sudo user to the Linux VM"); @@ -140,12 +142,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Add a third sudo user to Linux VM by updating VMAccess extension linuxVM.update() - .updateExtension(linuxVMAccessExtensionName) - .withProtectedSetting("username", thirdLinuxUserName) - .withProtectedSetting("password", thirdLinuxUserPassword) - .withProtectedSetting("expiration", thirdLinuxUserExpiration) - .parent() - .apply(); + .updateExtension(linuxVMAccessExtensionName) + .withProtectedSetting("username", thirdLinuxUserName) + .withProtectedSetting("password", thirdLinuxUserPassword) + .withProtectedSetting("expiration", thirdLinuxUserExpiration) + .parent() + .apply(); System.out.println("Added a third sudo user to the Linux VM"); @@ -153,12 +155,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Reset ssh password of first user of Linux VM by updating VMAccess extension linuxVM.update() - .updateExtension(linuxVMAccessExtensionName) - .withProtectedSetting("username", firstLinuxUserName) - .withProtectedSetting("password", firstLinuxUserNewPassword) - .withProtectedSetting("reset_ssh", "true") - .parent() - .apply(); + .updateExtension(linuxVMAccessExtensionName) + .withProtectedSetting("username", firstLinuxUserName) + .withProtectedSetting("password", firstLinuxUserNewPassword) + .withProtectedSetting("reset_ssh", "true") + .parent() + .apply(); System.out.println("Password of first user of Linux VM has been updated"); @@ -166,24 +168,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Removes the second sudo user from Linux VM using VMAccess extension linuxVM.update() - .updateExtension(linuxVMAccessExtensionName) - .withProtectedSetting("remove_user", secondLinuxUserName) - .parent() - .apply(); + .updateExtension(linuxVMAccessExtensionName) + .withProtectedSetting("remove_user", secondLinuxUserName) + .parent() + .apply(); //============================================================= // Install MySQL in Linux VM using CustomScript extension linuxVM.update() - .defineNewExtension(linuxCustomScriptExtensionName) - .withPublisher(linuxCustomScriptExtensionPublisherName) - .withType(linuxCustomScriptExtensionTypeName) - .withVersion(linuxCustomScriptExtensionVersionName) - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", linuxScriptFileUris) - .withPublicSetting("commandToExecute", installMySQLLinuxCommand) - .attach() - .apply(); + .defineNewExtension(linuxCustomScriptExtensionName) + .withPublisher(linuxCustomScriptExtensionPublisherName) + .withType(linuxCustomScriptExtensionTypeName) + .withVersion(linuxCustomScriptExtensionVersionName) + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", linuxScriptFileUris) + .withPublicSetting("commandToExecute", installMySQLLinuxCommand) + .attach() + .apply(); System.out.println("Installed MySql using custom script extension"); Utils.print(linuxVM); @@ -192,9 +194,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Removes the extensions from Linux VM linuxVM.update() - .withoutExtension(linuxCustomScriptExtensionName) - .withoutExtension(linuxVMAccessExtensionName) - .apply(); + .withoutExtension(linuxCustomScriptExtensionName) + .withoutExtension(linuxVMAccessExtensionName) + .apply(); System.out.println("Removed the custom script and VM Access extensions from Linux VM"); Utils.print(linuxVM); @@ -203,25 +205,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Windows VM"); - VirtualMachine windowsVM = azureResourceManager.virtualMachines().define(windowsVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipDnsLabelWindowsVM) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(firstWindowsUserName) - .withAdminPassword(firstWindowsUserPassword) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .defineNewExtension(windowsCustomScriptExtensionName) - .withPublisher(windowsCustomScriptExtensionPublisherName) - .withType(windowsCustomScriptExtensionTypeName) - .withVersion(windowsCustomScriptExtensionVersionName) - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", windowsScriptFileUris) - .withPublicSetting("commandToExecute", installMySQLWindowsCommand) - .attach() - .create(); + VirtualMachine windowsVM = azureResourceManager.virtualMachines() + .define(windowsVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipDnsLabelWindowsVM) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(firstWindowsUserName) + .withAdminPassword(firstWindowsUserPassword) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .defineNewExtension(windowsCustomScriptExtensionName) + .withPublisher(windowsCustomScriptExtensionPublisherName) + .withType(windowsCustomScriptExtensionTypeName) + .withVersion(windowsCustomScriptExtensionVersionName) + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", windowsScriptFileUris) + .withPublicSetting("commandToExecute", installMySQLWindowsCommand) + .attach() + .create(); System.out.println("Created a Windows VM" + windowsVM.id()); Utils.print(windowsVM); @@ -230,14 +233,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Add a second admin user to Windows VM using VMAccess extension windowsVM.update() - .defineNewExtension(windowsVMAccessExtensionName) - .withPublisher(windowsVMAccessExtensionPublisherName) - .withType(windowsVMAccessExtensionTypeName) - .withVersion(windowsVMAccessExtensionVersionName) - .withPublicSetting("UserName", secondWindowsUserName) - .withProtectedSetting("Password", secondWindowsUserPassword) - .attach() - .apply(); + .defineNewExtension(windowsVMAccessExtensionName) + .withPublisher(windowsVMAccessExtensionPublisherName) + .withType(windowsVMAccessExtensionTypeName) + .withVersion(windowsVMAccessExtensionVersionName) + .withPublicSetting("UserName", secondWindowsUserName) + .withProtectedSetting("Password", secondWindowsUserPassword) + .attach() + .apply(); System.out.println("Added a second admin user to the Windows VM"); @@ -245,11 +248,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Add a third admin user to Windows VM by updating VMAccess extension windowsVM.update() - .updateExtension(windowsVMAccessExtensionName) - .withPublicSetting("UserName", thirdWindowsUserName) - .withProtectedSetting("Password", thirdWindowsUserPassword) - .parent() - .apply(); + .updateExtension(windowsVMAccessExtensionName) + .withPublicSetting("UserName", thirdWindowsUserName) + .withProtectedSetting("Password", thirdWindowsUserPassword) + .parent() + .apply(); System.out.println("Added a third admin user to the Windows VM"); @@ -257,20 +260,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Reset admin password of first user of Windows VM by updating VMAccess extension windowsVM.update() - .updateExtension(windowsVMAccessExtensionName) - .withPublicSetting("UserName", firstWindowsUserName) - .withProtectedSetting("Password", firstWindowsUserNewPassword) - .parent() - .apply(); + .updateExtension(windowsVMAccessExtensionName) + .withPublicSetting("UserName", firstWindowsUserName) + .withProtectedSetting("Password", firstWindowsUserNewPassword) + .parent() + .apply(); System.out.println("Password of first user of Windows VM has been updated"); //============================================================= // Removes the extensions from Windows VM - windowsVM.update() - .withoutExtension(windowsVMAccessExtensionName) - .apply(); + windowsVM.update().withoutExtension(windowsVMAccessExtensionName).apply(); System.out.println("Removed the VM Access extensions from Windows VM"); Utils.print(windowsVM); return true; @@ -302,8 +303,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java index 6ce8c3d9a172d..9682abee8a76e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java @@ -33,7 +33,8 @@ public static void main(String[] args) { // see https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview // - final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\" [] []\""; + final String usage + = "Usage: mvn clean compile exec:java -Dexec.args=\" [] []\""; if (args.length < 2) { throw new IllegalArgumentException(usage); } @@ -49,9 +50,7 @@ public static void main(String[] args) { //============================================================= // ManagedIdentityCredential Authenticate - ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder() - .clientId(clientId) - .build(); + ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(clientId).build(); AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java index 2e36f1f040e5a..242875f474d8f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java @@ -67,12 +67,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String httpsLoadBalancingRule = "httpsRule"; final String natPool50XXto22 = "natPool50XXto22"; final String natPool60XXto23 = "natPool60XXto23"; - final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); + final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); final String userName = "tirekicker"; final String sshKey = Utils.sshPublicKey(); - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String installCommand = "bash install_apache.sh"; List fileUris = new ArrayList<>(); fileUris.add(apacheInstallScript); @@ -82,14 +83,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a virtual network with a frontend subnet System.out.println("Creating virtual network with a frontend subnet ..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .create(); System.out.println("Created a virtual network"); // Print the virtual network details @@ -99,11 +101,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a public IP address System.out.println("Creating a public IP address..."); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(publicIpName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName) - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(publicIpName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName) + .create(); System.out.println("Created a public IP address"); // Print the virtual network details @@ -125,122 +128,122 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Internet facing load balancer with ..."); System.out.println("- A frontend IP address"); System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" - + " machines to receive HTTP and HTTPS network traffic from the load balancer"); + + " machines to receive HTTP and HTTPS network traffic from the load balancer"); System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers().define(loadBalancerName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - - // Add nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatPool(natPool50XXto22) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPool60XXto23) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) - .attach() - - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers() + .define(loadBalancerName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + + // Add nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatPool(natPool50XXto22) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPool60XXto23) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) + .attach() + + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) + .attach() + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + + .create(); // Print load balancer details System.out.println("Created a load balancer"); Utils.print(loadBalancer1); - //============================================================= // Create a virtual machine scale set with three virtual machines // And, install Apache Web servers on them - System.out.println("Creating virtual machine scale set with three virtual machines" - + " in the frontend subnet ..."); + System.out.println( + "Creating virtual machine scale set with three virtual machines" + " in the frontend subnet ..."); Date t1 = new Date(); - ImageReference imageReference = new ImageReference() - .withPublisher("Canonical") - .withOffer("UbuntuServer") - .withSku("18.04-LTS") - .withVersion("latest"); - - VirtualMachineScaleSet virtualMachineScaleSet = azureResourceManager.virtualMachineScaleSets().define(vmssName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "Front-end") - .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) - .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) - .withoutPrimaryInternalLoadBalancer() - .withSpecificLinuxImageVersion(imageReference) - .withRootUsername(userName) - .withSsh(sshKey) - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) - .withCapacity(3) - .create(); + ImageReference imageReference = new ImageReference().withPublisher("Canonical") + .withOffer("UbuntuServer") + .withSku("18.04-LTS") + .withVersion("latest"); + + VirtualMachineScaleSet virtualMachineScaleSet = azureResourceManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "Front-end") + .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) + .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) + .withoutPrimaryInternalLoadBalancer() + .withSpecificLinuxImageVersion(imageReference) + .withRootUsername(userName) + .withSsh(sshKey) + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) + .withCapacity(3) + .create(); // VM may take some time to init its pkgs ResourceManagerUtils.sleep(Duration.ofMinutes(1)); virtualMachineScaleSet.update() - // Use a VM extension to install Apache Web servers - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .apply(); + // Use a VM extension to install Apache Web servers + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .apply(); Date t2 = new Date(); - System.out.println("Created a virtual machine scale set with " - + "3 Linux VMs & Apache Web servers on them: (took " + System.out.println( + "Created a virtual machine scale set with " + "3 Linux VMs & Apache Web servers on them: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) "); System.out.println(); @@ -251,7 +254,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // List virtual machine scale set network interfaces System.out.println("Listing scale set network interfaces ..."); - PagedIterable vmssNics = virtualMachineScaleSet.listNetworkInterfaces(); + PagedIterable vmssNics + = virtualMachineScaleSet.listNetworkInterfaces(); for (VirtualMachineScaleSetNetworkInterface vmssNic : vmssNics) { System.out.println(vmssNic.id()); } @@ -259,19 +263,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // List virtual machine scale set instance network interfaces and SSH connection string - System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); + System.out + .println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); for (VirtualMachineScaleSetVM instance : virtualMachineScaleSet.virtualMachines().list()) { System.out.println("Scale set virtual machine instance #" + instance.instanceId()); System.out.println(instance.id()); - PagedIterable networkInterfaces = instance.listNetworkInterfaces(); + PagedIterable networkInterfaces + = instance.listNetworkInterfaces(); // Pick the first NIC VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.iterator().next(); - for (VirtualMachineScaleSetNicIpConfiguration ipConfig :networkInterface.ipConfigurations().values()) { + for (VirtualMachineScaleSetNicIpConfiguration ipConfig : networkInterface.ipConfigurations().values()) { if (ipConfig.isPrimary()) { - List natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); + List natRules + = ipConfig.listAssociatedLoadBalancerInboundNatRules(); for (LoadBalancerInboundNatRule natRule : natRules) { if (natRule.backendPort() == 22) { - System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + ":" + natRule.frontendPort()); + System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + + ":" + natRule.frontendPort()); break; } } @@ -287,7 +295,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { virtualMachineScaleSet.powerOff(); System.out.println("Stopped virtual machine scale set"); - //============================================================= // Deallocate the virtual machine scale set @@ -299,10 +306,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Update the virtual machine scale set by removing and adding disk System.out.println("Updating virtual machine scale set managed data disks..."); - virtualMachineScaleSet.update() - .withoutDataDisk(0) - .withoutDataDisk(200) - .apply(); + virtualMachineScaleSet.update().withoutDataDisk(0).withoutDataDisk(200).apply(); System.out.println("Updated virtual machine scale set"); //============================================================= @@ -312,21 +316,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { virtualMachineScaleSet.start(); System.out.println("Started virtual machine scale set"); - //============================================================= // Update the virtual machine scale set // - double the no. of virtual machines - System.out.println("Updating virtual machine scale set " - + "- double the no. of virtual machines ..."); - - virtualMachineScaleSet.update() - .withCapacity(6) - .apply(); + System.out.println("Updating virtual machine scale set " + "- double the no. of virtual machines ..."); - System.out.println("Doubled the no. of virtual machines in " - + "the virtual machine scale set"); + virtualMachineScaleSet.update().withCapacity(6).apply(); + System.out.println("Doubled the no. of virtual machines in " + "the virtual machine scale set"); //============================================================= // re-start virtual machine scale set @@ -365,8 +363,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java index 3bf25c4ef799c..49a86d43f44b3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java @@ -62,12 +62,13 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final String httpsLoadBalancingRule = "httpsRule"; final String natPool50XXto22 = "natPool50XXto22"; final String natPool60XXto23 = "natPool60XXto23"; - final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); + final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); final String userName = "tirekicker"; final String sshKey = Utils.sshPublicKey(); - final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/install_apache.sh"; final String installCommand = "bash install_apache.sh"; List fileUris = new ArrayList<>(); fileUris.add(apacheInstallScript); @@ -81,102 +82,105 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final List createdResources = new ArrayList<>(); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); Flux.merge( - azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") + azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .createAsync(), + azureResourceManager.publicIpAddresses() + .define(publicIpName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName) + .createAsync() + .flatMapMany(publicIp -> { + //============================================================= + // Create an Internet facing load balancer with + // One frontend IP address + // Two backend address pools which contain network interfaces for the virtual + // machines to receive HTTP and HTTPS network traffic from the load balancer + // Two load balancing rules for HTTP and HTTPS to map public ports on the load + // balancer to ports in the backend address pool + // Two probes which contain HTTP and HTTPS health probes used to check availability + // of virtual machines in the backend address pool + // Three inbound NAT rules which contain rules that map a public port on the load + // balancer to a port for a specific virtual machine in the backend address pool + // - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23 + + System.out.println("Creating a Internet facing load balancer with ..."); + System.out.println("- A frontend IP address"); + System.out + .println("- Two backend address pools which contain network interfaces for the virtual\n" + + " machines to receive HTTP and HTTPS network traffic from the load balancer"); + System.out + .println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" + + " balancer to ports in the backend address pool"); + System.out.println( + "- Two probes which contain HTTP and HTTPS health probes used to check availability\n" + + " of virtual machines in the backend address pool"); + System.out + .println("- Two inbound NAT rules which contain rules that map a public port on the load\n" + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + return Flux.merge(Flux.just(publicIp), + azureResourceManager.loadBalancers() + .define(loadBalancerName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + // Add nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatPool(natPool50XXto22) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPool60XXto23) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIp) + .attach() + + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) .attach() - .createAsync(), - azureResourceManager.publicIpAddresses().define(publicIpName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName) - .createAsync() - .flatMapMany(publicIp -> { - //============================================================= - // Create an Internet facing load balancer with - // One frontend IP address - // Two backend address pools which contain network interfaces for the virtual - // machines to receive HTTP and HTTPS network traffic from the load balancer - // Two load balancing rules for HTTP and HTTPS to map public ports on the load - // balancer to ports in the backend address pool - // Two probes which contain HTTP and HTTPS health probes used to check availability - // of virtual machines in the backend address pool - // Three inbound NAT rules which contain rules that map a public port on the load - // balancer to a port for a specific virtual machine in the backend address pool - // - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23 - - System.out.println("Creating a Internet facing load balancer with ..."); - System.out.println("- A frontend IP address"); - System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" - + " machines to receive HTTP and HTTPS network traffic from the load balancer"); - System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" - + " balancer to ports in the backend address pool"); - System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" - + " of virtual machines in the backend address pool"); - System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - return Flux.merge( - Flux.just(publicIp), - azureResourceManager.loadBalancers().define(loadBalancerName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - // Add nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatPool(natPool50XXto22) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPool60XXto23) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIp) - .attach() - - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - .createAsync()); - }) - ) + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + .createAsync()); + })) .doOnNext(createdResources::add) .blockLast(); @@ -207,47 +211,47 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) // Create a virtual machine scale set with three virtual machines // And, install Apache Web servers on them - System.out.println("Creating virtual machine scale set with three virtual machines" - + " in the frontend subnet ..."); + System.out.println( + "Creating virtual machine scale set with three virtual machines" + " in the frontend subnet ..."); final Date t1 = new Date(); VirtualMachineScaleSet virtualMachineScaleSet = azureResourceManager.virtualMachineScaleSets() - .define(vmssName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "Front-end") - .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) - .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) - .withCapacity(3) - // Use a VM extension to install Apache Web servers - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .createAsync() - .map(indexable -> { - Date t2 = new Date(); - System.out.println("Created a virtual machine scale set with " - + "3 Linux VMs & Apache Web servers on them: (took " + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "Front-end") + .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) + .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + .withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS) + .withCapacity(3) + // Use a VM extension to install Apache Web servers + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .createAsync() + .map(indexable -> { + Date t2 = new Date(); + System.out.println( + "Created a virtual machine scale set with " + "3 Linux VMs & Apache Web servers on them: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) "); - System.out.println(); - return indexable; - }) - .block(); + System.out.println(); + return indexable; + }) + .block(); if (virtualMachineScaleSet == null) { return false; @@ -257,33 +261,32 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) //============================================================= // List virtual machine scale set instance network interfaces and SSH connection string - System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); - virtualMachineScaleSet.virtualMachines() - .listAsync() - .map(instance -> { - System.out.println("Scale set virtual machine instance #" + instance.instanceId()); - System.out.println(instance.id()); - - instance.listNetworkInterfacesAsync() - .single() - .map(networkInterface -> { - for (VirtualMachineScaleSetNicIpConfiguration ipConfig :networkInterface.ipConfigurations().values()) { - if (ipConfig.isPrimary()) { - List natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); - for (LoadBalancerInboundNatRule natRule : natRules) { - if (natRule.backendPort() == 22) { - System.out.println("SSH connection string: " + userName + "@" + pipFqdn + ":" + natRule.frontendPort()); - break; - } - } - break; - } + System.out + .println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); + virtualMachineScaleSet.virtualMachines().listAsync().map(instance -> { + System.out.println("Scale set virtual machine instance #" + instance.instanceId()); + System.out.println(instance.id()); + + instance.listNetworkInterfacesAsync().single().map(networkInterface -> { + for (VirtualMachineScaleSetNicIpConfiguration ipConfig : networkInterface.ipConfigurations() + .values()) { + if (ipConfig.isPrimary()) { + List natRules + = ipConfig.listAssociatedLoadBalancerInboundNatRules(); + for (LoadBalancerInboundNatRule natRule : natRules) { + if (natRule.backendPort() == 22) { + System.out.println("SSH connection string: " + userName + "@" + pipFqdn + ":" + + natRule.frontendPort()); + break; } - return networkInterface; - }); - return instance; - }) - .last().block(); + } + break; + } + } + return networkInterface; + }); + return instance; + }).last().block(); //============================================================= // Stop the virtual machine scale set @@ -292,21 +295,23 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) // Stop the virtual machine scale set virtualMachineScaleSet.powerOffAsync() - // Deallocate the virtual machine scale set - .concatWith(virtualMachineScaleSet.deallocateAsync()) - // Start the virtual machine scale set - .concatWith(virtualMachineScaleSet.startAsync()) - // Update the virtual machine scale set by removing and adding disk - .concatWith(virtualMachineScaleSet.update() - .withCapacity(6) - .withoutDataDisk(0) - .withoutDataDisk(200) - .applyAsync() - .flatMap(vmss -> { - System.out.println("Updated virtual machine scale set"); - // Restart the virtual machine scale set - return vmss.restartAsync(); - })).singleOrEmpty().block(); + // Deallocate the virtual machine scale set + .concatWith(virtualMachineScaleSet.deallocateAsync()) + // Start the virtual machine scale set + .concatWith(virtualMachineScaleSet.startAsync()) + // Update the virtual machine scale set by removing and adding disk + .concatWith(virtualMachineScaleSet.update() + .withCapacity(6) + .withoutDataDisk(0) + .withoutDataDisk(200) + .applyAsync() + .flatMap(vmss -> { + System.out.println("Updated virtual machine scale set"); + // Restart the virtual machine scale set + return vmss.restartAsync(); + })) + .singleOrEmpty() + .block(); return true; } finally { @@ -338,8 +343,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java index 5318a86f3c3da..0d5ef2f07d6dc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java @@ -66,7 +66,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String natPool50XXto22 = "natPool50XXto22"; final String natPool60XXto23 = "natPool60XXto23"; - final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); + final String vmssName = Utils.randomResourceName(azureResourceManager, "vmss", 24); final String storageAccountName1 = Utils.randomResourceName(azureResourceManager, "stg1", 24); final String storageAccountName2 = Utils.randomResourceName(azureResourceManager, "stg2", 24); final String storageAccountName3 = Utils.randomResourceName(azureResourceManager, "stg3", 24); @@ -74,7 +74,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String userName = "tirekicker"; final String sshKey = Utils.sshPublicKey(); - final String apacheInstallScript = "https://raw.githubusercontent.com/anuchandy/azure-libraries-for-java/master/azure-samples/src/main/resources/install_apache.sh"; + final String apacheInstallScript + = "https://raw.githubusercontent.com/anuchandy/azure-libraries-for-java/master/azure-samples/src/main/resources/install_apache.sh"; final String installCommand = "bash install_apache.sh"; List fileUris = new ArrayList<>(); fileUris.add(apacheInstallScript); @@ -83,14 +84,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a virtual network with a frontend subnet System.out.println("Creating virtual network with a frontend subnet ..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .create(); System.out.println("Created a virtual network"); // Print the virtual network details @@ -100,11 +102,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a public IP address System.out.println("Creating a public IP address..."); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(publicIpName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName) - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(publicIpName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName) + .create(); System.out.println("Created a public IP address"); // Print the virtual network details @@ -126,124 +129,124 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Internet facing load balancer with ..."); System.out.println("- A frontend IP address"); System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" - + " machines to receive HTTP and HTTPS network traffic from the load balancer"); + + " machines to receive HTTP and HTTPS network traffic from the load balancer"); System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers().define(loadBalancerName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - - // Add nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatPool(natPool50XXto22) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPool60XXto23) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) - .attach() - - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers() + .define(loadBalancerName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + + // Add nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatPool(natPool50XXto22) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPool60XXto23) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) + .attach() + + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) + .attach() + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + + .create(); // Print load balancer details System.out.println("Created a load balancer"); Utils.print(loadBalancer1); - //============================================================= // Create a virtual machine scale set with three virtual machines // And, install Apache Web servers on them - System.out.println("Creating virtual machine scale set with three virtual machines" - + " in the frontend subnet ..."); + System.out.println( + "Creating virtual machine scale set with three virtual machines" + " in the frontend subnet ..."); Date t1 = new Date(); - ImageReference imageReference = new ImageReference() - .withPublisher("Canonical") - .withOffer("UbuntuServer") - .withSku("18.04-LTS") - .withVersion("latest"); - - VirtualMachineScaleSet virtualMachineScaleSet = azureResourceManager.virtualMachineScaleSets().define(vmssName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "Front-end") - .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) - .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) - .withoutPrimaryInternalLoadBalancer() - .withSpecificLinuxImageVersion(imageReference) - .withRootUsername(userName) - .withSsh(sshKey) - .withUnmanagedDisks() - .withNewStorageAccount(storageAccountName1) - .withNewStorageAccount(storageAccountName2) - .withNewStorageAccount(storageAccountName3) - .withCapacity(3) - .create(); + ImageReference imageReference = new ImageReference().withPublisher("Canonical") + .withOffer("UbuntuServer") + .withSku("18.04-LTS") + .withVersion("latest"); + + VirtualMachineScaleSet virtualMachineScaleSet = azureResourceManager.virtualMachineScaleSets() + .define(vmssName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "Front-end") + .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) + .withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) + .withoutPrimaryInternalLoadBalancer() + .withSpecificLinuxImageVersion(imageReference) + .withRootUsername(userName) + .withSsh(sshKey) + .withUnmanagedDisks() + .withNewStorageAccount(storageAccountName1) + .withNewStorageAccount(storageAccountName2) + .withNewStorageAccount(storageAccountName3) + .withCapacity(3) + .create(); // VM may take some time to init its pkgs ResourceManagerUtils.sleep(Duration.ofMinutes(1)); virtualMachineScaleSet.update() - // Use a VM extension to install Apache Web servers - .defineNewExtension("CustomScriptForLinux") - .withPublisher("Microsoft.OSTCExtensions") - .withType("CustomScriptForLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .withPublicSetting("fileUris", fileUris) - .withPublicSetting("commandToExecute", installCommand) - .attach() - .apply(); + // Use a VM extension to install Apache Web servers + .defineNewExtension("CustomScriptForLinux") + .withPublisher("Microsoft.OSTCExtensions") + .withType("CustomScriptForLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .withPublicSetting("fileUris", fileUris) + .withPublicSetting("commandToExecute", installCommand) + .attach() + .apply(); Date t2 = new Date(); - System.out.println("Created a virtual machine scale set with " - + "3 Linux VMs & Apache Web servers on them: (took " + System.out.println( + "Created a virtual machine scale set with " + "3 Linux VMs & Apache Web servers on them: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) "); System.out.println(); @@ -254,7 +257,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // List virtual machine scale set network interfaces System.out.println("Listing scale set network interfaces ..."); - PagedIterable vmssNics = virtualMachineScaleSet.listNetworkInterfaces(); + PagedIterable vmssNics + = virtualMachineScaleSet.listNetworkInterfaces(); for (VirtualMachineScaleSetNetworkInterface vmssNic : vmssNics) { System.out.println(vmssNic.id()); } @@ -262,19 +266,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // List virtual machine scale set instance network interfaces and SSH connection string - System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); + System.out + .println("Listing scale set virtual machine instance network interfaces and SSH connection string..."); for (VirtualMachineScaleSetVM instance : virtualMachineScaleSet.virtualMachines().list()) { System.out.println("Scale set virtual machine instance #" + instance.instanceId()); System.out.println(instance.id()); - PagedIterable networkInterfaces = instance.listNetworkInterfaces(); + PagedIterable networkInterfaces + = instance.listNetworkInterfaces(); // Pick the first NIC VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.iterator().next(); - for (VirtualMachineScaleSetNicIpConfiguration ipConfig :networkInterface.ipConfigurations().values()) { + for (VirtualMachineScaleSetNicIpConfiguration ipConfig : networkInterface.ipConfigurations().values()) { if (ipConfig.isPrimary()) { - List natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); + List natRules + = ipConfig.listAssociatedLoadBalancerInboundNatRules(); for (LoadBalancerInboundNatRule natRule : natRules) { if (natRule.backendPort() == 22) { - System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + ":" + natRule.frontendPort()); + System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + + ":" + natRule.frontendPort()); break; } } @@ -290,7 +298,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { virtualMachineScaleSet.powerOff(); System.out.println("Stopped virtual machine scale set"); - //============================================================= // Start the virtual machine scale set @@ -298,21 +305,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { virtualMachineScaleSet.start(); System.out.println("Started virtual machine scale set"); - //============================================================= // Update the virtual machine scale set // - double the no. of virtual machines - System.out.println("Updating virtual machine scale set " - + "- double the no. of virtual machines ..."); - - virtualMachineScaleSet.update() - .withCapacity(6) - .apply(); + System.out.println("Updating virtual machine scale set " + "- double the no. of virtual machines ..."); - System.out.println("Doubled the no. of virtual machines in " - + "the virtual machine scale set"); + virtualMachineScaleSet.update().withCapacity(6).apply(); + System.out.println("Doubled the no. of virtual machines in " + "the virtual machine scale set"); //============================================================= // re-start virtual machine scale set @@ -351,8 +352,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java index 81f12bd834c72..051244a7c74cf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java @@ -56,57 +56,61 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // System.out.println("Creating an empty managed disk"); - Disk dataDisk1 = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withNewResourceGroup(rgName) - .withData() - .withSizeInGB(50) - .create(); + Disk dataDisk1 = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withNewResourceGroup(rgName) + .withData() + .withSizeInGB(50) + .create(); System.out.println("Created managed disk"); // Prepare first creatable data disk // - Creatable dataDiskCreatable1 = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100); + Creatable dataDiskCreatable1 = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100); // Prepare second creatable data disk // - Creatable dataDiskCreatable2 = azureResourceManager.disks().define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(50) - .withSku(DiskSkuTypes.STANDARD_LRS); + Creatable dataDiskCreatable2 = azureResourceManager.disks() + .define(Utils.randomResourceName(azureResourceManager, "dsk-", 15)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(50) + .withSku(DiskSkuTypes.STANDARD_LRS); //====================================================================== // Create a Linux VM using a PIR image with managed OS and Data disks System.out.println("Creating a managed Linux VM"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - - // Begin: Managed data disks - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - .withNewDataDisk(dataDiskCreatable1) - .withNewDataDisk(dataDiskCreatable2, 2, CachingTypes.READ_ONLY) - .withExistingDataDisk(dataDisk1) - - // End: Managed data disks - .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + + // Begin: Managed data disks + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + .withNewDataDisk(dataDiskCreatable1) + .withNewDataDisk(dataDiskCreatable2, 2, CachingTypes.READ_ONLY) + .withExistingDataDisk(dataDisk1) + + // End: Managed data disks + .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) + .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); @@ -118,11 +122,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { String lun3DiskId = linuxVM.dataDisks().get(3).id(); - linuxVM.update() - .withoutDataDisk(3) - .withoutDataDisk(4) - .withNewDataDisk(200) - .apply(); + linuxVM.update().withoutDataDisk(3).withoutDataDisk(4).withNewDataDisk(200).apply(); System.out.println("Updated Linux VM: " + linuxVM.id()); Utils.print(linuxVM); @@ -158,18 +158,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Update OS disk: " + osDisk.id()); - osDisk.update() - .withSizeInGB(2 * osDisk.sizeInGB()) - .apply(); + osDisk.update().withSizeInGB(2 * osDisk.sizeInGB()).apply(); System.out.println("OS disk updated"); for (Disk dataDisk : dataDisks) { System.out.println("Update data disk: " + dataDisk.id()); - dataDisk.update() - .withSizeInGB(dataDisk.sizeInGB() + 10) - .apply(); + dataDisk.update().withSizeInGB(dataDisk.sizeInGB() + 10).apply(); System.out.println("Data disk updated"); } @@ -212,8 +208,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java index 28f533b8361df..eed0e92cdc75f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java @@ -61,62 +61,54 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - VirtualMachine windowsVM = azureResourceManager.virtualMachines().define(windowsVMName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withUnmanagedDisks() - .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) - .create(); + VirtualMachine windowsVM = azureResourceManager.virtualMachines() + .define(windowsVMName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withUnmanagedDisks() + .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) + .create(); Date t2 = new Date(); - System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id()); + System.out + .println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id()); // Print virtual machine details Utils.print(windowsVM); - //============================================================= // Update - Tag the virtual machine - windowsVM.update() - .withTag("who-rocks", "java") - .withTag("where", "on azure") - .apply(); + windowsVM.update().withTag("who-rocks", "java").withTag("where", "on azure").apply(); System.out.println("Tagged VM: " + windowsVM.id()); - //============================================================= // Update - Attach data disks windowsVM.update() - .withNewUnmanagedDataDisk(10) - .defineUnmanagedDataDisk(dataDiskName) - .withNewVhd(20) - .withCaching(CachingTypes.READ_WRITE) - .attach() - .apply(); - + .withNewUnmanagedDataDisk(10) + .defineUnmanagedDataDisk(dataDiskName) + .withNewVhd(20) + .withCaching(CachingTypes.READ_WRITE) + .attach() + .apply(); System.out.println("Attached a new data disk" + dataDiskName + " to VM" + windowsVM.id()); Utils.print(windowsVM); - //============================================================= // Update - detach data disk - windowsVM.update() - .withoutUnmanagedDataDisk(dataDiskName) - .apply(); + windowsVM.update().withoutUnmanagedDataDisk(dataDiskName).apply(); System.out.println("Detached data disk " + dataDiskName + " from VM " + windowsVM.id()); - //============================================================= // Update - Resize (expand) the data disk // First, deallocate the virtual machine and then proceed with resize @@ -129,15 +121,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { VirtualMachineUnmanagedDataDisk dataDisk = windowsVM.unmanagedDataDisks().get(0); - windowsVM.update() - .updateUnmanagedDataDisk(dataDisk.name()) - .withSizeInGB(30) - .parent() - .apply(); + windowsVM.update().updateUnmanagedDataDisk(dataDisk.name()).withSizeInGB(30).parent().apply(); System.out.println("Expanded VM " + windowsVM.id() + "'s data disk to 30GB"); - //============================================================= // Update - Expand the OS drive size by 10 GB @@ -149,13 +136,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { osDiskSizeInGb = 256; } - windowsVM.update() - .withOSDiskSizeInGB(osDiskSizeInGb + 10) - .apply(); + windowsVM.update().withOSDiskSizeInGB(osDiskSizeInGb + 10).apply(); System.out.println("Expanded VM " + windowsVM.id() + "'s OS disk to " + (osDiskSizeInGb + 10)); - //============================================================= // Start the virtual machine @@ -165,7 +149,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Started VM: " + windowsVM.id() + "; state = " + windowsVM.powerState()); - //============================================================= // Restart the virtual machine @@ -175,7 +158,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Restarted VM: " + windowsVM.id() + "; state = " + windowsVM.powerState()); - //============================================================= // Stop (powerOff) the virtual machine @@ -188,25 +170,25 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Get the network where Windows VM is hosted Network network = windowsVM.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); - //============================================================= // Create a Linux VM in the same virtual network System.out.println("Creating a Linux VM in the network"); - VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withUnmanagedDisks() - .withSize(VirtualMachineSizeTypes.STANDARD_B1S) - .create(); + VirtualMachine linuxVM = azureResourceManager.virtualMachines() + .define(linuxVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") // Referencing the default subnet name when no name specified at creation + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withUnmanagedDisks() + .withSize(VirtualMachineSizeTypes.STANDARD_B1S) + .create(); System.out.println("Created a Linux VM (in the same virtual network): " + linuxVM.id()); Utils.print(linuxVM); @@ -218,7 +200,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Printing list of VMs ======="); - for (VirtualMachine virtualMachine : azureResourceManager.virtualMachines().listByResourceGroup(resourceGroupName)) { + for (VirtualMachine virtualMachine : azureResourceManager.virtualMachines() + .listByResourceGroup(resourceGroupName)) { Utils.print(virtualMachine); } @@ -259,8 +242,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java index e80f016bec0ec..e2b68139c358f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java @@ -45,37 +45,38 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); try { // Create a resource group [Where all resources gets created] - ResourceGroup resourceGroup = azureResourceManager.resourceGroups() - .define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); // Prepare Creatable Network definition [Where all the virtual machines get added to] - Creatable creatableNetwork = azureResourceManager.networks().define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("172.16.0.0/16"); + Creatable creatableNetwork = azureResourceManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("172.16.0.0/16"); // Prepare Creatable Storage account definition [For storing VMs disk] - Creatable creatableStorageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable creatableStorageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); // Prepare a batch of Creatable Virtual Machines definitions List> creatableVirtualMachines = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { - Creatable creatableVirtualMachine = azureResourceManager.virtualMachines().define("VM-" + i) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(creatableNetwork) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(creatableStorageAccount); + Creatable creatableVirtualMachine = azureResourceManager.virtualMachines() + .define("VM-" + i) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(creatableNetwork) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(creatableStorageAccount); creatableVirtualMachines.add(creatableVirtualMachine); } @@ -83,7 +84,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating the virtual machines"); stopwatch.start(); - Collection virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); stopwatch.stop(); System.out.println("Created virtual machines"); @@ -106,6 +108,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -121,8 +124,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java index 83fa078ef70d2..962be145b7594 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java @@ -51,20 +51,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a zonal VM with implicitly zoned related resources (PublicIP, Disk)"); VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines() - .define(vmName1) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipName1) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - // Optional - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - // Create VM - .create(); + .define(vmName1) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipName1) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + // Optional + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + // Create VM + .create(); System.out.println("Created a zoned virtual machine: " + virtualMachine1.id()); Utils.print(virtualMachine1); @@ -75,15 +75,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a zonal public ip address"); PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() - .define(pipName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - // Optional - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withStaticIP() - .withSku(PublicIPSkuType.STANDARD) - // Create PIP - .create(); + .define(pipName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + // Optional + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withStaticIP() + .withSku(PublicIPSkuType.STANDARD) + // Create PIP + .create(); System.out.println("Created a zoned public ip address: " + publicIPAddress.id()); Utils.print(publicIPAddress); @@ -94,40 +94,39 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a zonal data disk"); Disk dataDisk = azureResourceManager.disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100) - // Optional - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - // Create Disk - .create(); + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100) + // Optional + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + // Create Disk + .create(); System.out.println("Created a zoned managed data disk: " + dataDisk.id()); //============================================================= // Create a zonal virtual machine with zonal public ip and data disk - System.out.println("Creating a zonal VM with implicitly zoned related resources (PublicIP, Disk)"); VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines() - .define(vmName2) - .withRegion(region) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIPAddress) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - // Optional - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .withExistingDataDisk(dataDisk) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - // Create VM - .create(); + .define(vmName2) + .withRegion(region) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIPAddress) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + // Optional + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .withExistingDataDisk(dataDisk) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + // Create VM + .create(); System.out.println("Created a zoned virtual machine: " + virtualMachine2.id()); Utils.print(virtualMachine2); @@ -162,8 +161,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java index 5e008ea2e35b3..0c7d3e493a97b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java @@ -57,10 +57,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sshPublicKey = Utils.sshPublicKey(); try { - ResourceGroup resourceGroup = azureResourceManager.resourceGroups() - .define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); //============================================================= // Create a zone resilient PublicIP address @@ -68,15 +66,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a zone resilient public ip address"); PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() - .define(publicIPName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(publicIPName) - // Optionals - .withStaticIP() - .withSku(PublicIPSkuType.STANDARD) - // Create PublicIP - .create(); + .define(publicIPName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(publicIPName) + // Optionals + .withStaticIP() + .withSku(PublicIPSkuType.STANDARD) + // Create PublicIP + .create(); System.out.println("Created a zone resilient public ip address: " + publicIPAddress.id()); Utils.print(publicIPAddress); @@ -87,51 +85,51 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a zone resilient load balancer"); LoadBalancer loadBalancer = azureResourceManager.loadBalancers() - .define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule("httpRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe("httpProbe") - .attach() - .defineLoadBalancingRule("httpsRule") - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe("httpsProbe") - .attach() - // Add two nat pools to enable direct VMSS connectivity to port SSH and 23 - .defineInboundNatPool(natPoolName1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(5000, 5099) - .toBackendPort(22) - .attach() - .defineInboundNatPool(natPoolName2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPortRange(6000, 6099) - .toBackendPort(23) - .attach() - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer - .attach() - // Add two probes one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - .defineHttpProbe("httpsProbe") - .withRequestPath("/") - .attach() - .withSku(LoadBalancerSkuType.STANDARD) - .create(); + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule("httpRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe("httpProbe") + .attach() + .defineLoadBalancingRule("httpsRule") + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe("httpsProbe") + .attach() + // Add two nat pools to enable direct VMSS connectivity to port SSH and 23 + .defineInboundNatPool(natPoolName1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(5000, 5099) + .toBackendPort(22) + .attach() + .defineInboundNatPool(natPoolName2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPortRange(6000, 6099) + .toBackendPort(23) + .attach() + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) // Frontend with PIP means internet-facing load-balancer + .attach() + // Add two probes one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + .defineHttpProbe("httpsProbe") + .withRequestPath("/") + .attach() + .withSku(LoadBalancerSkuType.STANDARD) + .create(); System.out.println("Created a zone resilient load balancer: " + publicIPAddress.id()); Utils.print(loadBalancer); @@ -147,14 +145,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating network for virtual machine scale sets"); - Network network = azureResourceManager - .networks() - .define("vmssvnet") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/28") - .create(); + Network network = azureResourceManager.networks() + .define("vmssvnet") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/28") + .create(); System.out.println("Created network for virtual machine scale sets"); Utils.print(network); @@ -167,20 +164,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // HTTP goes to this virtual machine scale set // VirtualMachineScaleSet virtualMachineScaleSet1 = azureResourceManager.virtualMachineScaleSets() - .define(vmssName1) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0)) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(0)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .create(); + .define(vmssName1) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(0)) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(0)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .create(); System.out.println("Created zone aware virtual machine scale set: " + virtualMachineScaleSet1.id()); @@ -192,20 +189,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // HTTPS goes to this virtual machine scale set // VirtualMachineScaleSet virtualMachineScaleSet2 = azureResourceManager.virtualMachineScaleSets() - .define(vmssName2) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) - .withExistingPrimaryNetworkSubnet(network, "subnet1") - .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer) - .withPrimaryInternetFacingLoadBalancerBackends(backends.get(1)) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(1)) - .withoutPrimaryInternalLoadBalancer() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshPublicKey) - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .create(); + .define(vmssName2) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2) + .withExistingPrimaryNetworkSubnet(network, "subnet1") + .withExistingPrimaryInternetFacingLoadBalancer(loadBalancer) + .withPrimaryInternetFacingLoadBalancerBackends(backends.get(1)) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.get(1)) + .withoutPrimaryInternalLoadBalancer() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshPublicKey) + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .create(); System.out.println("Created zone aware virtual machine scale set: " + virtualMachineScaleSet2.id()); @@ -238,8 +235,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java index 579db3534dc75..57f855d48cd5c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java @@ -47,17 +47,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously // as read/write shared container volume. - ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + ContainerGroup containerGroup = azureResourceManager.containerGroups() + .define(aciName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withLinux() .withPublicImageRegistryOnly() .withNewAzureFileShareVolume(volumeMountName, shareName) .defineContainerInstance(aciName) - .withImage(containerImageName) - .withExternalTcpPort(80) - .withVolumeMountSetting(volumeMountName, "/aci/logs/") - .attach() + .withImage(containerImageName) + .withExternalTcpPort(80) + .withVolumeMountSetting(volumeMountName, "/aci/logs/") + .attach() .withDnsPrefix(aciName) .create(); @@ -83,15 +84,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // List the file share content String storageAccountName = containerGroup.volumes().get(volumeMountName).azureFile().storageAccountName(); - StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); - ShareClient shareClient = new ShareClientBuilder() - .connectionString(ResourceManagerUtils.getStorageConnectionString( - storageAccountName, - storageAccount.getKeys().get(0).value(), - azureResourceManager.containerGroups().manager().environment() - )) - .shareName(shareName) - .buildClient(); + StorageAccount storageAccount + = azureResourceManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); + ShareClient shareClient + = new ShareClientBuilder() + .connectionString(ResourceManagerUtils.getStorageConnectionString(storageAccountName, + storageAccount.getKeys().get(0).value(), + azureResourceManager.containerGroups().manager().environment())) + .shareName(shareName) + .buildClient(); Iterable shareContent = shareClient.getRootDirectoryClient().listFilesAndDirectories(); @@ -133,8 +134,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java index 5ee66d3c79b43..dd0cd2f5dfeec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java @@ -48,21 +48,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create a new storage account and an Azure file share resource - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .create(); StorageAccountKey storageAccountKey = storageAccount.getKeys().get(0); - ShareClient shareClient = new ShareClientBuilder() - .connectionString(ResourceManagerUtils.getStorageConnectionString( - saName, - storageAccountKey.value(), - azureResourceManager.containerGroups().manager().environment() - )) - .shareName(shareName) - .buildClient(); + ShareClient shareClient + = new ShareClientBuilder() + .connectionString(ResourceManagerUtils.getStorageConnectionString(saName, storageAccountKey.value(), + azureResourceManager.containerGroups().manager().environment())) + .shareName(shareName) + .buildClient(); shareClient.create(); //============================================================= @@ -70,21 +69,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously // as read/write shared container volume. - ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + ContainerGroup containerGroup = azureResourceManager.containerGroups() + .define(aciName) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withLinux() .withPublicImageRegistryOnly() .defineVolume(volumeMountName) - .withExistingReadWriteAzureFileShare(shareName) - .withStorageAccountName(saName) - .withStorageAccountKey(storageAccountKey.value()) - .attach() + .withExistingReadWriteAzureFileShare(shareName) + .withStorageAccountName(saName) + .withStorageAccountKey(storageAccountKey.value()) + .attach() .defineContainerInstance(aciName) - .withImage(containerImageName) - .withExternalTcpPort(80) - .withVolumeMountSetting(volumeMountName, "/aci/logs/") - .attach() + .withImage(containerImageName) + .withExternalTcpPort(80) + .withVolumeMountSetting(volumeMountName, "/aci/logs/") + .attach() .withDnsPrefix(aciName) .create(); @@ -149,8 +149,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java index 420ebe47f40ab..0009a871b6d90 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java @@ -42,24 +42,25 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create a container group with two container instances - ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + ContainerGroup containerGroup = azureResourceManager.containerGroups() + .define(aciName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withLinux() .withPublicImageRegistryOnly() .withoutVolume() .defineContainerInstance(aciName + "-1") - .withImage(containerImageName1) - .withExternalTcpPort(80) - .withCpuCoreCount(.5) - .withMemorySizeInGB(0.8) - .attach() + .withImage(containerImageName1) + .withExternalTcpPort(80) + .withCpuCoreCount(.5) + .withMemorySizeInGB(0.8) + .attach() .defineContainerInstance(aciName + "-2") - .withImage(containerImageName2) - .withoutPorts() - .withCpuCoreCount(.5) - .withMemorySizeInGB(0.8) - .attach() + .withImage(containerImageName2) + .withoutPorts() + .withCpuCoreCount(.5) + .withMemorySizeInGB(0.8) + .attach() .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) .withDnsPrefix(aciName) .create(); @@ -118,8 +119,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java index e1a9669eb4e4d..1c0ffc61119d4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java @@ -89,7 +89,8 @@ public class ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOr * @param secret secondary service principal secret * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, InterruptedException, JSchException { + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) + throws IOException, InterruptedException, JSchException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgaci", 15); final Region region = Region.US_EAST2; @@ -116,7 +117,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin Date t1 = new Date(); - Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + Registry azureRegistry = azureResourceManager.containerRegistries() + .define(acrName) .withRegion(region) .withNewResourceGroup(rgName) .withBasicSku() @@ -124,16 +126,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); - //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + DockerClient dockerClient + = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image @@ -150,13 +153,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } - CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(containerImageName + ":" + containerImageTag) - .withName(dockerContainerName) - .exec(); + CreateContainerResponse dockerContainerInstance + = dockerClient.createContainerCmd(containerImageName + ":" + containerImageTag) + .withName(dockerContainerName) + .exec(); System.out.println("List Docker containers:"); - List dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) - .exec(); + List dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } @@ -167,19 +169,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl) - .withTag("latest").exec(); + .withTag("latest") + .exec(); // We can now remove the temporary container instance - dockerClient.removeContainerCmd(dockerContainerInstance.getId()) - .withForce(true) - .exec(); + dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry dockerClient.pushImageCmd(privateRepoUrl) .withAuthConfig(dockerClient.authConfig()) - .exec(new PushImageResultCallback()).awaitSuccess(); + .exec(new PushImageResultCallback()) + .awaitSuccess(); // Remove the temp image from the local Docker host try { @@ -193,16 +195,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // using public Docker image "microsoft/aci-helloworld" and mounts a new file share as read/write // shared container volume. - ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + ContainerGroup containerGroup = azureResourceManager.containerGroups() + .define(aciName) .withRegion(region) .withNewResourceGroup(rgName) .withLinux() - .withPrivateImageRegistry(azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withPrivateImageRegistry(azureRegistry.loginServerUrl(), acrCredentials.username(), + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .withoutVolume() .defineContainerInstance(aciName) - .withImage(privateRepoUrl) - .withExternalTcpPort(80) - .attach() + .withImage(privateRepoUrl) + .withExternalTcpPort(80) + .attach() .withDnsPrefix(aciName) .create(); @@ -230,13 +234,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // // If the environment variable was not set then reuse the main service principal set for running this sample. - if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + if (servicePrincipalClientId == null + || servicePrincipalClientId.isEmpty() + || servicePrincipalSecret == null + || servicePrincipalSecret.isEmpty()) { servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); - if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + if (servicePrincipalClientId == null + || servicePrincipalClientId.isEmpty() + || servicePrincipalSecret == null + || servicePrincipalSecret.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); - if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + if (envSecondaryServicePrincipal == null + || !envSecondaryServicePrincipal.isEmpty() + || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } @@ -245,7 +257,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin } } - //============================================================= // Create an SSH private/public key pair to be used when creating the container service @@ -255,15 +266,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); - //============================================================= // Create an Azure Container Service with Kubernetes orchestration - System.out.println("Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); + System.out.println( + "Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); t1 = new Date(); - KubernetesCluster azureKubernetesCluster = azureResourceManager.kubernetesClusters().define(acsName) + KubernetesCluster azureKubernetesCluster = azureResourceManager.kubernetesClusters() + .define(acsName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() @@ -272,21 +284,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withServicePrincipalClientId(servicePrincipalClientId) .withServicePrincipalSecret(servicePrincipalSecret) .defineAgentPool("agentpool") - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) -// .withDnsPrefix("dns-ap-" + acsName) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + // .withDnsPrefix("dns-ap-" + acsName) + .attach() .withDnsPrefix("dns-" + acsName) .create(); t2 = new Date(); - System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureKubernetesCluster.id()); + System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureKubernetesCluster.id()); Utils.print(azureKubernetesCluster); ResourceManagerUtils.sleep(Duration.ofMinutes(2)); - //============================================================= // Download the Kubernetes config file from one of the master virtual machines @@ -296,15 +308,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin byte[] kubeConfigContent = azureKubernetesCluster.adminKubeConfigContent(); System.out.println("Found Kubernetes config:%n" + Arrays.toString(kubeConfigContent)); - //============================================================= // Instantiate the Kubernetes client using the downloaded ".kube/config" file content // The Kubernetes client API requires setting an environment variable pointing at a real file; // we will create a temporary file that will be deleted automatically when the sample exits - File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); + File tempKubeConfigFile + = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); tempKubeConfigFile.deleteOnExit(); - try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { + try (BufferedWriter buffOut = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); } @@ -315,21 +328,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Wait for 15 minutes for kube endpoint to be available ResourceManagerUtils.sleep(Duration.ofMinutes(15)); - //============================================================= // List all the nodes available in the Kubernetes cluster System.out.println(kubernetesClient.nodes().list()); - //============================================================= // Create a namespace where all the sample Kubernetes resources will be created - Namespace ns = new NamespaceBuilder() - .withNewMetadata() - .withName(acsNamespace) - .addToLabels("acr", "sample") - .endMetadata() + Namespace ns = new NamespaceBuilder().withNewMetadata() + .withName(acsNamespace) + .addToLabels("acr", "sample") + .endMetadata() .build(); try { System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); @@ -342,29 +352,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); } - //============================================================= // Create a secret of type "docker-repository" that will be used for downloading the container image from // our Azure private container repo - String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + String basicAuth = new String(Base64 + .encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .getBytes(StandardCharsets.UTF_8)), + StandardCharsets.UTF_8); HashMap secretData = new HashMap<>(1); String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", - azureRegistry.loginServerUrl(), - basicAuth, - "acrsample@azure.com"); + azureRegistry.loginServerUrl(), basicAuth, "acrsample@azure.com"); dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); secretData.put(".dockercfg", dockerCfg); - SecretBuilder secretBuilder = new SecretBuilder() - .withNewMetadata() - .withName(acsSecretName) - .withNamespace(acsNamespace) - .endMetadata() + SecretBuilder secretBuilder = new SecretBuilder().withNewMetadata() + .withName(acsSecretName) + .withNamespace(acsNamespace) + .endMetadata() .withData(secretData) .withType("kubernetes.io/dockercfg"); - System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build())); + System.out.println("Creating new secret: " + + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build())); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); @@ -372,37 +382,36 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound secret: " + kubeS); } - //============================================================= // Create a replication controller for our image stored in the Azure Container Registry - ReplicationController rc = new ReplicationControllerBuilder() + ReplicationController rc = new ReplicationControllerBuilder().withNewMetadata() + .withName("acrsample-rc") + .withNamespace(acsNamespace) + .addToLabels("acrsample-myimg", "myimg") + .endMetadata() + .withNewSpec() + .withReplicas(2) + .withNewTemplate() .withNewMetadata() - .withName("acrsample-rc") - .withNamespace(acsNamespace) - .addToLabels("acrsample-myimg", "myimg") - .endMetadata() + .addToLabels("acrsample-myimg", "myimg") + .endMetadata() .withNewSpec() - .withReplicas(2) - .withNewTemplate() - .withNewMetadata() - .addToLabels("acrsample-myimg", "myimg") - .endMetadata() - .withNewSpec() - .addNewImagePullSecret(acsSecretName) - .addNewContainer() - .withName("acrsample-pod-myimg") - .withImage(privateRepoUrl) - .addNewPort() - .withContainerPort(80) - .endPort() - .endContainer() - .endSpec() - .endTemplate() - .endSpec() + .addNewImagePullSecret(acsSecretName) + .addNewContainer() + .withName("acrsample-pod-myimg") + .withImage(privateRepoUrl) + .addNewPort() + .withContainerPort(80) + .endPort() + .endContainer() + .endSpec() + .endTemplate() + .endSpec() .build(); - System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc)); + System.out.println("Creating a replication controller: " + + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc)); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get(); @@ -412,31 +421,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound Kubernetes pods: " + pod.toString()); } - //============================================================= // Create a Load Balancer service that will expose the service to the world - Service lbService = new ServiceBuilder() - .withNewMetadata() - .withName(acsLbIngressName) - .withNamespace(acsNamespace) - .endMetadata() + Service lbService = new ServiceBuilder().withNewMetadata() + .withName(acsLbIngressName) + .withNamespace(acsNamespace) + .endMetadata() .withNewSpec() - .withType("LoadBalancer") - .addNewPort() - .withPort(80) - .withProtocol("TCP") - .endPort() - .addToSelector("acrsample-myimg", "myimg") - .endSpec() + .withType("LoadBalancer") + .addNewPort() + .withPort(80) + .withProtocol("TCP") + .endPort() + .addToSelector("acrsample-myimg", "myimg") + .endSpec() .build(); - System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(acsNamespace).create(lbService)); + System.out.println( + "Creating a service: " + kubernetesClient.services().inNamespace(acsNamespace).create(lbService)); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); - System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get()); - + System.out.println("\tFound service: " + + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get()); //============================================================= // Wait until the external IP becomes available @@ -448,8 +456,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin while (timeout > 0) { try { - List lbIngressList = kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress(); - if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { + List lbIngressList = kubernetesClient.services() + .inNamespace(acsNamespace) + .withName(acsLbIngressName) + .get() + .getStatus() + .getLoadBalancer() + .getIngress(); + if (lbIngressList != null + && !lbIngressList.isEmpty() + && lbIngressList.get(0) != null + && lbIngressList.get(0).getIp().matches(matchIPV4)) { serviceIP = lbIngressList.get(0).getIp(); System.out.println("\tFound ingress IP: " + serviceIP); timeout = 0; @@ -510,8 +527,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java index 6c9c8799c6537..7cb21b6892051 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java @@ -62,48 +62,49 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw Date t1 = new Date(); - Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withBasicSku() - .withRegistryNameAsAdminUser() - .create(); + Registry azureRegistry = azureResourceManager.containerRegistries() + .define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); - //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + DockerClient dockerClient + = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR dockerClient.pullImageCmd(dockerImageName) - .withTag(dockerImageTag) - .withAuthConfig(new AuthConfig()) // anonymous - .exec(new PullImageResultCallback()) - .awaitSuccess(); + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) // anonymous + .exec(new PullImageResultCallback()) + .awaitSuccess(); System.out.println("List local Docker images:"); List images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } - CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + CreateContainerResponse dockerContainerInstance + = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) .withName(dockerContainerName) .withCmd("/hello") .exec(); System.out.println("List Docker containers:"); - List dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) - .exec(); + List dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } @@ -114,18 +115,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl) - .withTag("latest").exec(); + .withTag("latest") + .exec(); // We can now remove the temporary container instance - dockerClient.removeContainerCmd(dockerContainerInstance.getId()) - .withForce(true) - .exec(); + dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry - dockerClient.pushImageCmd(privateRepoUrl) - .exec(new PushImageResultCallback()).awaitSuccess(); + dockerClient.pushImageCmd(privateRepoUrl).exec(new PushImageResultCallback()).awaitSuccess(); // Remove the temp image from the local Docker host try { @@ -138,22 +137,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally dockerClient.pullImageCmd(privateRepoUrl) - .withAuthConfig(dockerClient.authConfig()) - .exec(new PullImageResultCallback()).awaitSuccess(); - System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); - images = dockerClient.listImagesCmd() - .withShowAll(true) - .exec(); + .withAuthConfig(dockerClient.authConfig()) + .exec(new PullImageResultCallback()) + .awaitSuccess(); + System.out + .println("List local Docker images after pulling sample image from the Azure Container Registry:"); + images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } dockerClient.createContainerCmd(privateRepoUrl) .withName(dockerContainerName + "-private") - .withCmd("/hello").exec(); - System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); - dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) - .exec(); + .withCmd("/hello") + .exec(); + System.out.println( + "List Docker containers after instantiating container from the Azure Container Registry sample image:"); + dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } @@ -187,8 +186,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java index 5ab1062127efb..17eb1655fefd8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java @@ -49,7 +49,8 @@ public class ManageContainerRegistryWithWebhooks { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, InterruptedException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); final Region region = Region.US_WEST3; @@ -61,7 +62,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw final String webhookServiceUri1 = "https://www.bing.com"; final String webhookServiceUri2 = "https://www.bing.com"; - try { //============================================================= // Create an Azure Container Registry to store and manage private Docker container images @@ -70,38 +70,40 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw Date t1 = new Date(); - Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + Registry azureRegistry = azureResourceManager.containerRegistries() + .define(acrName) .withRegion(region) .withNewResourceGroup(rgName) .withBasicSku() .withRegistryNameAsAdminUser() .defineWebhook(webhookName1) - .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) - .withServiceUri(webhookServiceUri1) - .withTag("tag", "value") - .withCustomHeader("name", "value") - .attach() + .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) + .withServiceUri(webhookServiceUri1) + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() .defineWebhook(webhookName2) - .withTriggerWhen(WebhookAction.PUSH) - .withServiceUri(webhookServiceUri2) - .enabled(false) - .withRepositoriesScope("") - .attach() + .withTriggerWhen(WebhookAction.PUSH) + .withServiceUri(webhookServiceUri2) + .enabled(false) + .withRepositoriesScope("") + .attach() .withTag("tag1", "value1") .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); - //============================================================= // Ping the container registry webhook to validate it works as expected Webhook webhook = azureRegistry.webhooks().get(webhookName1); webhook.ping(); List webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); - System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); + System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), + webhook.name(), azureRegistry.name()); for (WebhookEventInfo webhookEventInfo : webhookEvents) { System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); } @@ -110,8 +112,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + DockerClient dockerClient + = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image @@ -128,14 +131,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } - CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) - .withName(dockerContainerName) - .withCmd("/hello") - .exec(); + CreateContainerResponse dockerContainerInstance + = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .withCmd("/hello") + .exec(); System.out.println("List Docker containers:"); - List dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) - .exec(); + List dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } @@ -146,19 +148,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl) - .withTag("latest").exec(); + .withTag("latest") + .exec(); // We can now remove the temporary container instance - dockerClient.removeContainerCmd(dockerContainerInstance.getId()) - .withForce(true) - .exec(); + dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry dockerClient.pushImageCmd(privateRepoUrl) .withAuthConfig(dockerClient.authConfig()) - .exec(new PushImageResultCallback()).awaitSuccess(); + .exec(new PushImageResultCallback()) + .awaitSuccess(); // Remove the temp image from the local Docker host try { @@ -172,7 +174,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw webhook = azureRegistry.webhooks().get(webhookName1); webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); - System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); + System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), + webhook.name(), azureRegistry.name()); for (WebhookEventInfo webhookEventInfo : webhookEvents) { System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); } @@ -206,8 +209,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java index af137011c3eee..ba6db3d4debcb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.cosmos.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -45,29 +44,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a virtual network with two subnets. System.out.println("Create a virtual network with two subnets: subnet1 and subnet2"); - Network virtualNetwork = azureResourceManager.networks().define(vnetName) + Network virtualNetwork = azureResourceManager.networks() + .define(vnetName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAddressSpace("192.168.0.0/16") .defineSubnet("subnet1") - .withAddressPrefix("192.168.1.0/24") - .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) - .attach() + .withAddressPrefix("192.168.1.0/24") + .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) + .attach() .defineSubnet("subnet2") - .withAddressPrefix("192.168.2.0/24") - .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) - .attach() + .withAddressPrefix("192.168.2.0/24") + .withAccessFromService(ServiceEndpointType.MICROSOFT_AZURECOSMOSDB) + .attach() .create(); System.out.println("Created a virtual network"); // Print the virtual network details Utils.print(virtualNetwork); - //============================================================ // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(docDBName) + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(docDBName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withDataModelAzureTable() @@ -79,7 +79,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); - // ============================================================ // Get the virtual network rule created above. List vnetRules = cosmosDBAccount.virtualNetworkRules(); @@ -89,13 +88,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("\t" + vnetRule.id()); } - // ============================================================ // Add new virtual network rules. - cosmosDBAccount.update() - .withVirtualNetwork(virtualNetwork.id(), "subnet2") - .apply(); - + cosmosDBAccount.update().withVirtualNetwork(virtualNetwork.id(), "subnet2").apply(); // ============================================================ // List then remove all virtual network rules. @@ -108,13 +103,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("\t" + vnetRule.id()); } - cosmosDBAccount.update() - .withVirtualNetworkRules(null) - .apply(); + cosmosDBAccount.update().withVirtualNetworkRules(null).apply(); azureResourceManager.networks().deleteById(virtualNetwork.id()); - //============================================================ // Delete CosmosDB System.out.println("Deleting the CosmosDB"); @@ -154,8 +146,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java index 6beb010f8af11..540e00230ba48 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.cosmos.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -48,14 +47,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a CosmosDB. System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(docDBName) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) - .withEventualConsistency() - .withWriteReplication(Region.US_EAST) - .withReadReplication(Region.US_WEST3) - .create(); + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(docDBName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) + .withEventualConsistency() + .withWriteReplication(Region.US_EAST) + .withReadReplication(Region.US_WEST3) + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); @@ -100,8 +100,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { private static void createDBAndAddCollection(String masterKey, String endPoint) { try { - CosmosClient cosmosClient = new CosmosClientBuilder() - .endpoint(endPoint) + CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(endPoint) .key(masterKey) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) @@ -136,8 +135,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java index a99ea16fccae3..0d33b97c69f63 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java @@ -38,17 +38,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(docDBName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) - .withSessionConsistency() - .withWriteReplication(Region.US_WEST) - .withReadReplication(Region.US_WEST3) - .withIpRules(Arrays.asList( - new IpAddressOrRange().withIpAddressOrRange("13.91.6.132"), - new IpAddressOrRange().withIpAddressOrRange("13.91.6.1/24"))) - .create(); + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(docDBName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) + .withSessionConsistency() + .withWriteReplication(Region.US_WEST) + .withReadReplication(Region.US_WEST3) + .withIpRules(Arrays.asList(new IpAddressOrRange().withIpAddressOrRange("13.91.6.132"), + new IpAddressOrRange().withIpAddressOrRange("13.91.6.1/24"))) + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); @@ -92,8 +92,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java index c8d5f89ee6efe..b0ee882f77bd5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.cosmos.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -41,22 +40,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(docDBName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withKind(DatabaseAccountKind.MONGO_DB) - .withEventualConsistency() - .withWriteReplication(Region.US_WEST) - .withReadReplication(Region.US_WEST3) - .create(); + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(docDBName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.MONGO_DB) + .withEventualConsistency() + .withWriteReplication(Region.US_WEST) + .withReadReplication(Region.US_WEST3) + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); System.out.println("Get the MongoDB connection string"); - DatabaseAccountListConnectionStringsResult databaseAccountListConnectionStringsResult = cosmosDBAccount.listConnectionStrings(); + DatabaseAccountListConnectionStringsResult databaseAccountListConnectionStringsResult + = cosmosDBAccount.listConnectionStrings(); System.out.println("MongoDB connection string: " - + databaseAccountListConnectionStringsResult.connectionStrings().get(0).connectionString()); + + databaseAccountListConnectionStringsResult.connectionStrings().get(0).connectionString()); //============================================================ // Delete CosmosDB @@ -97,8 +98,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java index a934db775397d..993ba40b4727f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.cosmos.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -49,14 +48,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a CosmosDB System.out.println("Creating a CosmosDB..."); - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(docDBName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) - .withSessionConsistency() - .withWriteReplication(Region.US_WEST) - .withReadReplication(Region.US_WEST3) - .create(); + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(docDBName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) + .withSessionConsistency() + .withWriteReplication(Region.US_WEST) + .withReadReplication(Region.US_WEST3) + .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); @@ -66,10 +66,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating CosmosDB with three additional read replication regions"); cosmosDBAccount = cosmosDBAccount.update() - .withReadReplication(Region.ASIA_EAST) - .withReadReplication(Region.AUSTRALIA_SOUTHEAST) - .withReadReplication(Region.UK_SOUTH) - .apply(); + .withReadReplication(Region.ASIA_EAST) + .withReadReplication(Region.AUSTRALIA_SOUTHEAST) + .withReadReplication(Region.UK_SOUTH) + .apply(); System.out.println("Updated CosmosDB"); Utils.print(cosmosDBAccount); @@ -114,8 +114,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { private static void createDBAndAddCollection(String masterKey, String endPoint) { try { - CosmosClient cosmosClient = new CosmosClientBuilder() - .endpoint(endPoint) + CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(endPoint) .key(masterKey) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) @@ -150,8 +149,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java index fc024f4a23a51..5970f8daf4b96 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java @@ -50,22 +50,22 @@ public class ManageDns { * @return true if sample runs successfully */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { - final String customDomainName = "THE CUSTOM DOMAIN THAT YOU OWN (e.g. contoso.com)"; - final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); - final String webAppName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String customDomainName = "THE CUSTOM DOMAIN THAT YOU OWN (e.g. contoso.com)"; + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String webAppName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); try { - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST2) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create(); //============================================================ // Creates root DNS Zone System.out.println("Creating root DNS zone " + customDomainName + "..."); - DnsZone rootDnsZone = azureResourceManager.dnsZones().define(customDomainName) - .withExistingResourceGroup(resourceGroup) - .create(); + DnsZone rootDnsZone = azureResourceManager.dnsZones() + .define(customDomainName) + .withExistingResourceGroup(resourceGroup) + .create(); System.out.println("Created root DNS zone " + rootDnsZone.name()); Utils.print(rootDnsZone); @@ -75,7 +75,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // source for name resolution for the zone System.out.println("Go to your registrar portal and configure your domain " + customDomainName - + " with following name server addresses"); + + " with following name server addresses"); for (String nameServer : rootDnsZone.nameServers()) { System.out.println(" " + nameServer); } @@ -86,15 +86,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Creates a web App System.out.println("Creating Web App " + webAppName + "..."); - WebApp webApp = azureResourceManager.webApps().define(webAppName) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.BASIC_B1) - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") - .withBranch("master") - .attach() - .create(); + WebApp webApp = azureResourceManager.webApps() + .define(webAppName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.BASIC_B1) + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); System.out.println("Created web app " + webAppName); Utils.print(webApp); @@ -105,9 +106,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // alias for www.[customDomainName] System.out.println("Updating DNS zone by adding a CName record..."); - rootDnsZone = rootDnsZone.update() - .withCNameRecordSet("www", webApp.defaultHostname()) - .apply(); + rootDnsZone = rootDnsZone.update().withCNameRecordSet("www", webApp.defaultHostname()).apply(); System.out.println("DNS zone updated"); Utils.print(rootDnsZone); @@ -120,12 +119,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Updating Web app with host name binding..."); webApp.update() - .defineHostnameBinding() - .withThirdPartyDomain(customDomainName) - .withSubDomain("www") - .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) - .attach() - .apply(); + .defineHostnameBinding() + .withThirdPartyDomain(customDomainName) + .withSubDomain("www") + .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) + .attach() + .apply(); System.out.println("Web app updated"); Utils.print(webApp); @@ -134,17 +133,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a virtual machine with public IP..."); VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines() - .define(Utils.randomResourceName(azureResourceManager, "employeesvm-", 20)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(Utils.randomResourceName(azureResourceManager, "empip-", 20)) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword("fakePasswordPlaceholder") - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + .define(Utils.randomResourceName(azureResourceManager, "employeesvm-", 20)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(Utils.randomResourceName(azureResourceManager, "empip-", 20)) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword("fakePasswordPlaceholder") + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Virtual machine created"); //============================================================ @@ -153,28 +152,25 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw PublicIpAddress vm1PublicIpAddress = virtualMachine1.getPrimaryPublicIPAddress(); System.out.println("Updating root DNS zone " + customDomainName + "..."); rootDnsZone = rootDnsZone.update() - .defineARecordSet("employees") - .withIPv4Address(vm1PublicIpAddress.ipAddress()) - .attach() - .apply(); + .defineARecordSet("employees") + .withIPv4Address(vm1PublicIpAddress.ipAddress()) + .attach() + .apply(); System.out.println("Updated root DNS zone " + rootDnsZone.name()); Utils.print(rootDnsZone); // Prints the CName and A Records in the root DNS zone // System.out.println("Getting CName record set in the root DNS zone " + customDomainName + "..."); - PagedIterable cnameRecordSets = rootDnsZone - .cNameRecordSets() - .list(); + PagedIterable cnameRecordSets = rootDnsZone.cNameRecordSets().list(); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { - System.out.println("Name: " + cnameRecordSet.name() + " Canonical Name: " + cnameRecordSet.canonicalName()); + System.out + .println("Name: " + cnameRecordSet.name() + " Canonical Name: " + cnameRecordSet.canonicalName()); } System.out.println("Getting ARecord record set in the root DNS zone " + customDomainName + "..."); - PagedIterable aRecordSets = rootDnsZone - .aRecordSets() - .list(); + PagedIterable aRecordSets = rootDnsZone.aRecordSets().list(); for (ARecordSet aRecordSet : aRecordSets) { System.out.println("Name: " + aRecordSet.name()); @@ -186,11 +182,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Creates a child DNS zone - String partnerSubDomainName = "partners." + customDomainName; + String partnerSubDomainName = "partners." + customDomainName; System.out.println("Creating child DNS zone " + partnerSubDomainName + "..."); - DnsZone partnersDnsZone = azureResourceManager.dnsZones().define(partnerSubDomainName) - .withExistingResourceGroup(resourceGroup) - .create(); + DnsZone partnersDnsZone = azureResourceManager.dnsZones() + .define(partnerSubDomainName) + .withExistingResourceGroup(resourceGroup) + .create(); System.out.println("Created child DNS zone " + partnersDnsZone.name()); Utils.print(partnersDnsZone); @@ -198,16 +195,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Adds NS records in the root dns zone to delegate partners.[customDomainName] to child dns zone System.out.println("Updating root DNS zone " + rootDnsZone + "..."); - DnsRecordSet.UpdateDefinitionStages.WithNSRecordNameServerOrAttachable nsRecordStage = rootDnsZone - .update() - .defineNSRecordSet("partners") - .withNameServer(partnersDnsZone.nameServers().get(0)); + DnsRecordSet.UpdateDefinitionStages.WithNSRecordNameServerOrAttachable nsRecordStage + = rootDnsZone.update() + .defineNSRecordSet("partners") + .withNameServer(partnersDnsZone.nameServers().get(0)); for (int i = 1; i < partnersDnsZone.nameServers().size(); i++) { nsRecordStage = nsRecordStage.withNameServer(partnersDnsZone.nameServers().get(i)); } - nsRecordStage - .attach() - .apply(); + nsRecordStage.attach().apply(); System.out.println("Root DNS zone updated"); Utils.print(rootDnsZone); @@ -216,17 +211,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a virtual machine with public IP..."); VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines() - .define(Utils.randomResourceName(azureResourceManager, "partnersvm-", 20)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(Utils.randomResourceName(azureResourceManager, "ptnerpip-", 20)) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword("fakePasswordPlaceholder") - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + .define(Utils.randomResourceName(azureResourceManager, "partnersvm-", 20)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(Utils.randomResourceName(azureResourceManager, "ptnerpip-", 20)) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword("fakePasswordPlaceholder") + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Virtual machine created"); //============================================================ @@ -235,10 +230,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw PublicIpAddress vm2PublicIpAddress = virtualMachine2.getPrimaryPublicIPAddress(); System.out.println("Updating child DNS zone " + partnerSubDomainName + "..."); partnersDnsZone = partnersDnsZone.update() - .defineARecordSet("@") - .withIPv4Address(vm2PublicIpAddress.ipAddress()) - .attach() - .apply(); + .defineARecordSet("@") + .withIPv4Address(vm2PublicIpAddress.ipAddress()) + .attach() + .apply(); System.out.println("Updated child DNS zone " + partnersDnsZone.name()); Utils.print(partnersDnsZone); @@ -246,9 +241,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Removes A record entry from the root DNS zone System.out.println("Removing A Record from root DNS zone " + rootDnsZone.name() + "..."); - rootDnsZone = rootDnsZone.update() - .withoutARecordSet("employees") - .apply(); + rootDnsZone = rootDnsZone.update().withoutARecordSet("employees").apply(); System.out.println("Removed A Record from root DNS zone"); Utils.print(rootDnsZone); @@ -287,8 +280,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java index 4b864b7a212e2..aa3399047f612 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java @@ -186,8 +186,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java index 5e90f9f65c6e9..b1fc9e46d5c46 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java @@ -68,7 +68,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { .withNewEventHub(eventHubName) .create(); - System.out.println(String.format("Created event hub namespace %s and event hub %s ", namespace.name(), eventHubName)); + System.out.println( + String.format("Created event hub namespace %s and event hub %s ", namespace.name(), eventHubName)); System.out.println(); Utils.print(namespace); @@ -78,7 +79,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Retrieving the namespace authorization rule"); - EventHubNamespaceAuthorizationRule eventHubAuthRule = azureResourceManager.eventHubNamespaces().authorizationRules() + EventHubNamespaceAuthorizationRule eventHubAuthRule = azureResourceManager.eventHubNamespaces() + .authorizationRules() .getByName(namespace.resourceGroupName(), namespace.name(), "RootManageSharedAccessKey"); System.out.println("Namespace authorization rule Retrieved"); @@ -90,7 +92,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Enabling diagnostics events of a cosmosdb to stream to event hub"); // Store Id of created Diagnostic settings only for clean-up - DiagnosticSetting ds = azureResourceManager.diagnosticSettings() + DiagnosticSetting ds = azureResourceManager.diagnosticSettings() .define("DiaEventHub") .withResource(docDb.id()) .withEventHub(eventHubAuthRule.id(), eventHubName) @@ -139,8 +141,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java index 37a7697d4bc8c..2b66a7432d8bf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java @@ -50,9 +50,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create resource group for the namespaces and recovery pairings // - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_SOUTH_CENTRAL) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_SOUTH_CENTRAL).create(); System.out.println("Creating primary event hub namespace " + primaryNamespaceName); @@ -118,7 +117,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Retrieving the event hubs in secondary namespace"); - EventHub eventHubInSecondaryNamespace = azureResourceManager.eventHubs().getByName(rgName, secondaryNamespaceName, eventHubName); + EventHub eventHubInSecondaryNamespace + = azureResourceManager.eventHubs().getByName(rgName, secondaryNamespaceName, eventHubName); System.out.println("Retrieved the event hubs in secondary namespace"); Utils.print(eventHubInSecondaryNamespace); @@ -176,8 +176,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java index 3a4991277e229..108cfe72ef5f6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java @@ -46,11 +46,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Creating a key vault..."); - Vault vault1 = azureResourceManager.vaults().define(vaultName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withEmptyAccessPolicy() - .create(); + Vault vault1 = azureResourceManager.vaults() + .define(vaultName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withEmptyAccessPolicy() + .create(); System.out.println("Created key vault"); Utils.print(vault1); @@ -61,13 +62,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Authorizing the application associated with the current service principal..."); vault1 = vault1.update() - .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowKeyAllPermissions() - .allowSecretPermissions(SecretPermissions.GET) - .allowSecretPermissions(SecretPermissions.LIST) - .attach() - .apply(); + .defineAccessPolicy() + .forServicePrincipal(clientId) + .allowKeyAllPermissions() + .allowSecretPermissions(SecretPermissions.GET) + .allowSecretPermissions(SecretPermissions.LIST) + .attach() + .apply(); System.out.println("Updated key vault"); Utils.print(vault1); @@ -78,39 +79,38 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Update a key vault to enable deployments and add permissions to the application..."); vault1 = vault1.update() - .withDeploymentEnabled() - .withTemplateDeploymentEnabled() - .updateAccessPolicy(vault1.accessPolicies().get(0).objectId()) - .allowCertificatePermissions() - .allowSecretAllPermissions() - .parent() - .apply(); + .withDeploymentEnabled() + .withTemplateDeploymentEnabled() + .updateAccessPolicy(vault1.accessPolicies().get(0).objectId()) + .allowCertificatePermissions() + .allowSecretAllPermissions() + .parent() + .apply(); System.out.println("Updated key vault"); // Print the network security group Utils.print(vault1); - //============================================================ // Create another key vault - Vault vault2 = azureResourceManager.vaults().define(vaultName2) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowKeyPermissions(KeyPermissions.LIST) - .allowKeyPermissions(KeyPermissions.GET) - .allowKeyPermissions(KeyPermissions.DECRYPT) - .allowSecretPermissions(SecretPermissions.GET) - .attach() - .create(); + Vault vault2 = azureResourceManager.vaults() + .define(vaultName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(clientId) + .allowKeyPermissions(KeyPermissions.LIST) + .allowKeyPermissions(KeyPermissions.GET) + .allowKeyPermissions(KeyPermissions.DECRYPT) + .allowSecretPermissions(SecretPermissions.GET) + .attach() + .create(); System.out.println("Created key vault"); // Print the network security group Utils.print(vault2); - //============================================================ // List key vaults @@ -140,6 +140,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin } } } + /** * Main entry point. * @param args the parameters @@ -156,8 +157,7 @@ public static void main(String[] args) { .build(); final Configuration configuration = Configuration.getGlobalConfiguration(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java index 26411af8fc8b4..87fe095fe3712 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java @@ -80,7 +80,8 @@ public class DeployImageFromContainerRegistryToKubernetes { * @param secret secondary service principal secret * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, JSchException, InterruptedException { + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) + throws IOException, JSchException, InterruptedException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgaks", 15); final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); final String aksName = Utils.randomResourceName(azureResourceManager, "akssample", 30); @@ -103,13 +104,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // // If the environment variable was not set then reuse the main service principal set for running this sample. - if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + if (servicePrincipalClientId == null + || servicePrincipalClientId.isEmpty() + || servicePrincipalSecret == null + || servicePrincipalSecret.isEmpty()) { servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); - if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + if (servicePrincipalClientId == null + || servicePrincipalClientId.isEmpty() + || servicePrincipalSecret == null + || servicePrincipalSecret.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); - if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + if (envSecondaryServicePrincipal == null + || !envSecondaryServicePrincipal.isEmpty() + || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } @@ -118,7 +127,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin } } - //============================================================= // Create an SSH private/public key pair to be used when creating the container service @@ -128,15 +136,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); - //============================================================= // Create an Azure Container Service (AKS) with managed Kubernetes clusters - System.out.println("Creating an Azure Container Service with managed Kubernetes cluster and one agent pool with one virtual machine"); + System.out.println( + "Creating an Azure Container Service with managed Kubernetes cluster and one agent pool with one virtual machine"); Date t1 = new Date(); - KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() + .define(aksName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() @@ -145,18 +154,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withServicePrincipalClientId(servicePrincipalClientId) .withServicePrincipalSecret(servicePrincipalSecret) .defineAgentPool("agentpool") - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .withDnsPrefix("dns-" + aksName) .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + System.out.println("Created Azure Container Service (AKS) resource: (took " + + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); Utils.print(kubernetesCluster); - //============================================================= // Create an Azure Container Registry to store and manage private Docker container images @@ -164,7 +173,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin t1 = new Date(); - Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + Registry azureRegistry = azureResourceManager.containerRegistries() + .define(acrName) .withRegion(region) .withNewResourceGroup(rgName) .withBasicSku() @@ -172,17 +182,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .create(); t2 = new Date(); - System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); - //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, - azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); - + DockerClient dockerClient + = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), + acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image @@ -199,39 +209,36 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } - CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) - .withName(dockerContainerName) - .withCmd("/hello") - .exec(); + CreateContainerResponse dockerContainerInstance + = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .withCmd("/hello") + .exec(); System.out.println("List Docker containers:"); - List dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) - .exec(); + List dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } - //============================================================= // Commit the new container String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl) - .withTag("latest").exec(); - - // We can now remove the temporary container instance - dockerClient.removeContainerCmd(dockerContainerInstance.getId()) - .withForce(true) + .withTag("latest") .exec(); + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry dockerClient.pushImageCmd(privateRepoUrl) .withAuthConfig(dockerClient.authConfig()) - .exec(new PushImageResultCallback()).awaitSuccess(); + .exec(new PushImageResultCallback()) + .awaitSuccess(); // Remove the temp image from the local Docker host try { @@ -240,32 +247,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // just ignore if not exist } - //============================================================= // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally dockerClient.pullImageCmd(privateRepoUrl) .withAuthConfig(dockerClient.authConfig()) - .exec(new PullImageResultCallback()).awaitCompletion(); - System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); - images = dockerClient.listImagesCmd() - .withShowAll(true) - .exec(); + .exec(new PullImageResultCallback()) + .awaitCompletion(); + System.out + .println("List local Docker images after pulling sample image from the Azure Container Registry:"); + images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); } dockerClient.createContainerCmd(privateRepoUrl) .withName(dockerContainerName + "-private") - .withCmd("/hello").exec(); - System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); - dockerContainers = dockerClient.listContainersCmd() - .withShowAll(true) + .withCmd("/hello") .exec(); + System.out.println( + "List Docker containers after instantiating container from the Azure Container Registry sample image:"); + dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); } - //============================================================= // Instantiate the Kubernetes client using the ".kube/config" file content from the Kubernetes cluster // The Kubernetes client API requires setting an environment variable pointing at a real file; @@ -275,9 +280,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("Found Kubernetes master at: " + kubernetesCluster.fqdn()); byte[] kubeConfigContent = kubernetesCluster.adminKubeConfigContent(); - File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); + File tempKubeConfigFile + = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); tempKubeConfigFile.deleteOnExit(); - try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { + try (BufferedWriter buffOut = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); } @@ -285,21 +292,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin Config config = new Config(); KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); - //============================================================= // List all the nodes available in the Kubernetes cluster System.out.println(kubernetesClient.nodes().list()); - //============================================================= // Create a namespace where all the sample Kubernetes resources will be created - Namespace ns = new NamespaceBuilder() - .withNewMetadata() - .withName(aksNamespace) - .addToLabels("acr", "sample") - .endMetadata() + Namespace ns = new NamespaceBuilder().withNewMetadata() + .withName(aksNamespace) + .addToLabels("acr", "sample") + .endMetadata() .build(); try { System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); @@ -312,29 +316,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); } - //============================================================= // Create a secret of type "docker-repository" that will be used for downloading the container image from // our Azure private container repo - String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + String basicAuth = new String(Base64 + .encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .getBytes(StandardCharsets.UTF_8)), + StandardCharsets.UTF_8); HashMap secretData = new HashMap<>(1); String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", - azureRegistry.loginServerUrl(), - basicAuth, - "acrsample@azure.com"); + azureRegistry.loginServerUrl(), basicAuth, "acrsample@azure.com"); dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); secretData.put(".dockercfg", dockerCfg); - SecretBuilder secretBuilder = new SecretBuilder() - .withNewMetadata() - .withName(aksSecretName) - .withNamespace(aksNamespace) - .endMetadata() + SecretBuilder secretBuilder = new SecretBuilder().withNewMetadata() + .withName(aksSecretName) + .withNamespace(aksNamespace) + .endMetadata() .withData(secretData) .withType("kubernetes.io/dockercfg"); - System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(aksNamespace).create(secretBuilder.build())); + System.out.println("Creating new secret: " + + kubernetesClient.secrets().inNamespace(aksNamespace).create(secretBuilder.build())); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); @@ -342,37 +346,36 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound secret: " + kubeS); } - //============================================================= // Create a replication controller for our image stored in the Azure Container Registry - ReplicationController rc = new ReplicationControllerBuilder() + ReplicationController rc = new ReplicationControllerBuilder().withNewMetadata() + .withName("acrsample-rc") + .withNamespace(aksNamespace) + .addToLabels("acrsample-nginx", "nginx") + .endMetadata() + .withNewSpec() + .withReplicas(2) + .withNewTemplate() .withNewMetadata() - .withName("acrsample-rc") - .withNamespace(aksNamespace) - .addToLabels("acrsample-nginx", "nginx") - .endMetadata() + .addToLabels("acrsample-nginx", "nginx") + .endMetadata() .withNewSpec() - .withReplicas(2) - .withNewTemplate() - .withNewMetadata() - .addToLabels("acrsample-nginx", "nginx") - .endMetadata() - .withNewSpec() - .addNewImagePullSecret(aksSecretName) - .addNewContainer() - .withName("acrsample-pod-nginx") - .withImage(privateRepoUrl) - .addNewPort() - .withContainerPort(80) - .endPort() - .endContainer() - .endSpec() - .endTemplate() - .endSpec() + .addNewImagePullSecret(aksSecretName) + .addNewContainer() + .withName("acrsample-pod-nginx") + .withImage(privateRepoUrl) + .addNewPort() + .withContainerPort(80) + .endPort() + .endContainer() + .endSpec() + .endTemplate() + .endSpec() .build(); - System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(aksNamespace).create(rc)); + System.out.println("Creating a replication controller: " + + kubernetesClient.replicationControllers().inNamespace(aksNamespace).create(rc)); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); rc = kubernetesClient.replicationControllers().inNamespace(aksNamespace).withName("acrsample-rc").get(); @@ -382,31 +385,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.println("\tFound Kubernetes pods: " + pod.toString()); } - //============================================================= // Create a Load Balancer service that will expose the service to the world - Service lbService = new ServiceBuilder() - .withNewMetadata() - .withName(aksLbIngressName) - .withNamespace(aksNamespace) - .endMetadata() + Service lbService = new ServiceBuilder().withNewMetadata() + .withName(aksLbIngressName) + .withNamespace(aksNamespace) + .endMetadata() .withNewSpec() - .withType("LoadBalancer") - .addNewPort() - .withPort(80) - .withProtocol("TCP") - .endPort() - .addToSelector("acrsample-nginx", "nginx") - .endSpec() + .withType("LoadBalancer") + .addNewPort() + .withPort(80) + .withProtocol("TCP") + .endPort() + .addToSelector("acrsample-nginx", "nginx") + .endSpec() .build(); - System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(aksNamespace).create(lbService)); + System.out.println( + "Creating a service: " + kubernetesClient.services().inNamespace(aksNamespace).create(lbService)); ResourceManagerUtils.sleep(Duration.ofSeconds(5)); - System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get()); - + System.out.println("\tFound service: " + + kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get()); //============================================================= // Wait until the external IP becomes available @@ -416,8 +418,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin while (timeout > 0) { try { - List lbIngressList = kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get().getStatus().getLoadBalancer().getIngress(); - if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { + List lbIngressList = kubernetesClient.services() + .inNamespace(aksNamespace) + .withName(aksLbIngressName) + .get() + .getStatus() + .getLoadBalancer() + .getIngress(); + if (lbIngressList != null + && !lbIngressList.isEmpty() + && lbIngressList.get(0) != null + && lbIngressList.get(0).getIp().matches(matchIPV4)) { System.out.println("\tFound ingress IP: " + lbIngressList.get(0).getIp()); timeout = 0; } @@ -462,8 +473,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java index 1f661933faedd..c22db1740d9a5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java @@ -45,21 +45,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() + .define(aksName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool("agentpool") - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .withDnsPrefix("dns-" + aksName) .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + System.out.println("Created Azure Container Service (AKS) resource: (took " + + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); Utils.print(kubernetesCluster); //============================================================= @@ -71,12 +73,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { kubernetesCluster.update() .updateAgentPool("agentpool") - .withAgentPoolVirtualMachineCount(2) - .parent() + .withAgentPoolVirtualMachineCount(2) + .parent() .apply(); t2 = new Date(); - System.out.println("Updated Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + System.out.println("Updated Azure Container Service (AKS) resource: (took " + + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); Utils.print(kubernetesCluster); return true; @@ -108,8 +111,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java index 467f772a21cf4..3577aa85c290b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java @@ -56,9 +56,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withRegion(region) .withNewResourceGroup(rgName) .defineAccessPolicy() - .forServicePrincipal(clientId) - .allowKeyPermissions(KeyPermissions.CREATE) - .attach() + .forServicePrincipal(clientId) + .allowKeyPermissions(KeyPermissions.CREATE) + .attach() .withPurgeProtectionEnabled() .create(); @@ -67,11 +67,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================= // Create a key in key vault - Key vaultKey = vault.keys() - .define(keyName) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key vaultKey = vault.keys().define(keyName).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); System.out.println("Created key vault key: " + vaultKey.id()); @@ -95,9 +91,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin vault.update() .defineAccessPolicy() - .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(des.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .apply(); System.out.println("Granted des access to the key vault."); @@ -105,8 +101,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================= // Create an Azure Container Service (AKS) with managed Kubernetes cluster, os disk encrypted using customer-managed key - KubernetesCluster kubernetesCluster = azureResourceManager - .kubernetesClusters() + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() .define(aksName) .withRegion(region) .withExistingResourceGroup(rgName) @@ -114,11 +109,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .withSystemAssignedManagedServiceIdentity() .withDiskEncryptionSet(des.id()) .defineAgentPool("agentpool") - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withOSDiskSizeInGB(30) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withOSDiskSizeInGB(30) + .attach() .withDnsPrefix("mp1" + aksName) .create(); @@ -155,8 +150,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java index 5094a49025fb0..1211b9dfe0cbe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java @@ -45,16 +45,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a virtual network with two subnets. System.out.println("Create a virtual network with two subnets: subnet1 and subnet2"); - Network virtualNetwork = azureResourceManager.networks().define(vnetName) + Network virtualNetwork = azureResourceManager.networks() + .define(vnetName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("192.168.0.0/16") .defineSubnet("subnet1") - .withAddressPrefix("192.168.1.0/24") - .attach() + .withAddressPrefix("192.168.1.0/24") + .attach() .defineSubnet("subnet2") - .withAddressPrefix("192.168.2.0/24") - .attach() + .withAddressPrefix("192.168.2.0/24") + .attach() .create(); System.out.println("Created a virtual network"); @@ -68,27 +69,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() + .define(aksName) .withRegion(region) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool("agentpool") - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withVirtualNetwork(virtualNetwork.id(), "subnet1") - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withVirtualNetwork(virtualNetwork.id(), "subnet1") + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() .withDnsPrefix("dns-" + aksName) .defineNetworkProfile() - .withNetworkPlugin(NetworkPlugin.AZURE) - .withServiceCidr("10.0.0.0/16") - .withDnsServiceIP("10.0.0.10") - .attach() + .withNetworkPlugin(NetworkPlugin.AZURE) + .withServiceCidr("10.0.0.0/16") + .withDnsServiceIP("10.0.0.10") + .attach() .create(); Date t2 = new Date(); - System.out.println("Created Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + System.out.println("Created Azure Container Service (AKS) resource: (took " + + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); Utils.print(kubernetesCluster); //============================================================= @@ -100,12 +103,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { kubernetesCluster.update() .updateAgentPool("agentpool") - .withAgentPoolVirtualMachineCount(2) - .parent() + .withAgentPoolVirtualMachineCount(2) + .parent() .apply(); t2 = new Date(); - System.out.println("Updated Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + System.out.println("Updated Azure Container Service (AKS) resource: (took " + + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); Utils.print(kubernetesCluster); return true; @@ -137,8 +141,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java index 18f7fa719c662..b3ebd8127cdba 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java @@ -49,53 +49,57 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a Web App and App Service Plan System.out.println("Creating a web app and service plan"); - WebApp webapp = azureResourceManager.webApps().define(webappName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .withNewWindowsPlan(PricingTier.PREMIUM_P1) - .create(); + WebApp webapp = azureResourceManager.webApps() + .define(webappName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.PREMIUM_P1) + .create(); System.out.println("Created a web app:"); Utils.print(webapp); // ============================================================ // Configure autoscale rules for scale-in and scale out based on the number of requests a Web App receives - AutoscaleSetting scaleSettings = azureResourceManager.autoscaleSettings().define(autoscaleSettingsName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withTargetResource(webapp.appServicePlanId()) - // defining Default profile. Note: first created profile is always the default one. - .defineAutoscaleProfile("Default profile") - .withFixedInstanceCount(1) - .attach() - // defining Monday to Friday profile - .defineAutoscaleProfile("Monday to Friday") - .withMetricBasedScale(1, 2, 1) - // Create a scale-out rule - .defineScaleRule() - .withMetricSource(webapp.id()) - .withMetricName("Requests") - .withStatistic(Duration.ofMinutes(5), MetricStatisticType.SUM) - .withCondition(TimeAggregationType.TOTAL, ComparisonOperationType.GREATER_THAN, 10) - .withScaleAction(ScaleDirection.INCREASE, ScaleType.CHANGE_COUNT, 1, Duration.ofMinutes(5)) - .attach() - // Create a scale-in rule - .defineScaleRule() - .withMetricSource(webapp.id()) - .withMetricName("Requests") - .withStatistic(Duration.ofMinutes(10), MetricStatisticType.AVERAGE) - .withCondition(TimeAggregationType.TOTAL, ComparisonOperationType.LESS_THAN, 5) - .withScaleAction(ScaleDirection.DECREASE, ScaleType.CHANGE_COUNT, 1, Duration.ofMinutes(5)) - .attach() - // Create profile schedule - .withRecurrentSchedule("Pacific Standard Time", "09:00", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY) - .attach() - // define end time for the "Monday to Friday" profile specified above - .defineAutoscaleProfile("{\"name\":\"Default\",\"for\":\"Monday to Friday\"}") - .withScheduleBasedScale(1) - .withRecurrentSchedule("Pacific Standard Time", "18:30", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY) - .attach() - .create(); + AutoscaleSetting scaleSettings = azureResourceManager.autoscaleSettings() + .define(autoscaleSettingsName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withTargetResource(webapp.appServicePlanId()) + // defining Default profile. Note: first created profile is always the default one. + .defineAutoscaleProfile("Default profile") + .withFixedInstanceCount(1) + .attach() + // defining Monday to Friday profile + .defineAutoscaleProfile("Monday to Friday") + .withMetricBasedScale(1, 2, 1) + // Create a scale-out rule + .defineScaleRule() + .withMetricSource(webapp.id()) + .withMetricName("Requests") + .withStatistic(Duration.ofMinutes(5), MetricStatisticType.SUM) + .withCondition(TimeAggregationType.TOTAL, ComparisonOperationType.GREATER_THAN, 10) + .withScaleAction(ScaleDirection.INCREASE, ScaleType.CHANGE_COUNT, 1, Duration.ofMinutes(5)) + .attach() + // Create a scale-in rule + .defineScaleRule() + .withMetricSource(webapp.id()) + .withMetricName("Requests") + .withStatistic(Duration.ofMinutes(10), MetricStatisticType.AVERAGE) + .withCondition(TimeAggregationType.TOTAL, ComparisonOperationType.LESS_THAN, 5) + .withScaleAction(ScaleDirection.DECREASE, ScaleType.CHANGE_COUNT, 1, Duration.ofMinutes(5)) + .attach() + // Create profile schedule + .withRecurrentSchedule("Pacific Standard Time", "09:00", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, + DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY) + .attach() + // define end time for the "Monday to Friday" profile specified above + .defineAutoscaleProfile("{\"name\":\"Default\",\"for\":\"Monday to Friday\"}") + .withScheduleBasedScale(1) + .withRecurrentSchedule("Pacific Standard Time", "18:30", DayOfWeek.MONDAY, DayOfWeek.TUESDAY, + DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY) + .attach() + .create(); System.out.println("Auto-scale Setting: " + scaleSettings.id()); @@ -140,8 +144,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java index 26d91cb106a44..98e809196612c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java @@ -69,19 +69,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a Storage Account"); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withBlobStorageAccountKind() - .withAccessTier(AccessTier.COOL) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withBlobStorageAccountKind() + .withAccessTier(AccessTier.COOL) + .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount); List storageAccountKeys = storageAccount.getKeys(); - final String storageConnectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", - storageAccount.name(), + final String storageConnectionString + = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), storageAccountKeys.get(0).value()); // Add some blob transaction events @@ -89,17 +90,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw OffsetDateTime recordDateTime = OffsetDateTime.now(); // get metric definitions for storage account. - for (MetricDefinition metricDefinition : azureResourceManager.metricDefinitions().listByResource(storageAccount.id())) { + for (MetricDefinition metricDefinition : azureResourceManager.metricDefinitions() + .listByResource(storageAccount.id())) { // find metric definition for Transactions if (metricDefinition.name().localizedValue().equalsIgnoreCase("transactions")) { // get metric records MetricCollection metricCollection = metricDefinition.defineQuery() - .startingFrom(recordDateTime.minusDays(7)) - .endsBefore(recordDateTime) - .withAggregation("Average") - .withInterval(Duration.ofMinutes(5)) - .withOdataFilter("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'") - .execute(); + .startingFrom(recordDateTime.minusDays(7)) + .endsBefore(recordDateTime) + .withAggregation("Average") + .withInterval(Duration.ofMinutes(5)) + .withOdataFilter("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'") + .execute(); System.out.println("Metrics for '" + storageAccount.id() + "':"); System.out.println("Namespacse: " + metricCollection.namespace()); @@ -115,16 +117,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw for (TimeSeriesElement timeElement : metric.timeseries()) { System.out.println("\t\tMetadata: "); for (MetadataValueInner metadata : timeElement.metadatavalues()) { - System.out.println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); + System.out + .println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); } System.out.println("\t\tData: "); for (MetricValue data : timeElement.data()) { - System.out.println("\t\t\t" + data.timestamp() - + " : (Min) " + data.minimum() - + " : (Max) " + data.maximum() - + " : (Avg) " + data.average() - + " : (Total) " + data.total() - + " : (Count) " + data.count()); + System.out.println("\t\t\t" + data.timestamp() + " : (Min) " + data.minimum() + + " : (Max) " + data.maximum() + " : (Avg) " + data.average() + " : (Total) " + + data.total() + " : (Count) " + data.count()); } } } @@ -133,12 +133,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } // get activity logs for the same period. - PagedIterable logs = azureResourceManager.activityLogs().defineQuery() - .startingFrom(recordDateTime.minusDays(7)) - .endsBefore(recordDateTime) - .withAllPropertiesInResponse() - .filterByResource(storageAccount.id()) - .execute(); + PagedIterable logs = azureResourceManager.activityLogs() + .defineQuery() + .startingFrom(recordDateTime.minusDays(7)) + .endsBefore(recordDateTime) + .withAllPropertiesInResponse() + .filterByResource(storageAccount.id()) + .execute(); System.out.println("Activity logs for the Storage Account:"); @@ -178,8 +179,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -197,7 +197,8 @@ public static void main(String[] args) { private static void addBlobTransactions(String storageConnectionString, HttpClient httpClient) throws IOException { // Get the script to upload // - try (InputStream scriptFileAsStream = QueryMetricsAndActivityLogs.class.getResourceAsStream("/install_apache.sh")) { + try (InputStream scriptFileAsStream + = QueryMetricsAndActivityLogs.class.getResourceAsStream("/install_apache.sh")) { // Get the size of the stream // @@ -207,37 +208,31 @@ private static void addBlobTransactions(String storageConnectionString, HttpClie // Upload the script file as block blob // - BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() - .connectionString(storageConnectionString) - .containerName("scripts") - .httpClient(httpClient) - .buildClient(); + BlobContainerClient blobContainerClient + = new BlobContainerClientBuilder().connectionString(storageConnectionString) + .containerName("scripts") + .httpClient(httpClient) + .buildClient(); blobContainerClient.create(); // Get the service properties. - BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() - .connectionString(storageConnectionString) - .httpClient(httpClient) - .buildClient(); + BlobServiceClient blobServiceClient + = new BlobServiceClientBuilder().connectionString(storageConnectionString) + .httpClient(httpClient) + .buildClient(); BlobServiceProperties serviceProps = blobServiceClient.getProperties(); // configure Storage logging and metrics - BlobAnalyticsLogging logProps = new BlobAnalyticsLogging() - .setRead(true) + BlobAnalyticsLogging logProps = new BlobAnalyticsLogging().setRead(true) .setWrite(true) - .setRetentionPolicy(new BlobRetentionPolicy() - .setEnabled(true) - .setDays(2)) + .setRetentionPolicy(new BlobRetentionPolicy().setEnabled(true).setDays(2)) .setVersion("1.0"); serviceProps.setLogging(logProps); - BlobMetrics metricProps = new BlobMetrics() - .setEnabled(true) + BlobMetrics metricProps = new BlobMetrics().setEnabled(true) .setIncludeApis(true) - .setRetentionPolicy(new BlobRetentionPolicy() - .setEnabled(true) - .setDays(2)) + .setRetentionPolicy(new BlobRetentionPolicy().setEnabled(true).setDays(2)) .setVersion("1.0"); serviceProps.setHourMetrics(metricProps); serviceProps.setMinuteMetrics(metricProps); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java index c8ba68fe3d6bb..081784e071a30 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java @@ -47,47 +47,50 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a storage account System.out.println("Creating a Storage Account"); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withBlobStorageAccountKind() - .withAccessTier(AccessTier.COOL) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withBlobStorageAccountKind() + .withAccessTier(AccessTier.COOL) + .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount); // ============================================================ // Create an action group to send notifications in case activity log alert condition will be triggered - ActionGroup ag = azureResourceManager.actionGroups().define("securityBreachActionGroup") - .withExistingResourceGroup(rgName) - .defineReceiver("tierOne") - .withPushNotification("security_on_duty@securecorporation.com") - .withEmail("security_guards@securecorporation.com") - .withSms("1", "4255655665") - .withVoice("1", "2062066050") - .withWebhook("https://www.weseemstobehacked.securecorporation.com") - .attach() - .defineReceiver("tierTwo") - .withEmail("ceo@securecorporation.com") - .attach() - .create(); + ActionGroup ag = azureResourceManager.actionGroups() + .define("securityBreachActionGroup") + .withExistingResourceGroup(rgName) + .defineReceiver("tierOne") + .withPushNotification("security_on_duty@securecorporation.com") + .withEmail("security_guards@securecorporation.com") + .withSms("1", "4255655665") + .withVoice("1", "2062066050") + .withWebhook("https://www.weseemstobehacked.securecorporation.com") + .attach() + .defineReceiver("tierTwo") + .withEmail("ceo@securecorporation.com") + .attach() + .create(); Utils.print(ag); // ============================================================ // Set a trigger to fire each time - ActivityLogAlert ala = azureResourceManager.alertRules().activityLogAlerts() - .define("Potential security breach alert") - .withExistingResourceGroup(rgName) - .withTargetSubscription(azureResourceManager.subscriptionId()) - .withDescription("Security StorageAccounts ListAccountKeys trigger") - .withRuleEnabled() - .withActionGroups(ag.id()) - // fire an alert when all the conditions below will be true - .withEqualsCondition("category", "Security") - .withEqualsCondition("resourceId", storageAccount.id()) - .withEqualsCondition("operationName", "Microsoft.Storage/storageAccounts/listkeys/action") - .create(); + ActivityLogAlert ala = azureResourceManager.alertRules() + .activityLogAlerts() + .define("Potential security breach alert") + .withExistingResourceGroup(rgName) + .withTargetSubscription(azureResourceManager.subscriptionId()) + .withDescription("Security StorageAccounts ListAccountKeys trigger") + .withRuleEnabled() + .withActionGroups(ag.id()) + // fire an alert when all the conditions below will be true + .withEqualsCondition("category", "Security") + .withEqualsCondition("resourceId", storageAccount.id()) + .withEqualsCondition("operationName", "Microsoft.Storage/storageAccounts/listkeys/action") + .create(); Utils.print(ala); // this should trigger an action @@ -100,12 +103,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { OffsetDateTime recordDateTime = OffsetDateTime.now().truncatedTo(ChronoUnit.DAYS); // get activity logs for the same period. - PagedIterable logs = azureResourceManager.activityLogs().defineQuery() - .startingFrom(recordDateTime.minusDays(7)) - .endsBefore(recordDateTime) - .withAllPropertiesInResponse() - .filterByResource(ala.id()) - .execute(); + PagedIterable logs = azureResourceManager.activityLogs() + .defineQuery() + .startingFrom(recordDateTime.minusDays(7)) + .endsBefore(recordDateTime) + .withAllPropertiesInResponse() + .filterByResource(ala.id()) + .execute(); System.out.println("Activity logs for the Storage Account:"); @@ -148,8 +152,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java index 43afbb7e3134f..8f913c7a5dc53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java @@ -43,48 +43,53 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create an App Service plan System.out.println("Creating App Service plan"); - AppServicePlan servicePlan = azureResourceManager.appServicePlans().define("HighlyAvailableWebApps") - .withRegion(Region.US_SOUTH_CENTRAL) - .withNewResourceGroup(rgName) - .withPricingTier(PricingTier.PREMIUM_P1) - .withOperatingSystem(OperatingSystem.WINDOWS) - .create(); + AppServicePlan servicePlan = azureResourceManager.appServicePlans() + .define("HighlyAvailableWebApps") + .withRegion(Region.US_SOUTH_CENTRAL) + .withNewResourceGroup(rgName) + .withPricingTier(PricingTier.PREMIUM_P1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); System.out.println("App Service plan created:"); Utils.print(servicePlan); // ============================================================ // Create an action group to send notifications in case metric alert condition will be triggered - ActionGroup ag = azureResourceManager.actionGroups().define("criticalPerformanceActionGroup") - .withExistingResourceGroup(rgName) - .defineReceiver("tierOne") - .withPushNotification("ops_on_duty@performancemonitoring.com") - .withEmail("ops_on_duty@performancemonitoring.com") - .withSms("1", "4255655665") - .withVoice("1", "2062066050") - .withWebhook("https://www.weeneedmorepower.performancemonitoring.com") - .attach() - .defineReceiver("tierTwo") - .withEmail("ceo@performancemonitoring.com") - .attach() - .create(); + ActionGroup ag = azureResourceManager.actionGroups() + .define("criticalPerformanceActionGroup") + .withExistingResourceGroup(rgName) + .defineReceiver("tierOne") + .withPushNotification("ops_on_duty@performancemonitoring.com") + .withEmail("ops_on_duty@performancemonitoring.com") + .withSms("1", "4255655665") + .withVoice("1", "2062066050") + .withWebhook("https://www.weeneedmorepower.performancemonitoring.com") + .attach() + .defineReceiver("tierTwo") + .withEmail("ceo@performancemonitoring.com") + .attach() + .create(); Utils.print(ag); // ============================================================ // Set a trigger to fire each time - MetricAlert ma = azureResourceManager.alertRules().metricAlerts().define("Critical performance alert") - .withExistingResourceGroup(rgName) - .withTargetResource(servicePlan.id()) - .withPeriod(Duration.ofMinutes(5)) - .withFrequency(Duration.ofMinutes(1)) - .withAlertDetails(3, "This alert rule is for U5 - Single resource-multiple criteria - with dimensions - with star") - .withActionGroups(ag.id()) - .defineAlertCriteria("Metric1") - .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms") - .withCondition(MetricAlertRuleTimeAggregation.TOTAL, MetricAlertRuleCondition.GREATER_THAN, 80) - .withDimension("Instance", "*") - .attach() - .create(); + MetricAlert ma = azureResourceManager.alertRules() + .metricAlerts() + .define("Critical performance alert") + .withExistingResourceGroup(rgName) + .withTargetResource(servicePlan.id()) + .withPeriod(Duration.ofMinutes(5)) + .withFrequency(Duration.ofMinutes(1)) + .withAlertDetails(3, + "This alert rule is for U5 - Single resource-multiple criteria - with dimensions - with star") + .withActionGroups(ag.id()) + .defineAlertCriteria("Metric1") + .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms") + .withCondition(MetricAlertRuleTimeAggregation.TOTAL, MetricAlertRuleCondition.GREATER_THAN, 80) + .withDimension("Instance", "*") + .attach() + .create(); Utils.print(ma); return true; @@ -111,8 +116,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java index e538dad6199e3..511f1eb80c8ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.network.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -69,53 +68,57 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String availabilitySetName = Utils.randomResourceName(azureResourceManager, "av", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; try { //============================================================= // Define a common availability set for the backend virtual machines - Creatable availabilitySetDefinition = azureResourceManager.availabilitySets().define(availabilitySetName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withSku(AvailabilitySetSkuTypes.ALIGNED); + Creatable availabilitySetDefinition = azureResourceManager.availabilitySets() + .define(availabilitySetName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withSku(AvailabilitySetSkuTypes.ALIGNED); //============================================================= // Define a common virtual network for the virtual machines - Creatable networkDefinition = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withAddressSpace("10.0.0.0/28"); + Creatable networkDefinition = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withAddressSpace("10.0.0.0/28"); //============================================================= // Create two virtual machines for the backend of the load balancer System.out.println("Creating two virtual machines in the frontend subnet ...\n" - + "and putting them in the shared availability set and virtual network."); + + "and putting them in the shared availability set and virtual network."); List> virtualMachineDefinitions = new ArrayList>(); for (int i = 0; i < 2; i++) { - virtualMachineDefinitions.add( - azureResourceManager.virtualMachines().define(Utils.randomResourceName(azureResourceManager, "vm", 24)) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) - .withNewPrimaryNetwork(networkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availabilitySetDefinition)); + virtualMachineDefinitions.add(azureResourceManager.virtualMachines() + .define(Utils.randomResourceName(azureResourceManager, "vm", 24)) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .withNewPrimaryNetwork(networkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availabilitySetDefinition)); } StopWatch stopwatch = new StopWatch(); stopwatch.start(); // Create and retrieve the VMs by the interface accepted by the load balancing rule - Collection virtualMachines = azureResourceManager.virtualMachines().create(virtualMachineDefinitions).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(virtualMachineDefinitions).values(); stopwatch.stop(); System.out.println("Created 2 Linux VMs: (took " + (stopwatch.getTime() / 1000) + " seconds)\n"); @@ -132,27 +135,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // - implicitly creating a backend and assigning the created virtual machines to it // - creating a load balancing rule, mapping public ports on the load balancer to ports in the backend address pool - System.out.println( - "Creating a Internet facing load balancer with ...\n" - + "- A frontend public IP address\n" - + "- One backend address pool with the two virtual machines\n" - + "- One load balancing rule for HTTP, mapping public ports on the load\n" - + " balancer to ports in the backend address pool"); + System.out.println("Creating a Internet facing load balancer with ...\n" + + "- A frontend public IP address\n" + "- One backend address pool with the two virtual machines\n" + + "- One load balancing rule for HTTP, mapping public ports on the load\n" + + " balancer to ports in the backend address pool"); - LoadBalancer loadBalancer = azureResourceManager.loadBalancers().define(loadBalancerName) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) + LoadBalancer loadBalancer = azureResourceManager.loadBalancers() + .define(loadBalancerName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) - // Add a load balancing rule sending traffic from an implicitly created frontend with the public IP address - // to an implicitly created backend with the two virtual machines - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromNewPublicIPAddress(publicIpName) - .fromFrontendPort(80) - .toExistingVirtualMachines(new ArrayList(virtualMachines)) // Convert VMs to the expected interface - .attach() + // Add a load balancing rule sending traffic from an implicitly created frontend with the public IP address + // to an implicitly created backend with the two virtual machines + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromNewPublicIPAddress(publicIpName) + .fromFrontendPort(80) + .toExistingVirtualMachines(new ArrayList(virtualMachines)) // Convert VMs to the expected interface + .attach() - .create(); + .create(); // Print load balancer details System.out.println("Created a load balancer"); @@ -164,25 +166,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating the load balancer ..."); loadBalancer.update() - .updateLoadBalancingRule(httpLoadBalancingRule) - .withIdleTimeoutInMinutes(15) - .parent() - .apply(); + .updateLoadBalancingRule(httpLoadBalancingRule) + .withIdleTimeoutInMinutes(15) + .parent() + .apply(); System.out.println("Update the load balancer with a TCP idle timeout to 15 minutes"); - //============================================================= // Show the load balancer info Utils.print(loadBalancer); - //============================================================= // Remove a load balancer - System.out.println("Deleting load balancer " + loadBalancerName - + "(" + loadBalancer.id() + ")"); + System.out.println("Deleting load balancer " + loadBalancerName + "(" + loadBalancer.id() + ")"); azureResourceManager.loadBalancers().deleteById(loadBalancer.id()); System.out.println("Deleted load balancer" + loadBalancerName); @@ -217,8 +216,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java index 1cbb2af0fd8fc..966de50ca1cb0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.network.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -89,13 +88,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw final String pipName = Utils.randomResourceName(azureResourceManager, "pip" + "-", 18); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; int backendPools = 2; int vmCountInAPool = 4; - Region[] regions = {Region.US_EAST, Region.US_WEST}; - String[] addressSpaces = {"172.16.0.0/16", "172.17.0.0/16"}; + Region[] regions = { Region.US_EAST, Region.US_WEST }; + String[] addressSpaces = { "172.16.0.0/16", "172.17.0.0/16" }; String[][] publicIpCreatableKeys = new String[backendPools][vmCountInAPool]; String[][] ipAddresses = new String[backendPools][vmCountInAPool]; @@ -104,23 +104,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================= // Create a resource group (Where all resources gets created) // - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); System.out.println("Created a new resource group - " + resourceGroup.id()); - //============================================================= // Create a public IP address for the Application Gateway System.out.println("Creating a public IP address for the application gateway ..."); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(pipName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP() - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(pipName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP() + .create(); System.out.println("Created a public IP address"); // Print the virtual network details @@ -134,62 +133,59 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw for (int i = 0; i < backendPools; i++) { - //============================================================= // Create 1 network creatable per region // Prepare Creatable Network definition (Where all the virtual machines get added to) String networkName = Utils.randomResourceName(azureResourceManager, "vnetNEAG-", 20); - Creatable networkCreatable = azureResourceManager.networks().define(networkName) - .withRegion(regions[i]) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace(addressSpaces[i]); - + Creatable networkCreatable = azureResourceManager.networks() + .define(networkName) + .withRegion(regions[i]) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace(addressSpaces[i]); //============================================================= // Create 1 storage creatable per region (For storing VMs disk) String storageAccountName = Utils.randomResourceName(azureResourceManager, "stgneag", 20); - Creatable storageAccountCreatable = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(regions[i]) - .withExistingResourceGroup(resourceGroup); + Creatable storageAccountCreatable = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(regions[i]) + .withExistingResourceGroup(resourceGroup); String linuxVMNamePrefix = Utils.randomResourceName(azureResourceManager, "vm-", 15); for (int j = 0; j < vmCountInAPool; j++) { - //============================================================= // Create 1 public IP address creatable Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses() - .define(String.format("%s-%d", linuxVMNamePrefix, j)) - .withRegion(regions[i]) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(String.format("%s-%d", linuxVMNamePrefix, j)) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP(); + .define(String.format("%s-%d", linuxVMNamePrefix, j)) + .withRegion(regions[i]) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(String.format("%s-%d", linuxVMNamePrefix, j)) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP(); publicIpCreatableKeys[i][j] = publicIPAddressCreatable.key(); - //============================================================= // Create 1 virtual machine creatable Creatable virtualMachineCreatable = azureResourceManager.virtualMachines() - .define(String.format("%s-%d", linuxVMNamePrefix, j)) - .withRegion(regions[i]) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(storageAccountCreatable); + .define(String.format("%s-%d", linuxVMNamePrefix, j)) + .withRegion(regions[i]) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(storageAccountCreatable); creatableVirtualMachines.add(virtualMachineCreatable); } } - //============================================================= // Create two backend pools of virtual machines @@ -197,7 +193,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating virtual machines (two backend pools)"); stopwatch.start(); - CreatedResources virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines); + CreatedResources virtualMachines + = azureResourceManager.virtualMachines().create(creatableVirtualMachines); stopwatch.stop(); System.out.println("Created virtual machines (two backend pools)"); @@ -206,9 +203,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println(virtualMachine.id()); } - System.out.println("Virtual machines created: (took " + (stopwatch.getTime() / 1000) + " seconds) to create == " + virtualMachines.size() - + " == virtual machines (4 virtual machines per backend pool)"); - + System.out + .println("Virtual machines created: (took " + (stopwatch.getTime() / 1000) + " seconds) to create == " + + virtualMachines.size() + " == virtual machines (4 virtual machines per backend pool)"); //======================================================================= // Get IP addresses from created resources @@ -216,8 +213,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("IP Addresses in the backend pools are - "); for (int i = 0; i < backendPools; i++) { for (int j = 0; j < vmCountInAPool; j++) { - PublicIpAddress pip = (PublicIpAddress) virtualMachines - .createdRelatedResource(publicIpCreatableKeys[i][j]); + PublicIpAddress pip + = (PublicIpAddress) virtualMachines.createdRelatedResource(publicIpCreatableKeys[i][j]); pip.refresh(); ipAddresses[i][j] = pip.ipAddress(); System.out.println(String.format("[backend pool = %d][vm = %d] = %s", i, j, ipAddresses[i][j])); @@ -226,7 +223,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("======"); } - //======================================================================= // Create an application gateway @@ -235,31 +231,31 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw stopwatch.reset(); stopwatch.start(); - ApplicationGateway applicationGateway = azureResourceManager.applicationGateways().define("myFirstAppGateway") - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - - // Request routing rule for HTTP from public 80 to public 8080 - .defineRequestRoutingRule("HTTP-80-to-8080") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress(ipAddresses[0][0]) - .toBackendIPAddress(ipAddresses[0][1]) - .toBackendIPAddress(ipAddresses[0][2]) - .toBackendIPAddress(ipAddresses[0][3]) - .attach() - - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withExistingPublicIpAddress(publicIPAddress) - .create(); + ApplicationGateway applicationGateway = azureResourceManager.applicationGateways() + .define("myFirstAppGateway") + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + + // Request routing rule for HTTP from public 80 to public 8080 + .defineRequestRoutingRule("HTTP-80-to-8080") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress(ipAddresses[0][0]) + .toBackendIPAddress(ipAddresses[0][1]) + .toBackendIPAddress(ipAddresses[0][2]) + .toBackendIPAddress(ipAddresses[0][3]) + .attach() + + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withExistingPublicIpAddress(publicIPAddress) + .create(); stopwatch.stop(); System.out.println("Application gateway created: (took " + (stopwatch.getTime() / 1000) + " seconds)"); Utils.print(applicationGateway); - //======================================================================= // Update an application gateway // configure the first routing rule for SSL offload @@ -270,19 +266,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw stopwatch.start(); applicationGateway.update() - .withoutRequestRoutingRule("HTTP-80-to-8080") - .defineRequestRoutingRule("HTTP-81-to-8080") - .fromPublicFrontend() - .fromFrontendHttpPort(81) - .toBackendHttpPort(8080) - .toBackendIPAddress(ipAddresses[0][0]) - .toBackendIPAddress(ipAddresses[0][1]) - .toBackendIPAddress(ipAddresses[0][2]) - .toBackendIPAddress(ipAddresses[0][3]) - .withHostname("www.contoso.com") - .withCookieBasedAffinity() - .attach() - .apply(); + .withoutRequestRoutingRule("HTTP-80-to-8080") + .defineRequestRoutingRule("HTTP-81-to-8080") + .fromPublicFrontend() + .fromFrontendHttpPort(81) + .toBackendHttpPort(8080) + .toBackendIPAddress(ipAddresses[0][0]) + .toBackendIPAddress(ipAddresses[0][1]) + .toBackendIPAddress(ipAddresses[0][2]) + .toBackendIPAddress(ipAddresses[0][3]) + .withHostname("www.contoso.com") + .withCookieBasedAffinity() + .attach() + .apply(); stopwatch.stop(); System.out.println("Application gateway updated: (took " + (stopwatch.getTime() / 1000) + " seconds)"); @@ -318,8 +314,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java index fee812e6df368..a7d947c52c683 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.network.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -46,64 +45,67 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // create Express Route Circuit System.out.println("Creating express route circuit..."); - ExpressRouteCircuit erc = azureResourceManager.expressRouteCircuits().define(ercName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withServiceProvider("Equinix") - .withPeeringLocation("Silicon Valley") - .withBandwidthInMbps(50) - .withSku(ExpressRouteCircuitSkuType.PREMIUM_METEREDDATA) - .create(); + ExpressRouteCircuit erc = azureResourceManager.expressRouteCircuits() + .define(ercName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withServiceProvider("Equinix") + .withPeeringLocation("Silicon Valley") + .withBandwidthInMbps(50) + .withSku(ExpressRouteCircuitSkuType.PREMIUM_METEREDDATA) + .create(); System.out.println("Created express route circuit"); //============================================================ // Create Express Route circuit peering. Please note: express route circuit should be provisioned by connectivity provider before this step. System.out.println("Creating express route circuit peering..."); - erc.peerings().defineAzurePrivatePeering() - .withPrimaryPeerAddressPrefix("123.0.0.0/30") - .withSecondaryPeerAddressPrefix("123.0.0.4/30") - .withVlanId(200) - .withPeerAsn(100) - .create(); + erc.peerings() + .defineAzurePrivatePeering() + .withPrimaryPeerAddressPrefix("123.0.0.0/30") + .withSecondaryPeerAddressPrefix("123.0.0.4/30") + .withVlanId(200) + .withPeerAsn(100) + .create(); System.out.println("Created express route circuit peering"); //============================================================ // Adding authorization to express route circuit - erc.update() - .withAuthorization("myAuthorization") - .apply(); + erc.update().withAuthorization("myAuthorization").apply(); //============================================================ // Create virtual network to be associated with virtual network gateway System.out.println("Creating virtual network..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("192.168.0.0/16") - .withSubnet("GatewaySubnet", "192.168.200.0/26") - .withSubnet("FrontEnd", "192.168.1.0/24") - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .withSubnet("GatewaySubnet", "192.168.200.0/26") + .withSubnet("FrontEnd", "192.168.1.0/24") + .create(); //============================================================ // Create virtual network gateway System.out.println("Creating virtual network gateway..."); - VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways().define(gatewayName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withExistingNetwork(network) - .withExpressRoute() - .withSku(VirtualNetworkGatewaySkuName.STANDARD) - .create(); + VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways() + .define(gatewayName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withExistingNetwork(network) + .withExpressRoute() + .withSku(VirtualNetworkGatewaySkuName.STANDARD) + .create(); System.out.println("Created virtual network gateway"); //============================================================ // Create virtual network gateway connection System.out.println("Creating virtual network gateway connection..."); - vngw1.connections().define(connectionName) - .withExpressRoute(erc) - // Note: authorization key is required only in case express route circuit and virtual network gateway are in different subscriptions - // .withAuthorization(erc.inner().authorizations().get(0).authorizationKey()) - .create(); + vngw1.connections() + .define(connectionName) + .withExpressRoute(erc) + // Note: authorization key is required only in case express route circuit and virtual network gateway are in different subscriptions + // .withAuthorization(erc.inner().authorizations().get(0).authorizationKey()) + .create(); System.out.println("Created virtual network gateway connection"); return true; @@ -133,8 +135,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java index ab9cc661e4b7f..77c18ad291295 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.network.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -34,61 +33,64 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // list Express Route Cross Connections System.out.println("List express route cross connection..."); - azureResourceManager.expressRouteCrossConnections().list().forEach(expressRouteCrossConnection -> - System.out.println(expressRouteCrossConnection.name())); + azureResourceManager.expressRouteCrossConnections() + .list() + .forEach(expressRouteCrossConnection -> System.out.println(expressRouteCrossConnection.name())); System.out.println(); //============================================================ // get Express Route Cross Connection by id - ExpressRouteCrossConnection crossConnection = azureResourceManager.expressRouteCrossConnections().getById(connectionId); + ExpressRouteCrossConnection crossConnection + = azureResourceManager.expressRouteCrossConnections().getById(connectionId); //============================================================ // create Express Route Cross Connection private peering crossConnection.peerings() - .defineAzurePrivatePeering() - .withPrimaryPeerAddressPrefix("10.0.0.0/30") - .withSecondaryPeerAddressPrefix("10.0.0.4/30") - .withVlanId(100) - .withPeerAsn(500) - .withSharedKey("A1B2C3D4") - .create(); + .defineAzurePrivatePeering() + .withPrimaryPeerAddressPrefix("10.0.0.0/30") + .withSecondaryPeerAddressPrefix("10.0.0.4/30") + .withVlanId(100) + .withPeerAsn(500) + .withSharedKey("A1B2C3D4") + .create(); //============================================================ // create Express Route Cross Connection Microsoft peering crossConnection.peerings() - .defineMicrosoftPeering() - .withAdvertisedPublicPrefixes("123.1.0.0/24") - .withCustomerAsn(45) - .withRoutingRegistryName("ARIN") - .withPrimaryPeerAddressPrefix("10.0.0.0/30") - .withSecondaryPeerAddressPrefix("10.0.0.4/30") - .withVlanId(600) - .withPeerAsn(500) - .withSharedKey("A1B2C3D4") - .defineIpv6Config() - .withAdvertisedPublicPrefix("3FFE:FFFF:0:CD31::/120") - .withCustomerAsn(23) - .withRoutingRegistryName("ARIN") - .withPrimaryPeerAddressPrefix("3FFE:FFFF:0:CD30::/126") - .withSecondaryPeerAddressPrefix("3FFE:FFFF:0:CD30::4/126") - .attach() - .create(); + .defineMicrosoftPeering() + .withAdvertisedPublicPrefixes("123.1.0.0/24") + .withCustomerAsn(45) + .withRoutingRegistryName("ARIN") + .withPrimaryPeerAddressPrefix("10.0.0.0/30") + .withSecondaryPeerAddressPrefix("10.0.0.4/30") + .withVlanId(600) + .withPeerAsn(500) + .withSharedKey("A1B2C3D4") + .defineIpv6Config() + .withAdvertisedPublicPrefix("3FFE:FFFF:0:CD31::/120") + .withCustomerAsn(23) + .withRoutingRegistryName("ARIN") + .withPrimaryPeerAddressPrefix("3FFE:FFFF:0:CD30::/126") + .withSecondaryPeerAddressPrefix("3FFE:FFFF:0:CD30::4/126") + .attach() + .create(); //============================================================ // update Microsoft peering crossConnection.peerings() - .getByName("MicrosoftPeering") - .update() - .withoutIpv6Config() - .withAdvertisedPublicPrefixes("123.1.0.0/30") - .apply(); + .getByName("MicrosoftPeering") + .update() + .withoutIpv6Config() + .withAdvertisedPublicPrefixes("123.1.0.0/30") + .apply(); //============================================================ // update private peering from crossconnection resource - crossConnection.peeringsMap().get("AzurePrivatePeering") - .update() - .withPrimaryPeerAddressPrefix("10.1.0.0/30") - .apply(); + crossConnection.peeringsMap() + .get("AzurePrivatePeering") + .update() + .withPrimaryPeerAddressPrefix("10.1.0.0/30") + .apply(); //============================================================ // delete peerings @@ -112,8 +114,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java index 3f6a59b94d577..e3e31d716978b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java @@ -54,11 +54,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a public IP address..."); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(publicIPAddressName1) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withLeafDomainLabel(publicIPAddressLeafDNS1) - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(publicIPAddressName1) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withLeafDomainLabel(publicIPAddressLeafDNS1) + .create(); System.out.println("Created a public IP address"); @@ -71,25 +72,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - VirtualMachine vm = azureResourceManager.virtualMachines().define(vmName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIPAddress) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine vm = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIPAddress) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t2 = new Date(); - System.out.println("Created VM: (took " - + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id()); + System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id()); // Print virtual machine details Utils.print(vm); - //============================================================ // Gets the public IP address associated with the VM's primary NIC @@ -97,27 +97,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Print the public IP address details Utils.print(vm.getPrimaryPublicIPAddress()); - //============================================================ // Assign a new public IP address for the VM // Define a new public IP address - PublicIpAddress publicIpAddress2 = azureResourceManager.publicIpAddresses().define(publicIPAddressName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withLeafDomainLabel(publicIPAddressLeafDNS2) - .create(); + PublicIpAddress publicIpAddress2 = azureResourceManager.publicIpAddresses() + .define(publicIPAddressName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withLeafDomainLabel(publicIPAddressLeafDNS2) + .create(); // Update VM's primary NIC to use the new public IP address System.out.println("Updating the VM's primary NIC with new public IP address"); NetworkInterface primaryNetworkInterface = vm.getPrimaryNetworkInterface(); - primaryNetworkInterface.update() - .withExistingPrimaryPublicIPAddress(publicIpAddress2) - .apply(); - + primaryNetworkInterface.update().withExistingPrimaryPublicIPAddress(publicIpAddress2).apply(); //============================================================ // Gets the updated public IP address associated with the VM @@ -127,7 +124,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { vm.refresh(); Utils.print(vm.getPrimaryPublicIPAddress()); - //============================================================ // Remove public IP associated with the VM @@ -135,13 +131,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { vm.refresh(); primaryNetworkInterface = vm.getPrimaryNetworkInterface(); publicIPAddress = primaryNetworkInterface.primaryIPConfiguration().getPublicIpAddress(); - primaryNetworkInterface.update() - .withoutPrimaryPublicIPAddress() - .apply(); + primaryNetworkInterface.update().withoutPrimaryPublicIPAddress().apply(); System.out.println("Removed public IP address associated with the VM"); - //============================================================ // Delete the public ip System.out.println("Deleting the public IP address"); @@ -168,7 +161,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { - try { //============================================================= @@ -179,8 +171,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java index a9dbbf50cf5f5..bd82f32d709b4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java @@ -100,24 +100,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String vmName3 = Utils.randomResourceName(azureResourceManager, "lVM3", 24); final String vmName4 = Utils.randomResourceName(azureResourceManager, "lVM4", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; try { //============================================================= // Create a virtual network with a frontend and a backend subnets System.out.println("Creating virtual network with a frontend and a backend subnets..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .defineSubnet("Back-end") - .withAddressPrefix("172.16.3.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .defineSubnet("Back-end") + .withAddressPrefix("172.16.3.0/24") + .attach() + .create(); System.out.println("Created a virtual network"); // Print the virtual network details @@ -139,70 +141,71 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating an internal facing load balancer with ..."); System.out.println("- A private IP address"); System.out.println("- One backend address pool which contain network interfaces for the virtual\n" - + " machines to receive 1521 network traffic from the load balancer"); + + " machines to receive 1521 network traffic from the load balancer"); System.out.println("- One load balancing rules for 1521 to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- One probe which contains HTTP health probe used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer3 = azureResourceManager.loadBalancers().define(loadBalancerName3) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - - // Add one rule that uses above backend and probe - .defineLoadBalancingRule(tcpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(orcaleSQLNodePort) - .toBackend(backendPoolName3) - .withProbe(httpProbe) - .attach() - - // Add two nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatRule(natRule6000to22forVM3) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6000) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule6001to23forVM3) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6001) - .toBackendPort(23) - .attach() - - .defineInboundNatRule(natRule6002to22forVM4) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6002) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule6003to23forVM4) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6003) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePrivateFrontend(privateFrontEndName) - .withExistingSubnet(network, "Back-end") - .withPrivateIpAddressStatic("172.16.3.5") - .attach() - - // Add one probes - one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer3 = azureResourceManager.loadBalancers() + .define(loadBalancerName3) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + + // Add one rule that uses above backend and probe + .defineLoadBalancingRule(tcpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(orcaleSQLNodePort) + .toBackend(backendPoolName3) + .withProbe(httpProbe) + .attach() + + // Add two nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatRule(natRule6000to22forVM3) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6000) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule6001to23forVM3) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6001) + .toBackendPort(23) + .attach() + + .defineInboundNatRule(natRule6002to22forVM4) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6002) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule6003to23forVM4) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6003) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePrivateFrontend(privateFrontEndName) + .withExistingSubnet(network, "Back-end") + .withPrivateIpAddressStatic("172.16.3.5") + .attach() + + // Add one probes - one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + + .create(); // Print load balancer details System.out.println("Created an internal load balancer"); @@ -212,35 +215,38 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Define two network interfaces in the backend subnet // associate network interfaces to NAT rules, backend pools - Creatable networkInterface3Creatable = azureResourceManager.networkInterfaces().define(networkInterfaceName3) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Back-end") - .withPrimaryPrivateIPAddressDynamic() - .withExistingLoadBalancerBackend(loadBalancer3, backendPoolName3) - .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6000to22forVM3) - .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6001to23forVM3); - - Creatable networkInterface4Creatable = azureResourceManager.networkInterfaces().define(networkInterfaceName4) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Back-end") - .withPrimaryPrivateIPAddressDynamic() - .withExistingLoadBalancerBackend(loadBalancer3, backendPoolName3) - .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6002to22forVM4) - .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6003to23forVM4); + Creatable networkInterface3Creatable = azureResourceManager.networkInterfaces() + .define(networkInterfaceName3) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Back-end") + .withPrimaryPrivateIPAddressDynamic() + .withExistingLoadBalancerBackend(loadBalancer3, backendPoolName3) + .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6000to22forVM3) + .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6001to23forVM3); + + Creatable networkInterface4Creatable = azureResourceManager.networkInterfaces() + .define(networkInterfaceName4) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Back-end") + .withPrimaryPrivateIPAddressDynamic() + .withExistingLoadBalancerBackend(loadBalancer3, backendPoolName3) + .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6002to22forVM4) + .withExistingLoadBalancerInboundNatRule(loadBalancer3, natRule6003to23forVM4); //============================================================= // Define an availability set - Creatable availSet2Definition = azureResourceManager.availabilitySets().define(availSetName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withFaultDomainCount(2) - .withUpdateDomainCount(4) - .withSku(AvailabilitySetSkuTypes.ALIGNED); + Creatable availSet2Definition = azureResourceManager.availabilitySets() + .define(availSetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withFaultDomainCount(2) + .withUpdateDomainCount(4) + .withSku(AvailabilitySetSkuTypes.ALIGNED); //============================================================= // Create two virtual machines and assign network interfaces @@ -250,34 +256,37 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List> virtualMachineCreateables2 = new ArrayList>(); - Creatable virtualMachine3Creatable = azureResourceManager.virtualMachines().define(vmName3) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetworkInterface(networkInterface3Creatable) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availSet2Definition); + Creatable virtualMachine3Creatable = azureResourceManager.virtualMachines() + .define(vmName3) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetworkInterface(networkInterface3Creatable) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availSet2Definition); virtualMachineCreateables2.add(virtualMachine3Creatable); - Creatable virtualMachine4Creatable = azureResourceManager.virtualMachines().define(vmName4) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetworkInterface(networkInterface4Creatable) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availSet2Definition); + Creatable virtualMachine4Creatable = azureResourceManager.virtualMachines() + .define(vmName4) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetworkInterface(networkInterface4Creatable) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availSet2Definition); virtualMachineCreateables2.add(virtualMachine4Creatable); StopWatch stopwatch = new StopWatch(); stopwatch.start(); - Collection virtualMachines = azureResourceManager.virtualMachines().create(virtualMachineCreateables2).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(virtualMachineCreateables2).values(); stopwatch.stop(); System.out.println("Created 2 Linux VMs: (took " + (stopwatch.getTime() / 1000) + " seconds) "); @@ -296,14 +305,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating the load balancer ..."); loadBalancer3.update() - .updateLoadBalancingRule(tcpLoadBalancingRule) - .withIdleTimeoutInMinutes(15) - .parent() - .apply(); + .updateLoadBalancingRule(tcpLoadBalancingRule) + .withIdleTimeoutInMinutes(15) + .parent() + .apply(); System.out.println("Update the load balancer with a TCP idle timeout to 15 minutes"); - //============================================================= // Create another internal load balancer // Create a frontend IP address @@ -320,70 +328,71 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another internal facing load balancer with ..."); System.out.println("- A private IP address"); System.out.println("- One backend address pool which contain network interfaces for the virtual\n" - + " machines to receive 1521 network traffic from the load balancer"); + + " machines to receive 1521 network traffic from the load balancer"); System.out.println("- One load balancing rules for 1521 to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- One probe which contains HTTP health probe used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer4 = azureResourceManager.loadBalancers().define(loadBalancerName4) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - - // Add one rule that uses above backend and probe - .defineLoadBalancingRule(tcpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(orcaleSQLNodePort) - .toBackend(backendPoolName3) - .withProbe(httpProbe) - .attach() - - // Add two nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatRule(natRule6000to22forVM3) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6000) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule6001to23forVM3) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6001) - .toBackendPort(23) - .attach() - - .defineInboundNatRule(natRule6002to22forVM4) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6002) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule6003to23forVM4) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(privateFrontEndName) - .fromFrontendPort(6003) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePrivateFrontend(privateFrontEndName) - .withExistingSubnet(network, "Back-end") - .withPrivateIpAddressStatic("172.16.3.15") - .attach() - - // Add one probes - one per rule - .defineHttpProbe("httpProbe") - .withRequestPath("/") - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer4 = azureResourceManager.loadBalancers() + .define(loadBalancerName4) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + + // Add one rule that uses above backend and probe + .defineLoadBalancingRule(tcpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(orcaleSQLNodePort) + .toBackend(backendPoolName3) + .withProbe(httpProbe) + .attach() + + // Add two nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatRule(natRule6000to22forVM3) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6000) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule6001to23forVM3) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6001) + .toBackendPort(23) + .attach() + + .defineInboundNatRule(natRule6002to22forVM4) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6002) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule6003to23forVM4) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(privateFrontEndName) + .fromFrontendPort(6003) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePrivateFrontend(privateFrontEndName) + .withExistingSubnet(network, "Back-end") + .withPrivateIpAddressStatic("172.16.3.15") + .attach() + + // Add one probes - one per rule + .defineHttpProbe("httpProbe") + .withRequestPath("/") + .attach() + + .create(); // Print load balancer details System.out.println("Created an internal load balancer"); @@ -401,12 +410,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println(); } - //============================================================= // Remove a load balancer - System.out.println("Deleting load balancer " + loadBalancerName4 - + "(" + loadBalancer4.id() + ")"); + System.out.println("Deleting load balancer " + loadBalancerName4 + "(" + loadBalancer4.id() + ")"); azureResourceManager.loadBalancers().deleteById(loadBalancer4.id()); System.out.println("Deleted load balancer" + loadBalancerName4); @@ -440,8 +447,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java index ec594ba75a6fe..c3761e4b22558 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java @@ -101,24 +101,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String availSetName = Utils.randomResourceName(azureResourceManager, "av", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; try { //============================================================= // Create a virtual network with a frontend and a backend subnets System.out.println("Creating virtual network with a frontend and a backend subnets..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .defineSubnet("Back-end") - .withAddressPrefix("172.16.3.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .defineSubnet("Back-end") + .withAddressPrefix("172.16.3.0/24") + .attach() + .create(); System.out.println("Created a virtual network"); @@ -129,11 +131,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a public IP address System.out.println("Creating a public IP address..."); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(publicIpName1) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName1) - .create(); + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(publicIpName1) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName1) + .create(); System.out.println("Created a public IP address"); @@ -156,83 +159,84 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Internet facing load balancer with ..."); System.out.println("- A frontend public IP address"); System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" - + " machines to receive HTTP and HTTPS network traffic from the load balancer"); + + " machines to receive HTTP and HTTPS network traffic from the load balancer"); System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers().define(loadBalancerName1) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - - // Add two nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatRule(natRule5000to22forVM1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5000) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule5001to23forVM1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5001) - .toBackendPort(23) - .attach() - - .defineInboundNatRule(natRule5002to22forVM2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5002) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule5003to23forVM2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5003) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIPAddress) - .attach() - - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer1 = azureResourceManager.loadBalancers() + .define(loadBalancerName1) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + + // Add two nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatRule(natRule5000to22forVM1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5000) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule5001to23forVM1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5001) + .toBackendPort(23) + .attach() + + .defineInboundNatRule(natRule5002to22forVM2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5002) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule5003to23forVM2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5003) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIPAddress) + .attach() + + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) + .attach() + + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + + .create(); // Print load balancer details System.out.println("Created a load balancer"); @@ -247,43 +251,44 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List> networkInterfaceCreatables = new ArrayList>(); - Creatable networkInterface1Creatable = azureResourceManager.networkInterfaces().define(networkInterfaceName1) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Front-end") - .withPrimaryPrivateIPAddressDynamic() - .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1) - .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2) - .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5000to22forVM1) - .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5001to23forVM1); + Creatable networkInterface1Creatable = azureResourceManager.networkInterfaces() + .define(networkInterfaceName1) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Front-end") + .withPrimaryPrivateIPAddressDynamic() + .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1) + .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2) + .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5000to22forVM1) + .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5001to23forVM1); networkInterfaceCreatables.add(networkInterface1Creatable); - Creatable networkInterface2Creatable = azureResourceManager.networkInterfaces().define(networkInterfaceName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Front-end") - .withPrimaryPrivateIPAddressDynamic() - .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1) - .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2) - .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5002to22forVM2) - .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5003to23forVM2); + Creatable networkInterface2Creatable = azureResourceManager.networkInterfaces() + .define(networkInterfaceName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Front-end") + .withPrimaryPrivateIPAddressDynamic() + .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1) + .withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2) + .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5002to22forVM2) + .withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5003to23forVM2); networkInterfaceCreatables.add(networkInterface2Creatable); - //============================================================= // Define an availability set - Creatable availSet1Definition = azureResourceManager.availabilitySets().define(availSetName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withFaultDomainCount(2) - .withUpdateDomainCount(4) - .withSku(AvailabilitySetSkuTypes.ALIGNED); - + Creatable availSet1Definition = azureResourceManager.availabilitySets() + .define(availSetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withFaultDomainCount(2) + .withUpdateDomainCount(4) + .withSku(AvailabilitySetSkuTypes.ALIGNED); //============================================================= // Create two virtual machines and assign network interfaces @@ -294,21 +299,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List> virtualMachineCreateables1 = new ArrayList>(); for (Creatable nicDefinition : networkInterfaceCreatables) { - virtualMachineCreateables1.add(azureResourceManager.virtualMachines().define(Utils.randomResourceName(azureResourceManager, "lVM1", 24)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetworkInterface(nicDefinition) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(availSet1Definition)); + virtualMachineCreateables1.add(azureResourceManager.virtualMachines() + .define(Utils.randomResourceName(azureResourceManager, "lVM1", 24)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetworkInterface(nicDefinition) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(availSet1Definition)); } StopWatch stopwatch = new StopWatch(); stopwatch.start(); - Collection virtualMachines = azureResourceManager.virtualMachines().create(virtualMachineCreateables1).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(virtualMachineCreateables1).values(); stopwatch.stop(); System.out.println("Created 2 Linux VMs: (took " + (stopwatch.getTime() / 1000) + " seconds) "); @@ -327,32 +334,31 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updating the load balancer ..."); loadBalancer1.update() - .updateLoadBalancingRule(httpLoadBalancingRule) - .withIdleTimeoutInMinutes(15) - .parent() - .updateLoadBalancingRule(httpsLoadBalancingRule) - .withIdleTimeoutInMinutes(15) - .parent() - .apply(); + .updateLoadBalancingRule(httpLoadBalancingRule) + .withIdleTimeoutInMinutes(15) + .parent() + .updateLoadBalancingRule(httpsLoadBalancingRule) + .withIdleTimeoutInMinutes(15) + .parent() + .apply(); System.out.println("Update the load balancer with a TCP idle timeout to 15 minutes"); - //============================================================= // Create another public IP address System.out.println("Creating another public IP address..."); - PublicIpAddress publicIpAddress2 = azureResourceManager.publicIpAddresses().define(publicIpName2) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName2) - .create(); + PublicIpAddress publicIpAddress2 = azureResourceManager.publicIpAddresses() + .define(publicIpName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName2) + .create(); System.out.println("Created another public IP address"); // Print the virtual network details Utils.print(publicIpAddress2); - //============================================================= // Create another Internet facing load balancer // Create a frontend IP address @@ -369,83 +375,84 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating another Internet facing load balancer with ..."); System.out.println("- A frontend IP address"); System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" - + " machines to receive HTTP and HTTPS network traffic from the load balancer"); + + " machines to receive HTTP and HTTPS network traffic from the load balancer"); System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" - + " balancer to ports in the backend address pool"); + + " balancer to ports in the backend address pool"); System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" - + " of virtual machines in the backend address pool"); + + " of virtual machines in the backend address pool"); System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" - + " balancer to a port for a specific virtual machine in the backend address pool\n" - + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); - - LoadBalancer loadBalancer2 = azureResourceManager.loadBalancers().define(loadBalancerName2) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - - // Add two rules that uses above backend and probe - .defineLoadBalancingRule(httpLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(80) - .toBackend(backendPoolName1) - .withProbe(httpProbe) - .attach() - - .defineLoadBalancingRule(httpsLoadBalancingRule) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(443) - .toBackend(backendPoolName2) - .withProbe(httpsProbe) - .attach() - - // Add two nat pools to enable direct VM connectivity for - // SSH to port 22 and TELNET to port 23 - .defineInboundNatRule(natRule5000to22forVM1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5000) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule5001to23forVM1) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5001) - .toBackendPort(23) - .attach() - - .defineInboundNatRule(natRule5002to22forVM2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5002) - .toBackendPort(22) - .attach() - - .defineInboundNatRule(natRule5003to23forVM2) - .withProtocol(TransportProtocol.TCP) - .fromFrontend(frontendName) - .fromFrontendPort(5003) - .toBackendPort(23) - .attach() - - // Explicitly define the frontend - .definePublicFrontend(frontendName) - .withExistingPublicIpAddress(publicIpAddress2) - .attach() - - // Add two probes one per rule - .defineHttpProbe(httpProbe) - .withRequestPath("/") - .withPort(80) - .attach() - - .defineHttpProbe(httpsProbe) - .withRequestPath("/") - .withPort(443) - .attach() - - .create(); + + " balancer to a port for a specific virtual machine in the backend address pool\n" + + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); + + LoadBalancer loadBalancer2 = azureResourceManager.loadBalancers() + .define(loadBalancerName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + + // Add two rules that uses above backend and probe + .defineLoadBalancingRule(httpLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(80) + .toBackend(backendPoolName1) + .withProbe(httpProbe) + .attach() + + .defineLoadBalancingRule(httpsLoadBalancingRule) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(443) + .toBackend(backendPoolName2) + .withProbe(httpsProbe) + .attach() + + // Add two nat pools to enable direct VM connectivity for + // SSH to port 22 and TELNET to port 23 + .defineInboundNatRule(natRule5000to22forVM1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5000) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule5001to23forVM1) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5001) + .toBackendPort(23) + .attach() + + .defineInboundNatRule(natRule5002to22forVM2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5002) + .toBackendPort(22) + .attach() + + .defineInboundNatRule(natRule5003to23forVM2) + .withProtocol(TransportProtocol.TCP) + .fromFrontend(frontendName) + .fromFrontendPort(5003) + .toBackendPort(23) + .attach() + + // Explicitly define the frontend + .definePublicFrontend(frontendName) + .withExistingPublicIpAddress(publicIpAddress2) + .attach() + + // Add two probes one per rule + .defineHttpProbe(httpProbe) + .withRequestPath("/") + .withPort(80) + .attach() + + .defineHttpProbe(httpsProbe) + .withRequestPath("/") + .withPort(443) + .attach() + + .create(); // Print load balancer details System.out.println("Created another load balancer"); @@ -462,12 +469,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(loadBalancer); } - //============================================================= // Remove a load balancer - System.out.println("Deleting load balancer " + loadBalancerName2 - + "(" + loadBalancer2.id() + ")"); + System.out.println("Deleting load balancer " + loadBalancerName2 + "(" + loadBalancer2.id() + ")"); azureResourceManager.loadBalancers().deleteById(loadBalancer2.id()); System.out.println("Deleted load balancer" + loadBalancerName2); @@ -501,8 +506,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java index 016a6fad16569..57ffb17f144f3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java @@ -59,20 +59,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a virtual network ..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .defineSubnet("Mid-tier") - .withAddressPrefix("172.16.2.0/24") - .attach() - .defineSubnet("Back-end") - .withAddressPrefix("172.16.3.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .defineSubnet("Mid-tier") + .withAddressPrefix("172.16.2.0/24") + .attach() + .defineSubnet("Back-end") + .withAddressPrefix("172.16.3.0/24") + .attach() + .create(); System.out.println("Created a virtual network: " + network.id()); Utils.print(network); @@ -80,45 +81,47 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating multiple network interfaces"); System.out.println("Creating network interface 1"); - NetworkInterface networkInterface1 = azureResourceManager.networkInterfaces().define(networkInterfaceName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Front-end") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1) - .withIPForwarding() - .create(); + NetworkInterface networkInterface1 = azureResourceManager.networkInterfaces() + .define(networkInterfaceName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Front-end") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1) + .withIPForwarding() + .create(); System.out.println("Created network interface 1"); Utils.print(networkInterface1); System.out.println("Creating network interface 2"); - NetworkInterface networkInterface2 = azureResourceManager.networkInterfaces().define(networkInterfaceName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Mid-tier") - .withPrimaryPrivateIPAddressDynamic() - .create(); + NetworkInterface networkInterface2 = azureResourceManager.networkInterfaces() + .define(networkInterfaceName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Mid-tier") + .withPrimaryPrivateIPAddressDynamic() + .create(); System.out.println("Created network interface 2"); Utils.print(networkInterface2); System.out.println("Creating network interface 3"); - NetworkInterface networkInterface3 = azureResourceManager.networkInterfaces().define(networkInterfaceName3) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Back-end") - .withPrimaryPrivateIPAddressDynamic() - .create(); + NetworkInterface networkInterface3 = azureResourceManager.networkInterfaces() + .define(networkInterfaceName3) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Back-end") + .withPrimaryPrivateIPAddressDynamic() + .create(); System.out.println("Created network interface 3"); Utils.print(networkInterface3); - //============================================================= // Create a virtual machine with multiple network interfaces @@ -126,47 +129,43 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - VirtualMachine vm = azureResourceManager.virtualMachines().define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetworkInterface(networkInterface1) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(userName) - .withAdminPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D8a_v4")) - .withExistingSecondaryNetworkInterface(networkInterface2) - .withExistingSecondaryNetworkInterface(networkInterface3) - .create(); + VirtualMachine vm = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetworkInterface(networkInterface1) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D8a_v4")) + .withExistingSecondaryNetworkInterface(networkInterface2) + .withExistingSecondaryNetworkInterface(networkInterface3) + .create(); Date t2 = new Date(); - System.out.println("Created VM: (took " - + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id()); + System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id()); // Print virtual machine details Utils.print(vm); - // =========================================================== // Configure a network interface System.out.println("Updating the first network interface"); - networkInterface1.update() - .withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS2) - .apply(); + networkInterface1.update().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS2).apply(); System.out.println("Updated the first network interface"); Utils.print(networkInterface1); System.out.println(); - //============================================================ // List network interfaces System.out.println("Walking through network inter4faces in resource group: " + rgName); - PagedIterable networkInterfaces = azureResourceManager.networkInterfaces().listByResourceGroup(rgName); + PagedIterable networkInterfaces + = azureResourceManager.networkInterfaces().listByResourceGroup(rgName); for (NetworkInterface networkinterface : networkInterfaces) { Utils.print(networkinterface); } - //============================================================ // Delete a network interface @@ -215,8 +214,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java index 9baff309f6196..41be1957b2a41 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java @@ -78,21 +78,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating two virtual networks in the same region and subscription..."); - Creatable networkADefinition = azureResourceManager.networks().define(vnetAName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withAddressSpace("10.0.0.0/27") - .withSubnet("subnet1", "10.0.0.0/28") - .withSubnet("subnet2", "10.0.0.16/28"); - - Creatable networkBDefinition = azureResourceManager.networks().define(vnetBName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withAddressSpace("10.1.0.0/27") - .withSubnet("subnet3", "10.1.0.0/27"); + Creatable networkADefinition = azureResourceManager.networks() + .define(vnetAName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withAddressSpace("10.0.0.0/27") + .withSubnet("subnet1", "10.0.0.0/28") + .withSubnet("subnet2", "10.0.0.16/28"); + + Creatable networkBDefinition = azureResourceManager.networks() + .define(vnetBName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withAddressSpace("10.1.0.0/27") + .withSubnet("subnet3", "10.1.0.0/27"); // Create the networks in parallel for better performance - CreatedResources created = azureResourceManager.networks().create(Arrays.asList(networkADefinition, networkBDefinition)); + CreatedResources created + = azureResourceManager.networks().create(Arrays.asList(networkADefinition, networkBDefinition)); // Print virtual network details for (Network network : created.values()) { @@ -107,15 +110,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Peer the two networks using default settings - System.out.println( - "Peering the networks using default settings...\n" - + "- Network access enabled\n" - + "- Traffic forwarding disabled\n" - + "- Gateway use (transit) by the peered network disabled"); + System.out.println("Peering the networks using default settings...\n" + "- Network access enabled\n" + + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the peered network disabled"); - NetworkPeering peeringAB = networkA.peerings().define(peeringABName) - .withRemoteNetwork(networkB) - .create(); // This implicitly creates a matching peering object on network B as well, if both networks are in the same subscription + NetworkPeering peeringAB = networkA.peerings().define(peeringABName).withRemoteNetwork(networkB).create(); // This implicitly creates a matching peering object on network B as well, if both networks are in the same subscription // Print network details showing new peering System.out.println("Created a peering"); @@ -126,12 +124,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Update a the peering disallowing access from B to A but allowing traffic forwarding from B to A System.out.println("Updating the peering ..."); - peeringAB.update() - .withoutAccessFromEitherNetwork() - .withTrafficForwardingFromRemoteNetwork() - .apply(); + peeringAB.update().withoutAccessFromEitherNetwork().withTrafficForwardingFromRemoteNetwork().apply(); - System.out.println("Updated the peering to disallow network access between B and A but allow traffic forwarding from B to A."); + System.out.println( + "Updated the peering to disallow network access between B and A but allow traffic forwarding from B to A."); //============================================================= // Show the new network information @@ -179,8 +175,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java index 8536107ae4925..57be006828ddc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java @@ -43,7 +43,8 @@ public final class ManageNetworkSecurityGroup { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws UnsupportedEncodingException, JSchException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws UnsupportedEncodingException, JSchException { final Region region = Region.US_WEST; final String frontEndNSGName = Utils.randomResourceName(azureResourceManager, "fensg", 24); final String backEndNSGName = Utils.randomResourceName(azureResourceManager, "bensg", 24); @@ -62,17 +63,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a virtual network ..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .attach() - .defineSubnet("Back-end") - .withAddressPrefix("172.16.2.0/24") - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .attach() + .defineSubnet("Back-end") + .withAddressPrefix("172.16.2.0/24") + .attach() + .create(); System.out.println("Created a virtual network: " + network.id()); Utils.print(network); @@ -84,35 +86,35 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // - ALLOW-WEB- allows HTTP traffic into the front end subnet System.out.println("Creating a security group for the front end - allows SSH and HTTP"); - NetworkSecurityGroup frontEndNSG = azureResourceManager.networkSecurityGroups().define(frontEndNSGName) - .withRegion(region) - .withNewResourceGroup(rgName) - .defineRule("ALLOW-SSH") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPort(22) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(100) - .withDescription("Allow SSH") - .attach() - .defineRule("ALLOW-HTTP") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(101) - .withDescription("Allow HTTP") - .attach() - .create(); + NetworkSecurityGroup frontEndNSG = azureResourceManager.networkSecurityGroups() + .define(frontEndNSGName) + .withRegion(region) + .withNewResourceGroup(rgName) + .defineRule("ALLOW-SSH") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPort(22) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(100) + .withDescription("Allow SSH") + .attach() + .defineRule("ALLOW-HTTP") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(101) + .withDescription("Allow HTTP") + .attach() + .create(); System.out.println("Created a security group for the front end: " + frontEndNSG.id()); Utils.print(frontEndNSG); - //============================================================ // Create a network security group for the back end of a subnet // back end subnet contains two rules @@ -120,32 +122,33 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // - DENY-WEB - denies all outbound internet traffic from the back end subnet System.out.println("Creating a security group for the front end - allows SSH and " - + "denies all outbound internet traffic "); - - NetworkSecurityGroup backEndNSG = azureResourceManager.networkSecurityGroups().define(backEndNSGName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .defineRule("ALLOW-SQL") - .allowInbound() - .fromAddress("172.16.1.0/24") - .fromAnyPort() - .toAnyAddress() - .toPort(1433) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(100) - .withDescription("Allow SQL") - .attach() - .defineRule("DENY-WEB") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toAnyPort() - .withAnyProtocol() - .withDescription("Deny Web") - .withPriority(200) - .attach() - .create(); + + "denies all outbound internet traffic "); + + NetworkSecurityGroup backEndNSG = azureResourceManager.networkSecurityGroups() + .define(backEndNSGName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineRule("ALLOW-SQL") + .allowInbound() + .fromAddress("172.16.1.0/24") + .fromAnyPort() + .toAnyAddress() + .toPort(1433) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(100) + .withDescription("Allow SQL") + .attach() + .defineRule("DENY-WEB") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toAnyPort() + .withAnyProtocol() + .withDescription("Deny Web") + .withPriority(200) + .attach() + .create(); System.out.println("Created a security group for the back end: " + backEndNSG.id()); Utils.print(backEndNSG); @@ -153,126 +156,125 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating multiple network interfaces"); System.out.println("Creating network interface 1"); - //======================================================== // Create a network interface and apply the // front end network security group System.out.println("Creating a network interface for the front end"); - NetworkInterface networkInterface1 = azureResourceManager.networkInterfaces().define(networkInterfaceName1) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Front-end") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1) - .withIPForwarding() - .withExistingNetworkSecurityGroup(frontEndNSG) - .create(); + NetworkInterface networkInterface1 = azureResourceManager.networkInterfaces() + .define(networkInterfaceName1) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Front-end") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1) + .withIPForwarding() + .withExistingNetworkSecurityGroup(frontEndNSG) + .create(); System.out.println("Created network interface for the front end"); Utils.print(networkInterface1); - //======================================================== // Create a network interface and apply the // back end network security group System.out.println("Creating a network interface for the back end"); - NetworkInterface networkInterface2 = azureResourceManager.networkInterfaces().define(networkInterfaceName2) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("Back-end") - .withPrimaryPrivateIPAddressDynamic() - .withExistingNetworkSecurityGroup(backEndNSG) - .create(); + NetworkInterface networkInterface2 = azureResourceManager.networkInterfaces() + .define(networkInterfaceName2) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("Back-end") + .withPrimaryPrivateIPAddressDynamic() + .withExistingNetworkSecurityGroup(backEndNSG) + .create(); Utils.print(networkInterface2); - //============================================================= // Create a virtual machine (for the front end) // with the network interface that has the network security group for the front end System.out.println("Creating a Linux virtual machine (for the front end) - " - + "with the network interface that has the network security group for the front end"); + + "with the network interface that has the network security group for the front end"); Date t1 = new Date(); - VirtualMachine frontEndVM = azureResourceManager.virtualMachines().define(frontEndVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetworkInterface(networkInterface1) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine frontEndVM = azureResourceManager.virtualMachines() + .define(frontEndVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetworkInterface(networkInterface1) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t2 = new Date(); - System.out.println("Created Linux VM: (took " - + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id()); + System.out.println( + "Created Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id()); // Print virtual machine details Utils.print(frontEndVM); - //============================================================= // Create a virtual machine (for the back end) // with the network interface that has the network security group for the back end System.out.println("Creating a Linux virtual machine (for the back end) - " - + "with the network interface that has the network security group for the back end"); + + "with the network interface that has the network security group for the back end"); t1 = new Date(); - VirtualMachine backEndVM = azureResourceManager.virtualMachines().define(backEndVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetworkInterface(networkInterface2) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine backEndVM = azureResourceManager.virtualMachines() + .define(backEndVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetworkInterface(networkInterface2) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); t2 = new Date(); - System.out.println("Created a Linux VM: (took " - + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + backEndVM.id()); + System.out.println( + "Created a Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + backEndVM.id()); Utils.print(backEndVM); - //======================================================== // List network security groups System.out.println("Walking through network security groups"); - PagedIterable networkSecurityGroups = azureResourceManager.networkSecurityGroups().listByResourceGroup(rgName); + PagedIterable networkSecurityGroups + = azureResourceManager.networkSecurityGroups().listByResourceGroup(rgName); for (NetworkSecurityGroup networkSecurityGroup : networkSecurityGroups) { Utils.print(networkSecurityGroup); } - //======================================================== // Update a network security group System.out.println("Updating the front end network security group to allow FTP"); frontEndNSG.update() - .defineRule("ALLOW-FTP") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPortRange(20, 21) - .withProtocol(SecurityRuleProtocol.TCP) - .withDescription("Allow FTP") - .withPriority(200) - .attach() - .apply(); + .defineRule("ALLOW-FTP") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPortRange(20, 21) + .withProtocol(SecurityRuleProtocol.TCP) + .withDescription("Allow FTP") + .withPriority(200) + .attach() + .apply(); System.out.println("Updated the front end network security group"); Utils.print(frontEndNSG); @@ -298,7 +300,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw */ public static void main(String[] args) { - try { //============================================================= @@ -309,8 +310,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java index c416dcbdd8e17..3b8d4f343f480 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java @@ -94,10 +94,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create network watcher System.out.println("Creating network watcher..."); - nw = azureResourceManager.networkWatchers().define(nwName) - .withRegion(region) - .withNewResourceGroup() - .create(); + nw = azureResourceManager.networkWatchers() + .define(nwName) + .withRegion(region) + .withNewResourceGroup() + .create(); System.out.println("Created network watcher"); // Print the network watcher Utils.print(nw); @@ -107,69 +108,73 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create network security group, virtual network and VM; add packetCapture extension to enable System.out.println("Creating network security group..."); - NetworkSecurityGroup nsg = azureResourceManager.networkSecurityGroups().define(nsgName) - .withRegion(region) - .withNewResourceGroup(rgName) - .defineRule("DenyInternetInComing") - .denyInbound() - .fromAddress("INTERNET") - .fromAnyPort() - .toAnyAddress() - .toPort(443) - .withAnyProtocol() - .attach() - .create(); + NetworkSecurityGroup nsg = azureResourceManager.networkSecurityGroups() + .define(nsgName) + .withRegion(region) + .withNewResourceGroup(rgName) + .defineRule("DenyInternetInComing") + .denyInbound() + .fromAddress("INTERNET") + .fromAnyPort() + .toAnyAddress() + .toPort(443) + .withAnyProtocol() + .attach() + .create(); System.out.println("Defining a virtual network..."); - Creatable virtualNetworkDefinition = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withAddressSpace("192.168.0.0/16") - .defineSubnet(subnetName) - .withAddressPrefix("192.168.2.0/24") - .withExistingNetworkSecurityGroup(nsg) - .attach(); + Creatable virtualNetworkDefinition = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .defineSubnet(subnetName) + .withAddressPrefix("192.168.2.0/24") + .withExistingNetworkSecurityGroup(nsg) + .attach(); System.out.println("Creating a virtual machine..."); - VirtualMachine vm = azureResourceManager.virtualMachines().define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork(virtualNetworkDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(dnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername(userName) - .withRootPassword(Utils.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - // This extension is needed to enable packet capture - .defineNewExtension("packetCapture") - .withPublisher("Microsoft.Azure.NetworkWatcher") - .withType("NetworkWatcherAgentLinux") - .withVersion("1.4") - .withMinorVersionAutoUpgrade() - .attach() - .create(); + VirtualMachine vm = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork(virtualNetworkDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(dnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername(userName) + .withRootPassword(Utils.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + // This extension is needed to enable packet capture + .defineNewExtension("packetCapture") + .withPublisher("Microsoft.Azure.NetworkWatcher") + .withType("NetworkWatcherAgentLinux") + .withVersion("1.4") + .withMinorVersionAutoUpgrade() + .attach() + .create(); // Create storage account System.out.println("Creating storage account..."); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withGeneralPurposeAccountKindV2() - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withGeneralPurposeAccountKindV2() + .create(); // Start a packet capture System.out.println("Creating packet capture..."); PacketCapture packetCapture = nw.packetCaptures() - .define(packetCaptureName) - .withTarget(vm.id()) - .withStorageAccountId(storageAccount.id()) - .withStoragePath(storageAccount.endPoints().primary().blob() + packetCaptureStorageContainer) - .withTimeLimitInSeconds(1500) - .definePacketCaptureFilter() - .withProtocol(PcProtocol.TCP) - .attach() - .create(); + .define(packetCaptureName) + .withTarget(vm.id()) + .withStorageAccountId(storageAccount.id()) + .withStoragePath(storageAccount.endPoints().primary().blob() + packetCaptureStorageContainer) + .withTimeLimitInSeconds(1500) + .definePacketCaptureFilter() + .withProtocol(PcProtocol.TCP) + .attach() + .create(); System.out.println("Created packet capture"); Utils.print(packetCapture); @@ -194,23 +199,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Test IP flow on the NIC System.out.println("Verifying IP flow for VM ID " + vm.id() + "..."); VerificationIPFlow verificationIPFlow = nw.verifyIPFlow() - .withTargetResourceId(vm.id()) - .withDirection(Direction.INBOUND) - .withProtocol(IpFlowProtocol.TCP) - .withLocalIPAddress(ipAddress) - .withRemoteIPAddress("8.8.8.8") - .withLocalPort("443") - .withRemotePort("443") - .execute(); + .withTargetResourceId(vm.id()) + .withDirection(Direction.INBOUND) + .withProtocol(IpFlowProtocol.TCP) + .withLocalIPAddress(ipAddress) + .withRemoteIPAddress("8.8.8.8") + .withLocalPort("443") + .withRemotePort("443") + .execute(); Utils.print(verificationIPFlow); //============================================================ // Analyze next hop - get the next hop type and IP address for a virtual machine System.out.println("Calculating next hop..."); - NextHop nextHop = nw.nextHop().withTargetResourceId(vm.id()) - .withSourceIpAddress(ipAddress) - .withDestinationIpAddress("8.8.8.8") - .execute(); + NextHop nextHop = nw.nextHop() + .withTargetResourceId(vm.id()) + .withSourceIpAddress(ipAddress) + .withDestinationIpAddress("8.8.8.8") + .execute(); Utils.print(nextHop); //============================================================ @@ -235,11 +241,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Enable NSG flow log flowLogSettings.update() - .withLogging() - .withStorageAccount(storageAccount.id()) - .withRetentionPolicyDays(5) - .withRetentionPolicyEnabled() - .apply(); + .withLogging() + .withStorageAccount(storageAccount.id()) + .withRetentionPolicyDays(5) + .withRetentionPolicyEnabled() + .apply(); Utils.print(flowLogSettings); // wait for flow log to log an event @@ -248,9 +254,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Disable NSG flow log System.out.println("Disabling flow log..."); - flowLogSettings.update() - .withoutLogging() - .apply(); + flowLogSettings.update().withoutLogging().apply(); Utils.print(flowLogSettings); // TODO: Verify the below azure storage code based on Azure core. @@ -258,18 +262,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Download a packet capture String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", - storageAccount.name(), accountKey); + storageAccount.name(), accountKey); - BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() - .connectionString(connectionString) + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString) .httpClient(storageAccount.manager().httpPipeline().getHttpClient()) .buildClient(); - BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient(packetCaptureStorageContainer); + BlobContainerClient blobContainerClient + = blobServiceClient.getBlobContainerClient(packetCaptureStorageContainer); // iterate over subfolders structure to get the file BlobItem item = blobContainerClient.listBlobs().iterator().next(); -// while (item instanceof Blob) { -// item = ((CloudBlobDirectory) item).listBlobs().iterator().next(); -// } + // while (item instanceof Blob) { + // item = ((CloudBlobDirectory) item).listBlobs().iterator().next(); + // } // download packet capture file BlobClient blobClient = blobContainerClient.getBlobClient(item.getName()); blobClient.downloadToFile(packetCaptureFile); @@ -277,12 +281,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Download a flow log - blobContainerClient = blobServiceClient.getBlobContainerClient("insights-logs-networksecuritygroupflowevent"); + blobContainerClient + = blobServiceClient.getBlobContainerClient("insights-logs-networksecuritygroupflowevent"); // iterate over subfolders structure to get the file item = blobContainerClient.listBlobs().iterator().next(); -// while (item instanceof CloudBlobDirectory) { -// item = ((CloudBlobDirectory) item).listBlobs().iterator().next(); -// } + // while (item instanceof CloudBlobDirectory) { + // item = ((CloudBlobDirectory) item).listBlobs().iterator().next(); + // } blobClient = blobContainerClient.getBlobClient(item.getName()); System.out.println("Flow log:"); blobClient.download(System.out); @@ -328,8 +333,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java index 35b9379c60d83..aea0d5e450111 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java @@ -53,7 +53,8 @@ public final class ManagePrivateLink { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws JSchException, UnsupportedEncodingException, MalformedURLException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws JSchException, UnsupportedEncodingException, MalformedURLException { final boolean validateOnVirtualMachine = true; final Region region = Region.US_EAST; @@ -76,7 +77,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw try { System.out.println("Creating storage account..."); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_RAGRS) @@ -91,7 +93,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw String saDomainNameSecondary = new URL(storageAccount.endPoints().secondary().blob()).getHost(); System.out.println("Domain Name for Storage Account Blob Secondary: " + saDomainNameSecondary); - List privateLinkResources = storageAccount.listPrivateLinkResources().stream().collect(Collectors.toList()); + List privateLinkResources + = storageAccount.listPrivateLinkResources().stream().collect(Collectors.toList()); for (PrivateLinkResource privateLinkResource : privateLinkResources) { Utils.print(privateLinkResource); } @@ -109,26 +112,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("DNS Zone Name for Storage Account Blob Secondary: " + blobDnsZoneNameSecondary); System.out.println("Creating virtual network..."); - Network network = azureResourceManager.networks().define(vnName) + Network network = azureResourceManager.networks() + .define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) - .withAddressPrefix(vnAddressSpace) - .disableNetworkPoliciesOnPrivateEndpoint() // disable network policies on private endpoint - .attach() + .withAddressPrefix(vnAddressSpace) + .disableNetworkPoliciesOnPrivateEndpoint() // disable network policies on private endpoint + .attach() .create(); System.out.println("Creating private endpoint..."); // private endpoint - PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) + PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints() + .define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) - .withResourceId(storageAccount.id()) - .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) // primary blob - .attach() + .withResourceId(storageAccount.id()) + .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) // primary blob + .attach() .create(); System.out.println("Private Endpoint for Storage Account Blob Endpoint"); @@ -139,14 +144,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating private endpoint..."); // private endpoint - PrivateEndpoint privateEndpoint2 = azureResourceManager.privateEndpoints().define(peName2) + PrivateEndpoint privateEndpoint2 = azureResourceManager.privateEndpoints() + .define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName2) - .withResourceId(storageAccount.id()) - .withSubResource(PrivateLinkSubResourceName.fromString("blob_secondary")) // secondary blob - .attach() + .withResourceId(storageAccount.id()) + .withSubResource(PrivateLinkSubResourceName.fromString("blob_secondary")) // secondary blob + .attach() .create(); System.out.println("Private Endpoint for Storage Account Blob Secondary Endpoint"); @@ -159,7 +165,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw if (validateOnVirtualMachine) { System.out.println("Creating virtual machine..."); // create a test virtual machine - virtualMachine = azureResourceManager.virtualMachines().define(vmName) + virtualMachine = azureResourceManager.virtualMachines() + .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) @@ -173,11 +180,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw .create(); // verify private endpoint not yet works - RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); + RunCommandResult commandResult + = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } - commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainNameSecondary), null); + commandResult = virtualMachine + .runShellScript(Collections.singletonList("nslookup " + saDomainNameSecondary), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } @@ -186,31 +195,34 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating private dns zone..."); // private dns zone - PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define(blobDnsZoneName) + PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones() + .define(blobDnsZoneName) .withExistingResourceGroup(rgName) .defineARecordSet(saDomainName.split(Pattern.quote("."))[0]) - .withIPv4Address(saPrivateIp) - .attach() + .withIPv4Address(saPrivateIp) + .attach() .defineARecordSet(saDomainNameSecondary.split(Pattern.quote("."))[0]) - .withIPv4Address(saPrivateIpSecondary) - .attach() + .withIPv4Address(saPrivateIpSecondary) + .attach() .defineVirtualNetworkLink(vnlName) - .withVirtualNetworkId(network.id()) - .attach() + .withVirtualNetworkId(network.id()) + .attach() .create(); Utils.print(privateDnsZone); System.out.println("Creating private dns zone group..."); // private dns zone group on private endpoint - PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) + PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups() + .define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); System.out.println("Private DNS Zone Group Name: " + privateDnsZoneGroup.name()); System.out.println("Creating private dns zone group..."); - PrivateDnsZoneGroup privateDnsZoneGroup2 = privateEndpoint2.privateDnsZoneGroups().define(pdzgName) + PrivateDnsZoneGroup privateDnsZoneGroup2 = privateEndpoint2.privateDnsZoneGroups() + .define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone.id()) .create(); @@ -218,11 +230,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw if (validateOnVirtualMachine) { // verify private endpoint works - RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); + RunCommandResult commandResult + = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } - commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainNameSecondary), null); + commandResult = virtualMachine + .runShellScript(Collections.singletonList("nslookup " + saDomainNameSecondary), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } @@ -258,8 +272,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java index 6cf8f63e7bb9f..a5010994e0c2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java @@ -75,39 +75,40 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw long t1 = System.currentTimeMillis(); final String pipName = Utils.randomResourceName(azureResourceManager, "pip" + "-", 18); - PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses().define(pipName) + PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() + .define(pipName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(PublicIPSkuType.STANDARD) .withStaticIP() .create(); - ApplicationGateway applicationGateway = azureResourceManager.applicationGateways().define("myFirstAppGateway") - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - - // Request routing rule for HTTP from public 80 to public 8080 - .defineRequestRoutingRule("HTTP-80-to-8080") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .toBackendIPAddress("11.1.1.3") - .toBackendIPAddress("11.1.1.4") - .attach() - - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .withExistingPublicIpAddress(publicIPAddress) - .create(); + ApplicationGateway applicationGateway = azureResourceManager.applicationGateways() + .define("myFirstAppGateway") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + + // Request routing rule for HTTP from public 80 to public 8080 + .defineRequestRoutingRule("HTTP-80-to-8080") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .toBackendIPAddress("11.1.1.3") + .toBackendIPAddress("11.1.1.4") + .attach() + + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .withExistingPublicIpAddress(publicIPAddress) + .create(); long t2 = System.currentTimeMillis(); System.out.println("Application gateway created: (took " + (t2 - t1) / 1000 + " seconds)"); Utils.print(applicationGateway); - //======================================================================= // Update an application gateway // configure the first routing rule for SSL offload @@ -118,21 +119,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw t1 = System.currentTimeMillis(); applicationGateway.update() - .withoutRequestRoutingRule("HTTP-80-to-8080") - .defineRequestRoutingRule("HTTPs-1443-to-8080") - .fromPublicFrontend() - .fromFrontendHttpsPort(1443) - .withSslCertificateFromPfxFile(new File(ManageSimpleApplicationGateway.class.getClassLoader().getResource("myTest.pfx").getPath())) - .withSslCertificatePassword("Abc123") - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .toBackendIPAddress("11.1.1.3") - .toBackendIPAddress("11.1.1.4") - .withHostname("www.contoso.com") - .withCookieBasedAffinity() - .attach() - .apply(); + .withoutRequestRoutingRule("HTTP-80-to-8080") + .defineRequestRoutingRule("HTTPs-1443-to-8080") + .fromPublicFrontend() + .fromFrontendHttpsPort(1443) + .withSslCertificateFromPfxFile( + new File(ManageSimpleApplicationGateway.class.getClassLoader().getResource("myTest.pfx").getPath())) + .withSslCertificatePassword("Abc123") + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .toBackendIPAddress("11.1.1.3") + .toBackendIPAddress("11.1.1.4") + .withHostname("www.contoso.com") + .withCookieBasedAffinity() + .attach() + .apply(); t2 = System.currentTimeMillis(); @@ -169,8 +171,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -189,4 +190,3 @@ private ManageSimpleApplicationGateway() { } } - diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java index ae885f1069269..9ccd8afebe0e8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java @@ -54,9 +54,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final Region region = Region.US_SOUTH_CENTRAL; try { // Create a resource group [Where all resources gets created] - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); //============================================================ // Define a network security group for the front end of a subnet @@ -64,29 +63,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // - ALLOW-SSH - allows SSH traffic into the front end subnet // - ALLOW-WEB- allows HTTP traffic into the front end subnet - Creatable frontEndNSGCreatable = azureResourceManager.networkSecurityGroups().define(frontEndNsgName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .defineRule("ALLOW-SSH") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPort(22) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(100) - .withDescription("Allow SSH") - .attach() - .defineRule("ALLOW-HTTP") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(101) - .withDescription("Allow HTTP") - .attach(); + Creatable frontEndNSGCreatable = azureResourceManager.networkSecurityGroups() + .define(frontEndNsgName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .defineRule("ALLOW-SSH") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPort(22) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(100) + .withDescription("Allow SSH") + .attach() + .defineRule("ALLOW-HTTP") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(101) + .withDescription("Allow HTTP") + .attach(); //============================================================ // Define a network security group for the back end of a subnet @@ -94,36 +94,39 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // - ALLOW-SQL - allows SQL traffic only from the front end subnet // - DENY-WEB - denies all outbound internet traffic from the back end subnet - Creatable backEndNSGCreatable = azureResourceManager.networkSecurityGroups().define(backEndNsgName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .defineRule("ALLOW-SQL") - .allowInbound() - .fromAddress("172.16.1.0/24") - .fromAnyPort() - .toAnyAddress() - .toPort(1433) - .withProtocol(SecurityRuleProtocol.TCP) - .withPriority(100) - .withDescription("Allow SQL") - .attach() - .defineRule("DENY-WEB") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toAnyPort() - .withAnyProtocol() - .withDescription("Deny Web") - .withPriority(200) - .attach(); + Creatable backEndNSGCreatable = azureResourceManager.networkSecurityGroups() + .define(backEndNsgName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .defineRule("ALLOW-SQL") + .allowInbound() + .fromAddress("172.16.1.0/24") + .fromAnyPort() + .toAnyAddress() + .toPort(1433) + .withProtocol(SecurityRuleProtocol.TCP) + .withPriority(100) + .withDescription("Allow SQL") + .attach() + .defineRule("DENY-WEB") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toAnyPort() + .withAnyProtocol() + .withDescription("Deny Web") + .withPriority(200) + .attach(); System.out.println("Creating security group for the front ends - allows SSH and HTTP"); - System.out.println("Creating security group for the back ends - allows SSH and denies all outbound internet traffic"); + System.out.println( + "Creating security group for the back ends - allows SSH and denies all outbound internet traffic"); @SuppressWarnings("unchecked") Collection networkSecurityGroups = azureResourceManager.networkSecurityGroups() - .create(frontEndNSGCreatable, backEndNSGCreatable).values(); + .create(frontEndNSGCreatable, backEndNSGCreatable) + .values(); NetworkSecurityGroup frontendNSG = null; NetworkSecurityGroup backendNSG = null; @@ -144,58 +147,62 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(backendNSG); // Create Network [Where all the virtual machines get added to] - Network network = azureResourceManager.networks().define(networkName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("172.16.0.0/16") - .defineSubnet("Front-end") - .withAddressPrefix("172.16.1.0/24") - .withExistingNetworkSecurityGroup(frontendNSG) - .attach() - .defineSubnet("Back-end") - .withAddressPrefix("172.16.2.0/24") - .withExistingNetworkSecurityGroup(backendNSG) - .attach() - .create(); + Network network = azureResourceManager.networks() + .define(networkName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("172.16.0.0/16") + .defineSubnet("Front-end") + .withAddressPrefix("172.16.1.0/24") + .withExistingNetworkSecurityGroup(frontendNSG) + .attach() + .defineSubnet("Back-end") + .withAddressPrefix("172.16.2.0/24") + .withExistingNetworkSecurityGroup(backendNSG) + .attach() + .create(); // Prepare Creatable Storage account definition [For storing VMs disk] - Creatable creatableStorageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable creatableStorageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); // Prepare a batch of Creatable Virtual Machines definitions List> frontendCreatableVirtualMachines = new ArrayList<>(); for (int i = 0; i < frontendVMCount; i++) { - Creatable creatableVirtualMachine = azureResourceManager.virtualMachines().define("VM-FE-" + i) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withExistingPrimaryNetwork(network) - .withSubnet("Front-end") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withRootPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(creatableStorageAccount); + Creatable creatableVirtualMachine = azureResourceManager.virtualMachines() + .define("VM-FE-" + i) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withExistingPrimaryNetwork(network) + .withSubnet("Front-end") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withRootPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(creatableStorageAccount); frontendCreatableVirtualMachines.add(creatableVirtualMachine); } List> backendCreatableVirtualMachines = new ArrayList<>(); for (int i = 0; i < backendVMCount; i++) { - Creatable creatableVirtualMachine = azureResourceManager.virtualMachines().define("VM-BE-" + i) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withExistingPrimaryNetwork(network) - .withSubnet("Back-end") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withRootPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(creatableStorageAccount); + Creatable creatableVirtualMachine = azureResourceManager.virtualMachines() + .define("VM-BE-" + i) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withExistingPrimaryNetwork(network) + .withSubnet("Back-end") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withRootPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(creatableStorageAccount); backendCreatableVirtualMachines.add(creatableVirtualMachine); } @@ -207,7 +214,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { StopWatch stopwatch = new StopWatch(); stopwatch.start(); - Collection virtualMachines = azureResourceManager.virtualMachines().create(allCreatableVirtualMachines).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(allCreatableVirtualMachines).values(); stopwatch.stop(); System.out.println("Created virtual machines"); @@ -248,8 +256,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java index d00199b4e9aff..97a1d9b7dc33c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java @@ -48,7 +48,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String backEndVMName = Utils.randomResourceName(azureResourceManager, "bevm", 24); final String publicIPAddressLeafDnsForFrontEndVM = Utils.randomResourceName(azureResourceManager, "pip1", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); try { @@ -59,26 +60,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a network security group for virtual network backend subnet..."); - NetworkSecurityGroup backEndSubnetNsg = azureResourceManager.networkSecurityGroups().define(vnet1BackEndSubnetNsgName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .defineRule("DenyInternetInComing") - .denyInbound() - .fromAddress("INTERNET") - .fromAnyPort() - .toAnyAddress() - .toAnyPort() - .withAnyProtocol() - .attach() - .defineRule("DenyInternetOutGoing") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAddress("INTERNET") - .toAnyPort() - .withAnyProtocol() - .attach() - .create(); + NetworkSecurityGroup backEndSubnetNsg = azureResourceManager.networkSecurityGroups() + .define(vnet1BackEndSubnetNsgName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .defineRule("DenyInternetInComing") + .denyInbound() + .fromAddress("INTERNET") + .fromAnyPort() + .toAnyAddress() + .toAnyPort() + .withAnyProtocol() + .attach() + .defineRule("DenyInternetOutGoing") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAddress("INTERNET") + .toAnyPort() + .withAnyProtocol() + .attach() + .create(); System.out.println("Created network security group"); // Print the network security group @@ -89,22 +91,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating virtual network #1..."); - Network virtualNetwork1 = azureResourceManager.networks().define(vnetName1) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withAddressSpace("192.168.0.0/16") - .withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24") - .defineSubnet(vnet1BackEndSubnetName) - .withAddressPrefix("192.168.2.0/24") - .withExistingNetworkSecurityGroup(backEndSubnetNsg) - .attach() - .create(); + Network virtualNetwork1 = azureResourceManager.networks() + .define(vnetName1) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24") + .defineSubnet(vnet1BackEndSubnetName) + .withAddressPrefix("192.168.2.0/24") + .withExistingNetworkSecurityGroup(backEndSubnetNsg) + .attach() + .create(); System.out.println("Created a virtual network"); // Print the virtual network details Utils.print(virtualNetwork1); - //============================================================ // Update a virtual network @@ -112,26 +114,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a network security group for virtual network backend subnet..."); - NetworkSecurityGroup frontEndSubnetNsg = azureResourceManager.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .defineRule("AllowHttpInComing") - .allowInbound() - .fromAddress("INTERNET") - .fromAnyPort() - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() - .defineRule("DenyInternetOutGoing") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAddress("INTERNET") - .toAnyPort() - .withAnyProtocol() - .attach() - .create(); + NetworkSecurityGroup frontEndSubnetNsg = azureResourceManager.networkSecurityGroups() + .define(vnet1FrontEndSubnetNsgName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .defineRule("AllowHttpInComing") + .allowInbound() + .fromAddress("INTERNET") + .fromAnyPort() + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() + .defineRule("DenyInternetOutGoing") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAddress("INTERNET") + .toAnyPort() + .withAnyProtocol() + .attach() + .create(); System.out.println("Created network security group"); // Print the network security group @@ -142,16 +145,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Associating network security group rule to frontend subnet"); virtualNetwork1.update() - .updateSubnet(vnet1FrontEndSubnetName) - .withExistingNetworkSecurityGroup(frontEndSubnetNsg) - .parent() - .apply(); + .updateSubnet(vnet1FrontEndSubnetName) + .withExistingNetworkSecurityGroup(frontEndSubnetNsg) + .parent() + .apply(); System.out.println("Network security group rule associated with the frontend subnet"); // Print the virtual network details Utils.print(virtualNetwork1); - //============================================================ // Create a virtual machine in each subnet @@ -161,67 +163,67 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Date t1 = new Date(); - VirtualMachine frontEndVM = azureResourceManager.virtualMachines().define(frontEndVMName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(virtualNetwork1) - .withSubnet(vnet1FrontEndSubnetName) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine frontEndVM = azureResourceManager.virtualMachines() + .define(frontEndVMName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(virtualNetwork1) + .withSubnet(vnet1FrontEndSubnetName) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t2 = new Date(); - System.out.println("Created Linux VM: (took " - + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id()); + System.out.println( + "Created Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id()); // Print virtual machine details Utils.print(frontEndVM); - // Creates the second virtual machine in the backend subnet System.out.println("Creating a Linux virtual machine in the backend subnet"); Date t3 = new Date(); - VirtualMachine backEndVM = azureResourceManager.virtualMachines().define(backEndVMName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(virtualNetwork1) - .withSubnet(vnet1BackEndSubnetName) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine backEndVM = azureResourceManager.virtualMachines() + .define(backEndVMName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(virtualNetwork1) + .withSubnet(vnet1BackEndSubnetName) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t4 = new Date(); - System.out.println("Created Linux VM: (took " - + ((t4.getTime() - t3.getTime()) / 1000) + " seconds) " + backEndVM.id()); + System.out.println( + "Created Linux VM: (took " + ((t4.getTime() - t3.getTime()) / 1000) + " seconds) " + backEndVM.id()); // Print virtual machine details Utils.print(backEndVM); - //============================================================ // Create a virtual network with default address-space and one default subnet System.out.println("Creating virtual network #2..."); - Network virtualNetwork2 = azureResourceManager.networks().define(vnetName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + Network virtualNetwork2 = azureResourceManager.networks() + .define(vnetName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); System.out.println("Created a virtual network"); // Print the virtual network details Utils.print(virtualNetwork2); - //============================================================ // List virtual networks @@ -229,7 +231,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(virtualNetwork); } - //============================================================ // Delete a virtual network System.out.println("Deleting the virtual network"); @@ -263,8 +264,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java index cb706998e5dde..8338a7c8a3261 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java @@ -64,7 +64,8 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final String backEndVMName = Utils.randomResourceName(azureResourceManager, "bevm", 24); final String publicIPAddressLeafDnsForFrontEndVM = Utils.randomResourceName(azureResourceManager, "pip1", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); try { @@ -79,74 +80,77 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final Map createdResources = new TreeMap<>(); - Flux.merge( - azureResourceManager.networkSecurityGroups().define(vnet1BackEndSubnetNsgName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .defineRule("DenyInternetInComing") - .denyInbound() - .fromAddress("INTERNET") - .fromAnyPort() - .toAnyAddress() - .toAnyPort() - .withAnyProtocol() - .attach() - .defineRule("DenyInternetOutGoing") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAddress("INTERNET") - .toAnyPort() - .withAnyProtocol() - .attach() - .createAsync() - .flatMapMany(backEndNsg -> { - System.out.println("Creating virtual network #1..."); - return Flux.merge( - Flux.just(backEndNsg), - azureResourceManager.networks().define(vnetName1) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withAddressSpace("192.168.0.0/16") - .withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24") - .defineSubnet(vnet1BackEndSubnetName) - .withAddressPrefix("192.168.2.0/24") - .withExistingNetworkSecurityGroup(backEndNsg) - .attach() - .createAsync()); - }), - azureResourceManager.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName) + Flux.merge(azureResourceManager.networkSecurityGroups() + .define(vnet1BackEndSubnetNsgName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .defineRule("DenyInternetInComing") + .denyInbound() + .fromAddress("INTERNET") + .fromAnyPort() + .toAnyAddress() + .toAnyPort() + .withAnyProtocol() + .attach() + .defineRule("DenyInternetOutGoing") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAddress("INTERNET") + .toAnyPort() + .withAnyProtocol() + .attach() + .createAsync() + .flatMapMany(backEndNsg -> { + System.out.println("Creating virtual network #1..."); + return Flux.merge(Flux.just(backEndNsg), + azureResourceManager.networks() + .define(vnetName1) .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .defineRule("AllowHttpInComing") - .allowInbound() - .fromAddress("INTERNET") - .fromAnyPort() - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() - .defineRule("DenyInternetOutGoing") - .denyOutbound() - .fromAnyAddress() - .fromAnyPort() - .toAddress("INTERNET") - .toAnyPort() - .withAnyProtocol() + .withExistingResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24") + .defineSubnet(vnet1BackEndSubnetName) + .withAddressPrefix("192.168.2.0/24") + .withExistingNetworkSecurityGroup(backEndNsg) .attach() - .createAsync() - ).map(indexable -> { - if (indexable instanceof NetworkSecurityGroup) { - NetworkSecurityGroup nsg = (NetworkSecurityGroup) indexable; - createdResources.put(nsg.name(), nsg); - } else if (indexable instanceof Network) { - Network vn = (Network) indexable; - createdResources.put(vn.name(), vn); - } - return indexable; - }).blockLast(); - - NetworkSecurityGroup frontEndSubnetNsg = (NetworkSecurityGroup) createdResources.get(vnet1FrontEndSubnetNsgName); + .createAsync()); + }), + azureResourceManager.networkSecurityGroups() + .define(vnet1FrontEndSubnetNsgName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .defineRule("AllowHttpInComing") + .allowInbound() + .fromAddress("INTERNET") + .fromAnyPort() + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() + .defineRule("DenyInternetOutGoing") + .denyOutbound() + .fromAnyAddress() + .fromAnyPort() + .toAddress("INTERNET") + .toAnyPort() + .withAnyProtocol() + .attach() + .createAsync()) + .map(indexable -> { + if (indexable instanceof NetworkSecurityGroup) { + NetworkSecurityGroup nsg = (NetworkSecurityGroup) indexable; + createdResources.put(nsg.name(), nsg); + } else if (indexable instanceof Network) { + Network vn = (Network) indexable; + createdResources.put(vn.name(), vn); + } + return indexable; + }) + .blockLast(); + + NetworkSecurityGroup frontEndSubnetNsg + = (NetworkSecurityGroup) createdResources.get(vnet1FrontEndSubnetNsgName); Network virtualNetwork1 = (Network) createdResources.get(vnetName1); System.out.println("Created network security group"); @@ -165,17 +169,16 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) System.out.println("Associating network security group rule to frontend subnet"); virtualNetwork1.update() - .updateSubnet(vnet1FrontEndSubnetName) - .withExistingNetworkSecurityGroup(frontEndSubnetNsg) - .parent() - .applyAsync() - .block(); + .updateSubnet(vnet1FrontEndSubnetName) + .withExistingNetworkSecurityGroup(frontEndSubnetNsg) + .parent() + .applyAsync() + .block(); System.out.println("Network security group rule associated with the frontend subnet"); // Print the virtual network details Utils.print(virtualNetwork1); - //============================================================ // Create a virtual machine in each subnet and another virtual network // Creates the first virtual machine in frontend subnet @@ -189,52 +192,53 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final Date t1 = new Date(); Flux.merge( - azureResourceManager.virtualMachines().define(frontEndVMName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(virtualNetwork1) - .withSubnet(vnet1FrontEndSubnetName) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .createAsync(), - azureResourceManager.virtualMachines().define(backEndVMName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(virtualNetwork1) - .withSubnet(vnet1BackEndSubnetName) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .createAsync(), - azureResourceManager.networks().define(vnetName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .createAsync()) - .map(indexable -> { - Date t2 = new Date(); - long duration = ((t2.getTime() - t1.getTime()) / 1000); - creations.add(new Indexable2Duration(indexable, duration)); - return indexable; - }); + azureResourceManager.virtualMachines() + .define(frontEndVMName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(virtualNetwork1) + .withSubnet(vnet1FrontEndSubnetName) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .createAsync(), + azureResourceManager.virtualMachines() + .define(backEndVMName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(virtualNetwork1) + .withSubnet(vnet1BackEndSubnetName) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .createAsync(), + azureResourceManager.networks() + .define(vnetName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .createAsync()) + .map(indexable -> { + Date t2 = new Date(); + long duration = ((t2.getTime() - t1.getTime()) / 1000); + creations.add(new Indexable2Duration(indexable, duration)); + return indexable; + }); for (Indexable2Duration creation : creations) { if (creation.indexable instanceof VirtualMachine) { VirtualMachine vm = (VirtualMachine) creation.indexable; - System.out.println("Created Linux VM: (took " - + creation.duration + " seconds) " + vm.id()); + System.out.println("Created Linux VM: (took " + creation.duration + " seconds) " + vm.id()); // Print virtual machine details Utils.print(vm); } else if (creation.indexable instanceof Network) { Network vn = (Network) creation.indexable; - System.out.println("Created a virtual network: took " - + creation.duration + " seconds) " + vn.id()); + System.out.println("Created a virtual network: took " + creation.duration + " seconds) " + vn.id()); // Print the virtual network details Utils.print(vn); } @@ -275,8 +279,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java index 772a04fca0bda..927009b85fb8a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java @@ -55,15 +55,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Create virtual network with address spaces 192.168.0.0/16 and 10.254.0.0/16 and 3 subnets System.out.println("Creating virtual network..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("192.168.0.0/16") - .withAddressSpace("10.254.0.0/16") - .withSubnet("GatewaySubnet", "192.168.200.0/24") - .withSubnet("FrontEnd", "192.168.1.0/24") - .withSubnet("BackEnd", "10.254.1.0/24") - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .withAddressSpace("10.254.0.0/16") + .withSubnet("GatewaySubnet", "192.168.200.0/24") + .withSubnet("FrontEnd", "192.168.1.0/24") + .withSubnet("BackEnd", "10.254.1.0/24") + .create(); System.out.println("Created network"); // Print the virtual network Utils.print(network); @@ -71,31 +72,33 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Create virtual network gateway System.out.println("Creating virtual network gateway..."); - VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways().define(vpnGatewayName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingNetwork(network) - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); + VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways() + .define(vpnGatewayName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingNetwork(network) + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); System.out.println("Created virtual network gateway"); //============================================================ // Update virtual network gateway with Point-to-Site connection configuration System.out.println("Creating Point-to-Site configuration..."); vngw1.update() - .definePointToSiteConfiguration() - .withAddressPool("172.16.201.0/24") - .withAzureCertificateFromFile("p2scert.cer", new File(certPath)) - .attach() - .apply(); + .definePointToSiteConfiguration() + .withAddressPool("172.16.201.0/24") + .withAzureCertificateFromFile("p2scert.cer", new File(certPath)) + .attach() + .apply(); System.out.println("Created Point-to-Site configuration"); //============================================================ // Generate and download VPN client configuration package. Now it can be used to create VPN connection to Azure. System.out.println("Generating VPN profile..."); String profile = vngw1.generateVpnProfile(); - System.out.println(String.format("Profile generation is done. Please download client package at: %s", profile)); + System.out + .println(String.format("Profile generation is done. Please download client package at: %s", profile)); // At this point vpn client package can be downloaded from provided link. Unzip it and run the configuration corresponding to your OS. // For Windows machine, VPN client .exe can be run. For non-Windows, please use configuration from downloaded VpnSettings.xml @@ -103,10 +106,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw //============================================================ // Revoke a client certificate. After this command, you will no longer available to connect with the corresponding client certificate. System.out.println("Revoking client certificate..."); - vngw1.update().updatePointToSiteConfiguration() - .withRevokedCertificate("p2sclientcert.cer", clientCertThumbprint) - .parent() - .apply(); + vngw1.update() + .updatePointToSiteConfiguration() + .withRevokedCertificate("p2sclientcert.cer", clientCertThumbprint) + .parent() + .apply(); System.out.println("Revoked client certificate"); return true; @@ -137,8 +141,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java index 16bd70997eeac..8110d0e7b506a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java @@ -2,6 +2,7 @@ // Licensed under the MIT License. package com.azure.resourcemanager.network.samples; + import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -40,17 +41,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String localGatewayName = Utils.randomResourceName(azureResourceManager, "lngw", 20); final String connectionName = Utils.randomResourceName(azureResourceManager, "con", 20); - try { //============================================================ // Create virtual network System.out.println("Creating virtual network..."); - Network network = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.11.0.0/16") - .withSubnet("GatewaySubnet", "10.11.255.0/27") - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.11.0.0/16") + .withSubnet("GatewaySubnet", "10.11.255.0/27") + .create(); System.out.println("Created network"); // Print the virtual network Utils.print(network); @@ -58,35 +59,37 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create VPN gateway System.out.println("Creating virtual network gateway..."); - VirtualNetworkGateway vngw = azureResourceManager.virtualNetworkGateways().define(vpnGatewayName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingNetwork(network) - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); + VirtualNetworkGateway vngw = azureResourceManager.virtualNetworkGateways() + .define(vpnGatewayName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingNetwork(network) + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); System.out.println("Created virtual network gateway"); //============================================================ // Create local network gateway System.out.println("Creating virtual network gateway..."); - LocalNetworkGateway lngw = azureResourceManager.localNetworkGateways().define(localGatewayName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withIPAddress("40.71.184.214") - .withAddressSpace("192.168.3.0/24") - .create(); + LocalNetworkGateway lngw = azureResourceManager.localNetworkGateways() + .define(localGatewayName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withIPAddress("40.71.184.214") + .withAddressSpace("192.168.3.0/24") + .create(); System.out.println("Created virtual network gateway"); //============================================================ // Create VPN Site-to-Site connection System.out.println("Creating virtual network gateway connection..."); vngw.connections() - .define(connectionName) - .withSiteToSite() - .withLocalNetworkGateway(lngw) - .withSharedKey("MySecretKey") - .create(); + .define(connectionName) + .withSiteToSite() + .withLocalNetworkGateway(lngw) + .withSharedKey("MySecretKey") + .create(); System.out.println("Created virtual network gateway connection"); //============================================================ @@ -126,8 +129,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java index b9d84ff40bb74..f50ddfecf7b88 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java @@ -73,75 +73,81 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create 2 virtual networks with subnets and 2 virtual network gateways corresponding to each network System.out.println("Creating virtual network..."); - Network network1 = azureResourceManager.networks().define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.11.0.0/16") - .withSubnet("GatewaySubnet", "10.11.255.0/27") - .withSubnet("Subnet1", "10.11.0.0/24") - .create(); + Network network1 = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.11.0.0/16") + .withSubnet("GatewaySubnet", "10.11.255.0/27") + .withSubnet("Subnet1", "10.11.0.0/24") + .create(); System.out.println("Created network"); // Print the virtual network Utils.print(network1); System.out.println("Creating virtual network gateway..."); - VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways().define(vpnGatewayName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingNetwork(network1) - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); + VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways() + .define(vpnGatewayName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingNetwork(network1) + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); System.out.println("Created virtual network gateway"); System.out.println("Creating virtual network..."); - Network network2 = azureResourceManager.networks().define(vnet2Name) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.41.0.0/16") - .withSubnet("GatewaySubnet", "10.41.255.0/27") - .withSubnet("Subnet2", "10.41.0.0/24") - .create(); + Network network2 = azureResourceManager.networks() + .define(vnet2Name) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.41.0.0/16") + .withSubnet("GatewaySubnet", "10.41.255.0/27") + .withSubnet("Subnet2", "10.41.0.0/24") + .create(); System.out.println("Created virtual network"); System.out.println("Creating virtual network gateway..."); - VirtualNetworkGateway vngw2 = azureResourceManager.virtualNetworkGateways().define(vpnGateway2Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingNetwork(network2) - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); + VirtualNetworkGateway vngw2 = azureResourceManager.virtualNetworkGateways() + .define(vpnGateway2Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingNetwork(network2) + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); System.out.println("Created virtual network gateway"); System.out.println("Creating virtual network gateway connection..."); VirtualNetworkGatewayConnection connection = vngw1.connections() - .define(connectionName) - .withVNetToVNet() - .withSecondVirtualNetworkGateway(vngw2) - .withSharedKey("MySecretKey") - .create(); + .define(connectionName) + .withVNetToVNet() + .withSecondVirtualNetworkGateway(vngw2) + .withSharedKey("MySecretKey") + .create(); System.out.println("Created virtual network gateway connection"); //============================================================ // Troubleshoot the connection // create Network Watcher - NetworkWatcher nw = azureResourceManager.networkWatchers().define(nwName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .create(); + NetworkWatcher nw = azureResourceManager.networkWatchers() + .define(nwName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); // Create storage account to store troubleshooting information - StorageAccount storageAccount = azureResourceManager.storageAccounts().define("sa" + Utils.randomResourceName(azureResourceManager, "", 8)) - .withRegion(region) - .withExistingResourceGroup(rgName) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define("sa" + Utils.randomResourceName(azureResourceManager, "", 8)) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); // Create storage container to store troubleshooting results String accountKey = storageAccount.getKeys().get(0).value(); - String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey); - BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() - .connectionString(connectionString) + String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", + storageAccount.name(), accountKey); + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString) .httpClient(storageAccount.manager().httpPipeline().getHttpClient()) .buildClient(); BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(storageContainerName); @@ -149,26 +155,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first Troubleshooting troubleshooting = nw.troubleshoot() - .withTargetResourceId(connection.id()) - .withStorageAccount(storageAccount.id()) - .withStoragePath(storageAccount.endPoints().primary().blob() + storageContainerName) - .execute(); + .withTargetResourceId(connection.id()) + .withStorageAccount(storageAccount.id()) + .withStoragePath(storageAccount.endPoints().primary().blob() + storageContainerName) + .execute(); System.out.println("Troubleshooting status is: " + troubleshooting.code()); //============================================================ // Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'. vngw2.connections() - .define(connection2Name) - .withVNetToVNet() - .withSecondVirtualNetworkGateway(vngw1) - .withSharedKey("MySecretKey") - .create(); + .define(connection2Name) + .withVNetToVNet() + .withSecondVirtualNetworkGateway(vngw1) + .withSharedKey("MySecretKey") + .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(250)); troubleshooting = nw.troubleshoot() - .withTargetResourceId(connection.id()) - .withStorageAccount(storageAccount.id()) - .withStoragePath(storageAccount.endPoints().primary().blob() + storageContainerName) - .execute(); + .withTargetResourceId(connection.id()) + .withStorageAccount(storageAccount.id()) + .withStoragePath(storageAccount.endPoints().primary().blob() + storageContainerName) + .execute(); System.out.println("Troubleshooting status is: " + troubleshooting.code()); //============================================================ @@ -181,47 +187,49 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create 2 virtual machines, each one in its network and verify connectivity between them List> vmDefinitions = new ArrayList<>(); - vmDefinitions.add(azureResourceManager.virtualMachines().define(vm1Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network1) - .withSubnet("Subnet1") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(rootname) - .withRootPassword(password) - // Extension currently needed for network watcher support - .defineNewExtension("networkWatcher") - .withPublisher("Microsoft.Azure.NetworkWatcher") - .withType("NetworkWatcherAgentLinux") - .withVersion("1.4") - .attach()); - vmDefinitions.add(azureResourceManager.virtualMachines().define(vm2Name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network2) - .withSubnet("Subnet2") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(rootname) - .withRootPassword(password) - // Extension currently needed for network watcher support - .defineNewExtension("networkWatcher") - .withPublisher("Microsoft.Azure.NetworkWatcher") - .withType("NetworkWatcherAgentLinux") - .withVersion("1.4") - .attach()); + vmDefinitions.add(azureResourceManager.virtualMachines() + .define(vm1Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network1) + .withSubnet("Subnet1") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(rootname) + .withRootPassword(password) + // Extension currently needed for network watcher support + .defineNewExtension("networkWatcher") + .withPublisher("Microsoft.Azure.NetworkWatcher") + .withType("NetworkWatcherAgentLinux") + .withVersion("1.4") + .attach()); + vmDefinitions.add(azureResourceManager.virtualMachines() + .define(vm2Name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network2) + .withSubnet("Subnet2") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(rootname) + .withRootPassword(password) + // Extension currently needed for network watcher support + .defineNewExtension("networkWatcher") + .withPublisher("Microsoft.Azure.NetworkWatcher") + .withType("NetworkWatcherAgentLinux") + .withVersion("1.4") + .attach()); CreatedResources createdVMs = azureResourceManager.virtualMachines().create(vmDefinitions); VirtualMachine vm1 = createdVMs.get(vmDefinitions.get(0).key()); VirtualMachine vm2 = createdVMs.get(vmDefinitions.get(1).key()); ConnectivityCheck connectivity = nw.checkConnectivity() - .toDestinationResourceId(vm2.id()) - .toDestinationPort(22) - .fromSourceVirtualMachine(vm1.id()) - .execute(); + .toDestinationResourceId(vm2.id()) + .toDestinationPort(22) + .fromSourceVirtualMachine(vm1.id()) + .execute(); System.out.println("Connectivity status: " + connectivity.connectionStatus()); return true; } finally { @@ -251,8 +259,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java index c7ec417d8ea5a..2af0a011f2289 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java @@ -65,10 +65,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String vnetBName = Utils.randomResourceName(azureResourceManager, "net", 15); final String[] vmNames = Utils.randomResourceNames(azureResourceManager, "vm", 15, 2); - final String[] vmIPAddresses = new String[]{ - /* within subnetA */ "10.0.0.8", - /* within subnetB */ "10.1.0.8" - }; + final String[] vmIPAddresses + = new String[] { /* within subnetA */ "10.0.0.8", /* within subnetB */ "10.1.0.8" }; final String peeringABName = Utils.randomResourceName(azureResourceManager, "peer", 15); final String rootname = "tirekicker"; @@ -81,17 +79,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Define two virtual networks to peer and put the virtual machines in, at specific IP addresses List> networkDefinitions = new ArrayList<>(); - networkDefinitions.add(azureResourceManager.networks().define(vnetAName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withAddressSpace("10.0.0.0/27") - .withSubnet("subnetA", "10.0.0.0/27")); + networkDefinitions.add(azureResourceManager.networks() + .define(vnetAName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withAddressSpace("10.0.0.0/27") + .withSubnet("subnetA", "10.0.0.0/27")); - networkDefinitions.add(azureResourceManager.networks().define(vnetBName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .withAddressSpace("10.1.0.0/27") - .withSubnet("subnetB", "10.1.0.0/27")); + networkDefinitions.add(azureResourceManager.networks() + .define(vnetBName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .withAddressSpace("10.1.0.0/27") + .withSubnet("subnetB", "10.1.0.0/27")); //============================================================= // Define a couple of Linux VMs and place them in each of the networks @@ -99,22 +99,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List> vmDefinitions = new ArrayList<>(); for (int i = 0; i < networkDefinitions.size(); i++) { - vmDefinitions.add(azureResourceManager.virtualMachines().define(vmNames[i]) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) - .withNewPrimaryNetwork(networkDefinitions.get(i)) - .withPrimaryPrivateIPAddressStatic(vmIPAddresses[i]) - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(rootname) - .withRootPassword(password) - - // Extension currently needed for network watcher support - .defineNewExtension("packetCapture") - .withPublisher("Microsoft.Azure.NetworkWatcher") - .withType("NetworkWatcherAgentLinux") - .withVersion("1.4") - .attach()); + vmDefinitions.add(azureResourceManager.virtualMachines() + .define(vmNames[i]) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .withNewPrimaryNetwork(networkDefinitions.get(i)) + .withPrimaryPrivateIPAddressStatic(vmIPAddresses[i]) + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(rootname) + .withRootPassword(password) + + // Extension currently needed for network watcher support + .defineNewExtension("packetCapture") + .withPublisher("Microsoft.Azure.NetworkWatcher") + .withType("NetworkWatcherAgentLinux") + .withVersion("1.4") + .attach()); } // Create the VMs in parallel for better performance @@ -133,15 +134,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(networkA); Utils.print(networkB); - System.out.println( - "Peering the networks using default settings...\n" - + "- Network access enabled\n" - + "- Traffic forwarding disabled\n" - + "- Gateway use (transit) by the remote network disabled"); + System.out.println("Peering the networks using default settings...\n" + "- Network access enabled\n" + + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the remote network disabled"); - NetworkPeering peeringAB = networkA.peerings().define(peeringABName) - .withRemoteNetwork(networkB) - .create(); + NetworkPeering peeringAB = networkA.peerings().define(peeringABName).withRemoteNetwork(networkB).create(); Utils.print(networkA); Utils.print(networkB); @@ -151,10 +147,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Azure Network Watcher enabled by default // https://azure.microsoft.com/updates/azure-network-watcher-will-be-enabled-by-default-for-subscriptions-containing-virtual-networks/ - NetworkWatcher networkWatcher = azureResourceManager.networkWatchers().list().stream() - .filter(nw -> nw.region() == region).findFirst() - .orElseGet(() -> azureResourceManager - .networkWatchers() + NetworkWatcher networkWatcher = azureResourceManager.networkWatchers() + .list() + .stream() + .filter(nw -> nw.region() == region) + .findFirst() + .orElseGet(() -> azureResourceManager.networkWatchers() .define(networkWatcherName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) @@ -162,28 +160,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Verify bi-directional connectivity between the VMs on port 22 (SSH enabled by default on Linux VMs) Executable connectivityAtoB = networkWatcher.checkConnectivity() - .toDestinationAddress(vmIPAddresses[1]) - .toDestinationPort(22) - .fromSourceVirtualMachine(vmA); + .toDestinationAddress(vmIPAddresses[1]) + .toDestinationPort(22) + .fromSourceVirtualMachine(vmA); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); Executable connectivityBtoA = networkWatcher.checkConnectivity() - .toDestinationAddress(vmIPAddresses[0]) - .toDestinationPort(22) - .fromSourceVirtualMachine(vmB); + .toDestinationAddress(vmIPAddresses[0]) + .toDestinationPort(22) + .fromSourceVirtualMachine(vmB); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); // Change the peering to allow access between A and B System.out.println("Changing the peering to disable access between A and B..."); - peeringAB.update() - .withoutAccessFromEitherNetwork() - .apply(); + peeringAB.update().withoutAccessFromEitherNetwork().apply(); Utils.print(networkA); Utils.print(networkB); // Verify connectivity no longer possible between A and B - System.out.println("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A..."); + System.out.println( + "Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A..."); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); @@ -217,8 +214,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java index 8830fd922ae4e..0c375cc6b767a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java @@ -50,15 +50,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String password = Utils.password(); try { - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); //============================================================ // Creates a private DNS Zone System.out.println("Creating private DNS zone " + CUSTOM_DOMAIN_NAME + "..."); - PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define(CUSTOM_DOMAIN_NAME) + PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones() + .define(CUSTOM_DOMAIN_NAME) .withExistingResourceGroup(resourceGroup) .create(); @@ -69,7 +69,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Creates a virtual network System.out.println("Creating virtual network " + vnetName + "..."); - Network network = azureResourceManager.networks().define(vnetName) + Network network = azureResourceManager.networks() + .define(vnetName) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withAddressSpace("10.2.0.0/16") @@ -81,14 +82,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Links a virtual network - System.out.println("Creating virtual network link " + linkName - + " within private zone " + privateDnsZone.name() + " ..."); + System.out.println( + "Creating virtual network link " + linkName + " within private zone " + privateDnsZone.name() + " ..."); privateDnsZone.update() .defineVirtualNetworkLink(linkName) - .enableAutoRegistration() - .withVirtualNetworkId(network.id()) - .withETagCheck() - .attach() + .enableAutoRegistration() + .withVirtualNetworkId(network.id()) + .withETagCheck() + .attach() .apply(); System.out.println("Linked a virtual network " + network.id()); @@ -96,7 +97,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Creates test virtual machines System.out.println("Creating first virtual machine " + vm1Name + "..."); - VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines().define(vm1Name) + VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines() + .define(vm1Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) @@ -115,7 +117,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Started first virtual machine " + virtualMachine1.name()); System.out.println("Creating second virtual machine " + vm2Name + "..."); - VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines().define(vm2Name) + VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines() + .define(vm2Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) @@ -138,8 +141,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating additional record set " + rsName + "..."); privateDnsZone.update() .defineARecordSet(rsName) - .withIPv4Address(virtualMachine1.getPrimaryNetworkInterface().primaryPrivateIP()) - .attach() + .withIPv4Address(virtualMachine1.getPrimaryNetworkInterface().primaryPrivateIP()) + .attach() .apply(); System.out.println("Created additional record set " + rsName); Utils.print(privateDnsZone); @@ -157,7 +160,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Preparing third command: " + script3); System.out.println("Starting to run commands..."); - RunCommandResult result = virtualMachine2.runPowerShellScript(Arrays.asList(script1, script2, script3), null); + RunCommandResult result + = virtualMachine2.runPowerShellScript(Arrays.asList(script1, script2, script3), null); for (InstanceViewStatus status : result.value()) { System.out.println(status.message()); } @@ -189,8 +193,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java index 1d2547352fac9..8c39d7a66f170 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java @@ -38,7 +38,6 @@ public final class ManageRedisCache { - /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client @@ -55,25 +54,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Redis Cache"); - Creatable redisCache1Definition = azureResourceManager.redisCaches().define(redisCacheName1) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(rgName) - .withBasicSku(); + Creatable redisCache1Definition = azureResourceManager.redisCaches() + .define(redisCacheName1) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withBasicSku(); // ============================================================ // Define two more Redis caches - Creatable redisCache2Definition = azureResourceManager.redisCaches().define(redisCacheName2) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withShardCount(3); + Creatable redisCache2Definition = azureResourceManager.redisCaches() + .define(redisCacheName2) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withShardCount(3); - Creatable redisCache3Definition = azureResourceManager.redisCaches().define(redisCacheName3) - .withRegion(Region.US_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku(2) - .withShardCount(3); + Creatable redisCache3Definition = azureResourceManager.redisCaches() + .define(redisCacheName3) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku(2) + .withShardCount(3); // ============================================================ // Create all the caches in parallel to save time @@ -81,10 +83,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating three Redis Caches in parallel... (this will take several minutes)"); @SuppressWarnings("unchecked") - CreatedResources createdCaches = azureResourceManager.redisCaches().create( - redisCache1Definition, - redisCache2Definition, - redisCache3Definition); + CreatedResources createdCaches = azureResourceManager.redisCaches() + .create(redisCache1Definition, redisCache2Definition, redisCache3Definition); System.out.println("Created Redis caches:"); RedisCache redisCache1 = createdCaches.get(redisCache1Definition.key()); @@ -121,12 +121,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Update each Premium Sku Redis Cache instance System.out.println("Updating Premium Redis Cache"); premium.update() - .withPatchSchedule(DayOfWeek.MONDAY, 5) - .withShardCount(4) - .withNonSslPort() - .withRedisConfiguration("maxmemory-policy", "allkeys-random") - .withRedisConfiguration("maxmemory-reserved", "20") - .apply(); + .withPatchSchedule(DayOfWeek.MONDAY, 5) + .withShardCount(4) + .withNonSslPort() + .withRedisConfiguration("maxmemory-policy", "allkeys-random") + .withRedisConfiguration("maxmemory-reserved", "20") + .apply(); System.out.println("Updated Redis Cache:"); Utils.print(premium); @@ -173,8 +173,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java index c63fafb890e94..83822e3c58f1b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java @@ -35,25 +35,22 @@ public final class DeployUsingARMTemplate { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, IllegalAccessException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, IllegalAccessException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSAT", 24); final String deploymentName = Utils.randomResourceName(azureResourceManager, "dpRSAT", 24); try { String templateJson = DeployUsingARMTemplate.getTemplate(azureResourceManager); - //============================================================= // Create resource group. System.out.println("Creating a resource group with name: " + rgName); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_EAST2) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create(); System.out.println("Created a resource group with name: " + rgName); - //============================================================= // Create a deployment for an Azure App Service via an ARM // template. @@ -62,31 +59,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // System.out.println("Starting a deployment for an Azure App Service: " + deploymentName); - azureResourceManager.deployments().define(deploymentName) - .withExistingResourceGroup(rgName) - .withTemplate(templateJson) - .withParameters("{}") - .withMode(DeploymentMode.INCREMENTAL) - .create(); + azureResourceManager.deployments() + .define(deploymentName) + .withExistingResourceGroup(rgName) + .withTemplate(templateJson) + .withParameters("{}") + .withMode(DeploymentMode.INCREMENTAL) + .create(); System.out.println("Started a deployment for an Azure App Service: " + deploymentName); return true; } finally { try { - Deployment deployment = azureResourceManager.deployments() - .getByResourceGroup(rgName, deploymentName); - PagedIterable operations = deployment.deploymentOperations() - .list(); + Deployment deployment = azureResourceManager.deployments().getByResourceGroup(rgName, deploymentName); + PagedIterable operations = deployment.deploymentOperations().list(); for (DeploymentOperation operation : operations) { if (operation.targetResource() != null) { - String operationTxt = String.format("id:%s name:%s type: %s provisioning-state:%s code: %s msg: %s", - operation.targetResource().id(), - operation.targetResource().resourceName(), - operation.targetResource().resourceType(), - operation.provisioningState(), - operation.statusCode(), - operation.statusMessage()); + String operationTxt + = String.format("id:%s name:%s type: %s provisioning-state:%s code: %s msg: %s", + operation.targetResource().id(), operation.targetResource().resourceName(), + operation.targetResource().resourceType(), operation.provisioningState(), + operation.statusCode(), operation.statusMessage()); System.out.println(operationTxt); } } @@ -94,7 +88,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println(ex.getMessage()); } - try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); @@ -124,8 +117,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -137,7 +129,8 @@ public static void main(String[] args) { } } - private static String getTemplate(AzureResourceManager azureResourceManager) throws IllegalAccessException, JsonProcessingException, IOException { + private static String getTemplate(AzureResourceManager azureResourceManager) + throws IllegalAccessException, JsonProcessingException, IOException { final String hostingPlanName = Utils.randomResourceName(azureResourceManager, "hpRSAT", 24); final String webappName = Utils.randomResourceName(azureResourceManager, "wnRSAT", 24); @@ -156,7 +149,7 @@ private static String getTemplate(AzureResourceManager azureResourceManager) thr } private static void validateAndAddFieldValue(String type, String fieldValue, String fieldName, String errorMessage, - JsonNode tmp) throws IllegalAccessException { + JsonNode tmp) throws IllegalAccessException { // Add count variable for loop.... final ObjectMapper mapper = new ObjectMapper(); final ObjectNode parameter = mapper.createObjectNode(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java index bf78ae56e2829..ad9b7b4f03d43 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.resources.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -47,7 +46,8 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) try { // Use the Simple VM Template with SSH Key auth from GH quickstarts - final String templateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json"; + final String templateUri + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json"; final String templateContentVersion = "1.0.0.0"; // Template only needs an SSH Key parameter @@ -68,38 +68,32 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) final List succeeded = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); - Flux.range(1, numDeployments) - .flatMap(integer -> { - try { - String params; - if (integer == numDeployments) { - params = "{\"adminPublicKey\":{\"value\":\"bad content\"}}"; // Invalid parameters as a negative path - } else { - params = parameters; - } - String deploymentName = deploymentPrefix + "-" + integer; - deploymentList.add(deploymentName); - return azureResourceManager.deployments() - .define(deploymentName) - .withNewResourceGroup(rgPrefix + "-" + integer, Region.US_SOUTH_CENTRAL) - .withTemplateLink(templateUri, templateContentVersion) - .withParameters(params) - .withMode(DeploymentMode.COMPLETE) - .createAsync(); - } catch (IOException e) { - return Flux.error(e); - } - }) - .map(indexable -> indexable) - .doOnNext(deployment -> { - if (deployment != null) { - System.out.println("Deployment finished: " + deployment.name()); - succeeded.add(deployment.name()); - } - }) - .onErrorResume(e -> Mono.empty()) - .doOnComplete(() -> latch.countDown()) - .subscribe(); + Flux.range(1, numDeployments).flatMap(integer -> { + try { + String params; + if (integer == numDeployments) { + params = "{\"adminPublicKey\":{\"value\":\"bad content\"}}"; // Invalid parameters as a negative path + } else { + params = parameters; + } + String deploymentName = deploymentPrefix + "-" + integer; + deploymentList.add(deploymentName); + return azureResourceManager.deployments() + .define(deploymentName) + .withNewResourceGroup(rgPrefix + "-" + integer, Region.US_SOUTH_CENTRAL) + .withTemplateLink(templateUri, templateContentVersion) + .withParameters(params) + .withMode(DeploymentMode.COMPLETE) + .createAsync(); + } catch (IOException e) { + return Flux.error(e); + } + }).map(indexable -> indexable).doOnNext(deployment -> { + if (deployment != null) { + System.out.println("Deployment finished: " + deployment.name()); + succeeded.add(deployment.name()); + } + }).onErrorResume(e -> Mono.empty()).doOnComplete(() -> latch.countDown()).subscribe(); latch.await(); @@ -111,8 +105,8 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) failed.add(deployment); } } - System.out.println(String.format("Deployments %s succeeded. %s failed.", - String.join(", ", succeeded), String.join(", ", failed))); + System.out.println(String.format("Deployments %s succeeded. %s failed.", String.join(", ", succeeded), + String.join(", ", failed))); return true; } finally { @@ -147,8 +141,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java index e4ddc9e728335..fef3e0ae2deef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java @@ -41,7 +41,8 @@ public final class DeployUsingARMTemplateWithDeploymentOperations { * @param defaultPollingInterval polling interval in seconds * @return true if sample runs successfully */ - public static boolean runSample(final AzureResourceManager azureResourceManager, int defaultPollingInterval) throws InterruptedException { + public static boolean runSample(final AzureResourceManager azureResourceManager, int defaultPollingInterval) + throws InterruptedException { final String rgPrefix = Utils.randomResourceName(azureResourceManager, "rgJavaTest", 16); final String deploymentPrefix = Utils.randomResourceName(azureResourceManager, "javaTest", 16); final String sshKey = getSSHPublicKey(); @@ -51,7 +52,8 @@ public static boolean runSample(final AzureResourceManager azureResourceManager, try { // Use the Simple VM Template with SSH Key auth from GH quickstarts - final String templateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json"; + final String templateUri + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json"; final String templateContentVersion = "1.0.0.0"; // Template only needs an SSH Key parameter @@ -68,34 +70,29 @@ public static boolean runSample(final AzureResourceManager azureResourceManager, final List deploymentList = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); - Flux.range(1, numDeployments) - .flatMap(integer -> { - try { - String params; - if (integer == numDeployments) { - rootNode.set("adminPublicKey", mapper.createObjectNode().put("value", "bad content")); - params = rootNode.toString(); // Invalid parameters as a negative path - } else { - params = parameters; - } - return azureResourceManager.deployments() - .define(deploymentPrefix + "-" + integer) - .withNewResourceGroup(rgPrefix + "-" + integer, Region.US_SOUTH_CENTRAL) - .withTemplateLink(templateUri, templateContentVersion) - .withParameters(params) - .withMode(DeploymentMode.COMPLETE) - .beginCreateAsync(); - } catch (IOException e) { - return Flux.error(e); - } - }) - .doOnNext(deployment -> { - System.out.println("Deployment created: " + deployment.name()); - deploymentList.add(deployment); - }) - .onErrorResume(e -> Mono.empty()) - .doOnComplete(() -> latch.countDown()) - .subscribe(); + Flux.range(1, numDeployments).flatMap(integer -> { + try { + String params; + if (integer == numDeployments) { + rootNode.set("adminPublicKey", mapper.createObjectNode().put("value", "bad content")); + params = rootNode.toString(); // Invalid parameters as a negative path + } else { + params = parameters; + } + return azureResourceManager.deployments() + .define(deploymentPrefix + "-" + integer) + .withNewResourceGroup(rgPrefix + "-" + integer, Region.US_SOUTH_CENTRAL) + .withTemplateLink(templateUri, templateContentVersion) + .withParameters(params) + .withMode(DeploymentMode.COMPLETE) + .beginCreateAsync(); + } catch (IOException e) { + return Flux.error(e); + } + }).doOnNext(deployment -> { + System.out.println("Deployment created: " + deployment.name()); + deploymentList.add(deployment); + }).onErrorResume(e -> Mono.empty()).doOnComplete(() -> latch.countDown()).subscribe(); latch.await(); @@ -104,35 +101,33 @@ public static boolean runSample(final AzureResourceManager azureResourceManager, System.out.println("Checking deployment operations..."); final CountDownLatch operationLatch = new CountDownLatch(1); Flux.fromIterable(deploymentList) - .flatMap(deployment -> deployment.refreshAsync() - .flatMapMany(dp -> dp.deploymentOperations().listAsync()) - .collectList() - .map(deploymentOperations -> { - synchronized (deploymentList) { - System.out.println("--------------------" + deployment.name() + "--------------------"); - for (DeploymentOperation operation : deploymentOperations) { - if (operation.targetResource() != null) { - System.out.println(String.format("%s - %s: %s %s", - operation.targetResource().resourceName(), - operation.targetResource().resourceName(), - operation.provisioningState(), - operation.statusMessage() != null ? operation.statusMessage() : "")); - } - } + .flatMap(deployment -> deployment.refreshAsync() + .flatMapMany(dp -> dp.deploymentOperations().listAsync()) + .collectList() + .map(deploymentOperations -> { + synchronized (deploymentList) { + System.out.println("--------------------" + deployment.name() + "--------------------"); + for (DeploymentOperation operation : deploymentOperations) { + if (operation.targetResource() != null) { + System.out.println( + String.format("%s - %s: %s %s", operation.targetResource().resourceName(), + operation.targetResource().resourceName(), operation.provisioningState(), + operation.statusMessage() != null ? operation.statusMessage() : "")); } - return deploymentOperations; - }) - .repeatWhen(observable -> observable.delaySubscription(Duration.ofSeconds(pollingInterval))) - .takeUntil(deploymentOperations -> { - return "Succeeded".equalsIgnoreCase(deployment.provisioningState()) - || "Canceled".equalsIgnoreCase(deployment.provisioningState()) - || "Failed".equalsIgnoreCase(deployment.provisioningState()); - - }) - ) - .onErrorResume(e -> Mono.empty()) - .doOnComplete(() -> operationLatch.countDown()) - .subscribe(); + } + } + return deploymentOperations; + }) + .repeatWhen(observable -> observable.delaySubscription(Duration.ofSeconds(pollingInterval))) + .takeUntil(deploymentOperations -> { + return "Succeeded".equalsIgnoreCase(deployment.provisioningState()) + || "Canceled".equalsIgnoreCase(deployment.provisioningState()) + || "Failed".equalsIgnoreCase(deployment.provisioningState()); + + })) + .onErrorResume(e -> Mono.empty()) + .doOnComplete(() -> operationLatch.countDown()) + .subscribe(); operationLatch.await(); @@ -147,8 +142,8 @@ public static boolean runSample(final AzureResourceManager azureResourceManager, failed.add(deployment.name()); } } - System.out.println(String.format("Deployments %s succeeded. %s failed.", - String.join(", ", succeeded), String.join(", ", failed))); + System.out.println(String.format("Deployments %s succeeded. %s failed.", String.join(", ", succeeded), + String.join(", ", failed))); return true; } finally { @@ -183,8 +178,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -200,7 +194,8 @@ public static void main(String[] args) { private static String getSSHPublicKey() { byte[] content; try { - content = ByteStreams.toByteArray(DeployUsingARMTemplateWithDeploymentOperations.class.getResourceAsStream("/rsa.pub")); + content = ByteStreams + .toByteArray(DeployUsingARMTemplateWithDeploymentOperations.class.getResourceAsStream("/rsa.pub")); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java index d606b318bc726..bbe2d653ae621 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java @@ -36,7 +36,8 @@ public final class DeployUsingARMTemplateWithProgress { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, IllegalAccessException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, IllegalAccessException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSAP", 24); final String deploymentName = Utils.randomResourceName(azureResourceManager, "dpRSAP", 24); try { @@ -47,25 +48,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a resource group with name: " + rgName); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); System.out.println("Created a resource group with name: " + rgName); - //============================================================= // Create a deployment for an Azure App Service via an ARM // template. System.out.println("Starting a deployment for an Azure App Service: " + deploymentName); - azureResourceManager.deployments().define(deploymentName) - .withExistingResourceGroup(rgName) - .withTemplate(templateJson) - .withParameters("{}") - .withMode(DeploymentMode.INCREMENTAL) - .beginCreate(); + azureResourceManager.deployments() + .define(deploymentName) + .withExistingResourceGroup(rgName) + .withTemplate(templateJson) + .withParameters("{}") + .withMode(DeploymentMode.INCREMENTAL) + .beginCreate(); System.out.println("Started a deployment for an Azure App Service: " + deploymentName); @@ -73,8 +72,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Current deployment status : " + deployment.provisioningState()); while (!(deployment.provisioningState().equalsIgnoreCase("Succeeded") - || deployment.provisioningState().equalsIgnoreCase("Failed") - || deployment.provisioningState().equalsIgnoreCase("Cancelled"))) { + || deployment.provisioningState().equalsIgnoreCase("Failed") + || deployment.provisioningState().equalsIgnoreCase("Cancelled"))) { ResourceManagerUtils.sleep(Duration.ofSeconds(10)); deployment = azureResourceManager.deployments().getByResourceGroup(rgName, deploymentName); System.out.println("Current deployment status : " + deployment.provisioningState()); @@ -109,8 +108,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -123,16 +121,19 @@ public static void main(String[] args) { } - private static String getTemplate(AzureResourceManager azureResourceManager) throws IllegalAccessException, JsonProcessingException, IOException { + private static String getTemplate(AzureResourceManager azureResourceManager) + throws IllegalAccessException, JsonProcessingException, IOException { final String hostingPlanName = Utils.randomResourceName(azureResourceManager, "hpRSAT", 24); final String webappName = Utils.randomResourceName(azureResourceManager, "wnRSAT", 24); - try (InputStream embeddedTemplate = DeployUsingARMTemplateWithProgress.class.getResourceAsStream("/templateValue.json")) { + try (InputStream embeddedTemplate + = DeployUsingARMTemplateWithProgress.class.getResourceAsStream("/templateValue.json")) { final ObjectMapper mapper = new ObjectMapper(); final JsonNode tmp = mapper.readTree(embeddedTemplate); - DeployUsingARMTemplateWithProgress.validateAndAddFieldValue("string", hostingPlanName, "hostingPlanName", null, tmp); + DeployUsingARMTemplateWithProgress.validateAndAddFieldValue("string", hostingPlanName, "hostingPlanName", + null, tmp); DeployUsingARMTemplateWithProgress.validateAndAddFieldValue("string", webappName, "webSiteName", null, tmp); DeployUsingARMTemplateWithProgress.validateAndAddFieldValue("string", "F1", "skuName", null, tmp); DeployUsingARMTemplateWithProgress.validateAndAddFieldValue("int", "1", "skuCapacity", null, tmp); @@ -142,7 +143,7 @@ private static String getTemplate(AzureResourceManager azureResourceManager) thr } private static void validateAndAddFieldValue(String type, String fieldValue, String fieldName, String errorMessage, - JsonNode tmp) throws IllegalAccessException { + JsonNode tmp) throws IllegalAccessException { // Add count variable for loop.... final ObjectMapper mapper = new ObjectMapper(); final ObjectNode parameter = mapper.createObjectNode(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java index 5386df0f7fa8c..e251346ace4f8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java @@ -34,14 +34,14 @@ public final class DeployUsingARMTemplateWithTags { - /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, IllegalAccessException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, IllegalAccessException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSAT", 24); final String deploymentName = Utils.randomResourceName(azureResourceManager, "dpRSAT", 24); try { @@ -52,25 +52,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a resource group with name: " + rgName); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); System.out.println("Created a resource group with name: " + rgName); - //============================================================= // Create a deployment for an Azure App Service via an ARM // template. System.out.println("Starting a deployment for an Azure App Service: " + deploymentName); - Deployment deployment = azureResourceManager.deployments().define(deploymentName) - .withExistingResourceGroup(rgName) - .withTemplate(templateJson) - .withParameters("{}") - .withMode(DeploymentMode.INCREMENTAL) - .create(); + Deployment deployment = azureResourceManager.deployments() + .define(deploymentName) + .withExistingResourceGroup(rgName) + .withTemplate(templateJson) + .withParameters("{}") + .withMode(DeploymentMode.INCREMENTAL) + .create(); System.out.println("Finished a deployment for an Azure App Service: " + deploymentName); @@ -80,23 +78,27 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Getting created resources for (DeploymentOperation operation : operations) { if (operation.targetResource() != null) { - genericResources.add(azureResourceManager.genericResources().getById(operation.targetResource().id())); + genericResources + .add(azureResourceManager.genericResources().getById(operation.targetResource().id())); } } System.out.println("Resource created during deployment: " + deploymentName); for (GenericResource genericResource : genericResources) { - System.out.println(genericResource.resourceProviderNamespace() + "/" + genericResource.resourceType() + ": " + genericResource.name()); + System.out.println(genericResource.resourceProviderNamespace() + "/" + genericResource.resourceType() + + ": " + genericResource.name()); Map tags = new HashMap<>(genericResource.tags()); tags.put("label", "deploy1"); // Tag resource azureResourceManager.tagOperations().updateTags(genericResource, tags); } - PagedIterable listResources = azureResourceManager.genericResources().listByTag(rgName, "label", "deploy1"); + PagedIterable listResources + = azureResourceManager.genericResources().listByTag(rgName, "label", "deploy1"); System.out.println("Tagged resources for deployment: " + deploymentName); for (GenericResource genericResource : listResources) { - System.out.println(genericResource.resourceProviderNamespace() + "/" + genericResource.resourceType() + ": " + genericResource.name()); + System.out.println(genericResource.resourceProviderNamespace() + "/" + genericResource.resourceType() + + ": " + genericResource.name()); } return true; } finally { @@ -129,8 +131,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -142,11 +143,13 @@ public static void main(String[] args) { } } - private static String getTemplate(AzureResourceManager azureResourceManager) throws IllegalAccessException, JsonProcessingException, IOException { + private static String getTemplate(AzureResourceManager azureResourceManager) + throws IllegalAccessException, JsonProcessingException, IOException { final String hostingPlanName = Utils.randomResourceName(azureResourceManager, "hpRSAT", 24); final String webappName = Utils.randomResourceName(azureResourceManager, "wnRSAT", 24); - try (InputStream embeddedTemplate = DeployUsingARMTemplateWithTags.class.getResourceAsStream("/templateValue.json")) { + try (InputStream embeddedTemplate + = DeployUsingARMTemplateWithTags.class.getResourceAsStream("/templateValue.json")) { final ObjectMapper mapper = new ObjectMapper(); final JsonNode tmp = mapper.readTree(embeddedTemplate); @@ -161,7 +164,7 @@ private static String getTemplate(AzureResourceManager azureResourceManager) thr } private static void validateAndAddFieldValue(String type, String fieldValue, String fieldName, String errorMessage, - JsonNode tmp) throws IllegalAccessException { + JsonNode tmp) throws IllegalAccessException { // Add count variable for loop.... final ObjectMapper mapper = new ObjectMapper(); final ObjectNode parameter = mapper.createObjectNode(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java index 742864ffea64b..9b64b51433ed7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java @@ -33,7 +33,8 @@ public class DeployVirtualMachineUsingARMTemplate { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, IllegalAccessException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws IOException, IllegalAccessException { final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSAT", 24); final String deploymentName = Utils.randomResourceName(azureResourceManager, "dpRSAT", 24); try { @@ -46,33 +47,33 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a resource group with name: " + rgName); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); System.out.println("Created a resource group with name: " + rgName); - //============================================================= // Create a deployment for an Azure App Service via an ARM // template. - System.out.println("Starting a deployment for an Azure Virtual Machine with managed disks: " + deploymentName); + System.out + .println("Starting a deployment for an Azure Virtual Machine with managed disks: " + deploymentName); - azureResourceManager.deployments().define(deploymentName) - .withExistingResourceGroup(rgName) - .withTemplate(templateJson) - .withParameters("{}") - .withMode(DeploymentMode.INCREMENTAL) - .create(); + azureResourceManager.deployments() + .define(deploymentName) + .withExistingResourceGroup(rgName) + .withTemplate(templateJson) + .withParameters("{}") + .withMode(DeploymentMode.INCREMENTAL) + .create(); - System.out.println("Started a deployment for an Azure Virtual Machine with managed disks: " + deploymentName); + System.out + .println("Started a deployment for an Azure Virtual Machine with managed disks: " + deploymentName); Deployment deployment = azureResourceManager.deployments().getByResourceGroup(rgName, deploymentName); System.out.println("Current deployment status : " + deployment.provisioningState()); while (!(deployment.provisioningState().equalsIgnoreCase("Succeeded") - || deployment.provisioningState().equalsIgnoreCase("Failed") - || deployment.provisioningState().equalsIgnoreCase("Cancelled"))) { + || deployment.provisioningState().equalsIgnoreCase("Failed") + || deployment.provisioningState().equalsIgnoreCase("Cancelled"))) { ResourceManagerUtils.sleep(Duration.ofSeconds(10)); deployment = azureResourceManager.deployments().getByResourceGroup(rgName, deploymentName); System.out.println("Current deployment status : " + deployment.provisioningState()); @@ -108,8 +109,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -121,25 +121,30 @@ public static void main(String[] args) { } } - private static String getTemplate(AzureResourceManager azureResourceManager) throws IllegalAccessException, JsonProcessingException, IOException { + private static String getTemplate(AzureResourceManager azureResourceManager) + throws IllegalAccessException, JsonProcessingException, IOException { final String adminUsername = "tirekicker"; final String adminPassword = Utils.password(); final String osDiskName = Utils.randomResourceName(azureResourceManager, "osdisk-", 24); - try (InputStream embeddedTemplate = DeployVirtualMachineUsingARMTemplate.class.getResourceAsStream("/virtualMachineWithManagedDisksTemplate.json")) { + try (InputStream embeddedTemplate = DeployVirtualMachineUsingARMTemplate.class + .getResourceAsStream("/virtualMachineWithManagedDisksTemplate.json")) { final ObjectMapper mapper = new ObjectMapper(); final JsonNode tmp = mapper.readTree(embeddedTemplate); - DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", adminUsername, "adminUsername", null, tmp); - DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", adminPassword, "adminPassword", null, tmp); - DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", osDiskName, "osDiskName", null, tmp); + DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", adminUsername, "adminUsername", + null, tmp); + DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", adminPassword, "adminPassword", + null, tmp); + DeployVirtualMachineUsingARMTemplate.validateAndAddFieldValue("string", osDiskName, "osDiskName", null, + tmp); return tmp.toString(); } } private static void validateAndAddFieldValue(String type, String fieldValue, String fieldName, String errorMessage, - JsonNode tmp) throws IllegalAccessException { + JsonNode tmp) throws IllegalAccessException { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode parameter = mapper.createObjectNode(); parameter.put("type", type); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java index 97b41d50b8547..4f40c4e2b0859 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java @@ -51,20 +51,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final Region region = Region.US_WEST; ResourceGroup resourceGroup; - ManagementLock lockGroup = null, - lockVM = null, - lockStorage = null, - lockDiskRO = null, - lockDiskDel = null, + ManagementLock lockGroup = null, lockVM = null, lockStorage = null, lockDiskRO = null, lockDiskDel = null, lockSubnet = null; try { //============================================================= // Create a shared resource group for all the resources so they can all be deleted together // - resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + resourceGroup = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); System.out.println("Created a new resource group - " + resourceGroup.id()); //============================================================ @@ -72,20 +66,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // // Define a network to apply a lock to - Creatable netDefinition = azureResourceManager.networks().define(netName) + Creatable netDefinition = azureResourceManager.networks() + .define(netName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28"); // Define a managed disk for testing locks on that - Creatable diskDefinition = azureResourceManager.disks().define(diskName) + Creatable diskDefinition = azureResourceManager.disks() + .define(diskName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withData() .withSizeInGB(100); // Define a VM to apply a lock to - Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) + Creatable vmDefinition = azureResourceManager.virtualMachines() + .define(vmName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withNewPrimaryNetwork(netDefinition) @@ -98,16 +95,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); // Define a storage account to apply a lock to - Creatable storageDefinition = azureResourceManager.storageAccounts().define(storageName) + Creatable storageDefinition = azureResourceManager.storageAccounts() + .define(storageName) .withRegion(region) .withExistingResourceGroup(resourceGroup); // Create resources in parallel to save time System.out.println("Creating the needed resources..."); - Flux.merge( - storageDefinition.createAsync().subscribeOn(Schedulers.parallel()), - vmDefinition.createAsync().subscribeOn(Schedulers.parallel())) - .blockLast(); + Flux.merge(storageDefinition.createAsync().subscribeOn(Schedulers.parallel()), + vmDefinition.createAsync().subscribeOn(Schedulers.parallel())).blockLast(); System.out.println("Resources created."); VirtualMachine vm = (VirtualMachine) vmDefinition; @@ -124,13 +120,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating locks sequentially..."); // Apply a ReadOnly lock to the disk - lockDiskRO = azureResourceManager.managementLocks().define("diskLockRO") + lockDiskRO = azureResourceManager.managementLocks() + .define("diskLockRO") .withLockedResource(disk) .withLevel(LockLevel.READ_ONLY) .create(); // Apply a lock preventing the disk from being deleted - lockDiskDel = azureResourceManager.managementLocks().define("diskLockDel") + lockDiskDel = azureResourceManager.managementLocks() + .define("diskLockDel") .withLockedResource(disk) .withLevel(LockLevel.CAN_NOT_DELETE) .create(); @@ -139,32 +137,33 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating locks in parallel..."); // Define a subnet lock - Creatable lockSubnetDef = azureResourceManager.managementLocks().define("subnetLock") + Creatable lockSubnetDef = azureResourceManager.managementLocks() + .define("subnetLock") .withLockedResource(subnet.innerModel().id()) .withLevel(LockLevel.READ_ONLY); // Define a VM lock - Creatable lockVMDef = azureResourceManager.managementLocks().define("vmlock") + Creatable lockVMDef = azureResourceManager.managementLocks() + .define("vmlock") .withLockedResource(vm) .withLevel(LockLevel.READ_ONLY) .withNotes("vm readonly lock"); // Define a resource group lock - Creatable lockGroupDef = azureResourceManager.managementLocks().define("rglock") + Creatable lockGroupDef = azureResourceManager.managementLocks() + .define("rglock") .withLockedResource(resourceGroup.id()) .withLevel(LockLevel.CAN_NOT_DELETE); // Define a storage lock - Creatable lockStorageDef = azureResourceManager.managementLocks().define("stLock") + Creatable lockStorageDef = azureResourceManager.managementLocks() + .define("stLock") .withLockedResource(storage) .withLevel(LockLevel.CAN_NOT_DELETE); @SuppressWarnings("unchecked") - CreatedResources created = azureResourceManager.managementLocks().create( - lockVMDef, - lockGroupDef, - lockStorageDef, - lockSubnetDef); + CreatedResources created + = azureResourceManager.managementLocks().create(lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef); lockVM = created.get(lockVMDef.key()); lockStorage = created.get(lockStorageDef.key()); @@ -181,7 +180,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { int lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(vm.id())); System.out.println("Number of locks applied to the virtual machine: " + lockCount); lockCount = Utils.getSize(azureResourceManager.managementLocks().listByResourceGroup(resourceGroup.name())); - System.out.println("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount); + System.out + .println("Number of locks applied to the resource group (includes locks on resources in the group): " + + lockCount); lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(storage.id())); System.out.println("Number of locks applied to the storage account: " + lockCount); lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(disk.id())); @@ -221,13 +222,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { try { // Clean up (remember to unlock resources before deleting the resource group) - azureResourceManager.managementLocks().deleteByIds( - lockGroup.id(), - lockVM.id(), - lockDiskRO.id(), - lockDiskDel.id(), - lockStorage.id(), - lockSubnet.id()); + azureResourceManager.managementLocks() + .deleteByIds(lockGroup.id(), lockVM.id(), lockDiskRO.id(), lockDiskDel.id(), lockStorage.id(), + lockSubnet.id()); System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { @@ -254,8 +251,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java index d0612ae4ecdf8..f488ef8345dff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java @@ -37,55 +37,48 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String resourceName2 = Utils.randomResourceName(azureResourceManager, "rn2", 24); try { - //============================================================= // Create resource group. System.out.println("Creating a resource group with name: " + rgName); - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); - + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); //============================================================= // Create storage account. System.out.println("Creating a storage account with name: " + resourceName1); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(resourceName1) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(resourceName1) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Storage account created: " + storageAccount.id()); - //============================================================= // Update - set the sku name System.out.println("Updating the storage account with name: " + resourceName1); - storageAccount.update() - .withSku(StorageAccountSkuType.STANDARD_RAGRS) - .apply(); + storageAccount.update().withSku(StorageAccountSkuType.STANDARD_RAGRS).apply(); System.out.println("Updated the storage account with name: " + resourceName1); - //============================================================= // Create another storage account. System.out.println("Creating another storage account with name: " + resourceName2); - StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(resourceName2) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .create(); + StorageAccount storageAccount2 = azureResourceManager.storageAccounts() + .define(resourceName2) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .create(); System.out.println("Storage account created: " + storageAccount2.id()); - //============================================================= // List storage accounts. @@ -95,7 +88,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Storage account: " + sAccount.name()); } - //============================================================= // Delete a storage accounts. @@ -134,8 +126,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java index c9bf84ae08e08..a41a5217493c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java @@ -36,43 +36,34 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { final String resourceTagValue = Utils.randomResourceName(azureResourceManager, "rgRSTV", 24); try { - //============================================================= // Create resource group. System.out.println("Creating a resource group with name: " + rgName); - ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); System.out.println("Created a resource group with name: " + rgName); - //============================================================= // Update the resource group. System.out.println("Updating the resource group with name: " + rgName); - resourceGroup.update() - .withTag(resourceTagName, resourceTagValue) - .apply(); + resourceGroup.update().withTag(resourceTagName, resourceTagValue).apply(); System.out.println("Updated the resource group with name: " + rgName); - //============================================================= // Create another resource group. System.out.println("Creating another resource group with name: " + rgName2); - azureResourceManager.resourceGroups().define(rgName2) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName2).withRegion(Region.US_WEST).create(); System.out.println("Created another resource group with name: " + rgName2); - //============================================================= // List resource groups. @@ -82,7 +73,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Resource group: " + rGroup.name()); } - //============================================================= // Delete a resource group. @@ -118,8 +108,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/DockerUtils.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/DockerUtils.java index a5967d1a83634..850d3c280dd79 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/DockerUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/DockerUtils.java @@ -92,8 +92,8 @@ public SSLContext getSSLContext() { * @return an instance of DockerClient * @throws IOException exception thrown */ - public static DockerClient createDockerClient(AzureResourceManager azureResourceManager, String rgName, Region region, - String registryServerUrl, String username, String password) throws IOException { + public static DockerClient createDockerClient(AzureResourceManager azureResourceManager, String rgName, + Region region, String registryServerUrl, String username, String password) throws IOException { final String envDockerHost = System.getenv("DOCKER_HOST"); final String envDockerCertPath = System.getenv("DOCKER_CERT_PATH"); String dockerHostUrl; @@ -120,11 +120,10 @@ public static DockerClient createDockerClient(AzureResourceManager azureResource String caPemContent = new String(Files.readAllBytes(Paths.get(caPemPath)), StandardCharsets.UTF_8); dockerClientConfig = createDockerClientConfig(dockerHostUrl, registryServerUrl, username, password, - caPemContent, keyPemContent, certPemContent); + caPemContent, keyPemContent, certPemContent); } - dockerClient = DockerClientBuilder.getInstance(dockerClientConfig) - .build(); + dockerClient = DockerClientBuilder.getInstance(dockerClientConfig).build(); System.out.println("List Docker host info"); System.out.println("\tFound Docker version: " + dockerClient.versionCmd().exec().toString()); System.out.println("\tFound Docker info: " + dockerClient.infoCmd().exec().toString()); @@ -145,16 +144,16 @@ public static DockerClient createDockerClient(AzureResourceManager azureResource * @param certPemContent - content of the cert.pem certificate file * @return an instance of DockerClient configuration */ - public static DockerClientConfig createDockerClientConfig(String host, String registryServerUrl, String username, String password, - String caPemContent, String keyPemContent, String certPemContent) { + public static DockerClientConfig createDockerClientConfig(String host, String registryServerUrl, String username, + String password, String caPemContent, String keyPemContent, String certPemContent) { return DefaultDockerClientConfig.createDefaultConfigBuilder() - .withDockerHost(host) - .withDockerTlsVerify(true) - .withCustomSslConfig(new DockerSSLConfig(caPemContent, keyPemContent, certPemContent)) - .withRegistryUrl(registryServerUrl) - .withRegistryUsername(username) - .withRegistryPassword(password) - .build(); + .withDockerHost(host) + .withDockerTlsVerify(true) + .withCustomSslConfig(new DockerSSLConfig(caPemContent, keyPemContent, certPemContent)) + .withRegistryUrl(registryServerUrl) + .withRegistryUsername(username) + .withRegistryPassword(password) + .build(); } /** @@ -166,14 +165,15 @@ public static DockerClientConfig createDockerClientConfig(String host, String re * @param password - password to connect with to the private container registry * @return an instance of DockerClient configuration */ - public static DockerClientConfig createDockerClientConfig(String host, String registryServerUrl, String username, String password) { + public static DockerClientConfig createDockerClientConfig(String host, String registryServerUrl, String username, + String password) { return DefaultDockerClientConfig.createDefaultConfigBuilder() - .withDockerHost(host) - .withDockerTlsVerify(false) - .withRegistryUrl(registryServerUrl) - .withRegistryUsername(username) - .withRegistryPassword(password) - .build(); + .withDockerHost(host) + .withDockerTlsVerify(false) + .withRegistryUrl(registryServerUrl) + .withRegistryUsername(username) + .withRegistryPassword(password) + .build(); } /** @@ -188,7 +188,7 @@ public static DockerClientConfig createDockerClientConfig(String host, String re * @return an instance of DockerClient */ public static DockerClient fromNewDockerVM(AzureResourceManager azureResourceManager, String rgName, Region region, - String registryServerUrl, String username, String password) { + String registryServerUrl, String username, String password) { final String dockerVMName = Utils.randomResourceName(azureResourceManager, "dockervm", 15); final String publicIPDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 10); final String vmUserName = "dockerUser"; @@ -200,20 +200,22 @@ public static DockerClient fromNewDockerVM(AzureResourceManager azureResourceMan Date t1 = new Date(); - VirtualMachine dockerVM = azureResourceManager.virtualMachines().define(dockerVMName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPDnsLabel) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(vmUserName) - .withRootPassword(vmPassword) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine dockerVM = azureResourceManager.virtualMachines() + .define(dockerVMName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPDnsLabel) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(vmUserName) + .withRootPassword(vmPassword) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); Date t2 = new Date(); - System.out.println("Created Azure Virtual Machine: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + dockerVM.id()); + System.out.println("Created Azure Virtual Machine: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + dockerVM.id()); // Wait for a minute for PIP to be available ResourceManagerUtils.sleep(Duration.ofMinutes(1)); @@ -222,7 +224,8 @@ public static DockerClient fromNewDockerVM(AzureResourceManager azureResourceMan PublicIpAddress publicIp = nicIPConfiguration.getPublicIpAddress(); String dockerHostIP = publicIp.ipAddress(); - DockerClient dockerClient = installDocker(dockerHostIP, vmUserName, vmPassword, registryServerUrl, username, password); + DockerClient dockerClient + = installDocker(dockerHostIP, vmUserName, vmPassword, registryServerUrl, username, password); System.out.println("List Docker host info"); System.out.println("\tFound Docker version: " + dockerClient.versionCmd().exec().toString()); System.out.println("\tFound Docker info: " + dockerClient.infoCmd().exec().toString()); @@ -242,7 +245,7 @@ public static DockerClient fromNewDockerVM(AzureResourceManager azureResourceMan * @return an instance of DockerClient */ public static DockerClient installDocker(String dockerHostIP, String vmUserName, String vmPassword, - String registryServerUrl, String username, String password) { + String registryServerUrl, String username, String password) { String keyPemContent = ""; // it stores the content of the key.pem certificate file String certPemContent = ""; // it stores the content of the cert.pem certificate file String caPemContent = ""; // it stores the content of the ca.pem certificate file @@ -254,42 +257,29 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, System.out.println("Copy Docker setup scripts to remote host: " + dockerHostIP); sshShell = SSHShell.open(dockerHostIP, 22, vmUserName, vmPassword); - sshShell.upload(new ByteArrayInputStream(INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.getBytes(StandardCharsets.UTF_8)), - "INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh", - ".azuredocker", - true, - "4095"); - - sshShell.upload(new ByteArrayInputStream(CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.replaceAll("HOST_IP", dockerHostIP).getBytes(StandardCharsets.UTF_8)), - "CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh", - ".azuredocker", - true, - "4095"); - sshShell.upload(new ByteArrayInputStream(INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.getBytes(StandardCharsets.UTF_8)), - "INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh", - ".azuredocker", - true, - "4095"); - sshShell.upload(new ByteArrayInputStream(DEFAULT_DOCKERD_CONFIG_TLS_ENABLED.getBytes(StandardCharsets.UTF_8)), - "dockerd_tls.config", - ".azuredocker", - true, - "4095"); - sshShell.upload(new ByteArrayInputStream(CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.getBytes(StandardCharsets.UTF_8)), - "CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh", - ".azuredocker", - true, - "4095"); - sshShell.upload(new ByteArrayInputStream(DEFAULT_DOCKERD_CONFIG_TLS_DISABLED.getBytes(StandardCharsets.UTF_8)), - "dockerd_notls.config", - ".azuredocker", - true, - "4095"); - sshShell.upload(new ByteArrayInputStream(CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.getBytes(StandardCharsets.UTF_8)), - "CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh", - ".azuredocker", - true, - "4095"); + sshShell.upload( + new ByteArrayInputStream(INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.getBytes(StandardCharsets.UTF_8)), + "INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh", ".azuredocker", true, "4095"); + + sshShell.upload( + new ByteArrayInputStream(CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.replaceAll("HOST_IP", dockerHostIP) + .getBytes(StandardCharsets.UTF_8)), + "CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh", ".azuredocker", true, "4095"); + sshShell.upload( + new ByteArrayInputStream(INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.getBytes(StandardCharsets.UTF_8)), + "INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh", ".azuredocker", true, "4095"); + sshShell.upload( + new ByteArrayInputStream(DEFAULT_DOCKERD_CONFIG_TLS_ENABLED.getBytes(StandardCharsets.UTF_8)), + "dockerd_tls.config", ".azuredocker", true, "4095"); + sshShell.upload( + new ByteArrayInputStream(CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.getBytes(StandardCharsets.UTF_8)), + "CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh", ".azuredocker", true, "4095"); + sshShell.upload( + new ByteArrayInputStream(DEFAULT_DOCKERD_CONFIG_TLS_DISABLED.getBytes(StandardCharsets.UTF_8)), + "dockerd_notls.config", ".azuredocker", true, "4095"); + sshShell.upload( + new ByteArrayInputStream(CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.getBytes(StandardCharsets.UTF_8)), + "CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh", ".azuredocker", true, "4095"); } catch (JSchException jSchException) { System.out.println(jSchException.getMessage()); } catch (IOException ioException) { @@ -306,7 +296,8 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, System.out.println("Trying to install Docker host at: " + dockerHostIP); sshShell = SSHShell.open(dockerHostIP, 22, vmUserName, vmPassword); - String output = sshShell.executeCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh", true, true); + String output = sshShell + .executeCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh", true, true); System.out.println(output); } catch (JSchException jSchException) { System.out.println(jSchException.getMessage()); @@ -324,7 +315,8 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, System.out.println("Trying to create OPENSSL certificates"); sshShell = SSHShell.open(dockerHostIP, 22, vmUserName, vmPassword); - String output = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh", true, true); + String output + = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh", true, true); System.out.println(output); } catch (JSchException jSchException) { System.out.println(jSchException.getMessage()); @@ -342,7 +334,8 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, System.out.println("Trying to install TLS certificates"); sshShell = SSHShell.open(dockerHostIP, 22, vmUserName, vmPassword); - String output = sshShell.executeCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh", true, true); + String output + = sshShell.executeCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh", true, true); System.out.println(output); System.out.println("Download Docker client TLS certificates from: " + dockerHostIP); keyPemContent = sshShell.download("key.pem", ".azuredocker/tls", true); @@ -364,14 +357,15 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, System.out.println("Trying to setup Docker config: " + dockerHostIP); sshShell = SSHShell.open(dockerHostIP, 22, vmUserName, vmPassword); -// // Setup Docker daemon to allow connection from any Docker clients -// String output = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh", true, true); -// System.out.println(output); -// dockerHostPort = "2375"; // Default Docker port when secured connection is disabled -// dockerHostTlsEnabled = false; + // // Setup Docker daemon to allow connection from any Docker clients + // String output = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh", true, true); + // System.out.println(output); + // dockerHostPort = "2375"; // Default Docker port when secured connection is disabled + // dockerHostTlsEnabled = false; // Setup Docker daemon to allow connection from authorized Docker clients only - String output = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh", true, true); + String output = sshShell.executeCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh", + true, true); System.out.println(output); String dockerHostPort = "2376"; // Default Docker port when secured connection is enabled dockerHostTlsEnabled = true; @@ -392,7 +386,7 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, DockerClientConfig dockerClientConfig; if (dockerHostTlsEnabled) { dockerClientConfig = createDockerClientConfig(dockerHostUrl, registryServerUrl, username, password, - caPemContent, keyPemContent, certPemContent); + caPemContent, keyPemContent, certPemContent); } else { dockerClientConfig = createDockerClientConfig(dockerHostUrl, registryServerUrl, username, password); } @@ -400,48 +394,40 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, return DockerClientBuilder.getInstance(dockerClientConfig).build(); } - /** * Installs Docker Engine and tools and adds current user to the docker group. */ public static final String INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS = "" - + "echo Running: \"if [ ! -d ~/.azuredocker/tls ]; then mkdir -p ~/.azuredocker/tls ; fi\" \n" - + "if [ ! -d ~/.azuredocker/tls ]; then mkdir -p ~/.azuredocker/tls ; fi \n" - + "echo Running: sudo apt-get update \n" - + "sudo apt-get update \n" - + "echo Running: sudo apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl gnupg-agent software-properties-common \n" - + "sudo apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl software-properties-common \n" - + "echo Running: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - \n" - + "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - \n" - + "echo Running: sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" \n" - + "sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" \n" - + "echo Running: sudo apt-get update \n" - + "sudo apt-get update \n" - + "echo Running: sudo apt-get -y install docker-ce docker-ce-cli containerd.io \n" - + "sudo apt-get -y install docker-ce docker-ce-cli containerd.io \n" - + "echo Running: sudo groupadd docker \n" - + "sudo groupadd docker \n" - + "echo Running: sudo usermod -aG docker $USER \n" - + "sudo usermod -aG docker $USER \n"; + + "echo Running: \"if [ ! -d ~/.azuredocker/tls ]; then mkdir -p ~/.azuredocker/tls ; fi\" \n" + + "if [ ! -d ~/.azuredocker/tls ]; then mkdir -p ~/.azuredocker/tls ; fi \n" + + "echo Running: sudo apt-get update \n" + "sudo apt-get update \n" + + "echo Running: sudo apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl gnupg-agent software-properties-common \n" + + "sudo apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl software-properties-common \n" + + "echo Running: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - \n" + + "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - \n" + + "echo Running: sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" \n" + + "sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" \n" + + "echo Running: sudo apt-get update \n" + "sudo apt-get update \n" + + "echo Running: sudo apt-get -y install docker-ce docker-ce-cli containerd.io \n" + + "sudo apt-get -y install docker-ce docker-ce-cli containerd.io \n" + "echo Running: sudo groupadd docker \n" + + "sudo groupadd docker \n" + "echo Running: sudo usermod -aG docker $USER \n" + + "sudo usermod -aG docker $USER \n"; /** * Linux bash script that creates the TLS certificates for a secured Docker connection. */ - public static final String CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU = "" - + "echo Running: \"if [ ! -d ~/.azuredocker/tls ]; then rm -f -r ~/.azuredocker/tls ; fi\" \n" + public static final String CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU + = "" + "echo Running: \"if [ ! -d ~/.azuredocker/tls ]; then rm -f -r ~/.azuredocker/tls ; fi\" \n" + "if [ ! -d ~/.azuredocker/tls ]; then rm -f -r ~/.azuredocker/tls ; fi \n" - + "echo Running: mkdir -p ~/.azuredocker/tls \n" - + "mkdir -p ~/.azuredocker/tls \n" - + "echo Running: cd ~/.azuredocker/tls \n" - + "cd ~/.azuredocker/tls \n" + + "echo Running: mkdir -p ~/.azuredocker/tls \n" + "mkdir -p ~/.azuredocker/tls \n" + + "echo Running: cd ~/.azuredocker/tls \n" + "cd ~/.azuredocker/tls \n" // Generate CA certificate + "echo Running: openssl genrsa -passout pass:$CERT_CA_PWD_PARAM$ -aes256 -out ca-key.pem 2048 \n" + "openssl genrsa -passout pass:$CERT_CA_PWD_PARAM$ -aes256 -out ca-key.pem 2048 \n" // Generate Server certificates + "echo Running: openssl req -passin pass:$CERT_CA_PWD_PARAM$ -subj '/CN=Docker Host CA/C=US' -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem \n" + "openssl req -passin pass:$CERT_CA_PWD_PARAM$ -subj '/CN=Docker Host CA/C=US' -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem \n" - + "echo Running: openssl genrsa -out server-key.pem 2048 \n" - + "openssl genrsa -out server-key.pem 2048 \n" + + "echo Running: openssl genrsa -out server-key.pem 2048 \n" + "openssl genrsa -out server-key.pem 2048 \n" + "echo Running: openssl req -subj '/CN=HOST_IP' -sha256 -new -key server-key.pem -out server.csr \n" + "openssl req -subj '/CN=HOST_IP' -sha256 -new -key server-key.pem -out server.csr \n" + "echo Running: openssl x509 -req -passin pass:$CERT_CA_PWD_PARAM$ -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server.pem \n" @@ -455,14 +441,13 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, + "echo extendedKeyUsage = clientAuth,serverAuth > extfile.cnf \n" + "echo Running: openssl x509 -req -passin pass:$CERT_CA_PWD_PARAM$ -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf \n" + "openssl x509 -req -passin pass:$CERT_CA_PWD_PARAM$ -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf \n" - + "echo Running: cd ~ \n" - + "cd ~ \n"; + + "echo Running: cd ~ \n" + "cd ~ \n"; /** * Bash script that sets up the TLS certificates to be used in a secured Docker configuration file; must be run on the Docker dockerHostUrl after the VM is provisioned. */ - public static final String INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU = "" - + "echo \"if [ ! -d /etc/docker/tls ]; then sudo mkdir -p /etc/docker/tls ; fi\" \n" + public static final String INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU + = "" + "echo \"if [ ! -d /etc/docker/tls ]; then sudo mkdir -p /etc/docker/tls ; fi\" \n" + "if [ ! -d /etc/docker/tls ]; then sudo mkdir -p /etc/docker/tls ; fi \n" + "echo sudo cp -f ~/.azuredocker/tls/ca.pem /etc/docker/tls/ca.pem \n" + "sudo cp -f ~/.azuredocker/tls/ca.pem /etc/docker/tls/ca.pem \n" @@ -470,52 +455,41 @@ public static DockerClient installDocker(String dockerHostIP, String vmUserName, + "sudo cp -f ~/.azuredocker/tls/server.pem /etc/docker/tls/server.pem \n" + "echo sudo cp -f ~/.azuredocker/tls/server-key.pem /etc/docker/tls/server-key.pem \n" + "sudo cp -f ~/.azuredocker/tls/server-key.pem /etc/docker/tls/server-key.pem \n" - + "echo sudo chmod -R 755 /etc/docker \n" - + "sudo chmod -R 755 /etc/docker \n"; + + "echo sudo chmod -R 755 /etc/docker \n" + "sudo chmod -R 755 /etc/docker \n"; /** * Docker daemon config file allowing connections from any Docker client. */ - public static final String DEFAULT_DOCKERD_CONFIG_TLS_ENABLED = "" - + "[Service]\n" - + "ExecStart=\n" - + "ExecStart=/usr/bin/dockerd --tlsverify --tlscacert=/etc/docker/tls/ca.pem --tlscert=/etc/docker/tls/server.pem --tlskey=/etc/docker/tls/server-key.pem -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock\n"; + public static final String DEFAULT_DOCKERD_CONFIG_TLS_ENABLED = "" + "[Service]\n" + "ExecStart=\n" + + "ExecStart=/usr/bin/dockerd --tlsverify --tlscacert=/etc/docker/tls/ca.pem --tlscert=/etc/docker/tls/server.pem --tlskey=/etc/docker/tls/server-key.pem -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock\n"; /** * Bash script that creates a default TLS secured Docker configuration file; must be run on the Docker dockerHostUrl after the VM is provisioned. */ public static final String CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED = "" - + "echo Running: sudo service docker stop \n" - + "sudo service docker stop \n" - + "echo \"if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi\" \n" - + "if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi \n" - + "echo sudo cp -f ~/.azuredocker/dockerd_tls.config /etc/systemd/system/docker.service.d/custom.conf \n" - + "sudo cp -f ~/.azuredocker/dockerd_tls.config /etc/systemd/system/docker.service.d/custom.conf \n" - + "echo Running: sudo systemctl daemon-reload \n" - + "sudo systemctl daemon-reload \n" - + "echo Running: sudo service docker start \n" - + "sudo service docker start \n"; + + "echo Running: sudo service docker stop \n" + "sudo service docker stop \n" + + "echo \"if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi\" \n" + + "if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi \n" + + "echo sudo cp -f ~/.azuredocker/dockerd_tls.config /etc/systemd/system/docker.service.d/custom.conf \n" + + "sudo cp -f ~/.azuredocker/dockerd_tls.config /etc/systemd/system/docker.service.d/custom.conf \n" + + "echo Running: sudo systemctl daemon-reload \n" + "sudo systemctl daemon-reload \n" + + "echo Running: sudo service docker start \n" + "sudo service docker start \n"; /** * Docker daemon config file allowing connections from any Docker client. */ - public static final String DEFAULT_DOCKERD_CONFIG_TLS_DISABLED = "" - + "[Service]\n" - + "ExecStart=\n" - + "ExecStart=/usr/bin/dockerd --tls=false -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock\n"; + public static final String DEFAULT_DOCKERD_CONFIG_TLS_DISABLED = "" + "[Service]\n" + "ExecStart=\n" + + "ExecStart=/usr/bin/dockerd --tls=false -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock\n"; /** * Bash script that creates a default unsecured Docker configuration file; must be run on the Docker dockerHostUrl after the VM is provisioned. */ public static final String CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED = "" - + "echo Running: sudo service docker stop\n" - + "sudo service docker stop\n" - + "echo \"if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi\" \n" - + "if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi \n" - + "echo sudo cp -f ~/.azuredocker/dockerd_notls.config /etc/systemd/system/docker.service.d/custom.conf \n" - + "sudo cp -f ~/.azuredocker/dockerd_notls.config /etc/systemd/system/docker.service.d/custom.conf \n" - + "echo Running: sudo systemctl daemon-reload \n" - + "sudo systemctl daemon-reload \n" - + "echo Running: sudo service docker start \n" - + "sudo service docker start \n"; + + "echo Running: sudo service docker stop\n" + "sudo service docker stop\n" + + "echo \"if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi\" \n" + + "if [ ! -d /etc/systemd/system/docker.service.d ]; then sudo mkdir -p /etc/systemd/system/docker.service.d ; fi \n" + + "echo sudo cp -f ~/.azuredocker/dockerd_notls.config /etc/systemd/system/docker.service.d/custom.conf \n" + + "sudo cp -f ~/.azuredocker/dockerd_notls.config /etc/systemd/system/docker.service.d/custom.conf \n" + + "echo Running: sudo systemctl daemon-reload \n" + "sudo systemctl daemon-reload \n" + + "echo Running: sudo service docker start \n" + "sudo service docker start \n"; } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/SSHShell.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/SSHShell.java index 039c74918a0e4..0194dcf280b53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/SSHShell.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/SSHShell.java @@ -60,7 +60,7 @@ private SSHShell(String host, int port, String userName, String password) throws * @throws IOException IO exception thrown */ public static SSHShell open(String host, int port, String userName, String password) - throws JSchException, IOException { + throws JSchException, IOException { return new SSHShell(host, port, userName, password); } @@ -154,7 +154,8 @@ public String download(String fileName, String fromPath, boolean isUserHomeBased * @param filePerm file permissions to be set * @throws Exception exception thrown */ - public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) throws Exception { + public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) + throws Exception { ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp"); channel.connect(); String absolutePath = isUserHomeBased ? channel.getHome() + "/" + toPath : toPath; @@ -198,7 +199,8 @@ public void close() { * @throws UnsupportedEncodingException exception thrown * @throws JSchException exception thrown */ - public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws UnsupportedEncodingException, JSchException { + public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) + throws UnsupportedEncodingException, JSchException { JSch jsch = new JSch(); KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA); ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java index 3f28a2cace909..ab51455eb0ecb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java @@ -274,7 +274,8 @@ public static String sshPublicKey() { 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); + 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)); @@ -334,7 +335,8 @@ public static String randomUuid(AzureResourceManager azure) { * @param maxLen the max length of the name. * @return the randomized resource name. */ - public static String randomResourceName(AzureResourceManager.Authenticated authenticated, String prefix, int maxLen) { + public static String randomResourceName(AzureResourceManager.Authenticated authenticated, String prefix, + int maxLen) { return authenticated.roleAssignments().manager().internalContext().randomResourceName(prefix, maxLen); } @@ -345,10 +347,14 @@ public static String randomResourceName(AzureResourceManager.Authenticated authe */ public static void print(ResourceGroup resource) { StringBuilder info = new StringBuilder(); - info.append("Resource Group: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()); + info.append("Resource Group: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()); System.out.println(info.toString()); } @@ -359,13 +365,20 @@ public static void print(ResourceGroup resource) { */ public static void print(Identity resource) { StringBuilder info = new StringBuilder(); - info.append("Resource Group: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tService Principal Id: ").append(resource.principalId()) - .append("\n\tClient Id: ").append(resource.clientId()) - .append("\n\tTenant Id: ").append(resource.tenantId()); + info.append("Resource Group: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tService Principal Id: ") + .append(resource.principalId()) + .append("\n\tClient Id: ") + .append(resource.clientId()) + .append("\n\tTenant Id: ") + .append(resource.tenantId()); System.out.println(info.toString()); } @@ -406,17 +419,12 @@ public static void print(VirtualMachine resource) { } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); - storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); - storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource - .storageProfile() - .osDisk() - .encryptionSettings() - .diskEncryptionKey().secretUrl()); - storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource - .storageProfile() - .osDisk() - .encryptionSettings() - .keyEncryptionKey().keyUrl()); + storageProfile.append("\n\t\t\t\tEnabled: ") + .append(resource.storageProfile().osDisk().encryptionSettings().enabled()); + storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ") + .append(resource.storageProfile().osDisk().encryptionSettings().diskEncryptionKey().secretUrl()); + storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ") + .append(resource.storageProfile().osDisk().encryptionSettings().keyEncryptionKey().keyUrl()); } } @@ -433,7 +441,8 @@ public static void print(VirtualMachine resource) { if (disk.managedDisk() != null) { storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); if (disk.managedDisk().diskEncryptionSet() != null) { - storageProfile.append("\n\t\t\tDiskEncryptionSet Id: ").append(disk.managedDisk().diskEncryptionSet().id()); + storageProfile.append("\n\t\t\tDiskEncryptionSet Id: ") + .append(disk.managedDisk().diskEncryptionSet().id()); } } } else { @@ -453,17 +462,16 @@ public static void print(VirtualMachine resource) { if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); osProfile.append("\n\t\t\t\tProvisionVMAgent: ") - .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); + .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") - .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); - osProfile.append("\n\t\t\t\tTimeZone: ") - .append(resource.osProfile().windowsConfiguration().timeZone()); + .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); + osProfile.append("\n\t\t\t\tTimeZone: ").append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") - .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); + .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } } else { // OSProfile will be null for a VM attached to specialized VHD. @@ -478,21 +486,32 @@ public static void print(VirtualMachine resource) { StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); for (Map.Entry extensionEntry : resource.listExtensions().entrySet()) { VirtualMachineExtension extension = extensionEntry.getValue(); - extensions.append("\n\t\tExtension: ").append(extension.id()) - .append("\n\t\t\tName: ").append(extension.name()) - .append("\n\t\t\tTags: ").append(extension.tags()) - .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) - .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) - .append("\n\t\t\tPublisher: ").append(extension.publisherName()) - .append("\n\t\t\tType: ").append(extension.typeName()) - .append("\n\t\t\tVersion: ").append(extension.versionName()) - .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); + extensions.append("\n\t\tExtension: ") + .append(extension.id()) + .append("\n\t\t\tName: ") + .append(extension.name()) + .append("\n\t\t\tTags: ") + .append(extension.tags()) + .append("\n\t\t\tProvisioningState: ") + .append(extension.provisioningState()) + .append("\n\t\t\tAuto upgrade minor version enabled: ") + .append(extension.autoUpgradeMinorVersionEnabled()) + .append("\n\t\t\tPublisher: ") + .append(extension.publisherName()) + .append("\n\t\t\tType: ") + .append(extension.typeName()) + .append("\n\t\t\tVersion: ") + .append(extension.versionName()) + .append("\n\t\t\tPublic Settings: ") + .append(extension.publicSettingsAsJsonString()); } StringBuilder msi = new StringBuilder().append("\n\tMSI: "); msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); - msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); - msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); + msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:") + .append(resource.systemAssignedManagedServiceIdentityPrincipalId()); + msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:") + .append(resource.systemAssignedManagedServiceIdentityTenantId()); StringBuilder zones = new StringBuilder().append("\n\tZones: "); zones.append(resource.availabilityZones()); @@ -502,25 +521,31 @@ public static void print(VirtualMachine resource) { securityProfile.append("\n\t\t\tSecure Boot enabled: ").append(resource.isSecureBootEnabled()); securityProfile.append("\n\t\t\tvTPM enabled: ").append(resource.isVTpmEnabled()); - System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tHardwareProfile: ") - .append("\n\t\tSize: ").append(resource.size()) - .append("\n\ttimeCreated: ").append(resource.timeCreated()) - .append(storageProfile) - .append(osProfile) - .append(networkProfile) - .append(extensions) - .append(msi) - .append(zones) - .append(securityProfile) - .toString()); + System.out.println(new StringBuilder().append("Virtual Machine: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tHardwareProfile: ") + .append("\n\t\tSize: ") + .append(resource.size()) + .append("\n\ttimeCreated: ") + .append(resource.timeCreated()) + .append(storageProfile) + .append(osProfile) + .append(networkProfile) + .append(extensions) + .append(msi) + .append(zones) + .append(securityProfile) + .toString()); } - /** * Print availability set info. * @@ -528,14 +553,21 @@ public static void print(VirtualMachine resource) { */ public static void print(AvailabilitySet resource) { - System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tFault domain count: ").append(resource.faultDomainCount()) - .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) - .toString()); + System.out.println(new StringBuilder().append("Availability Set: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tFault domain count: ") + .append(resource.faultDomainCount()) + .append("\n\tUpdate domain count: ") + .append(resource.updateDomainCount()) + .toString()); } /** @@ -546,18 +578,27 @@ public static void print(AvailabilitySet resource) { */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); - info.append("Network: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tAddress spaces: ").append(resource.addressSpaces()) - .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); + info.append("Network: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tAddress spaces: ") + .append(resource.addressSpaces()) + .append("\n\tDNS server IPs: ") + .append(resource.dnsServerIPs()); // Output subnets for (Subnet subnet : resource.subnets().values()) { - info.append("\n\tSubnet: ").append(subnet.name()) - .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); + info.append("\n\tSubnet: ") + .append(subnet.name()) + .append("\n\t\tAddress prefix: ") + .append(subnet.addressPrefix()); // Output associated NSG NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); @@ -577,19 +618,24 @@ public static void print(Network resource) { info.append("\n\tServices with access"); for (Map.Entry> service : services.entrySet()) { info.append("\n\t\tService: ") - .append(service.getKey()) - .append(" Regions: " + service.getValue() + ""); + .append(service.getKey()) + .append(" Regions: " + service.getValue() + ""); } } } // Output peerings for (NetworkPeering peering : resource.peerings().list()) { - info.append("\n\tPeering: ").append(peering.name()) - .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) - .append("\n\t\tPeering state: ").append(peering.state()) - .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) - .append("\n\t\tGateway use: ").append(peering.gatewayUse()); + info.append("\n\tPeering: ") + .append(peering.name()) + .append("\n\t\tRemote network ID: ") + .append(peering.remoteNetworkId()) + .append("\n\t\tPeering state: ") + .append(peering.state()) + .append("\n\t\tIs traffic forwarded from remote network allowed? ") + .append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) + .append("\n\t\tGateway use: ") + .append(peering.gatewayUse()); } System.out.println(info.toString()); } @@ -601,30 +647,47 @@ public static void print(Network resource) { */ public static void print(NetworkInterface resource) { StringBuilder info = new StringBuilder(); - info.append("NetworkInterface: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) - .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) - .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) - .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) - .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) - .append("\n\tDNS server IPs: "); + info.append("NetworkInterface: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tInternal DNS name label: ") + .append(resource.internalDnsNameLabel()) + .append("\n\tInternal FQDN: ") + .append(resource.internalFqdn()) + .append("\n\tInternal domain name suffix: ") + .append(resource.internalDomainNameSuffix()) + .append("\n\tNetwork security group: ") + .append(resource.networkSecurityGroupId()) + .append("\n\tApplied DNS servers: ") + .append(resource.appliedDnsServers().toString()) + .append("\n\tDNS server IPs: "); // Output dns servers for (String dnsServerIp : resource.dnsServers()) { info.append("\n\t\t").append(dnsServerIp); } - info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) - .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) - .append("\n\tMAC Address:").append(resource.macAddress()) - .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) - .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) - .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) - .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); + info.append("\n\tIP forwarding enabled? ") + .append(resource.isIPForwardingEnabled()) + .append("\n\tAccelerated networking enabled? ") + .append(resource.isAcceleratedNetworkingEnabled()) + .append("\n\tMAC Address:") + .append(resource.macAddress()) + .append("\n\tPrivate IP:") + .append(resource.primaryPrivateIP()) + .append("\n\tPrivate allocation method:") + .append(resource.primaryPrivateIpAllocationMethod()) + .append("\n\tPrimary virtual network ID: ") + .append(resource.primaryIPConfiguration().networkId()) + .append("\n\tPrimary subnet name:") + .append(resource.primaryIPConfiguration().subnetName()); System.out.println(info.toString()); } @@ -636,23 +699,37 @@ public static void print(NetworkInterface resource) { */ public static void print(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); - info.append("NSG: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()); + info.append("NSG: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()); // Output security rules for (NetworkSecurityRule rule : resource.securityRules().values()) { - info.append("\n\tRule: ").append(rule.name()) - .append("\n\t\tAccess: ").append(rule.access()) - .append("\n\t\tDirection: ").append(rule.direction()) - .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) - .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) - .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) - .append("\n\t\tTo port: ").append(rule.destinationPortRange()) - .append("\n\t\tProtocol: ").append(rule.protocol()) - .append("\n\t\tPriority: ").append(rule.priority()); + info.append("\n\tRule: ") + .append(rule.name()) + .append("\n\t\tAccess: ") + .append(rule.access()) + .append("\n\t\tDirection: ") + .append(rule.direction()) + .append("\n\t\tFrom address: ") + .append(rule.sourceAddressPrefix()) + .append("\n\t\tFrom port range: ") + .append(rule.sourcePortRange()) + .append("\n\t\tTo address: ") + .append(rule.destinationAddressPrefix()) + .append("\n\t\tTo port: ") + .append(rule.destinationPortRange()) + .append("\n\t\tProtocol: ") + .append(rule.protocol()) + .append("\n\t\tPriority: ") + .append(rule.priority()); } System.out.println(info.toString()); @@ -664,19 +741,31 @@ public static void print(NetworkSecurityGroup resource) { * @param resource a public IP address */ public static void print(PublicIpAddress resource) { - System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tIP Address: ").append(resource.ipAddress()) - .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) - .append("\n\tFQDN: ").append(resource.fqdn()) - .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) - .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) - .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) - .append("\n\tZones: ").append(resource.availabilityZones()) - .toString()); + System.out.println(new StringBuilder().append("Public IP Address: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tIP Address: ") + .append(resource.ipAddress()) + .append("\n\tLeaf domain label: ") + .append(resource.leafDomainLabel()) + .append("\n\tFQDN: ") + .append(resource.fqdn()) + .append("\n\tReverse FQDN: ") + .append(resource.reverseFqdn()) + .append("\n\tIdle timeout (minutes): ") + .append(resource.idleTimeoutInMinutes()) + .append("\n\tIP allocation method: ") + .append(resource.ipAllocationMethod()) + .append("\n\tZones: ") + .append(resource.availabilityZones()) + .toString()); } /** @@ -685,24 +774,47 @@ public static void print(PublicIpAddress resource) { * @param vault the key vault resource */ public static void print(Vault vault) { - StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) - .append("Name: ").append(vault.name()) - .append("\n\tResource group: ").append(vault.resourceGroupName()) - .append("\n\tRegion: ").append(vault.region()) - .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) - .append("\n\tVault URI: ").append(vault.vaultUri()) - .append("\n\tAccess policies: "); + StringBuilder info = new StringBuilder().append("Key Vault: ") + .append(vault.id()) + .append("Name: ") + .append(vault.name()) + .append("\n\tResource group: ") + .append(vault.resourceGroupName()) + .append("\n\tRegion: ") + .append(vault.region()) + .append("\n\tSku: ") + .append(vault.sku().name()) + .append(" - ") + .append(vault.sku().family()) + .append("\n\tVault URI: ") + .append(vault.vaultUri()) + .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); if (accessPolicy.permissions() != null) { if (accessPolicy.permissions().keys() != null) { - info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); + info.append("\n\t\tKey permissions: ") + .append(accessPolicy.permissions() + .keys() + .stream() + .map(KeyPermissions::toString) + .collect(Collectors.joining(", "))); } if (accessPolicy.permissions().secrets() != null) { - info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); + info.append("\n\t\tSecret permissions: ") + .append(accessPolicy.permissions() + .secrets() + .stream() + .map(SecretPermissions::toString) + .collect(Collectors.joining(", "))); } if (accessPolicy.permissions().certificates() != null) { - info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); + info.append("\n\t\tCertificate permissions: ") + .append(accessPolicy.permissions() + .certificates() + .stream() + .map(CertificatePermissions::toString) + .collect(Collectors.joining(", "))); } } } @@ -715,21 +827,30 @@ public static void print(Vault vault) { * @param storageAccount a storage account */ public static void print(StorageAccount storageAccount) { - System.out.println(storageAccount.name() - + " created @ " + storageAccount.creationTime()); - - StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) - .append("Name: ").append(storageAccount.name()) - .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) - .append("\n\tRegion: ").append(storageAccount.region()) - .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) - .append("\n\tAccessTier: ").append(storageAccount.accessTier()) - .append("\n\tKind: ").append(storageAccount.kind()); + System.out.println(storageAccount.name() + " created @ " + storageAccount.creationTime()); + + StringBuilder info = new StringBuilder().append("Storage Account: ") + .append(storageAccount.id()) + .append("Name: ") + .append(storageAccount.name()) + .append("\n\tResource group: ") + .append(storageAccount.resourceGroupName()) + .append("\n\tRegion: ") + .append(storageAccount.region()) + .append("\n\tSKU: ") + .append(storageAccount.skuType().name().toString()) + .append("\n\tAccessTier: ") + .append(storageAccount.accessTier()) + .append("\n\tKind: ") + .append(storageAccount.kind()); info.append("\n\tNetwork Rule Configuration: ") - .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) - .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) - .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); + .append("\n\t\tAllow reading logs from any network: ") + .append(storageAccount.canReadLogEntriesFromAnyNetwork()) + .append("\n\t\tAllow reading metrics from any network: ") + .append(storageAccount.canReadMetricsFromAnyNetwork()) + .append("\n\t\tAllow access from all azure services: ") + .append(storageAccount.canAccessFromAzureServices()); if (storageAccount.networkSubnetsWithAccess().size() > 0) { info.append("\n\t\tNetwork subnets with access: "); @@ -749,12 +870,18 @@ public static void print(StorageAccount storageAccount) { info.append("\n\t\t\t").append(ipAddressRange); } } - info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); + info.append("\n\t\tTraffic allowed from only HTTPS: ") + .append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); - info.append("\n\t\tInfrastructure Encryption: ").append(storageAccount.infrastructureEncryptionEnabled() ? "Enabled" : "Disabled"); - for (Map.Entry eStatus : storageAccount.encryptionStatuses().entrySet()) { - info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); + info.append("\n\t\tInfrastructure Encryption: ") + .append(storageAccount.infrastructureEncryptionEnabled() ? "Enabled" : "Disabled"); + for (Map.Entry eStatus : storageAccount.encryptionStatuses() + .entrySet()) { + info.append("\n\t\t") + .append(eStatus.getValue().storageService()) + .append(": ") + .append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); } System.out.println(info.toString()); @@ -768,32 +895,40 @@ public static void print(StorageAccount storageAccount) { public static void print(List storageAccountKeys) { for (int i = 0; i < storageAccountKeys.size(); i++) { StorageAccountKey storageAccountKey = storageAccountKeys.get(i); - System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" - + storageAccountKey.value()); + System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" + storageAccountKey.value()); } } - /** * Print Redis Cache. * * @param redisCache a Redis cache. */ public static void print(RedisCache redisCache) { - StringBuilder redisInfo = new StringBuilder() - .append("Redis Cache Name: ").append(redisCache.name()) - .append("\n\tResource group: ").append(redisCache.resourceGroupName()) - .append("\n\tRegion: ").append(redisCache.region()) - .append("\n\tSKU Name: ").append(redisCache.sku().name()) - .append("\n\tSKU Family: ").append(redisCache.sku().family()) - .append("\n\tHostname: ").append(redisCache.hostname()) - .append("\n\tSSL port: ").append(redisCache.sslPort()) - .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); + StringBuilder redisInfo = new StringBuilder().append("Redis Cache Name: ") + .append(redisCache.name()) + .append("\n\tResource group: ") + .append(redisCache.resourceGroupName()) + .append("\n\tRegion: ") + .append(redisCache.region()) + .append("\n\tSKU Name: ") + .append(redisCache.sku().name()) + .append("\n\tSKU Family: ") + .append(redisCache.sku().family()) + .append("\n\tHostname: ") + .append(redisCache.hostname()) + .append("\n\tSSL port: ") + .append(redisCache.sslPort()) + .append("\n\tNon-SSL port (6379) enabled: ") + .append(redisCache.nonSslPort()); if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { redisInfo.append("\n\tRedis Configuration:"); for (Map.Entry redisConfiguration : redisCache.redisConfiguration().entrySet()) { - redisInfo.append("\n\t '").append(redisConfiguration.getKey()) - .append("' : '").append(redisConfiguration.getValue()).append("'"); + redisInfo.append("\n\t '") + .append(redisConfiguration.getKey()) + .append("' : '") + .append(redisConfiguration.getValue()) + .append("'"); } } if (redisCache.isPremium()) { @@ -802,10 +937,13 @@ public static void print(RedisCache redisCache) { if (scheduleEntries != null && !scheduleEntries.isEmpty()) { redisInfo.append("\n\tRedis Patch Schedule:"); for (ScheduleEntry schedule : scheduleEntries) { - redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) - .append("', start at: '").append(schedule.startHourUtc()) - .append("', maintenance window: '").append(schedule.maintenanceWindow()) - .append("'"); + redisInfo.append("\n\t\tDay: '") + .append(schedule.dayOfWeek()) + .append("', start at: '") + .append(schedule.startHourUtc()) + .append("', maintenance window: '") + .append(schedule.maintenanceWindow()) + .append("'"); } } } @@ -819,10 +957,13 @@ public static void print(RedisCache redisCache) { * @param redisAccessKeys a keys for Redis Cache */ public static void print(RedisAccessKeys redisAccessKeys) { - StringBuilder redisKeys = new StringBuilder() - .append("Redis Access Keys: ") - .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") - .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); + StringBuilder redisKeys = new StringBuilder().append("Redis Access Keys: ") + .append("\n\tPrimary Key: '") + .append(redisAccessKeys.primaryKey()) + .append("', ") + .append("\n\tSecondary Key: '") + .append(redisAccessKeys.secondaryKey()) + .append("', "); System.out.println(redisKeys.toString()); } @@ -834,9 +975,12 @@ public static void print(RedisAccessKeys redisAccessKeys) { */ public static void print(ManagementLock lock) { StringBuilder info = new StringBuilder(); - info.append("\nLock ID: ").append(lock.id()) - .append("\nLocked resource ID: ").append(lock.lockedResourceId()) - .append("\nLevel: ").append(lock.level()); + info.append("\nLock ID: ") + .append(lock.id()) + .append("\nLocked resource ID: ") + .append(lock.lockedResourceId()) + .append("\nLevel: ") + .append(lock.level()); System.out.println(info.toString()); } @@ -847,82 +991,99 @@ public static void print(ManagementLock lock) { */ public static void print(LoadBalancer resource) { StringBuilder info = new StringBuilder(); - info.append("Load balancer: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tBackends: ").append(resource.backends().keySet().toString()); + info.append("Load balancer: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tBackends: ") + .append(resource.backends().keySet().toString()); // Show public IP addresses - info.append("\n\tPublic IP address IDs: ") - .append(resource.publicIpAddressIds().size()); + info.append("\n\tPublic IP address IDs: ").append(resource.publicIpAddressIds().size()); for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } // Show TCP probes - info.append("\n\tTCP probes: ") - .append(resource.tcpProbes().size()); + info.append("\n\tTCP probes: ").append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { - info.append("\n\t\tProbe name: ").append(probe.name()) - .append("\n\t\t\tPort: ").append(probe.port()) - .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) - .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); + info.append("\n\t\tProbe name: ") + .append(probe.name()) + .append("\n\t\t\tPort: ") + .append(probe.port()) + .append("\n\t\t\tInterval in seconds: ") + .append(probe.intervalInSeconds()) + .append("\n\t\t\tRetries before unhealthy: ") + .append(probe.numberOfProbes()); // Show associated load balancing rules - info.append("\n\t\t\tReferenced from load balancing rules: ") - .append(probe.loadBalancingRules().size()); + info.append("\n\t\t\tReferenced from load balancing rules: ").append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } // Show HTTP probes - info.append("\n\tHTTP probes: ") - .append(resource.httpProbes().size()); + info.append("\n\tHTTP probes: ").append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { - info.append("\n\t\tProbe name: ").append(probe.name()) - .append("\n\t\t\tPort: ").append(probe.port()) - .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) - .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) - .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); + info.append("\n\t\tProbe name: ") + .append(probe.name()) + .append("\n\t\t\tPort: ") + .append(probe.port()) + .append("\n\t\t\tInterval in seconds: ") + .append(probe.intervalInSeconds()) + .append("\n\t\t\tRetries before unhealthy: ") + .append(probe.numberOfProbes()) + .append("\n\t\t\tHTTP request path: ") + .append(probe.requestPath()); // Show associated load balancing rules - info.append("\n\t\t\tReferenced from load balancing rules: ") - .append(probe.loadBalancingRules().size()); + info.append("\n\t\t\tReferenced from load balancing rules: ").append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } // Show HTTPS probes - info.append("\n\tHTTPS probes: ") - .append(resource.httpsProbes().size()); + info.append("\n\tHTTPS probes: ").append(resource.httpsProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { - info.append("\n\t\tProbe name: ").append(probe.name()) - .append("\n\t\t\tPort: ").append(probe.port()) - .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) - .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) - .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); + info.append("\n\t\tProbe name: ") + .append(probe.name()) + .append("\n\t\t\tPort: ") + .append(probe.port()) + .append("\n\t\t\tInterval in seconds: ") + .append(probe.intervalInSeconds()) + .append("\n\t\t\tRetries before unhealthy: ") + .append(probe.numberOfProbes()) + .append("\n\t\t\tHTTPS request path: ") + .append(probe.requestPath()); // Show associated load balancing rules - info.append("\n\t\t\tReferenced from load balancing rules: ") - .append(probe.loadBalancingRules().size()); + info.append("\n\t\t\tReferenced from load balancing rules: ").append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } // Show load balancing rules - info.append("\n\tLoad balancing rules: ") - .append(resource.loadBalancingRules().size()); + info.append("\n\tLoad balancing rules: ").append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { - info.append("\n\t\tLB rule name: ").append(rule.name()) - .append("\n\t\t\tProtocol: ").append(rule.protocol()) - .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) - .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) - .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); + info.append("\n\t\tLB rule name: ") + .append(rule.name()) + .append("\n\t\t\tProtocol: ") + .append(rule.protocol()) + .append("\n\t\t\tFloating IP enabled? ") + .append(rule.floatingIPEnabled()) + .append("\n\t\t\tIdle timeout in minutes: ") + .append(rule.idleTimeoutInMinutes()) + .append("\n\t\t\tLoad distribution method: ") + .append(rule.loadDistribution().toString()); LoadBalancerFrontend frontend = rule.frontend(); info.append("\n\t\t\tFrontend: "); @@ -954,154 +1115,167 @@ public static void print(LoadBalancer resource) { } // Show frontends - info.append("\n\tFrontends: ") - .append(resource.frontends().size()); + info.append("\n\tFrontends: ").append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { - info.append("\n\t\tFrontend name: ").append(frontend.name()) - .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); + info.append("\n\t\tFrontend name: ") + .append(frontend.name()) + .append("\n\t\t\tInternet facing: ") + .append(frontend.isPublic()); if (frontend.isPublic()) { - info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); + info.append("\n\t\t\tPublic IP Address ID: ") + .append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { - info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) - .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) - .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) - .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); + info.append("\n\t\t\tVirtual network ID: ") + .append(((LoadBalancerPrivateFrontend) frontend).networkId()) + .append("\n\t\t\tSubnet name: ") + .append(((LoadBalancerPrivateFrontend) frontend).subnetName()) + .append("\n\t\t\tPrivate IP address: ") + .append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) + .append("\n\t\t\tPrivate IP allocation method: ") + .append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } // Inbound NAT pool references - info.append("\n\t\t\tReferenced inbound NAT pools: ") - .append(frontend.inboundNatPools().size()); + info.append("\n\t\t\tReferenced inbound NAT pools: ").append(frontend.inboundNatPools().size()); for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { info.append("\n\t\t\t\tName: ").append(pool.name()); } // Inbound NAT rule references - info.append("\n\t\t\tReferenced inbound NAT rules: ") - .append(frontend.inboundNatRules().size()); + info.append("\n\t\t\tReferenced inbound NAT rules: ").append(frontend.inboundNatRules().size()); for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } // Load balancing rule references - info.append("\n\t\t\tReferenced load balancing rules: ") - .append(frontend.loadBalancingRules().size()); + info.append("\n\t\t\tReferenced load balancing rules: ").append(frontend.loadBalancingRules().size()); for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } // Show inbound NAT rules - info.append("\n\tInbound NAT rules: ") - .append(resource.inboundNatRules().size()); + info.append("\n\tInbound NAT rules: ").append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { - info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) - .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) - .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) - .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) - .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) - .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) - .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) - .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) - .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); + info.append("\n\t\tInbound NAT rule name: ") + .append(natRule.name()) + .append("\n\t\t\tProtocol: ") + .append(natRule.protocol().toString()) + .append("\n\t\t\tFrontend: ") + .append(natRule.frontend().name()) + .append("\n\t\t\tFrontend port: ") + .append(natRule.frontendPort()) + .append("\n\t\t\tBackend port: ") + .append(natRule.backendPort()) + .append("\n\t\t\tBackend NIC ID: ") + .append(natRule.backendNetworkInterfaceId()) + .append("\n\t\t\tBackend NIC IP config name: ") + .append(natRule.backendNicIpConfigurationName()) + .append("\n\t\t\tFloating IP? ") + .append(natRule.floatingIPEnabled()) + .append("\n\t\t\tIdle timeout in minutes: ") + .append(natRule.idleTimeoutInMinutes()); } // Show inbound NAT pools - info.append("\n\tInbound NAT pools: ") - .append(resource.inboundNatPools().size()); + info.append("\n\tInbound NAT pools: ").append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { - info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) - .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) - .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) - .append("\n\t\t\tFrontend port range: ") - .append(natPool.frontendPortRangeStart()) - .append("-") - .append(natPool.frontendPortRangeEnd()) - .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); + info.append("\n\t\tInbound NAT pool name: ") + .append(natPool.name()) + .append("\n\t\t\tProtocol: ") + .append(natPool.protocol().toString()) + .append("\n\t\t\tFrontend: ") + .append(natPool.frontend().name()) + .append("\n\t\t\tFrontend port range: ") + .append(natPool.frontendPortRangeStart()) + .append("-") + .append(natPool.frontendPortRangeEnd()) + .append("\n\t\t\tBackend port: ") + .append(natPool.backendPort()); } // Show backends - info.append("\n\tBackends: ") - .append(resource.backends().size()); + info.append("\n\tBackends: ").append(resource.backends().size()); for (LoadBalancerBackend backend : resource.backends().values()) { info.append("\n\t\tBackend name: ").append(backend.name()); // Show assigned backend NICs - info.append("\n\t\t\tReferenced NICs: ") - .append(backend.backendNicIPConfigurationNames().entrySet().size()); + info.append("\n\t\t\tReferenced NICs: ").append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Map.Entry entry : backend.backendNicIPConfigurationNames().entrySet()) { - info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) - .append(" - IP Config: ").append(entry.getValue()); + info.append("\n\t\t\t\tNIC ID: ") + .append(entry.getKey()) + .append(" - IP Config: ") + .append(entry.getValue()); } // Show assigned virtual machines Set vmIds = backend.getVirtualMachineIds(); - info.append("\n\t\t\tReferenced virtual machine ids: ") - .append(vmIds.size()); + info.append("\n\t\t\tReferenced virtual machine ids: ").append(vmIds.size()); for (String vmId : vmIds) { info.append("\n\t\t\t\tVM ID: ").append(vmId); } // Show assigned load balancing rules info.append("\n\t\t\tReferenced load balancing rules: ") - .append(new ArrayList(backend.loadBalancingRules().keySet())); + .append(new ArrayList(backend.loadBalancingRules().keySet())); } System.out.println(info.toString()); } -// -// /** -// * Prints batch account keys. -// * -// * @param batchAccountKeys a list of batch account keys -// */ -// public static void print(BatchAccountKeys batchAccountKeys) { -// System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" -// + batchAccountKeys.secondary() + ")"); -// } - -// /** -// * Prints batch account. -// * -// * @param batchAccount a Batch Account -// */ -// public static void print(BatchAccount batchAccount) { -// StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); -// -// if (batchAccount.applications().size() > 0) { -// for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { -// Application application = applicationEntry.getValue(); -// StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); -// -// for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { -// ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); -// StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); -// singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); -// -// applicationPackages.append(singleApplicationPackage); -// singleApplicationPackage.append("\n"); -// } -// -// StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); -// singleApplication.append("\n\t\tdisplayName: " + application.displayName()); -// singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); -// singleApplication.append(applicationPackages); -// applicationsOutput.append(singleApplication); -// applicationsOutput.append("\n"); -// } -// } -// -// System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) -// .append("Name: ").append(batchAccount.name()) -// .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) -// .append("\n\tRegion: ").append(batchAccount.region()) -// .append("\n\tTags: ").append(batchAccount.tags()) -// .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) -// .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) -// .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) -// .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) -// .append(applicationsOutput) -// .toString()); -// } + // + // /** + // * Prints batch account keys. + // * + // * @param batchAccountKeys a list of batch account keys + // */ + // public static void print(BatchAccountKeys batchAccountKeys) { + // System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" + // + batchAccountKeys.secondary() + ")"); + // } + + // /** + // * Prints batch account. + // * + // * @param batchAccount a Batch Account + // */ + // public static void print(BatchAccount batchAccount) { + // StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); + // + // if (batchAccount.applications().size() > 0) { + // for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { + // Application application = applicationEntry.getValue(); + // StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); + // + // for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { + // ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); + // StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); + // singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); + // + // applicationPackages.append(singleApplicationPackage); + // singleApplicationPackage.append("\n"); + // } + // + // StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); + // singleApplication.append("\n\t\tdisplayName: " + application.displayName()); + // singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); + // singleApplication.append(applicationPackages); + // applicationsOutput.append(singleApplication); + // applicationsOutput.append("\n"); + // } + // } + // + // System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) + // .append("Name: ").append(batchAccount.name()) + // .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) + // .append("\n\tRegion: ").append(batchAccount.region()) + // .append("\n\tTags: ").append(batchAccount.tags()) + // .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) + // .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) + // .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) + // .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) + // .append(applicationsOutput) + // .toString()); + // } /** * Print app service domain. @@ -1109,13 +1283,19 @@ public static void print(LoadBalancer resource) { * @param resource an app service domain */ public static void print(AppServiceDomain resource) { - StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tCreated time: ").append(resource.createdTime()) - .append("\n\tExpiration time: ").append(resource.expirationTime()) - .append("\n\tContact: "); + StringBuilder builder = new StringBuilder().append("Domain: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tCreated time: ") + .append(resource.createdTime()) + .append("\n\tExpiration time: ") + .append(resource.expirationTime()) + .append("\n\tContact: "); Contact contact = resource.registrantContact(); if (contact == null) { builder = builder.append("Private"); @@ -1135,16 +1315,26 @@ public static void print(AppServiceDomain resource) { * @param resource an app service certificate order */ public static void print(AppServiceCertificateOrder resource) { - StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tDistinguished name: ").append(resource.distinguishedName()) - .append("\n\tProduct type: ").append(resource.productType()) - .append("\n\tValid years: ").append(resource.validityInYears()) - .append("\n\tStatus: ").append(resource.status()) - .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) - .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); + StringBuilder builder = new StringBuilder().append("App service certificate order: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tDistinguished name: ") + .append(resource.distinguishedName()) + .append("\n\tProduct type: ") + .append(resource.productType()) + .append("\n\tValid years: ") + .append(resource.validityInYears()) + .append("\n\tStatus: ") + .append(resource.status()) + .append("\n\tIssuance time: ") + .append(resource.lastCertificateIssuanceTime()) + .append("\n\tSigned certificate: ") + .append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); System.out.println(builder.toString()); } @@ -1154,11 +1344,16 @@ public static void print(AppServiceCertificateOrder resource) { * @param resource an app service plan */ public static void print(AppServicePlan resource) { - StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tPricing tier: ").append(resource.pricingTier()); + StringBuilder builder = new StringBuilder().append("App service certificate order: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tPricing tier: ") + .append(resource.pricingTier()); System.out.println(builder.toString()); } @@ -1168,14 +1363,21 @@ public static void print(AppServicePlan resource) { * @param resource a web app */ public static void print(WebAppBase resource) { - StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tState: ").append(resource.state()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tDefault hostname: ").append(resource.defaultHostname()) - .append("\n\tApp service plan: ").append(resource.appServicePlanId()) - .append("\n\tHost name bindings: "); + StringBuilder builder = new StringBuilder().append("Web app: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tState: ") + .append(resource.state()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tDefault hostname: ") + .append(resource.defaultHostname()) + .append("\n\tApp service plan: ") + .append(resource.appServicePlanId()) + .append("\n\tHost name bindings: "); for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } @@ -1188,11 +1390,13 @@ public static void print(WebAppBase resource) { } builder = builder.append("\n\tApp settings: "); for (AppSetting setting : resource.getAppSettings().values()) { - builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); + builder = builder.append( + "\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); } builder = builder.append("\n\tConnection strings: "); for (ConnectionString conn : resource.getConnectionStrings().values()) { - builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); + builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + + (conn.sticky() ? " - slot setting" : "")); } System.out.println(builder.toString()); } @@ -1203,13 +1407,20 @@ public static void print(WebAppBase resource) { * @param resource a web site */ public static void print(WebSiteBase resource) { - StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tState: ").append(resource.state()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tDefault hostname: ").append(resource.defaultHostname()) - .append("\n\tApp service plan: ").append(resource.appServicePlanId()); + StringBuilder builder = new StringBuilder().append("Web app: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tState: ") + .append(resource.state()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tDefault hostname: ") + .append(resource.defaultHostname()) + .append("\n\tApp service plan: ") + .append(resource.appServicePlanId()); builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); @@ -1227,34 +1438,56 @@ public static void print(WebSiteBase resource) { */ public static void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); - info.append("Traffic Manager Profile: ").append(profile.id()) - .append("\n\tName: ").append(profile.name()) - .append("\n\tResource group: ").append(profile.resourceGroupName()) - .append("\n\tRegion: ").append(profile.regionName()) - .append("\n\tTags: ").append(profile.tags()) - .append("\n\tDNSLabel: ").append(profile.dnsLabel()) - .append("\n\tFQDN: ").append(profile.fqdn()) - .append("\n\tTTL: ").append(profile.timeToLive()) - .append("\n\tEnabled: ").append(profile.isEnabled()) - .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) - .append("\n\tMonitor status: ").append(profile.monitorStatus()) - .append("\n\tMonitoring port: ").append(profile.monitoringPort()) - .append("\n\tMonitoring path: ").append(profile.monitoringPath()); + info.append("Traffic Manager Profile: ") + .append(profile.id()) + .append("\n\tName: ") + .append(profile.name()) + .append("\n\tResource group: ") + .append(profile.resourceGroupName()) + .append("\n\tRegion: ") + .append(profile.regionName()) + .append("\n\tTags: ") + .append(profile.tags()) + .append("\n\tDNSLabel: ") + .append(profile.dnsLabel()) + .append("\n\tFQDN: ") + .append(profile.fqdn()) + .append("\n\tTTL: ") + .append(profile.timeToLive()) + .append("\n\tEnabled: ") + .append(profile.isEnabled()) + .append("\n\tRoutingMethod: ") + .append(profile.trafficRoutingMethod()) + .append("\n\tMonitor status: ") + .append(profile.monitorStatus()) + .append("\n\tMonitoring port: ") + .append(profile.monitoringPort()) + .append("\n\tMonitoring path: ") + .append(profile.monitoringPath()); Map azureEndpoints = profile.azureEndpoints(); if (!azureEndpoints.isEmpty()) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { - info.append("\n\t\tAzure endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) - .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); + info.append("\n\t\tAzure endpoint: #") + .append(idx++) + .append("\n\t\t\tId: ") + .append(endpoint.id()) + .append("\n\t\t\tType: ") + .append(endpoint.endpointType()) + .append("\n\t\t\tTarget resourceId: ") + .append(endpoint.targetAzureResourceId()) + .append("\n\t\t\tTarget resourceType: ") + .append(endpoint.targetResourceType()) + .append("\n\t\t\tMonitor status: ") + .append(endpoint.monitorStatus()) + .append("\n\t\t\tEnabled: ") + .append(endpoint.isEnabled()) + .append("\n\t\t\tRouting priority: ") + .append(endpoint.routingPriority()) + .append("\n\t\t\tRouting weight: ") + .append(endpoint.routingWeight()); } } @@ -1263,15 +1496,24 @@ public static void print(TrafficManagerProfile profile) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { - info.append("\n\t\tExternal endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) - .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); + info.append("\n\t\tExternal endpoint: #") + .append(idx++) + .append("\n\t\t\tId: ") + .append(endpoint.id()) + .append("\n\t\t\tType: ") + .append(endpoint.endpointType()) + .append("\n\t\t\tFQDN: ") + .append(endpoint.fqdn()) + .append("\n\t\t\tSource Traffic Location: ") + .append(endpoint.sourceTrafficLocation()) + .append("\n\t\t\tMonitor status: ") + .append(endpoint.monitorStatus()) + .append("\n\t\t\tEnabled: ") + .append(endpoint.isEnabled()) + .append("\n\t\t\tRouting priority: ") + .append(endpoint.routingPriority()) + .append("\n\t\t\tRouting weight: ") + .append(endpoint.routingWeight()); } } @@ -1280,16 +1522,26 @@ public static void print(TrafficManagerProfile profile) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { - info.append("\n\t\tNested profile endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) - .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) - .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); + info.append("\n\t\tNested profile endpoint: #") + .append(idx++) + .append("\n\t\t\tId: ") + .append(endpoint.id()) + .append("\n\t\t\tType: ") + .append(endpoint.endpointType()) + .append("\n\t\t\tNested profileId: ") + .append(endpoint.nestedProfileId()) + .append("\n\t\t\tMinimum child threshold: ") + .append(endpoint.minimumChildEndpointCount()) + .append("\n\t\t\tSource Traffic Location: ") + .append(endpoint.sourceTrafficLocation()) + .append("\n\t\t\tMonitor status: ") + .append(endpoint.monitorStatus()) + .append("\n\t\t\tEnabled: ") + .append(endpoint.isEnabled()) + .append("\n\t\t\tRouting priority: ") + .append(endpoint.routingPriority()) + .append("\n\t\t\tRouting weight: ") + .append(endpoint.routingWeight()); } } System.out.println(info.toString()); @@ -1302,33 +1554,48 @@ public static void print(TrafficManagerProfile profile) { */ public static void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); - info.append("DNS Zone: ").append(dnsZone.id()) - .append("\n\tName (Top level domain): ").append(dnsZone.name()) - .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) - .append("\n\tRegion: ").append(dnsZone.regionName()) - .append("\n\tTags: ").append(dnsZone.tags()) - .append("\n\tName servers:"); + info.append("DNS Zone: ") + .append(dnsZone.id()) + .append("\n\tName (Top level domain): ") + .append(dnsZone.name()) + .append("\n\tResource group: ") + .append(dnsZone.resourceGroupName()) + .append("\n\tRegion: ") + .append(dnsZone.regionName()) + .append("\n\tTags: ") + .append(dnsZone.tags()) + .append("\n\tName servers:"); for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") - .append("\n\t\tHost:").append(soaRecord.host()) - .append("\n\t\tEmail:").append(soaRecord.email()) - .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) - .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) - .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) - .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) - .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); + .append("\n\t\tHost:") + .append(soaRecord.host()) + .append("\n\t\tEmail:") + .append(soaRecord.email()) + .append("\n\t\tExpire time (seconds):") + .append(soaRecord.expireTime()) + .append("\n\t\tRefresh time (seconds):") + .append(soaRecord.refreshTime()) + .append("\n\t\tRetry time (seconds):") + .append(soaRecord.retryTime()) + .append("\n\t\tNegative response cache ttl (seconds):") + .append(soaRecord.minimumTtl()) + .append("\n\t\tTTL (seconds):") + .append(soaRecordSet.timeToLive()); PagedIterable aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { - info.append("\n\t\tId: ").append(aRecordSet.id()) - .append("\n\t\tName: ").append(aRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) - .append("\n\t\tIP v4 addresses: "); + info.append("\n\t\tId: ") + .append(aRecordSet.id()) + .append("\n\t\tName: ") + .append(aRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aRecordSet.timeToLive()) + .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } @@ -1337,10 +1604,13 @@ public static void print(DnsZone dnsZone) { PagedIterable aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { - info.append("\n\t\tId: ").append(aaaaRecordSet.id()) - .append("\n\t\tName: ").append(aaaaRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) - .append("\n\t\tIP v6 addresses: "); + info.append("\n\t\tId: ") + .append(aaaaRecordSet.id()) + .append("\n\t\tName: ") + .append(aaaaRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aaaaRecordSet.timeToLive()) + .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } @@ -1349,34 +1619,44 @@ public static void print(DnsZone dnsZone) { PagedIterable cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { - info.append("\n\t\tId: ").append(cnameRecordSet.id()) - .append("\n\t\tName: ").append(cnameRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) - .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); + info.append("\n\t\tId: ") + .append(cnameRecordSet.id()) + .append("\n\t\tName: ") + .append(cnameRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(cnameRecordSet.timeToLive()) + .append("\n\t\tCanonical name: ") + .append(cnameRecordSet.canonicalName()); } PagedIterable mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { - info.append("\n\t\tId: ").append(mxRecordSet.id()) - .append("\n\t\tName: ").append(mxRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(mxRecordSet.id()) + .append("\n\t\tName: ") + .append(mxRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(mxRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") - .append(mxRecord.exchange()) - .append(" ") - .append(mxRecord.preference()); + .append(mxRecord.exchange()) + .append(" ") + .append(mxRecord.preference()); } } PagedIterable nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { - info.append("\n\t\tId: ").append(nsRecordSet.id()) - .append("\n\t\tName: ").append(nsRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) - .append("\n\t\tName servers: "); + info.append("\n\t\tId: ") + .append(nsRecordSet.id()) + .append("\n\t\tName: ") + .append(nsRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(nsRecordSet.timeToLive()) + .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } @@ -1385,10 +1665,13 @@ public static void print(DnsZone dnsZone) { PagedIterable ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { - info.append("\n\t\tId: ").append(ptrRecordSet.id()) - .append("\n\t\tName: ").append(ptrRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) - .append("\n\t\tTarget domain names: "); + info.append("\n\t\tId: ") + .append(ptrRecordSet.id()) + .append("\n\t\tName: ") + .append(ptrRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(ptrRecordSet.timeToLive()) + .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } @@ -1397,29 +1680,35 @@ public static void print(DnsZone dnsZone) { PagedIterable srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { - info.append("\n\t\tId: ").append(srvRecordSet.id()) - .append("\n\t\tName: ").append(srvRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(srvRecordSet.id()) + .append("\n\t\tName: ") + .append(srvRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(srvRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") - .append(srvRecord.target()) - .append(", ") - .append(srvRecord.port()) - .append(", ") - .append(srvRecord.priority()) - .append(", ") - .append(srvRecord.weight()); + .append(srvRecord.target()) + .append(", ") + .append(srvRecord.port()) + .append(", ") + .append(srvRecord.priority()) + .append(", ") + .append(srvRecord.weight()); } } PagedIterable txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { - info.append("\n\t\tId: ").append(txtRecordSet.id()) - .append("\n\t\tName: ").append(txtRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(txtRecordSet.id()) + .append("\n\t\tName: ") + .append(txtRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(txtRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); @@ -1436,64 +1725,91 @@ public static void print(DnsZone dnsZone) { */ public static void print(PrivateDnsZone privateDnsZone) { StringBuilder info = new StringBuilder(); - info.append("Private DNS Zone: ").append(privateDnsZone.id()) - .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) - .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) - .append("\n\tRegion: ").append(privateDnsZone.regionName()) - .append("\n\tTags: ").append(privateDnsZone.tags()) + info.append("Private DNS Zone: ") + .append(privateDnsZone.id()) + .append("\n\tName (Top level domain): ") + .append(privateDnsZone.name()) + .append("\n\tResource group: ") + .append(privateDnsZone.resourceGroupName()) + .append("\n\tRegion: ") + .append(privateDnsZone.regionName()) + .append("\n\tTags: ") + .append(privateDnsZone.tags()) .append("\n\tName servers:"); com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") - .append("\n\t\tHost:").append(soaRecord.host()) - .append("\n\t\tEmail:").append(soaRecord.email()) - .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) - .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) - .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) - .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) - .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); - - PagedIterable aRecordSets = privateDnsZone - .aRecordSets().list(); + .append("\n\t\tHost:") + .append(soaRecord.host()) + .append("\n\t\tEmail:") + .append(soaRecord.email()) + .append("\n\t\tExpire time (seconds):") + .append(soaRecord.expireTime()) + .append("\n\t\tRefresh time (seconds):") + .append(soaRecord.refreshTime()) + .append("\n\t\tRetry time (seconds):") + .append(soaRecord.retryTime()) + .append("\n\t\tNegative response cache ttl (seconds):") + .append(soaRecord.minimumTtl()) + .append("\n\t\tTTL (seconds):") + .append(soaRecordSet.timeToLive()); + + PagedIterable aRecordSets + = privateDnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { - info.append("\n\t\tId: ").append(aRecordSet.id()) - .append("\n\t\tName: ").append(aRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(aRecordSet.id()) + .append("\n\t\tName: ") + .append(aRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } - PagedIterable aaaaRecordSets = privateDnsZone - .aaaaRecordSets().list(); + PagedIterable aaaaRecordSets + = privateDnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { - info.append("\n\t\tId: ").append(aaaaRecordSet.id()) - .append("\n\t\tName: ").append(aaaaRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(aaaaRecordSet.id()) + .append("\n\t\tName: ") + .append(aaaaRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } - PagedIterable cnameRecordSets = privateDnsZone.cnameRecordSets().list(); + PagedIterable cnameRecordSets + = privateDnsZone.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { - info.append("\n\t\tId: ").append(cnameRecordSet.id()) - .append("\n\t\tName: ").append(cnameRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) - .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); - } - - PagedIterable mxRecordSets = privateDnsZone.mxRecordSets().list(); + info.append("\n\t\tId: ") + .append(cnameRecordSet.id()) + .append("\n\t\tName: ") + .append(cnameRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(cnameRecordSet.timeToLive()) + .append("\n\t\tCanonical name: ") + .append(cnameRecordSet.canonicalName()); + } + + PagedIterable mxRecordSets + = privateDnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { - info.append("\n\t\tId: ").append(mxRecordSet.id()) - .append("\n\t\tName: ").append(mxRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(mxRecordSet.id()) + .append("\n\t\tName: ") + .append(mxRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") @@ -1503,26 +1819,32 @@ public static void print(PrivateDnsZone privateDnsZone) { } } - PagedIterable ptrRecordSets = privateDnsZone - .ptrRecordSets().list(); + PagedIterable ptrRecordSets + = privateDnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { - info.append("\n\t\tId: ").append(ptrRecordSet.id()) - .append("\n\t\tName: ").append(ptrRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(ptrRecordSet.id()) + .append("\n\t\tName: ") + .append(ptrRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } - PagedIterable srvRecordSets = privateDnsZone - .srvRecordSets().list(); + PagedIterable srvRecordSets + = privateDnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { - info.append("\n\t\tId: ").append(srvRecordSet.id()) - .append("\n\t\tName: ").append(srvRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(srvRecordSet.id()) + .append("\n\t\tName: ") + .append(srvRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") @@ -1536,13 +1858,16 @@ public static void print(PrivateDnsZone privateDnsZone) { } } - PagedIterable txtRecordSets = privateDnsZone - .txtRecordSets().list(); + PagedIterable txtRecordSets + = privateDnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { - info.append("\n\t\tId: ").append(txtRecordSet.id()) - .append("\n\t\tName: ").append(txtRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(txtRecordSet.id()) + .append("\n\t\tName: ") + .append(txtRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { @@ -1554,10 +1879,14 @@ public static void print(PrivateDnsZone privateDnsZone) { PagedIterable virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); info.append("\n\tVirtual Network Links:"); for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { - info.append("\n\tId: ").append(virtualNetworkLink.id()) - .append("\n\tName: ").append(virtualNetworkLink.name()) - .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) - .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); + info.append("\n\tId: ") + .append(virtualNetworkLink.id()) + .append("\n\tName: ") + .append(virtualNetworkLink.name()) + .append("\n\tReference of Virtual Network: ") + .append(virtualNetworkLink.referencedVirtualNetworkId()) + .append("\n\tRegistration enabled: ") + .append(virtualNetworkLink.isAutoRegistrationEnabled()); } System.out.println(info.toString()); } @@ -1571,12 +1900,18 @@ public static void print(Registry azureRegistry) { StringBuilder info = new StringBuilder(); RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - info.append("Azure Container Registry: ").append(azureRegistry.id()) - .append("\n\tName: ").append(azureRegistry.name()) - .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) - .append("\n\tUser: ").append(acrCredentials.username()) - .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) - .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); + info.append("Azure Container Registry: ") + .append(azureRegistry.id()) + .append("\n\tName: ") + .append(azureRegistry.name()) + .append("\n\tServer Url: ") + .append(azureRegistry.loginServerUrl()) + .append("\n\tUser: ") + .append(acrCredentials.username()) + .append("\n\tFirst Password: ") + .append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .append("\n\tSecond Password: ") + .append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); System.out.println(info.toString()); } @@ -1588,16 +1923,26 @@ public static void print(Registry azureRegistry) { public static void print(KubernetesCluster kubernetesCluster) { StringBuilder info = new StringBuilder(); - info.append("Azure Container Service: ").append(kubernetesCluster.id()) - .append("\n\tName: ").append(kubernetesCluster.name()) - .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) - .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) - .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) - .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) - .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) - .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) - .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) - .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); + info.append("Azure Container Service: ") + .append(kubernetesCluster.id()) + .append("\n\tName: ") + .append(kubernetesCluster.name()) + .append("\n\tFQDN: ") + .append(kubernetesCluster.fqdn()) + .append("\n\tDNS prefix label: ") + .append(kubernetesCluster.dnsPrefix()) + .append("\n\t\tWith Agent pool name: ") + .append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) + .append("\n\t\tAgent pool count: ") + .append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) + .append("\n\t\tAgent pool VM size: ") + .append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) + .append("\n\tLinux user name: ") + .append(kubernetesCluster.linuxRootUsername()) + .append("\n\tSSH key: ") + .append(kubernetesCluster.sshKey()) + .append("\n\tService principal client ID: ") + .append(kubernetesCluster.servicePrincipalClientId()); System.out.println(info.toString()); } @@ -1612,19 +1957,31 @@ public static void print(SearchService searchService) { AdminKeys adminKeys = searchService.getAdminKeys(); PagedIterable queryKeys = searchService.listQueryKeys(); - info.append("Azure Search: ").append(searchService.id()) - .append("\n\tResource group: ").append(searchService.resourceGroupName()) - .append("\n\tRegion: ").append(searchService.region()) - .append("\n\tTags: ").append(searchService.tags()) - .append("\n\tSku: ").append(searchService.sku().name()) - .append("\n\tStatus: ").append(searchService.status()) - .append("\n\tProvisioning State: ").append(searchService.provisioningState()) - .append("\n\tHosting Mode: ").append(searchService.hostingMode()) - .append("\n\tReplicas: ").append(searchService.replicaCount()) - .append("\n\tPartitions: ").append(searchService.partitionCount()) - .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) - .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) - .append("\n\tQuery keys:"); + info.append("Azure Search: ") + .append(searchService.id()) + .append("\n\tResource group: ") + .append(searchService.resourceGroupName()) + .append("\n\tRegion: ") + .append(searchService.region()) + .append("\n\tTags: ") + .append(searchService.tags()) + .append("\n\tSku: ") + .append(searchService.sku().name()) + .append("\n\tStatus: ") + .append(searchService.status()) + .append("\n\tProvisioning State: ") + .append(searchService.provisioningState()) + .append("\n\tHosting Mode: ") + .append(searchService.hostingMode()) + .append("\n\tReplicas: ") + .append(searchService.replicaCount()) + .append("\n\tPartitions: ") + .append(searchService.partitionCount()) + .append("\n\tPrimary Admin Key: ") + .append(adminKeys.primaryKey()) + .append("\n\tSecondary Admin Key: ") + .append(adminKeys.secondaryKey()) + .append("\n\tQuery keys:"); for (QueryKey queryKey : queryKeys) { info.append("\n\t\tKey name: ").append(queryKey.name()); @@ -1641,7 +1998,9 @@ public static void print(SearchService searchService) { * @throws IOException exception */ public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { - String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); + String content + = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8) + .trim(); HashMap auth = new HashMap<>(); if (content.startsWith("{")) { @@ -1664,7 +2023,9 @@ public static String getSecondaryServicePrincipalClientID(String envSecondarySer * @throws IOException exception */ public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { - String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); + String content + = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8) + .trim(); HashMap auth = new HashMap<>(); if (content.startsWith("{")) { @@ -1678,16 +2039,16 @@ public static String getSecondaryServicePrincipalSecret(String envSecondaryServi return authSettings.getProperty("key"); } } -// -// /** -// * Creates and returns a randomized name based on the prefix file for use by the sample. -// * -// * @param namePrefix The prefix string to be used in generating the name. -// * @return a random name -// */ -// public static String createRandomName(String namePrefix) { -// return ResourceManagerUtils.InternalRuntimeContext.randomResourceName(namePrefix, 30); -// } + // + // /** + // * Creates and returns a randomized name based on the prefix file for use by the sample. + // * + // * @param namePrefix The prefix string to be used in generating the name. + // * @return a random name + // */ + // public static String createRandomName(String namePrefix) { + // return ResourceManagerUtils.InternalRuntimeContext.randomResourceName(namePrefix, 30); + // } /** * This method creates a certificate for given password. @@ -1700,8 +2061,8 @@ public static String getSecondaryServicePrincipalSecret(String envSecondaryServi * @param dnsName dns name in subject alternate name * @throws IOException IO Exception */ - public static void createCertificate(String certPath, String pfxPath, String alias, - String password, String cnName, String dnsName) throws IOException { + public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName, + String dnsName) throws IOException { if (new File(pfxPath).exists()) { return; } @@ -1722,10 +2083,29 @@ public static void createCertificate(String certPath, String pfxPath, String ali } // Create Pfx file - String[] commandArgs = {command, "-genkey", "-alias", alias, - "-keystore", pfxPath, "-storepass", password, "-validity", - validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, - "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; + String[] commandArgs = { + command, + "-genkey", + "-alias", + alias, + "-keystore", + pfxPath, + "-storepass", + password, + "-validity", + validityInDays, + "-keyalg", + keyAlg, + "-sigalg", + sigAlg, + "-keysize", + keySize, + "-storetype", + storeType, + "-dname", + "CN=" + cnName, + "-ext", + "EKU=1.3.6.1.5.5.7.3.1" }; if (dnsName != null) { List args = new ArrayList<>(Arrays.asList(commandArgs)); args.add("-ext"); @@ -1737,9 +2117,20 @@ public static void createCertificate(String certPath, String pfxPath, String ali // Create cer file i.e. extract public key from pfx File pfxFile = new File(pfxPath); if (pfxFile.exists()) { - String[] certCommandArgs = {command, "-export", "-alias", alias, - "-storetype", storeType, "-keystore", pfxPath, - "-storepass", password, "-rfc", "-file", certPath}; + String[] certCommandArgs = { + command, + "-export", + "-alias", + alias, + "-storetype", + storeType, + "-keystore", + pfxPath, + "-storepass", + password, + "-rfc", + "-file", + certPath }; // output of keytool export command is going to error stream // although command is // executed successfully, hence ignoring error stream in this case @@ -1748,13 +2139,10 @@ public static void createCertificate(String certPath, String pfxPath, String ali // Check if file got created or not File cerFile = new File(pfxPath); if (!cerFile.exists()) { - throw new IOException( - "Error occurred while creating certificate" - + String.join(" ", certCommandArgs)); + throw new IOException("Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { - throw new IOException("Error occurred while creating certificates" - + String.join(" ", commandArgs)); + throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } @@ -1767,18 +2155,15 @@ public static void createCertificate(String certPath, String pfxPath, String ali * @return result :- depending on the method invocation. * @throws IOException exceptions thrown from the execution */ - public static String cmdInvocation(String[] command, - boolean ignoreErrorStream) throws IOException { + public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); - try ( - InputStream inputStream = process.getInputStream(); + try (InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); - ) { + BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8));) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); @@ -1795,19 +2180,24 @@ public static String cmdInvocation(String[] command, return result; } - /** * Prints information for passed SQL Server. * * @param sqlServer sqlServer to be printed */ public static void print(SqlServer sqlServer) { - StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) - .append("Name: ").append(sqlServer.name()) - .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) - .append("\n\tRegion: ").append(sqlServer.region()) - .append("\n\tSqlServer version: ").append(sqlServer.version()) - .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); + StringBuilder builder = new StringBuilder().append("Sql Server: ") + .append(sqlServer.id()) + .append("Name: ") + .append(sqlServer.name()) + .append("\n\tResource group: ") + .append(sqlServer.resourceGroupName()) + .append("\n\tRegion: ") + .append(sqlServer.region()) + .append("\n\tSqlServer version: ") + .append(sqlServer.version()) + .append("\n\tFully qualified name for Sql Server: ") + .append(sqlServer.fullyQualifiedDomainName()); System.out.println(builder.toString()); } @@ -1817,19 +2207,32 @@ public static void print(SqlServer sqlServer) { * @param database database to be printed */ public static void print(SqlDatabase database) { - StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) - .append("Name: ").append(database.name()) - .append("\n\tResource group: ").append(database.resourceGroupName()) - .append("\n\tRegion: ").append(database.region()) - .append("\n\tSqlServer Name: ").append(database.sqlServerName()) - .append("\n\tEdition of SQL database: ").append(database.edition()) - .append("\n\tCollation of SQL database: ").append(database.collation()) - .append("\n\tCreation date of SQL database: ").append(database.creationDate()) - .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) - .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) - .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) - .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) - .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); + StringBuilder builder = new StringBuilder().append("Sql Database: ") + .append(database.id()) + .append("Name: ") + .append(database.name()) + .append("\n\tResource group: ") + .append(database.resourceGroupName()) + .append("\n\tRegion: ") + .append(database.region()) + .append("\n\tSqlServer Name: ") + .append(database.sqlServerName()) + .append("\n\tEdition of SQL database: ") + .append(database.edition()) + .append("\n\tCollation of SQL database: ") + .append(database.collation()) + .append("\n\tCreation date of SQL database: ") + .append(database.creationDate()) + .append("\n\tIs data warehouse: ") + .append(database.isDataWarehouse()) + .append("\n\tRequested service objective of SQL database: ") + .append(database.requestedServiceObjectiveName()) + .append("\n\tName of current service objective of SQL database: ") + .append(database.currentServiceObjectiveName()) + .append("\n\tMax size bytes of SQL database: ") + .append(database.maxSizeBytes()) + .append("\n\tDefault secondary location of SQL database: ") + .append(database.defaultSecondaryLocation()); System.out.println(builder.toString()); } @@ -1840,13 +2243,20 @@ public static void print(SqlDatabase database) { * @param firewallRule firewall rule to be printed. */ public static void print(SqlFirewallRule firewallRule) { - StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) - .append("Name: ").append(firewallRule.name()) - .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) - .append("\n\tRegion: ").append(firewallRule.region()) - .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) - .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) - .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); + StringBuilder builder = new StringBuilder().append("Sql firewall rule: ") + .append(firewallRule.id()) + .append("Name: ") + .append(firewallRule.name()) + .append("\n\tResource group: ") + .append(firewallRule.resourceGroupName()) + .append("\n\tRegion: ") + .append(firewallRule.region()) + .append("\n\tSqlServer Name: ") + .append(firewallRule.sqlServerName()) + .append("\n\tStart IP Address of the firewall rule: ") + .append(firewallRule.startIpAddress()) + .append("\n\tEnd IP Address of the firewall rule: ") + .append(firewallRule.endIpAddress()); System.out.println(builder.toString()); } @@ -1857,12 +2267,18 @@ public static void print(SqlFirewallRule firewallRule) { * @param virtualNetworkRule virtual network rule to be printed. */ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { - StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) - .append("Name: ").append(virtualNetworkRule.name()) - .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) - .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) - .append("\n\tState: ").append(virtualNetworkRule.state()); + StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ") + .append(virtualNetworkRule.id()) + .append("Name: ") + .append(virtualNetworkRule.name()) + .append("\n\tResource group: ") + .append(virtualNetworkRule.resourceGroupName()) + .append("\n\tSqlServer Name: ") + .append(virtualNetworkRule.sqlServerName()) + .append("\n\tSubnet ID: ") + .append(virtualNetworkRule.subnetId()) + .append("\n\tState: ") + .append(virtualNetworkRule.state()); System.out.println(builder.toString()); } @@ -1873,13 +2289,20 @@ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { * @param subscriptionUsageMetric metric to be printed. */ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { - StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) - .append("Name: ").append(subscriptionUsageMetric.name()) - .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) - .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) - .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) - .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) - .append("\n\tType: ").append(subscriptionUsageMetric.type()); + StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ") + .append(subscriptionUsageMetric.id()) + .append("Name: ") + .append(subscriptionUsageMetric.name()) + .append("\n\tDisplay Name: ") + .append(subscriptionUsageMetric.displayName()) + .append("\n\tCurrent Value: ") + .append(subscriptionUsageMetric.currentValue()) + .append("\n\tLimit: ") + .append(subscriptionUsageMetric.limit()) + .append("\n\tUnit: ") + .append(subscriptionUsageMetric.unit()) + .append("\n\tType: ") + .append(subscriptionUsageMetric.type()); System.out.println(builder.toString()); } @@ -1891,11 +2314,16 @@ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { */ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") - .append("Name: ").append(dbUsageMetric.name()) - .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) - .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) - .append("\n\tLimit: ").append(dbUsageMetric.limit()) - .append("\n\tUnit: ").append(dbUsageMetric.unit()); + .append("Name: ") + .append(dbUsageMetric.name()) + .append("\n\tDisplay Name: ") + .append(dbUsageMetric.displayName()) + .append("\n\tCurrent Value: ") + .append(dbUsageMetric.currentValue()) + .append("\n\tLimit: ") + .append(dbUsageMetric.limit()) + .append("\n\tUnit: ") + .append(dbUsageMetric.unit()); System.out.println(builder.toString()); } @@ -1906,21 +2334,32 @@ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { * @param failoverGroup the SQL Failover Group to be printed. */ public static void print(SqlFailoverGroup failoverGroup) { - StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) - .append("Name: ").append(failoverGroup.name()) - .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) - .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) - .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) - .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) - .append("\n\tReplication state: ").append(failoverGroup.replicationState()) - .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); + StringBuilder builder = new StringBuilder().append("SQL Failover Group: ") + .append(failoverGroup.id()) + .append("Name: ") + .append(failoverGroup.name()) + .append("\n\tResource group: ") + .append(failoverGroup.resourceGroupName()) + .append("\n\tSqlServer Name: ") + .append(failoverGroup.sqlServerName()) + .append("\n\tRead-write endpoint policy: ") + .append(failoverGroup.readWriteEndpointPolicy()) + .append("\n\tData loss grace period: ") + .append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) + .append("\n\tRead-only endpoint policy: ") + .append(failoverGroup.readOnlyEndpointPolicy()) + .append("\n\tReplication state: ") + .append(failoverGroup.replicationState()) + .append("\n\tReplication role: ") + .append(failoverGroup.replicationRole()); builder.append("\n\tPartner Servers: "); for (PartnerInfo item : failoverGroup.partnerServers()) { - builder - .append("\n\t\tId: ").append(item.id()) - .append("\n\t\tLocation: ").append(item.location()) - .append("\n\t\tReplication role: ").append(item.replicationRole()); + builder.append("\n\t\tId: ") + .append(item.id()) + .append("\n\t\tLocation: ") + .append(item.location()) + .append("\n\t\tReplication role: ") + .append(item.replicationRole()); } builder.append("\n\tDatabases: "); for (String databaseId : failoverGroup.databases()) { @@ -1936,15 +2375,24 @@ public static void print(SqlFailoverGroup failoverGroup) { * @param serverKey virtual network rule to be printed. */ public static void print(SqlServerKey serverKey) { - StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) - .append("Name: ").append(serverKey.name()) - .append("\n\tResource group: ").append(serverKey.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) - .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") - .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) - .append("\n\tServer Key URI: ").append(serverKey.uri()) - .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) - .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); + StringBuilder builder = new StringBuilder().append("SQL server key: ") + .append(serverKey.id()) + .append("Name: ") + .append(serverKey.name()) + .append("\n\tResource group: ") + .append(serverKey.resourceGroupName()) + .append("\n\tSqlServer Name: ") + .append(serverKey.sqlServerName()) + .append("\n\tRegion: ") + .append(serverKey.region() != null ? serverKey.region().name() : "") + .append("\n\tServer Key Type: ") + .append(serverKey.serverKeyType()) + .append("\n\tServer Key URI: ") + .append(serverKey.uri()) + .append("\n\tServer Key Thumbprint: ") + .append(serverKey.thumbprint()) + .append("\n\tServer Key Creation Date: ") + .append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); System.out.println(builder.toString()); } @@ -1955,18 +2403,30 @@ public static void print(SqlServerKey serverKey) { * @param elasticPool elastic pool to be printed */ public static void print(SqlElasticPool elasticPool) { - StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) - .append("Name: ").append(elasticPool.name()) - .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) - .append("\n\tRegion: ").append(elasticPool.region()) - .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) - .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) - .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) - .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) - .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) - .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) - .append("\n\tState of the elastic pool: ").append(elasticPool.state()) - .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); + StringBuilder builder = new StringBuilder().append("Sql elastic pool: ") + .append(elasticPool.id()) + .append("Name: ") + .append(elasticPool.name()) + .append("\n\tResource group: ") + .append(elasticPool.resourceGroupName()) + .append("\n\tRegion: ") + .append(elasticPool.region()) + .append("\n\tSqlServer Name: ") + .append(elasticPool.sqlServerName()) + .append("\n\tEdition of elastic pool: ") + .append(elasticPool.edition()) + .append("\n\tTotal number of DTUs in the elastic pool: ") + .append(elasticPool.dtu()) + .append("\n\tMaximum DTUs a database can get in elastic pool: ") + .append(elasticPool.databaseDtuMax()) + .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ") + .append(elasticPool.databaseDtuMin()) + .append("\n\tCreation date for the elastic pool: ") + .append(elasticPool.creationDate()) + .append("\n\tState of the elastic pool: ") + .append(elasticPool.state()) + .append("\n\tStorage capacity in MBs for the elastic pool: ") + .append(elasticPool.storageCapacity()); System.out.println(builder.toString()); } @@ -1977,18 +2437,30 @@ public static void print(SqlElasticPool elasticPool) { * @param elasticPoolActivity elastic pool activity to be printed */ public static void print(ElasticPoolActivity elasticPoolActivity) { - StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) - .append("Name: ").append(elasticPoolActivity.name()) - .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) - .append("\n\tState: ").append(elasticPoolActivity.state()) - .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) - .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) - .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) - .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) - .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) - .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) - .append("\n\tOperation: ").append(elasticPoolActivity.operation()) - .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()); + StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ") + .append(elasticPoolActivity.id()) + .append("Name: ") + .append(elasticPoolActivity.name()) + .append("\n\tResource group: ") + .append(elasticPoolActivity.resourceGroupName()) + .append("\n\tState: ") + .append(elasticPoolActivity.state()) + .append("\n\tElastic pool name: ") + .append(elasticPoolActivity.elasticPoolName()) + .append("\n\tStart time of activity: ") + .append(elasticPoolActivity.startTime()) + .append("\n\tEnd time of activity: ") + .append(elasticPoolActivity.endTime()) + .append("\n\tError code of activity: ") + .append(elasticPoolActivity.errorCode()) + .append("\n\tError message of activity: ") + .append(elasticPoolActivity.errorMessage()) + .append("\n\tError severity of activity: ") + .append(elasticPoolActivity.errorSeverity()) + .append("\n\tOperation: ") + .append(elasticPoolActivity.operation()) + .append("\n\tCompleted percentage of activity: ") + .append(elasticPoolActivity.percentComplete()); System.out.println(builder.toString()); @@ -2001,34 +2473,48 @@ public static void print(ElasticPoolActivity elasticPoolActivity) { */ public static void print(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); - info.append("Application gateway: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tSKU: ").append(resource.sku().toString()) - .append("\n\tOperational state: ").append(resource.operationalState()) - .append("\n\tInternet-facing? ").append(resource.isPublic()) - .append("\n\tInternal? ").append(resource.isPrivate()) - .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) - .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) - .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); + info.append("Application gateway: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tSKU: ") + .append(resource.sku().toString()) + .append("\n\tOperational state: ") + .append(resource.operationalState()) + .append("\n\tInternet-facing? ") + .append(resource.isPublic()) + .append("\n\tInternal? ") + .append(resource.isPrivate()) + .append("\n\tDefault private IP address: ") + .append(resource.privateIpAddress()) + .append("\n\tPrivate IP address allocation method: ") + .append(resource.privateIpAllocationMethod()) + .append("\n\tDisabled SSL protocols: ") + .append(resource.disabledSslProtocols().toString()); // Show IP configs Map ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { - info.append("\n\t\tName: ").append(ipConfig.name()) - .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) - .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); + info.append("\n\t\tName: ") + .append(ipConfig.name()) + .append("\n\t\t\tNetwork id: ") + .append(ipConfig.networkId()) + .append("\n\t\t\tSubnet name: ") + .append(ipConfig.subnetName()); } // Show frontends Map frontends = resource.frontends(); info.append("\n\tFrontends: ").append(frontends.size()); for (ApplicationGatewayFrontend frontend : frontends.values()) { - info.append("\n\t\tName: ").append(frontend.name()) - .append("\n\t\t\tPublic? ").append(frontend.isPublic()); + info.append("\n\t\tName: ").append(frontend.name()).append("\n\t\t\tPublic? ").append(frontend.isPublic()); if (frontend.isPublic()) { // Show public frontend info @@ -2037,10 +2523,14 @@ public static void print(ApplicationGateway resource) { if (frontend.isPrivate()) { // Show private frontend info - info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) - .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) - .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) - .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); + info.append("\n\t\t\tPrivate IP address: ") + .append(frontend.privateIpAddress()) + .append("\n\t\t\tPrivate IP allocation method: ") + .append(frontend.privateIpAllocationMethod()) + .append("\n\t\t\tSubnet name: ") + .append(frontend.subnetName()) + .append("\n\t\t\tVirtual network ID: ") + .append(frontend.networkId()); } } @@ -2048,15 +2538,19 @@ public static void print(ApplicationGateway resource) { Map backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { - info.append("\n\t\tName: ").append(backend.name()) - .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); + info.append("\n\t\tName: ") + .append(backend.name()) + .append("\n\t\t\tAssociated NIC IP configuration IDs: ") + .append(backend.backendNicIPConfigurationNames().keySet()); // Show addresses Collection addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { - info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) - .append("\n\t\t\t\tIP: ").append(address.ipAddress()); + info.append("\n\t\t\t\tFQDN: ") + .append(address.fqdn()) + .append("\n\t\t\t\tIP: ") + .append(address.ipAddress()); } } @@ -2064,16 +2558,26 @@ public static void print(ApplicationGateway resource) { Map httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { - info.append("\n\t\tName: ").append(httpConfig.name()) - .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) - .append("\n\t\t\tPort: ").append(httpConfig.port()) - .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) - .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) - .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) - .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) - .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) - .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) - .append("\n\t\tPath: ").append(httpConfig.path()); + info.append("\n\t\tName: ") + .append(httpConfig.name()) + .append("\n\t\t\tCookie based affinity: ") + .append(httpConfig.cookieBasedAffinity()) + .append("\n\t\t\tPort: ") + .append(httpConfig.port()) + .append("\n\t\t\tRequest timeout in seconds: ") + .append(httpConfig.requestTimeout()) + .append("\n\t\t\tProtocol: ") + .append(httpConfig.protocol()) + .append("\n\t\tHost header: ") + .append(httpConfig.hostHeader()) + .append("\n\t\tHost header comes from backend? ") + .append(httpConfig.isHostHeaderFromBackend()) + .append("\n\t\tConnection draining timeout in seconds: ") + .append(httpConfig.connectionDrainingTimeoutInSeconds()) + .append("\n\t\tAffinity cookie name: ") + .append(httpConfig.affinityCookieName()) + .append("\n\t\tPath: ") + .append(httpConfig.path()); ApplicationGatewayProbe probe = httpConfig.probe(); if (probe != null) { info.append("\n\t\tProbe: " + probe.name()); @@ -2085,34 +2589,47 @@ public static void print(ApplicationGateway resource) { Map sslCerts = resource.sslCertificates(); info.append("\n\tSSL certificates: ").append(sslCerts.size()); for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { - info.append("\n\t\tName: ").append(cert.name()) - .append("\n\t\t\tCert data: ").append(cert.publicData()); + info.append("\n\t\tName: ").append(cert.name()).append("\n\t\t\tCert data: ").append(cert.publicData()); } // Show redirect configurations Map redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { - info.append("\n\t\tName: ").append(redirect.name()) - .append("\n\t\tTarget URL: ").append(redirect.type()) - .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) - .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) - .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) - .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) - .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); + info.append("\n\t\tName: ") + .append(redirect.name()) + .append("\n\t\tTarget URL: ") + .append(redirect.type()) + .append("\n\t\tTarget URL: ") + .append(redirect.targetUrl()) + .append("\n\t\tTarget listener: ") + .append(redirect.targetListener() != null ? redirect.targetListener().name() : null) + .append("\n\t\tIs path included? ") + .append(redirect.isPathIncluded()) + .append("\n\t\tIs query string included? ") + .append(redirect.isQueryStringIncluded()) + .append("\n\t\tReferencing request routing rules: ") + .append(redirect.requestRoutingRules().values()); } // Show HTTP listeners Map listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { - info.append("\n\t\tName: ").append(listener.name()) - .append("\n\t\t\tHost name: ").append(listener.hostname()) - .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) - .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) - .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) - .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) - .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); + info.append("\n\t\tName: ") + .append(listener.name()) + .append("\n\t\t\tHost name: ") + .append(listener.hostname()) + .append("\n\t\t\tServer name indication required? ") + .append(listener.requiresServerNameIndication()) + .append("\n\t\t\tAssociated frontend name: ") + .append(listener.frontend().name()) + .append("\n\t\t\tFrontend port name: ") + .append(listener.frontendPortName()) + .append("\n\t\t\tFrontend port number: ") + .append(listener.frontendPortNumber()) + .append("\n\t\t\tProtocol: ") + .append(listener.protocol().toString()); if (listener.sslCertificate() != null) { info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); } @@ -2122,38 +2639,54 @@ public static void print(ApplicationGateway resource) { Map probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { - info.append("\n\t\tName: ").append(probe.name()) - .append("\n\t\tProtocol:").append(probe.protocol().toString()) - .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) - .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) - .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) - .append("\n\t\tHost: ").append(probe.host()) - .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) - .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); + info.append("\n\t\tName: ") + .append(probe.name()) + .append("\n\t\tProtocol:") + .append(probe.protocol().toString()) + .append("\n\t\tInterval in seconds: ") + .append(probe.timeBetweenProbesInSeconds()) + .append("\n\t\tRetries: ") + .append(probe.retriesBeforeUnhealthy()) + .append("\n\t\tTimeout: ") + .append(probe.timeoutInSeconds()) + .append("\n\t\tHost: ") + .append(probe.host()) + .append("\n\t\tHealthy HTTP response status code ranges: ") + .append(probe.healthyHttpResponseStatusCodeRanges()) + .append("\n\t\tHealthy HTTP response body contents: ") + .append(probe.healthyHttpResponseBodyContents()); } // Show request routing rules Map rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { - info.append("\n\t\tName: ").append(rule.name()) - .append("\n\t\tType: ").append(rule.ruleType()) - .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) - .append("\n\t\tHost name: ").append(rule.hostname()) - .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) - .append("\n\t\tFrontend port: ").append(rule.frontendPort()) - .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) - .append("\n\t\tBackend port: ").append(rule.backendPort()) - .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) - .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); + info.append("\n\t\tName: ") + .append(rule.name()) + .append("\n\t\tType: ") + .append(rule.ruleType()) + .append("\n\t\tPublic IP address ID: ") + .append(rule.publicIpAddressId()) + .append("\n\t\tHost name: ") + .append(rule.hostname()) + .append("\n\t\tServer name indication required? ") + .append(rule.requiresServerNameIndication()) + .append("\n\t\tFrontend port: ") + .append(rule.frontendPort()) + .append("\n\t\tFrontend protocol: ") + .append(rule.frontendProtocol().toString()) + .append("\n\t\tBackend port: ") + .append(rule.backendPort()) + .append("\n\t\tCookie based affinity enabled? ") + .append(rule.cookieBasedAffinity()) + .append("\n\t\tRedirect configuration: ") + .append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); // Show backend addresses Collection addresses = rule.backendAddresses(); info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { - info.append("\n\t\t\t\t") - .append(address.fqdn()) - .append(" [").append(address.ipAddress()).append("]"); + info.append("\n\t\t\t\t").append(address.fqdn()).append(" [").append(address.ipAddress()).append("]"); } // Show SSL cert @@ -2201,16 +2734,24 @@ public static void print(ApplicationGateway resource) { * @param image the image */ public static void print(VirtualMachineCustomImage image) { - StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) - .append("Name: ").append(image.name()) - .append("\n\tResource group: ").append(image.resourceGroupName()) - .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); + StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ") + .append(image.id()) + .append("Name: ") + .append(image.name()) + .append("\n\tResource group: ") + .append(image.resourceGroupName()) + .append("\n\tCreated from virtual machine: ") + .append(image.sourceVirtualMachineId()); builder.append("\n\tOS disk image: ") - .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) - .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) - .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) - .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); + .append("\n\t\tOperating system: ") + .append(image.osDiskImage().osType()) + .append("\n\t\tOperating system state: ") + .append(image.osDiskImage().osState()) + .append("\n\t\tCaching: ") + .append(image.osDiskImage().caching()) + .append("\n\t\tSize (GB): ") + .append(image.osDiskImage().diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } @@ -2225,9 +2766,12 @@ public static void print(VirtualMachineCustomImage image) { } if (image.dataDiskImages() != null) { for (ImageDataDisk diskImage : image.dataDiskImages().values()) { - builder.append("\n\tDisk Image (Lun) #: ").append(diskImage.lun()) - .append("\n\t\tCaching: ").append(diskImage.caching()) - .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); + builder.append("\n\tDisk Image (Lun) #: ") + .append(diskImage.lun()) + .append("\n\t\tCaching: ") + .append(diskImage.caching()) + .append("\n\t\tSize (GB): ") + .append(diskImage.diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } @@ -2302,19 +2846,29 @@ private static void uploadFileViaFtp(PublishingProfile profile, String fileName, * @param serviceBusNamespace a service bus namespace */ public static void print(ServiceBusNamespace serviceBusNamespace) { - StringBuilder builder = new StringBuilder() - .append("Service bus Namespace: ").append(serviceBusNamespace.id()) - .append("\n\tName: ").append(serviceBusNamespace.name()) - .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) - .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) - .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) - .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) - .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) - .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) - .append("\n\tSku: ") - .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) - .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) - .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); + StringBuilder builder = new StringBuilder().append("Service bus Namespace: ") + .append(serviceBusNamespace.id()) + .append("\n\tName: ") + .append(serviceBusNamespace.name()) + .append("\n\tRegion: ") + .append(serviceBusNamespace.regionName()) + .append("\n\tResourceGroupName: ") + .append(serviceBusNamespace.resourceGroupName()) + .append("\n\tCreatedAt: ") + .append(serviceBusNamespace.createdAt()) + .append("\n\tUpdatedAt: ") + .append(serviceBusNamespace.updatedAt()) + .append("\n\tDnsLabel: ") + .append(serviceBusNamespace.dnsLabel()) + .append("\n\tFQDN: ") + .append(serviceBusNamespace.fqdn()) + .append("\n\tSku: ") + .append("\n\t\tCapacity: ") + .append(serviceBusNamespace.sku().capacity()) + .append("\n\t\tSkuName: ") + .append(serviceBusNamespace.sku().name()) + .append("\n\t\tTier: ") + .append(serviceBusNamespace.sku().tier()); System.out.println(builder.toString()); } @@ -2325,33 +2879,58 @@ public static void print(ServiceBusNamespace serviceBusNamespace) { * @param queue a service bus queue */ public static void print(Queue queue) { - StringBuilder builder = new StringBuilder() - .append("Service bus Queue: ").append(queue.id()) - .append("\n\tName: ").append(queue.name()) - .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) - .append("\n\tCreatedAt: ").append(queue.createdAt()) - .append("\n\tUpdatedAt: ").append(queue.updatedAt()) - .append("\n\tAccessedAt: ").append(queue.accessedAt()) - .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) - .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) - .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) - .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) - .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) - .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) - .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) - .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) - .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) - .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) - .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) - .append("\n\tMessageCount: ").append(queue.messageCount()) - .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) - .append("\n\tStatus: ").append(queue.status()) - .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) - .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) - .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); + StringBuilder builder = new StringBuilder().append("Service bus Queue: ") + .append(queue.id()) + .append("\n\tName: ") + .append(queue.name()) + .append("\n\tResourceGroupName: ") + .append(queue.resourceGroupName()) + .append("\n\tCreatedAt: ") + .append(queue.createdAt()) + .append("\n\tUpdatedAt: ") + .append(queue.updatedAt()) + .append("\n\tAccessedAt: ") + .append(queue.accessedAt()) + .append("\n\tActiveMessageCount: ") + .append(queue.activeMessageCount()) + .append("\n\tCurrentSizeInBytes: ") + .append(queue.currentSizeInBytes()) + .append("\n\tDeadLetterMessageCount: ") + .append(queue.deadLetterMessageCount()) + .append("\n\tDefaultMessageTtlDuration: ") + .append(queue.defaultMessageTtlDuration()) + .append("\n\tDuplicateMessageDetectionHistoryDuration: ") + .append(queue.duplicateMessageDetectionHistoryDuration()) + .append("\n\tIsBatchedOperationsEnabled: ") + .append(queue.isBatchedOperationsEnabled()) + .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ") + .append(queue.isDeadLetteringEnabledForExpiredMessages()) + .append("\n\tIsDuplicateDetectionEnabled: ") + .append(queue.isDuplicateDetectionEnabled()) + .append("\n\tIsExpressEnabled: ") + .append(queue.isExpressEnabled()) + .append("\n\tIsPartitioningEnabled: ") + .append(queue.isPartitioningEnabled()) + .append("\n\tIsSessionEnabled: ") + .append(queue.isSessionEnabled()) + .append("\n\tDeleteOnIdleDurationInMinutes: ") + .append(queue.deleteOnIdleDurationInMinutes()) + .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ") + .append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) + .append("\n\tMaxSizeInMB: ") + .append(queue.maxSizeInMB()) + .append("\n\tMessageCount: ") + .append(queue.messageCount()) + .append("\n\tScheduledMessageCount: ") + .append(queue.scheduledMessageCount()) + .append("\n\tStatus: ") + .append(queue.status()) + .append("\n\tTransferMessageCount: ") + .append(queue.transferMessageCount()) + .append("\n\tLockDurationInSeconds: ") + .append(queue.lockDurationInSeconds()) + .append("\n\tTransferDeadLetterMessageCount: ") + .append(queue.transferDeadLetterMessageCount()); System.out.println(builder.toString()); @@ -2363,18 +2942,21 @@ public static void print(Queue queue) { * @param queueAuthorizationRule a service bus queue authorization keys */ public static void print(QueueAuthorizationRule queueAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) - .append("\n\tName: ").append(queueAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) - .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); + StringBuilder builder = new StringBuilder().append("Service bus queue authorization rule: ") + .append(queueAuthorizationRule.id()) + .append("\n\tName: ") + .append(queueAuthorizationRule.name()) + .append("\n\tResourceGroupName: ") + .append(queueAuthorizationRule.resourceGroupName()) + .append("\n\tNamespace Name: ") + .append(queueAuthorizationRule.namespaceName()) + .append("\n\tQueue Name: ") + .append(queueAuthorizationRule.queueName()); List rights = queueAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); + builder.append("\n\t\tAccessRight: ").append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); @@ -2386,12 +2968,15 @@ public static void print(QueueAuthorizationRule queueAuthorizationRule) { * @param keys a service bus namespace authorization keys */ public static void print(AuthorizationKeys keys) { - StringBuilder builder = new StringBuilder() - .append("Authorization keys: ") - .append("\n\tPrimaryKey: ").append(keys.primaryKey()) - .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) - .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) - .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); + StringBuilder builder = new StringBuilder().append("Authorization keys: ") + .append("\n\tPrimaryKey: ") + .append(keys.primaryKey()) + .append("\n\tPrimaryConnectionString: ") + .append(keys.primaryConnectionString()) + .append("\n\tSecondaryKey: ") + .append(keys.secondaryKey()) + .append("\n\tSecondaryConnectionString: ") + .append(keys.secondaryConnectionString()); System.out.println(builder.toString()); } @@ -2402,17 +2987,19 @@ public static void print(AuthorizationKeys keys) { * @param namespaceAuthorizationRule a service bus namespace authorization rule */ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) - .append("\n\tName: ").append(namespaceAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); + StringBuilder builder = new StringBuilder().append("Service bus queue authorization rule: ") + .append(namespaceAuthorizationRule.id()) + .append("\n\tName: ") + .append(namespaceAuthorizationRule.name()) + .append("\n\tResourceGroupName: ") + .append(namespaceAuthorizationRule.resourceGroupName()) + .append("\n\tNamespace Name: ") + .append(namespaceAuthorizationRule.namespaceName()); List rights = namespaceAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); + builder.append("\n\t\tAccessRight: ").append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); @@ -2424,29 +3011,50 @@ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) * @param topic a service bus topic */ public static void print(Topic topic) { - StringBuilder builder = new StringBuilder() - .append("Service bus topic: ").append(topic.id()) - .append("\n\tName: ").append(topic.name()) - .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) - .append("\n\tCreatedAt: ").append(topic.createdAt()) - .append("\n\tUpdatedAt: ").append(topic.updatedAt()) - .append("\n\tAccessedAt: ").append(topic.accessedAt()) - .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) - .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) - .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) - .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) - .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) - .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) - .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) - .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) - .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) - .append("\n\tStatus: ").append(topic.status()) - .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) - .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) - .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); + StringBuilder builder = new StringBuilder().append("Service bus topic: ") + .append(topic.id()) + .append("\n\tName: ") + .append(topic.name()) + .append("\n\tResourceGroupName: ") + .append(topic.resourceGroupName()) + .append("\n\tCreatedAt: ") + .append(topic.createdAt()) + .append("\n\tUpdatedAt: ") + .append(topic.updatedAt()) + .append("\n\tAccessedAt: ") + .append(topic.accessedAt()) + .append("\n\tActiveMessageCount: ") + .append(topic.activeMessageCount()) + .append("\n\tCurrentSizeInBytes: ") + .append(topic.currentSizeInBytes()) + .append("\n\tDeadLetterMessageCount: ") + .append(topic.deadLetterMessageCount()) + .append("\n\tDefaultMessageTtlDuration: ") + .append(topic.defaultMessageTtlDuration()) + .append("\n\tDuplicateMessageDetectionHistoryDuration: ") + .append(topic.duplicateMessageDetectionHistoryDuration()) + .append("\n\tIsBatchedOperationsEnabled: ") + .append(topic.isBatchedOperationsEnabled()) + .append("\n\tIsDuplicateDetectionEnabled: ") + .append(topic.isDuplicateDetectionEnabled()) + .append("\n\tIsExpressEnabled: ") + .append(topic.isExpressEnabled()) + .append("\n\tIsPartitioningEnabled: ") + .append(topic.isPartitioningEnabled()) + .append("\n\tDeleteOnIdleDurationInMinutes: ") + .append(topic.deleteOnIdleDurationInMinutes()) + .append("\n\tMaxSizeInMB: ") + .append(topic.maxSizeInMB()) + .append("\n\tScheduledMessageCount: ") + .append(topic.scheduledMessageCount()) + .append("\n\tStatus: ") + .append(topic.status()) + .append("\n\tTransferMessageCount: ") + .append(topic.transferMessageCount()) + .append("\n\tSubscriptionCount: ") + .append(topic.subscriptionCount()) + .append("\n\tTransferDeadLetterMessageCount: ") + .append(topic.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } @@ -2457,28 +3065,48 @@ public static void print(Topic topic) { * @param serviceBusSubscription a service bus subscription */ public static void print(ServiceBusSubscription serviceBusSubscription) { - StringBuilder builder = new StringBuilder() - .append("Service bus subscription: ").append(serviceBusSubscription.id()) - .append("\n\tName: ").append(serviceBusSubscription.name()) - .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) - .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) - .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) - .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) - .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) - .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) - .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) - .append("\n\tStatus: ").append(serviceBusSubscription.status()) - .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) - .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) - .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) - .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) - .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) - .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) - .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) - .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); + StringBuilder builder = new StringBuilder().append("Service bus subscription: ") + .append(serviceBusSubscription.id()) + .append("\n\tName: ") + .append(serviceBusSubscription.name()) + .append("\n\tResourceGroupName: ") + .append(serviceBusSubscription.resourceGroupName()) + .append("\n\tCreatedAt: ") + .append(serviceBusSubscription.createdAt()) + .append("\n\tUpdatedAt: ") + .append(serviceBusSubscription.updatedAt()) + .append("\n\tAccessedAt: ") + .append(serviceBusSubscription.accessedAt()) + .append("\n\tActiveMessageCount: ") + .append(serviceBusSubscription.activeMessageCount()) + .append("\n\tDeadLetterMessageCount: ") + .append(serviceBusSubscription.deadLetterMessageCount()) + .append("\n\tDefaultMessageTtlDuration: ") + .append(serviceBusSubscription.defaultMessageTtlDuration()) + .append("\n\tIsBatchedOperationsEnabled: ") + .append(serviceBusSubscription.isBatchedOperationsEnabled()) + .append("\n\tDeleteOnIdleDurationInMinutes: ") + .append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) + .append("\n\tScheduledMessageCount: ") + .append(serviceBusSubscription.scheduledMessageCount()) + .append("\n\tStatus: ") + .append(serviceBusSubscription.status()) + .append("\n\tTransferMessageCount: ") + .append(serviceBusSubscription.transferMessageCount()) + .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ") + .append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) + .append("\n\tIsSessionEnabled: ") + .append(serviceBusSubscription.isSessionEnabled()) + .append("\n\tLockDurationInSeconds: ") + .append(serviceBusSubscription.lockDurationInSeconds()) + .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ") + .append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) + .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ") + .append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) + .append("\n\tTransferMessageCount: ") + .append(serviceBusSubscription.transferMessageCount()) + .append("\n\tTransferDeadLetterMessageCount: ") + .append(serviceBusSubscription.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } @@ -2489,18 +3117,21 @@ public static void print(ServiceBusSubscription serviceBusSubscription) { * @param topicAuthorizationRule a topic Authorization Rule */ public static void print(TopicAuthorizationRule topicAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) - .append("\n\tName: ").append(topicAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) - .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); + StringBuilder builder = new StringBuilder().append("Service bus topic authorization rule: ") + .append(topicAuthorizationRule.id()) + .append("\n\tName: ") + .append(topicAuthorizationRule.name()) + .append("\n\tResourceGroupName: ") + .append(topicAuthorizationRule.resourceGroupName()) + .append("\n\tNamespace Name: ") + .append(topicAuthorizationRule.namespaceName()) + .append("\n\tTopic Name: ") + .append(topicAuthorizationRule.topicName()); List rights = topicAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); + builder.append("\n\t\tAccessRight: ").append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); @@ -2512,31 +3143,37 @@ public static void print(TopicAuthorizationRule topicAuthorizationRule) { * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { - StringBuilder builder = new StringBuilder() - .append("CosmosDB: ").append(cosmosDBAccount.id()) - .append("\n\tName: ").append(cosmosDBAccount.name()) - .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) - .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) - .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) - .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); + StringBuilder builder = new StringBuilder().append("CosmosDB: ") + .append(cosmosDBAccount.id()) + .append("\n\tName: ") + .append(cosmosDBAccount.name()) + .append("\n\tResourceGroupName: ") + .append(cosmosDBAccount.resourceGroupName()) + .append("\n\tKind: ") + .append(cosmosDBAccount.kind().toString()) + .append("\n\tDefault consistency level: ") + .append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) + .append("\n\tIP range filter: ") + .append(cosmosDBAccount.ipRangeFilter()); DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); - builder - .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) - .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) - .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) - .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); + builder.append("\n\tPrimary Master Key: ") + .append(keys.primaryMasterKey()) + .append("\n\tSecondary Master Key: ") + .append(keys.secondaryMasterKey()) + .append("\n\tPrimary Read-Only Key: ") + .append(readOnlyKeys.primaryReadonlyMasterKey()) + .append("\n\tSecondary Read-Only Key: ") + .append(readOnlyKeys.secondaryReadonlyMasterKey()); for (Location writeReplica : cosmosDBAccount.writableReplications()) { - builder.append("\n\t\tWrite replication: ") - .append("\n\t\t\tName :").append(writeReplica.locationName()); + builder.append("\n\t\tWrite replication: ").append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); for (Location readReplica : cosmosDBAccount.readableReplications()) { - builder.append("\n\t\tRead replication: ") - .append("\n\t\t\tName :").append(readReplica.locationName()); + builder.append("\n\t\tRead replication: ").append("\n\t\t\tName :").append(readReplica.locationName()); } } @@ -2547,12 +3184,16 @@ public static void print(CosmosDBAccount cosmosDBAccount) { * @param user active directory user */ public static void print(ActiveDirectoryUser user) { - StringBuilder builder = new StringBuilder() - .append("Active Directory User: ").append(user.id()) - .append("\n\tName: ").append(user.name()) - .append("\n\tMail: ").append(user.mail()) - .append("\n\tMail Nickname: ").append(user.mailNickname()) - .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); + StringBuilder builder = new StringBuilder().append("Active Directory User: ") + .append(user.id()) + .append("\n\tName: ") + .append(user.name()) + .append("\n\tMail: ") + .append(user.mail()) + .append("\n\tMail Nickname: ") + .append(user.mailNickname()) + .append("\n\tUser Principal Name: ") + .append(user.userPrincipalName()); System.out.println(builder.toString()); } @@ -2563,13 +3204,18 @@ public static void print(ActiveDirectoryUser user) { * @param role role definition */ public static void print(RoleDefinition role) { - StringBuilder builder = new StringBuilder() - .append("Role Definition: ").append(role.id()) - .append("\n\tName: ").append(role.name()) - .append("\n\tRole Name: ").append(role.roleName()) - .append("\n\tType: ").append(role.type()) - .append("\n\tDescription: ").append(role.description()) - .append("\n\tType: ").append(role.type()); + StringBuilder builder = new StringBuilder().append("Role Definition: ") + .append(role.id()) + .append("\n\tName: ") + .append(role.name()) + .append("\n\tRole Name: ") + .append(role.roleName()) + .append("\n\tType: ") + .append(role.type()) + .append("\n\tDescription: ") + .append(role.description()) + .append("\n\tType: ") + .append(role.type()); Set permissions = role.permissions(); builder.append("\n\tPermissions: ").append(permissions.size()); @@ -2595,8 +3241,7 @@ public static void print(RoleDefinition role) { Set assignableScopes = role.assignableScopes(); builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); for (String scope : assignableScopes) { - builder.append("\n\t\tAssignable Scope: ") - .append("\n\t\t\tName :").append(scope); + builder.append("\n\t\tAssignable Scope: ").append("\n\t\t\tName :").append(scope); } System.out.println(builder.toString()); @@ -2608,11 +3253,13 @@ public static void print(RoleDefinition role) { * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { - StringBuilder builder = new StringBuilder() - .append("Role Assignment: ") - .append("\n\tScope: ").append(roleAssignment.scope()) - .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) - .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); + StringBuilder builder = new StringBuilder().append("Role Assignment: ") + .append("\n\tScope: ") + .append(roleAssignment.scope()) + .append("\n\tPrincipal Id: ") + .append(roleAssignment.principalId()) + .append("\n\tRole Definition Id: ") + .append(roleAssignment.roleDefinitionId()); System.out.println(builder.toString()); } @@ -2623,16 +3270,21 @@ public static void print(RoleAssignment roleAssignment) { * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { - StringBuilder builder = new StringBuilder() - .append("Active Directory Group: ").append(group.id()) - .append("\n\tName: ").append(group.name()) - .append("\n\tMail: ").append(group.mail()) - .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) - .append("\n\tGroup members:"); + StringBuilder builder = new StringBuilder().append("Active Directory Group: ") + .append(group.id()) + .append("\n\tName: ") + .append(group.name()) + .append("\n\tMail: ") + .append(group.mail()) + .append("\n\tSecurity Enabled: ") + .append(group.securityEnabled()) + .append("\n\tGroup members:"); for (ActiveDirectoryObject object : group.listMembers()) { - builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) - .append("\tName: ").append(object.name()); + builder.append("\n\t\tType: ") + .append(object.getClass().getSimpleName()) + .append("\tName: ") + .append(object.name()); } System.out.println(builder.toString()); @@ -2644,11 +3296,13 @@ public static void print(ActiveDirectoryGroup group) { * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { - StringBuilder builder = new StringBuilder() - .append("Active Directory Application: ").append(application.id()) - .append("\n\tName: ").append(application.name()) - .append("\n\tSign on URL: ").append(application.signOnUrl()) - .append("\n\tReply URLs:"); + StringBuilder builder = new StringBuilder().append("Active Directory Application: ") + .append(application.id()) + .append("\n\tName: ") + .append(application.name()) + .append("\n\tSign on URL: ") + .append(application.signOnUrl()) + .append("\n\tReply URLs:"); for (String replyUrl : application.replyUrls()) { builder.append("\n\t\t").append(replyUrl); } @@ -2662,10 +3316,12 @@ public static void print(ActiveDirectoryApplication application) { * @param servicePrincipal service principal */ public static void print(ServicePrincipal servicePrincipal) { - StringBuilder builder = new StringBuilder() - .append("Service Principal: ").append(servicePrincipal.id()) - .append("\n\tName: ").append(servicePrincipal.name()) - .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); + StringBuilder builder = new StringBuilder().append("Service Principal: ") + .append(servicePrincipal.id()) + .append("\n\tName: ") + .append(servicePrincipal.name()) + .append("\n\tApplication Id: ") + .append(servicePrincipal.applicationId()); List names = servicePrincipal.servicePrincipalNames(); builder.append("\n\tNames: ").append(names.size()); @@ -2681,11 +3337,14 @@ public static void print(ServicePrincipal servicePrincipal) { * @param nw network watcher */ public static void print(NetworkWatcher nw) { - StringBuilder builder = new StringBuilder() - .append("Network Watcher: ").append(nw.id()) - .append("\n\tName: ").append(nw.name()) - .append("\n\tResource group name: ").append(nw.resourceGroupName()) - .append("\n\tRegion name: ").append(nw.regionName()); + StringBuilder builder = new StringBuilder().append("Network Watcher: ") + .append(nw.id()) + .append("\n\tName: ") + .append(nw.name()) + .append("\n\tResource group name: ") + .append(nw.resourceGroupName()) + .append("\n\tRegion name: ") + .append(nw.regionName()); System.out.println(builder.toString()); } @@ -2695,17 +3354,27 @@ public static void print(NetworkWatcher nw) { * @param resource packet capture */ public static void print(PacketCapture resource) { - StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tTarget id: ").append(resource.targetId()) - .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) - .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) - .append("\n\tProvisioning state: ").append(resource.provisioningState()) - .append("\n\tStorage location:") - .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) - .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) - .append("\n\tFile path: ").append(resource.storageLocation().filePath()) - .append("\n\t Packet capture filters: ").append(resource.filters().size()); + StringBuilder sb = new StringBuilder().append("Packet Capture: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tTarget id: ") + .append(resource.targetId()) + .append("\n\tTime limit in seconds: ") + .append(resource.timeLimitInSeconds()) + .append("\n\tBytes to capture per packet: ") + .append(resource.bytesToCapturePerPacket()) + .append("\n\tProvisioning state: ") + .append(resource.provisioningState()) + .append("\n\tStorage location:") + .append("\n\tStorage account id: ") + .append(resource.storageLocation().storageId()) + .append("\n\tStorage account path: ") + .append(resource.storageLocation().storagePath()) + .append("\n\tFile path: ") + .append(resource.storageLocation().filePath()) + .append("\n\t Packet capture filters: ") + .append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); @@ -2722,10 +3391,11 @@ public static void print(PacketCapture resource) { * @param resource IP flow verification info */ public static void print(VerificationIPFlow resource) { - System.out.println(new StringBuilder("IP flow verification: ") - .append("\n\tAccess: ").append(resource.access()) - .append("\n\tRule name: ").append(resource.ruleName()) - .toString()); + System.out.println(new StringBuilder("IP flow verification: ").append("\n\tAccess: ") + .append(resource.access()) + .append("\n\tRule name: ") + .append(resource.ruleName()) + .toString()); } /** @@ -2734,22 +3404,38 @@ public static void print(VerificationIPFlow resource) { * @param resource topology */ public static void print(Topology resource) { - StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) - .append("\n\tTopology parameters: ") - .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) - .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) - .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) - .append("\n\tCreated time: ").append(resource.createdTime()) - .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); + StringBuilder sb = new StringBuilder().append("Topology: ") + .append(resource.id()) + .append("\n\tTopology parameters: ") + .append("\n\t\tResource group: ") + .append(resource.topologyParameters().targetResourceGroupName()) + .append("\n\t\tVirtual network: ") + .append(resource.topologyParameters().targetVirtualNetwork() == null + ? "" + : resource.topologyParameters().targetVirtualNetwork().id()) + .append("\n\t\tSubnet id: ") + .append(resource.topologyParameters().targetSubnet() == null + ? "" + : resource.topologyParameters().targetSubnet().id()) + .append("\n\tCreated time: ") + .append(resource.createdTime()) + .append("\n\tLast modified time: ") + .append(resource.lastModifiedTime()); for (TopologyResource tr : resource.resources().values()) { - sb.append("\n\tTopology resource: ").append(tr.id()) - .append("\n\t\tName: ").append(tr.name()) - .append("\n\t\tLocation: ").append(tr.location()) - .append("\n\t\tAssociations:"); + sb.append("\n\tTopology resource: ") + .append(tr.id()) + .append("\n\t\tName: ") + .append(tr.name()) + .append("\n\t\tLocation: ") + .append(tr.location()) + .append("\n\t\tAssociations:"); for (TopologyAssociation association : tr.associations()) { - sb.append("\n\t\t\tName:").append(association.name()) - .append("\n\t\t\tResource id:").append(association.resourceId()) - .append("\n\t\t\tAssociation type:").append(association.associationType()); + sb.append("\n\t\t\tName:") + .append(association.name()) + .append("\n\t\t\tResource id:") + .append(association.resourceId()) + .append("\n\t\t\tAssociation type:") + .append(association.associationType()); } } System.out.println(sb.toString()); @@ -2762,12 +3448,17 @@ public static void print(Topology resource) { */ public static void print(FlowLogSettings resource) { System.out.println(new StringBuilder().append("Flow log settings: ") - .append("Target resource id: ").append(resource.targetResourceId()) - .append("\n\tFlow log enabled: ").append(resource.enabled()) - .append("\n\tStorage account id: ").append(resource.storageId()) - .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) - .append("\n\tRetention policy days: ").append(resource.retentionDays()) - .toString()); + .append("Target resource id: ") + .append(resource.targetResourceId()) + .append("\n\tFlow log enabled: ") + .append(resource.enabled()) + .append("\n\tStorage account id: ") + .append(resource.storageId()) + .append("\n\tRetention policy enabled: ") + .append(resource.isRetentionEnabled()) + .append("\n\tRetention policy days: ") + .append(resource.retentionDays()) + .toString()); } /** @@ -2777,26 +3468,38 @@ public static void print(FlowLogSettings resource) { */ public static void print(SecurityGroupView resource) { StringBuilder sb = new StringBuilder().append("Security group view: ") - .append("\n\tVirtual machine id: ").append(resource.vmId()); + .append("\n\tVirtual machine id: ") + .append(resource.vmId()); for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { - sb.append("\n\tSecurity group network interface:").append(sgni.id()) - .append("\n\t\tSecurity group network interface:") - .append("\n\t\tEffective security rules:"); + sb.append("\n\tSecurity group network interface:") + .append(sgni.id()) + .append("\n\t\tSecurity group network interface:") + .append("\n\t\tEffective security rules:"); for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { - sb.append("\n\t\t\tName: ").append(rule.name()) - .append("\n\t\t\tDirection: ").append(rule.direction()) - .append("\n\t\t\tAccess: ").append(rule.access()) - .append("\n\t\t\tPriority: ").append(rule.priority()) - .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) - .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) - .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) - .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) - .append("\n\t\t\tProtocol: ").append(rule.protocol()); + sb.append("\n\t\t\tName: ") + .append(rule.name()) + .append("\n\t\t\tDirection: ") + .append(rule.direction()) + .append("\n\t\t\tAccess: ") + .append(rule.access()) + .append("\n\t\t\tPriority: ") + .append(rule.priority()) + .append("\n\t\t\tSource address prefix: ") + .append(rule.sourceAddressPrefix()) + .append("\n\t\t\tSource port range: ") + .append(rule.sourcePortRange()) + .append("\n\t\t\tDestination address prefix: ") + .append(rule.destinationAddressPrefix()) + .append("\n\t\t\tDestination port range: ") + .append(rule.destinationPortRange()) + .append("\n\t\t\tProtocol: ") + .append(rule.protocol()); } sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { - sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); + sb.append("\n\t\tNetwork interface:") + .append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); } sb.append("\n\t\tDefault security rules:"); @@ -2807,17 +3510,28 @@ public static void print(SecurityGroupView resource) { private static void printSecurityRule(StringBuilder sb, List rules) { for (SecurityRuleInner rule : rules) { - sb.append("\n\t\t\tName: ").append(rule.name()) - .append("\n\t\t\tDirection: ").append(rule.direction()) - .append("\n\t\t\tAccess: ").append(rule.access()) - .append("\n\t\t\tPriority: ").append(rule.priority()) - .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) - .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) - .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) - .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) - .append("\n\t\t\tProtocol: ").append(rule.protocol()) - .append("\n\t\t\tDescription: ").append(rule.description()) - .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); + sb.append("\n\t\t\tName: ") + .append(rule.name()) + .append("\n\t\t\tDirection: ") + .append(rule.direction()) + .append("\n\t\t\tAccess: ") + .append(rule.access()) + .append("\n\t\t\tPriority: ") + .append(rule.priority()) + .append("\n\t\t\tSource address prefix: ") + .append(rule.sourceAddressPrefix()) + .append("\n\t\t\tSource port range: ") + .append(rule.sourcePortRange()) + .append("\n\t\t\tDestination address prefix: ") + .append(rule.destinationAddressPrefix()) + .append("\n\t\t\tDestination port range: ") + .append(rule.destinationPortRange()) + .append("\n\t\t\tProtocol: ") + .append(rule.protocol()) + .append("\n\t\t\tDescription: ") + .append(rule.description()) + .append("\n\t\t\tProvisioning state: ") + .append(rule.provisioningState()); } } @@ -2827,11 +3541,13 @@ private static void printSecurityRule(StringBuilder sb, List * @param resource an availability set */ public static void print(NextHop resource) { - System.out.println(new StringBuilder("Next hop: ") - .append("Next hop type: ").append(resource.nextHopType()) - .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) - .append("\n\tRoute table id: ").append(resource.routeTableId()) - .toString()); + System.out.println(new StringBuilder("Next hop: ").append("Next hop type: ") + .append(resource.nextHopType()) + .append("\n\tNext hop ip address: ") + .append(resource.nextHopIpAddress()) + .append("\n\tRoute table id: ") + .append(resource.routeTableId()) + .toString()); } /** @@ -2840,12 +3556,18 @@ public static void print(NextHop resource) { * @param resource a container group */ public static void print(ContainerGroup resource) { - StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tOS type: ").append(resource.osType()); + StringBuilder info = new StringBuilder().append("Container Group: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tOS type: ") + .append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); @@ -2871,8 +3593,12 @@ public static void print(ContainerGroup resource) { if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry entry : resource.volumes().entrySet()) { - info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") - .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); + info.append("\n\t\tName: ") + .append(entry.getKey()) + .append(" -> ") + .append(entry.getValue().azureFile() != null + ? entry.getValue().azureFile().shareName() + : "empty direcory volume"); } } if (resource.containers() != null) { @@ -2918,17 +3644,28 @@ public static void print(ContainerGroup resource) { */ public static void print(EventHubNamespace resource) { StringBuilder info = new StringBuilder(); - info.append("Eventhub Namespace: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) - .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) - .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) - .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) - .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) - .append("\n\tCreated time: ").append(resource.createdAt()) - .append("\n\tUpdated time: ").append(resource.updatedAt()); + info.append("Eventhub Namespace: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tAzureInsightMetricId: ") + .append(resource.azureInsightMetricId()) + .append("\n\tIsAutoScale enabled: ") + .append(resource.isAutoScaleEnabled()) + .append("\n\tServiceBus endpoint: ") + .append(resource.serviceBusEndpoint()) + .append("\n\tThroughPut upper limit: ") + .append(resource.throughputUnitsUpperLimit()) + .append("\n\tCurrent ThroughPut: ") + .append(resource.currentThroughputUnits()) + .append("\n\tCreated time: ") + .append(resource.createdAt()) + .append("\n\tUpdated time: ") + .append(resource.updatedAt()); System.out.println(info.toString()); } @@ -2940,18 +3677,27 @@ public static void print(EventHubNamespace resource) { */ public static void print(EventHub resource) { StringBuilder info = new StringBuilder(); - info.append("Eventhub: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) - .append("\n\tNamespace: ").append(resource.namespaceName()) - .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) - .append("\n\tPartition ids: ").append(resource.partitionIds()); + info.append("Eventhub: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tNamespace resource group: ") + .append(resource.namespaceResourceGroupName()) + .append("\n\tNamespace: ") + .append(resource.namespaceName()) + .append("\n\tIs data capture enabled: ") + .append(resource.isDataCaptureEnabled()) + .append("\n\tPartition ids: ") + .append(resource.partitionIds()); if (resource.isDataCaptureEnabled()) { info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); - info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); + info.append("\n\t\t\tData capture window size in seconds: ") + .append(resource.dataCaptureWindowSizeInSeconds()); if (resource.captureDestination() != null) { - info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); - info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); + info.append("\n\t\t\tData capture storage account: ") + .append(resource.captureDestination().storageAccountResourceId()); + info.append("\n\t\t\tData capture storage container: ") + .append(resource.captureDestination().blobContainer()); } } System.out.println(info.toString()); @@ -2964,12 +3710,18 @@ public static void print(EventHub resource) { */ public static void print(EventHubDisasterRecoveryPairing resource) { StringBuilder info = new StringBuilder(); - info.append("DisasterRecoveryPairing: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) - .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) - .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) - .append("\n\tNamespace role: ").append(resource.namespaceRole()); + info.append("DisasterRecoveryPairing: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tPrimary namespace resource group name: ") + .append(resource.primaryNamespaceResourceGroupName()) + .append("\n\tPrimary namespace name: ") + .append(resource.primaryNamespaceName()) + .append("\n\tSecondary namespace: ") + .append(resource.secondaryNamespaceId()) + .append("\n\tNamespace role: ") + .append(resource.namespaceRole()); System.out.println(info.toString()); } @@ -2997,12 +3749,18 @@ public static void print(DisasterRecoveryPairingAuthorizationRule resource) { public static void print(DisasterRecoveryPairingAuthorizationKey resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth key: ") - .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) - .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) - .append("\n\t Primary key: ").append(resource.primaryKey()) - .append("\n\t Secondary key: ").append(resource.secondaryKey()) - .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) - .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); + .append("\n\t Alias primary connection string: ") + .append(resource.aliasPrimaryConnectionString()) + .append("\n\t Alias secondary connection string: ") + .append(resource.aliasSecondaryConnectionString()) + .append("\n\t Primary key: ") + .append(resource.primaryKey()) + .append("\n\t Secondary key: ") + .append(resource.secondaryKey()) + .append("\n\t Primary connection string: ") + .append(resource.primaryConnectionString()) + .append("\n\t Secondary connection string: ") + .append(resource.secondaryConnectionString()); System.out.println(info.toString()); } @@ -3013,30 +3771,41 @@ public static void print(DisasterRecoveryPairingAuthorizationKey resource) { */ public static void print(EventHubConsumerGroup resource) { StringBuilder info = new StringBuilder(); - info.append("Event hub consumer group: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) - .append("\n\tNamespace: ").append(resource.namespaceName()) - .append("\n\tEvent hub name: ").append(resource.eventHubName()) - .append("\n\tUser metadata: ").append(resource.userMetadata()); + info.append("Event hub consumer group: ") + .append(resource.id()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tNamespace resource group: ") + .append(resource.namespaceResourceGroupName()) + .append("\n\tNamespace: ") + .append(resource.namespaceName()) + .append("\n\tEvent hub name: ") + .append(resource.eventHubName()) + .append("\n\tUser metadata: ") + .append(resource.userMetadata()); System.out.println(info.toString()); } - /** * Print Diagnostic Setting. * * @param resource Diagnostic Setting instance */ public static void print(DiagnosticSetting resource) { - StringBuilder info = new StringBuilder("Diagnostic Setting: ") - .append("\n\tId: ").append(resource.id()) - .append("\n\tAssociated resource Id: ").append(resource.resourceId()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) - .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) - .append("\n\tEventHub name: ").append(resource.eventHubName()) - .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); + StringBuilder info = new StringBuilder("Diagnostic Setting: ").append("\n\tId: ") + .append(resource.id()) + .append("\n\tAssociated resource Id: ") + .append(resource.resourceId()) + .append("\n\tName: ") + .append(resource.name()) + .append("\n\tStorage Account Id: ") + .append(resource.storageAccountId()) + .append("\n\tEventHub Namespace Autorization Rule Id: ") + .append(resource.eventHubAuthorizationRuleId()) + .append("\n\tEventHub name: ") + .append(resource.eventHubName()) + .append("\n\tLog Analytics workspace Id: ") + .append(resource.workspaceId()); if (resource.logs() != null && !resource.logs().isEmpty()) { info.append("\n\tLog Settings: "); for (LogSettings ls : resource.logs()) { @@ -3071,10 +3840,12 @@ public static void print(DiagnosticSetting resource) { * @param actionGroup action group instance */ public static void print(ActionGroup actionGroup) { - StringBuilder info = new StringBuilder("Action Group: ") - .append("\n\tId: ").append(actionGroup.id()) - .append("\n\tName: ").append(actionGroup.name()) - .append("\n\tShort Name: ").append(actionGroup.shortName()); + StringBuilder info = new StringBuilder("Action Group: ").append("\n\tId: ") + .append(actionGroup.id()) + .append("\n\tName: ") + .append(actionGroup.name()) + .append("\n\tShort Name: ") + .append(actionGroup.shortName()); if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { info.append("\n\tEmail receivers: "); @@ -3178,11 +3949,14 @@ public static void print(ActionGroup actionGroup) { */ public static void print(ActivityLogAlert activityLogAlert) { - StringBuilder info = new StringBuilder("Activity Log Alert: ") - .append("\n\tId: ").append(activityLogAlert.id()) - .append("\n\tName: ").append(activityLogAlert.name()) - .append("\n\tDescription: ").append(activityLogAlert.description()) - .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); + StringBuilder info = new StringBuilder("Activity Log Alert: ").append("\n\tId: ") + .append(activityLogAlert.id()) + .append("\n\tName: ") + .append(activityLogAlert.name()) + .append("\n\tDescription: ") + .append(activityLogAlert.description()) + .append("\n\tIs Enabled: ") + .append(activityLogAlert.enabled()); if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); @@ -3214,15 +3988,22 @@ public static void print(ActivityLogAlert activityLogAlert) { */ public static void print(MetricAlert metricAlert) { - StringBuilder info = new StringBuilder("Metric Alert: ") - .append("\n\tId: ").append(metricAlert.id()) - .append("\n\tName: ").append(metricAlert.name()) - .append("\n\tDescription: ").append(metricAlert.description()) - .append("\n\tIs Enabled: ").append(metricAlert.enabled()) - .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) - .append("\n\tSeverity: ").append(metricAlert.severity()) - .append("\n\tWindow Size: ").append(metricAlert.windowSize()) - .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); + StringBuilder info = new StringBuilder("Metric Alert: ").append("\n\tId: ") + .append(metricAlert.id()) + .append("\n\tName: ") + .append(metricAlert.name()) + .append("\n\tDescription: ") + .append(metricAlert.description()) + .append("\n\tIs Enabled: ") + .append(metricAlert.enabled()) + .append("\n\tIs Auto Mitigated: ") + .append(metricAlert.autoMitigate()) + .append("\n\tSeverity: ") + .append(metricAlert.severity()) + .append("\n\tWindow Size: ") + .append(metricAlert.windowSize()) + .append("\n\tEvaluation Frequency: ") + .append(metricAlert.evaluationFrequency()); if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); @@ -3242,15 +4023,24 @@ public static void print(MetricAlert metricAlert) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry er : metricAlert.alertCriterias().entrySet()) { MetricAlertCondition alertCondition = er.getValue(); - info.append("\n\t\tCondition name: ").append(er.getKey()) - .append("\n\t\tSignal name: ").append(alertCondition.metricName()) - .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) - .append("\n\t\tOperator: ").append(alertCondition.condition()) - .append("\n\t\tThreshold: ").append(alertCondition.threshold()) - .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); + info.append("\n\t\tCondition name: ") + .append(er.getKey()) + .append("\n\t\tSignal name: ") + .append(alertCondition.metricName()) + .append("\n\t\tMetric Namespace: ") + .append(alertCondition.metricNamespace()) + .append("\n\t\tOperator: ") + .append(alertCondition.condition()) + .append("\n\t\tThreshold: ") + .append(alertCondition.threshold()) + .append("\n\t\tTime Aggregation: ") + .append(alertCondition.timeAggregation()); if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { for (MetricDimension dimon : alertCondition.dimensions()) { - info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); + info.append("\n\t\tDimension Filter: ") + .append("Name [") + .append(dimon.name()) + .append("] operator [Include] values["); for (String vals : dimon.values()) { info.append(vals).append(", "); } @@ -3268,16 +4058,22 @@ public static void print(MetricAlert metricAlert) { * @param springService spring service instance */ public static void print(SpringService springService) { - StringBuilder info = new StringBuilder("Spring Service: ") - .append("\n\tId: ").append(springService.id()) - .append("\n\tName: ").append(springService.name()) - .append("\n\tResource Group: ").append(springService.resourceGroupName()) - .append("\n\tRegion: ").append(springService.region()) - .append("\n\tTags: ").append(springService.tags()); + StringBuilder info = new StringBuilder("Spring Service: ").append("\n\tId: ") + .append(springService.id()) + .append("\n\tName: ") + .append(springService.name()) + .append("\n\tResource Group: ") + .append(springService.resourceGroupName()) + .append("\n\tRegion: ") + .append(springService.region()) + .append("\n\tTags: ") + .append(springService.tags()); ConfigServerProperties serverProperties = springService.getServerProperties(); - if (serverProperties != null && serverProperties.provisioningState() != null - && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { + if (serverProperties != null + && serverProperties.provisioningState() != null + && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) + && serverProperties.configServer() != null) { info.append("\n\tProperties: "); if (serverProperties.configServer().gitProperty() != null) { info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); @@ -3286,17 +4082,23 @@ public static void print(SpringService springService) { if (springService.sku() != null) { info.append("\n\tSku: ") - .append("\n\t\tName: ").append(springService.sku().name()) - .append("\n\t\tTier: ").append(springService.sku().tier()) - .append("\n\t\tCapacity: ").append(springService.sku().capacity()); + .append("\n\t\tName: ") + .append(springService.sku().name()) + .append("\n\t\tTier: ") + .append(springService.sku().tier()) + .append("\n\t\tCapacity: ") + .append(springService.sku().capacity()); } MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); - if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null + if (monitoringSettingProperties != null + && monitoringSettingProperties.provisioningState() != null && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { info.append("\n\tTrace: ") - .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) - .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); + .append("\n\t\tEnabled: ") + .append(monitoringSettingProperties.traceEnabled()) + .append("\n\t\tApp Insight Instrumentation Key: ") + .append(monitoringSettingProperties.appInsightsInstrumentationKey()); } System.out.println(info.toString()); @@ -3308,32 +4110,45 @@ public static void print(SpringService springService) { * @param springApp spring app instance */ public static void print(SpringApp springApp) { - StringBuilder info = new StringBuilder("Spring Service: ") - .append("\n\tId: ").append(springApp.id()) - .append("\n\tName: ").append(springApp.name()) - .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) - .append("\n\tUrl: ").append(springApp.url()) - .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) - .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) - .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); + StringBuilder info = new StringBuilder("Spring Service: ").append("\n\tId: ") + .append(springApp.id()) + .append("\n\tName: ") + .append(springApp.name()) + .append("\n\tPublic Endpoint: ") + .append(springApp.isPublic()) + .append("\n\tUrl: ") + .append(springApp.url()) + .append("\n\tHttps Only: ") + .append(springApp.isHttpsOnly()) + .append("\n\tFully Qualified Domain Name: ") + .append(springApp.fqdn()) + .append("\n\tActive Deployment Name: ") + .append(springApp.activeDeploymentName()); if (springApp.temporaryDisk() != null) { info.append("\n\tTemporary Disk:") - .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) - .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); + .append("\n\t\tSize In GB: ") + .append(springApp.temporaryDisk().sizeInGB()) + .append("\n\t\tMount Path: ") + .append(springApp.temporaryDisk().mountPath()); } if (springApp.persistentDisk() != null) { info.append("\n\tPersistent Disk:") - .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) - .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); + .append("\n\t\tSize In GB: ") + .append(springApp.persistentDisk().sizeInGB()) + .append("\n\t\tMount Path: ") + .append(springApp.persistentDisk().mountPath()); } if (springApp.identity() != null) { info.append("\n\tIdentity:") - .append("\n\t\tType: ").append(springApp.identity().type()) - .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) - .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); + .append("\n\t\tType: ") + .append(springApp.identity().type()) + .append("\n\t\tPrincipal Id: ") + .append(springApp.identity().principalId()) + .append("\n\t\tTenant Id: ") + .append(springApp.identity().tenantId()); } System.out.println(info.toString()); @@ -3345,10 +4160,12 @@ public static void print(SpringApp springApp) { * @param privateLinkResource the private link resource */ public static void print(PrivateLinkResource privateLinkResource) { - StringBuilder info = new StringBuilder("Private Link Resource: ") - .append("\n\tGroup ID: ").append(privateLinkResource.groupId()) - .append("\n\tRequired Member Names: ").append(privateLinkResource.requiredMemberNames()) - .append("\n\tRequired DNS Zone Names: ").append(privateLinkResource.requiredDnsZoneNames()); + StringBuilder info = new StringBuilder("Private Link Resource: ").append("\n\tGroup ID: ") + .append(privateLinkResource.groupId()) + .append("\n\tRequired Member Names: ") + .append(privateLinkResource.requiredMemberNames()) + .append("\n\tRequired DNS Zone Names: ") + .append(privateLinkResource.requiredDnsZoneNames()); System.out.println(info); } @@ -3359,37 +4176,51 @@ public static void print(PrivateLinkResource privateLinkResource) { * @param privateEndpoint the private endpoint */ public static void print(PrivateEndpoint privateEndpoint) { - StringBuilder info = new StringBuilder("Private Endpoint: ") - .append("\n\tId: ").append(privateEndpoint.id()) - .append("\n\tName: ").append(privateEndpoint.name()); - - if (privateEndpoint.privateLinkServiceConnections() != null && !privateEndpoint.privateLinkServiceConnections().isEmpty()) { - for (PrivateEndpoint.PrivateLinkServiceConnection connection : privateEndpoint.privateLinkServiceConnections().values()) { - info - .append("\n\t\tPrivate Link Service Connection Name: ").append(connection.name()) - .append("\n\t\tPrivate Link Resource ID: ").append(connection.privateLinkResourceId()) - .append("\n\t\tSub Resource Names: ").append(connection.subResourceNames()) - .append("\n\t\tProvision Status: ").append(connection.state().status()); + StringBuilder info = new StringBuilder("Private Endpoint: ").append("\n\tId: ") + .append(privateEndpoint.id()) + .append("\n\tName: ") + .append(privateEndpoint.name()); + + if (privateEndpoint.privateLinkServiceConnections() != null + && !privateEndpoint.privateLinkServiceConnections().isEmpty()) { + for (PrivateEndpoint.PrivateLinkServiceConnection connection : privateEndpoint + .privateLinkServiceConnections() + .values()) { + info.append("\n\t\tPrivate Link Service Connection Name: ") + .append(connection.name()) + .append("\n\t\tPrivate Link Resource ID: ") + .append(connection.privateLinkResourceId()) + .append("\n\t\tSub Resource Names: ") + .append(connection.subResourceNames()) + .append("\n\t\tProvision Status: ") + .append(connection.state().status()); } } - if (privateEndpoint.privateLinkServiceConnections() != null && !privateEndpoint.privateLinkServiceConnections().isEmpty()) { + if (privateEndpoint.privateLinkServiceConnections() != null + && !privateEndpoint.privateLinkServiceConnections().isEmpty()) { info.append("\n\tPrivate Link Service Connections:"); - for (PrivateEndpoint.PrivateLinkServiceConnection connection : privateEndpoint.privateLinkServiceConnections().values()) { - info - .append("\n\t\tName: ").append(connection.name()) - .append("\n\t\tPrivate Link Resource ID: ").append(connection.privateLinkResourceId()) - .append("\n\t\tSub Resource Names: ").append(connection.subResourceNames()) - .append("\n\t\tStatus: ").append(connection.state().status()); + for (PrivateEndpoint.PrivateLinkServiceConnection connection : privateEndpoint + .privateLinkServiceConnections() + .values()) { + info.append("\n\t\tName: ") + .append(connection.name()) + .append("\n\t\tPrivate Link Resource ID: ") + .append(connection.privateLinkResourceId()) + .append("\n\t\tSub Resource Names: ") + .append(connection.subResourceNames()) + .append("\n\t\tStatus: ") + .append(connection.state().status()); } } if (privateEndpoint.customDnsConfigurations() != null && !privateEndpoint.customDnsConfigurations().isEmpty()) { info.append("\n\tCustom DNS Configure:"); for (CustomDnsConfigPropertiesFormat customDns : privateEndpoint.customDnsConfigurations()) { - info - .append("\n\t\tFQDN: ").append(customDns.fqdn()) - .append("\n\t\tIP Address: ").append(customDns.ipAddresses()); + info.append("\n\t\tFQDN: ") + .append(customDns.fqdn()) + .append("\n\t\tIP Address: ") + .append(customDns.ipAddresses()); } } @@ -3407,32 +4238,27 @@ public static void print(PrivateEndpoint privateEndpoint) { */ public static String sendGetRequest(String urlString) { HttpRequest request = new HttpRequest(HttpMethod.GET, urlString); - Mono> response = - stringResponse(HTTP_PIPELINE.send(request) - .flatMap(response1 -> { - int code = response1.getStatusCode(); - if (code == 200 || code == 400 || code == 404) { - return Mono.just(response1); - } else { - return Mono.error(new HttpResponseException(response1)); - } - }) - .retryWhen(Retry - .fixedDelay(5, Duration.ofSeconds(30)) - .filter(t -> { - boolean retry = false; - if (t instanceof TimeoutException) { - retry = true; - } else if (t instanceof HttpResponseException - && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { - retry = true; - } + Mono> response = stringResponse(HTTP_PIPELINE.send(request).flatMap(response1 -> { + int code = response1.getStatusCode(); + if (code == 200 || code == 400 || code == 404) { + return Mono.just(response1); + } else { + return Mono.error(new HttpResponseException(response1)); + } + }).retryWhen(Retry.fixedDelay(5, Duration.ofSeconds(30)).filter(t -> { + boolean retry = false; + if (t instanceof TimeoutException) { + retry = true; + } else if (t instanceof HttpResponseException + && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { + retry = true; + } - if (retry) { - LOGGER.info("retry GET request to {}", urlString); - } - return retry; - }))); + if (retry) { + LOGGER.info("retry GET request to {}", urlString); + } + return retry; + }))); Response ret = response.block(); return ret == null ? null : ret.getValue(); } @@ -3449,29 +4275,24 @@ public static String sendGetRequest(String urlString) { public static String sendPostRequest(String urlString, String body) { try { HttpRequest request = new HttpRequest(HttpMethod.POST, urlString).setBody(body); - Mono> response = - stringResponse(HTTP_PIPELINE.send(request) - .flatMap(response1 -> { - int code = response1.getStatusCode(); - if (code == 200 || code == 400 || code == 404) { - return Mono.just(response1); - } else { - return Mono.error(new HttpResponseException(response1)); - } - }) - .retryWhen(Retry - .fixedDelay(5, Duration.ofSeconds(30)) - .filter(t -> { - boolean retry = false; - if (t instanceof TimeoutException) { - retry = true; - } - - if (retry) { - LOGGER.info("retry POST request to {}", urlString); - } - return retry; - }))); + Mono> response = stringResponse(HTTP_PIPELINE.send(request).flatMap(response1 -> { + int code = response1.getStatusCode(); + if (code == 200 || code == 400 || code == 404) { + return Mono.just(response1); + } else { + return Mono.error(new HttpResponseException(response1)); + } + }).retryWhen(Retry.fixedDelay(5, Duration.ofSeconds(30)).filter(t -> { + boolean retry = false; + if (t instanceof TimeoutException) { + retry = true; + } + + if (retry) { + LOGGER.info("retry POST request to {}", urlString); + } + return retry; + }))); Response ret = response.block(); return ret == null ? null : ret.getValue(); } catch (Exception e) { @@ -3482,14 +4303,15 @@ public static String sendPostRequest(String urlString, String body) { private static Mono> stringResponse(Mono responseMono) { return responseMono.flatMap(response -> response.getBodyAsString() - .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); + .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), + str))); } - private static final HttpPipeline HTTP_PIPELINE = new HttpPipelineBuilder() - .policies( - new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), - new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) - .build(); + private static final HttpPipeline HTTP_PIPELINE + = new HttpPipelineBuilder() + .policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), + new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) + .build(); /** * Get the size of the iterable. diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java index 05fbce33ca77d..be4ed9ef4bd5f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java @@ -68,14 +68,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { t1 = new Date(); - SearchService searchServiceFree = azureResourceManager.searchServices().define(searchServiceName + "free") + SearchService searchServiceFree = azureResourceManager.searchServices() + .define(searchServiceName + "free") .withRegion(region) .withNewResourceGroup(rgName) .withFreeSku() .create(); t2 = new Date(); - System.out.println("Created Azure Search service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + searchServiceFree.id()); + System.out.println("Created Azure Search service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + searchServiceFree.id()); Utils.print(searchServiceFree); } @@ -86,7 +88,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { t1 = new Date(); - SearchService searchService = azureResourceManager.searchServices().define(searchServiceName) + SearchService searchService = azureResourceManager.searchServices() + .define(searchServiceName) .withRegion(region) .withNewResourceGroup(rgName) .withStandardSku() @@ -95,10 +98,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { .create(); t2 = new Date(); - System.out.println("Created Azure Search service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + searchService.id()); + System.out.println("Created Azure Search service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + + " seconds) " + searchService.id()); Utils.print(searchService); - //============================================================= // Iterate through the Azure Search service resources @@ -108,7 +111,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(service); } - //============================================================= // Add a query key for the Search service resource @@ -116,7 +118,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { searchService.createQueryKey("testKey1"); - //============================================================= // Regenerate the admin keys for an Azure Search service resource @@ -125,7 +126,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { searchService.regenerateAdminKeys(AdminKeyKind.PRIMARY); searchService.regenerateAdminKeys(AdminKeyKind.SECONDARY); - //============================================================= // Update the Search service to use three replicas and three partitions and update the tags @@ -141,7 +141,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(searchService); - //============================================================= // Delete a query key for an Azure Search service resource @@ -151,7 +150,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(searchService); - //============================================================= // Delete the Search service resource @@ -187,11 +185,9 @@ public static void main(String[] args) { // Authenticate final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); - final TokenCredential credential = new DefaultAzureCredentialBuilder() - .build(); + final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java index 44d3ea66a507a..ba09dff9ebf19 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java @@ -82,7 +82,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a service bus subscription in the topic with session and dead-letter enabled. System.out.println("Creating subscription " + subscription1Name + " in topic " + topic1Name + "..."); - ServiceBusSubscription firstSubscription = firstTopic.subscriptions().define(subscription1Name) + ServiceBusSubscription firstSubscription = firstTopic.subscriptions() + .define(subscription1Name) .withSession() .withDefaultMessageTTL(Duration.ofMinutes(20)) .withMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20) @@ -95,9 +96,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create another subscription in the topic with auto deletion of idle entities. - System.out.println("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "..."); + System.out + .println("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "..."); - ServiceBusSubscription secondSubscription = firstTopic.subscriptions().define(subscription2Name) + ServiceBusSubscription secondSubscription = firstTopic.subscriptions() + .define(subscription2Name) .withSession() .withDeleteOnIdleDurationInMinutes(20) .create(); @@ -108,9 +111,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. - System.out.println("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features..."); + System.out.println( + "Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features..."); - Topic secondTopic = serviceBusNamespace.topics().define(topic2Name) + Topic secondTopic = serviceBusNamespace.topics() + .define(topic2Name) .withNewSendRule(sendRuleName) .withPartitioning() .withNewSubscription(subscription3Name) @@ -123,7 +128,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating following authorization rules in second topic "); PagedIterable authorizationRules = secondTopic.authorizationRules().list(); - for (TopicAuthorizationRule authorizationRule: authorizationRules) { + for (TopicAuthorizationRule authorizationRule : authorizationRules) { Utils.print(authorizationRule); } @@ -140,21 +145,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Updated second topic to change its auto deletion time"); Utils.print(secondTopic); - System.out.println("Updated following authorization rules in second topic, new list of authorization rules are "); + System.out.println( + "Updated following authorization rules in second topic, new list of authorization rules are "); authorizationRules = secondTopic.authorizationRules().list(); - for (TopicAuthorizationRule authorizationRule: authorizationRules) { + for (TopicAuthorizationRule authorizationRule : authorizationRules) { Utils.print(authorizationRule); } //============================================================= // Get connection string for default authorization rule of namespace - PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); - System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + PagedIterable namespaceAuthorizationRules + = serviceBusNamespace.authorizationRules().list(); + System.out + .println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - - for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) { Utils.print(namespaceAuthorizationRule); } @@ -165,11 +172,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Send a message to topic. - ServiceBusSenderClient sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) - .sender() - .topicName(topic1Name) - .buildClient(); + ServiceBusSenderClient sender + = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) + .sender() + .topicName(topic1Name) + .buildClient(); sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); sender.close(); @@ -210,8 +217,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java index 2a2a20ee6a5d8..2a77f25247e45 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java @@ -75,9 +75,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating topic " + topicName + " in namespace " + namespaceName + "..."); - Topic topic = serviceBusNamespace.topics().define(topicName) - .withSizeInMB(2048) - .create(); + Topic topic = serviceBusNamespace.topics().define(topicName).withSizeInMB(2048).create(); System.out.println("Created second queue in namespace"); @@ -87,10 +85,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Get and update topic with new size and a subscription System.out.println("Updating topic " + topicName + " with new size and a subscription..."); topic = serviceBusNamespace.topics().getByName(topicName); - topic = topic.update() - .withNewSubscription(subscription1Name) - .withSizeInMB(3072) - .apply(); + topic = topic.update().withNewSubscription(subscription1Name).withSizeInMB(3072).apply(); System.out.println("Updated topic to change its size in MB along with a subscription"); @@ -101,7 +96,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create a subscription System.out.println("Adding second subscription" + subscription2Name + " to topic " + topicName + "..."); - ServiceBusSubscription secondSubscription = topic.subscriptions().define(subscription2Name).withDeleteOnIdleDurationInMinutes(10).create(); + ServiceBusSubscription secondSubscription + = topic.subscriptions().define(subscription2Name).withDeleteOnIdleDurationInMinutes(10).create(); System.out.println("Added second subscription" + subscription2Name + " to topic " + topicName + "..."); Utils.print(secondSubscription); @@ -129,11 +125,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Get connection string for default authorization rule of namespace - PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); - System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - + PagedIterable namespaceAuthorizationRules + = serviceBusNamespace.authorizationRules().list(); + System.out + .println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) { Utils.print(namespaceAuthorizationRule); } @@ -147,21 +144,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Send a message to topic. - ServiceBusSenderClient sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) - .sender() - .topicName(topicName) - .buildClient(); + ServiceBusSenderClient sender + = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) + .sender() + .topicName(topicName) + .buildClient(); sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); sender.close(); //============================================================= // Delete a queue and namespace - System.out.println("Deleting subscription " + subscription1Name + " in topic " + topicName + " via update flow..."); + System.out.println( + "Deleting subscription " + subscription1Name + " in topic " + topicName + " via update flow..."); topic = topic.update().withoutSubscription(subscription1Name).apply(); System.out.println("Deleted subscription " + subscription1Name + "..."); - System.out.println("Number of subscriptions in the topic after deleting first subscription: " + topic.subscriptionCount()); + System.out.println( + "Number of subscriptions in the topic after deleting first subscription: " + topic.subscriptionCount()); System.out.println("Deleting namespace " + namespaceName + "..."); // This will delete the namespace and queue within it. @@ -194,8 +193,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java index 7a82ad27aec93..58023d5960137 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java @@ -72,9 +72,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Add a queue in namespace with features session and dead-lettering. - System.out.println("Creating first queue " + queue1Name + ", with session, time to live and move to dead-letter queue features..."); + System.out.println("Creating first queue " + queue1Name + + ", with session, time to live and move to dead-letter queue features..."); - Queue firstQueue = serviceBusNamespace.queues().define(queue1Name) + Queue firstQueue = serviceBusNamespace.queues() + .define(queue1Name) .withSession() .withDefaultMessageTTL(Duration.ofMinutes(10)) .withExpiredMessageMovedToDeadLetterQueue() @@ -85,9 +87,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create second queue with Deduplication and AutoDeleteOnIdle feature - System.out.println("Creating second queue " + queue2Name + ", with De-duplication and AutoDeleteOnIdle features..."); + System.out.println( + "Creating second queue " + queue2Name + ", with De-duplication and AutoDeleteOnIdle features..."); - Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) + Queue secondQueue = serviceBusNamespace.queues() + .define(queue2Name) .withSizeInMB(2048) .withDuplicateMessageDetection(Duration.ofMinutes(10)) .withDeleteOnIdleDurationInMinutes(10) @@ -100,9 +104,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Update second queue to change time for AutoDeleteOnIdle. - secondQueue = secondQueue.update() - .withDeleteOnIdleDurationInMinutes(5) - .apply(); + secondQueue = secondQueue.update().withDeleteOnIdleDurationInMinutes(5).apply(); System.out.println("Updated second queue to change its auto deletion time"); @@ -122,11 +124,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Get connection string for default authorization rule of namespace - PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); - System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - + PagedIterable namespaceAuthorizationRules + = serviceBusNamespace.authorizationRules().list(); + System.out + .println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) { Utils.print(namespaceAuthorizationRule); } @@ -141,11 +144,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Send a message to queue. - ServiceBusSenderClient sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) - .sender() - .queueName(queue1Name) - .buildClient(); + ServiceBusSenderClient sender + = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queue1Name) + .buildClient(); sender.sendMessage(new ServiceBusMessage("Hello").setSessionId("23424")); sender.close(); @@ -186,8 +189,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java index c567a3c4d20fb..2d5628a931e42 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java @@ -76,7 +76,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating second queue " + queue2Name + " in namespace " + namespaceName + "..."); - Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) + Queue secondQueue = serviceBusNamespace.queues() + .define(queue2Name) .withExpiredMessageMovedToDeadLetterQueue() .withSizeInMB(2048) .withMessageLockDurationInSeconds(20) @@ -100,10 +101,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Update namespace System.out.println("Updating sku of namespace " + serviceBusNamespace.name() + "..."); - serviceBusNamespace = serviceBusNamespace - .update() - .withSku(NamespaceSku.STANDARD) - .apply(); + serviceBusNamespace = serviceBusNamespace.update().withSku(NamespaceSku.STANDARD).apply(); System.out.println("Updated sku of namespace " + serviceBusNamespace.name()); //============================================================= @@ -111,7 +109,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("List of namespaces in resource group " + rgName + "..."); - for (ServiceBusNamespace serviceBusNamespace1 : azureResourceManager.serviceBusNamespaces().listByResourceGroup(rgName)) { + for (ServiceBusNamespace serviceBusNamespace1 : azureResourceManager.serviceBusNamespaces() + .listByResourceGroup(rgName)) { Utils.print(serviceBusNamespace1); } @@ -128,10 +127,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Get connection string for default authorization rule of namespace - PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); - System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + PagedIterable namespaceAuthorizationRules + = serviceBusNamespace.authorizationRules().list(); + System.out + .println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); - for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) { Utils.print(namespaceAuthorizationRule); } @@ -145,11 +146,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Send a message to queue. - ServiceBusSenderClient sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) - .sender() - .queueName(queue1Name) - .buildClient(); + ServiceBusSenderClient sender + = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queue1Name) + .buildClient(); sender.sendMessage(new ServiceBusMessage("Hello World").setSessionId("23424")); sender.close(); @@ -190,8 +191,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java index d6f1f5fa3605b..780d40e5ac023 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java @@ -53,7 +53,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================ // Create a namespace. - System.out.println("Creating name space " + namespaceName + " along with a queue " + queueName + " and a topic " + topicName + " in resource group " + rgName + "..."); + System.out.println("Creating name space " + namespaceName + " along with a queue " + queueName + + " and a topic " + topicName + " in resource group " + rgName + "..."); ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() .define(namespaceName) @@ -80,7 +81,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { ServiceBusSubscription subscription1 = topic.subscriptions().getByName(subscription1Name); - System.out.println("Creating another subscription in the topic using direct create method for subscription"); + System.out + .println("Creating another subscription in the topic using direct create method for subscription"); ServiceBusSubscription subscription2 = topic.subscriptions().define(subscription2Name).create(); Utils.print(subscription1); @@ -89,7 +91,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create new authorization rule for queue to send message. System.out.println("Create authorization rule for queue ..."); - NamespaceAuthorizationRule sendQueueAuthorizationRule = serviceBusNamespace.authorizationRules().define("SendRule").withSendingEnabled().create(); + NamespaceAuthorizationRule sendQueueAuthorizationRule + = serviceBusNamespace.authorizationRules().define("SendRule").withSendingEnabled().create(); Utils.print(sendQueueAuthorizationRule); System.out.println("Getting keys for authorization rule ..."); @@ -98,19 +101,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Send a message to queue. - ServiceBusSenderClient sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) - .sender() - .queueName(queueName) - .buildClient(); + ServiceBusSenderClient sender + = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queueName) + .buildClient(); sender.sendMessage(new ServiceBusMessage("Hello").setMessageId("1")); sender.close(); - //============================================================= // Send a message to topic. - sender = new ServiceBusClientBuilder() - .connectionString(keys.primaryConnectionString()) + sender = new ServiceBusClientBuilder().connectionString(keys.primaryConnectionString()) .sender() .topicName(topicName) .buildClient(); @@ -119,7 +120,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Delete a namespace - System.out.println("Deleting namespace " + namespaceName + " [topic, queues and subscription will delete along with that]..."); + System.out.println("Deleting namespace " + namespaceName + + " [topic, queues and subscription will delete along with that]..."); // This will delete the namespace and queue within it. azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); System.out.println("Deleted namespace " + namespaceName + "..."); @@ -150,8 +152,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java index 2028b0e936815..77c43d1620422 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -49,15 +48,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a SQL Server, with 2 firewall rules. - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() - .defineFirewallRule("filewallRule2") - .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() - .create(); + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("filewallRule1") + .withIpAddress(firewallRuleIPAddress) + .attach() + .defineFirewallRule("filewallRule2") + .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress) + .attach() + .create(); Utils.print(sqlServer); @@ -65,18 +68,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a Database in SQL server created above. System.out.println("Creating a database"); - SqlDatabase database = sqlServer.databases() - .define(databaseName) - .create(); + SqlDatabase database = sqlServer.databases().define(databaseName).create(); Utils.print(database); // ============================================================ // Update the edition of database. System.out.println("Updating a database"); database = database.update() - .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) - .withMaxSizeBytes(1024 * 1024 * 1024 * 20) - .apply(); + .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) + .withMaxSizeBytes(1024 * 1024 * 1024 * 20) + .apply(); Utils.print(database); // ============================================================ @@ -84,7 +85,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Listing all firewall rules"); List firewallRules = sqlServer.firewallRules().list(); - for (SqlFirewallRule firewallRule: firewallRules) { + for (SqlFirewallRule firewallRule : firewallRules) { // Print information of the firewall rule. Utils.print(firewallRule); @@ -96,9 +97,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Add new firewall rules. System.out.println("Creating a firewall rule for SQL Server"); - SqlFirewallRule firewallRule = sqlServer.firewallRules().define("myFirewallRule") - .withIpAddress("10.10.10.10") - .create(); + SqlFirewallRule firewallRule + = sqlServer.firewallRules().define("myFirewallRule").withIpAddress("10.10.10.10").create(); Utils.print(firewallRule); @@ -122,6 +122,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -134,8 +135,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -154,5 +154,4 @@ private ManageSqlDatabase() { } - } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java index 29f92faced604..7d80892c32e6a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -52,21 +51,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a SQL Server, with 2 firewall rules. - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineElasticPool(elasticPoolName).withStandardPool().attach() - .defineDatabase(database1Name).withExistingElasticPool(elasticPoolName).attach() - .defineDatabase(database2Name).withExistingElasticPool(elasticPoolName).attach() - .create(); + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineElasticPool(elasticPoolName) + .withStandardPool() + .attach() + .defineDatabase(database1Name) + .withExistingElasticPool(elasticPoolName) + .attach() + .defineDatabase(database2Name) + .withExistingElasticPool(elasticPoolName) + .attach() + .create(); Utils.print(sqlServer); // ============================================================ // List and prints the elastic pools - for (SqlElasticPool elasticPool: sqlServer.elasticPools().list()) { + for (SqlElasticPool elasticPool : sqlServer.elasticPools().list()) { Utils.print(elasticPool); } @@ -78,16 +84,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Change DTUs in the elastic pools. elasticPool = elasticPool.update() - .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_200) - .withStorageCapacity(204800 * 1024 * 1024L) - .withDatabaseMinCapacity(10) - .withDatabaseMaxCapacity(50) - .apply(); + .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_200) + .withStorageCapacity(204800 * 1024 * 1024L) + .withDatabaseMinCapacity(10) + .withDatabaseMaxCapacity(50) + .apply(); Utils.print(elasticPool); System.out.println("Start ------- Current databases in the elastic pool"); - for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + for (SqlDatabase databaseInElasticPool : elasticPool.listDatabases()) { Utils.print(databaseInElasticPool); } System.out.println("End --------- Current databases in the elastic pool"); @@ -96,13 +102,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a Database in SQL server created above. System.out.println("Creating a database"); - SqlDatabase database = sqlServer.databases() - .define("myNewDatabase") - .create(); + SqlDatabase database = sqlServer.databases().define("myNewDatabase").create(); Utils.print(database); System.out.println("Start ------- Current databases in the elastic pool"); - for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + for (SqlDatabase databaseInElasticPool : elasticPool.listDatabases()) { Utils.print(databaseInElasticPool); } System.out.println("End --------- Current databases in the elastic pool"); @@ -110,24 +114,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Move newly created database to the pool. System.out.println("Updating a database"); - database = database.update() - .withExistingElasticPool(elasticPoolName) - .apply(); + database = database.update().withExistingElasticPool(elasticPoolName).apply(); Utils.print(database); // ============================================================ // Create another database and move it in elastic pool as update to the elastic pool. - SqlDatabase anotherDatabase = sqlServer.databases().define(anotherDatabaseName) - .create(); + SqlDatabase anotherDatabase = sqlServer.databases().define(anotherDatabaseName).create(); // ============================================================ // Update the elastic pool to have newly created database. - elasticPool.update() - .withExistingDatabase(anotherDatabase) - .apply(); + elasticPool.update().withExistingDatabase(anotherDatabase).apply(); System.out.println("Start ------- Current databases in the elastic pool"); - for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + for (SqlDatabase databaseInElasticPool : elasticPool.listDatabases()) { Utils.print(databaseInElasticPool); } System.out.println("End --------- Current databases in the elastic pool"); @@ -136,23 +135,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Remove the database from the elastic pool. System.out.println("Remove the database from the pool."); anotherDatabase = anotherDatabase.update() - .withoutElasticPool() - .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) - .withMaxSizeBytes(1024 * 1024 * 1024 * 20) - .apply(); + .withoutElasticPool() + .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) + .withMaxSizeBytes(1024 * 1024 * 1024 * 20) + .apply(); Utils.print(anotherDatabase); System.out.println("Start ------- Current databases in the elastic pool"); - for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + for (SqlDatabase databaseInElasticPool : elasticPool.listDatabases()) { Utils.print(databaseInElasticPool); } System.out.println("End --------- Current databases in the elastic pool"); - // ============================================================ // Get list of elastic pool's activities and print the same. System.out.println("Start ------- Activities in a elastic pool"); - for (ElasticPoolActivity activity: elasticPool.listActivities()) { + for (ElasticPoolActivity activity : elasticPool.listActivities()) { Utils.print(activity); } System.out.println("End ------- Activities in a elastic pool"); @@ -160,7 +158,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // List databases in the sql server and delete the same. System.out.println("List and delete all databases from SQL Server"); - for (SqlDatabase databaseInServer: sqlServer.databases().list()) { + for (SqlDatabase databaseInServer : sqlServer.databases().list()) { Utils.print(databaseInServer); // Can not delete reserved database "master" if (!databaseInServer.name().equals("master")) { @@ -171,9 +169,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create another elastic pool in SQL Server System.out.println("Create ElasticPool in existing SQL Server"); - SqlElasticPool elasticPool2 = sqlServer.elasticPools().define(elasticPool2Name) - .withStandardPool() - .create(); + SqlElasticPool elasticPool2 = sqlServer.elasticPools().define(elasticPool2Name).withStandardPool().create(); Utils.print(elasticPool2); @@ -210,8 +206,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); @@ -230,5 +225,4 @@ private ManageSqlDatabaseInElasticPool() { } - } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java index 448850df54247..e41c4561147d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -49,24 +48,25 @@ public final class ManageSqlDatabasesAcrossDifferentDataCenters { */ public static boolean runSample(AzureResourceManager azureResourceManager) { final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); - final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDRE", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDRE", 20); final String administratorLogin = "sqladmin3423"; final String administratorPassword = Utils.password(); - final String slaveSqlServer1Name = Utils.randomResourceName(azureResourceManager, "slave1sql", 20); - final String slaveSqlServer2Name = Utils.randomResourceName(azureResourceManager, "slave2sql", 20); + final String slaveSqlServer1Name = Utils.randomResourceName(azureResourceManager, "slave1sql", 20); + final String slaveSqlServer2Name = Utils.randomResourceName(azureResourceManager, "slave2sql", 20); final String databaseName = "mydatabase"; - final String networkPrefix = "network"; - final String virtualMachinePrefix = "samplevm"; + final String networkPrefix = "network"; + final String virtualMachinePrefix = "samplevm"; try { // ============================================================ // Create a SQL Server, with 2 firewall rules. - SqlServer masterSqlServer = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); + SqlServer masterSqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); Utils.print(masterSqlServer); @@ -74,9 +74,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a Database in master SQL server created above. System.out.println("Creating a database"); - SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName) - .withBasicEdition() - .create(); + SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName).withBasicEdition().create(); Utils.print(masterDatabase); // ============================================================ @@ -84,38 +82,40 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating server in secondary location for master SQL Server"); SqlServer sqlServerInSecondaryLocation = azureResourceManager.sqlServers() - .define(slaveSqlServer1Name) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); + .define(slaveSqlServer1Name) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); Utils.print(sqlServerInSecondaryLocation); System.out.println("Creating database in slave SQL Server."); - SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases().define(databaseName) - .withSourceDatabase(masterDatabase) - .withMode(CreateMode.ONLINE_SECONDARY) - .create(); + SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases() + .define(databaseName) + .withSourceDatabase(masterDatabase) + .withMode(CreateMode.ONLINE_SECONDARY) + .create(); Utils.print(secondaryDatabase); // ============================================================ // Create another slave SQLServer/Database for the master database System.out.println("Creating server in another location for master SQL Server"); SqlServer sqlServerInEurope = azureResourceManager.sqlServers() - .define(slaveSqlServer2Name) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); + .define(slaveSqlServer2Name) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); Utils.print(sqlServerInEurope); System.out.println("Creating database in second slave SQL Server."); - SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases().define(databaseName) - .withSourceDatabase(masterDatabase) - .withMode(CreateMode.ONLINE_SECONDARY) - .create(); + SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases() + .define(databaseName) + .withSourceDatabase(masterDatabase) + .withMode(CreateMode.ONLINE_SECONDARY) + .create(); Utils.print(secondaryDatabaseInEurope); // ============================================================ @@ -132,10 +132,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating virtual networks in different regions."); - for (Region region: regions) { - creatableNetworks.add(azureResourceManager.networks().define(Utils.randomResourceName(azureResourceManager, networkPrefix, 20)) - .withRegion(region) - .withExistingResourceGroup(rgName)); + for (Region region : regions) { + creatableNetworks.add(azureResourceManager.networks() + .define(Utils.randomResourceName(azureResourceManager, networkPrefix, 20)) + .withRegion(region) + .withExistingResourceGroup(rgName)); } Collection networks = azureResourceManager.networks().create(creatableNetworks).values(); @@ -144,27 +145,31 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { List> creatableVirtualMachines = new ArrayList<>(); System.out.println("Creating virtual machines in different regions."); - for (Network network: networks) { + for (Network network : networks) { String virtualMachineName = Utils.randomResourceName(azureResourceManager, virtualMachinePrefix, 20); - Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses().define(virtualMachineName) - .withRegion(network.region()) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(virtualMachineName); - creatableVirtualMachines.add(azureResourceManager.virtualMachines().define(virtualMachineName) - .withRegion(network.region()) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(network.subnets().values().iterator().next().name()) - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername(administratorLogin) - .withAdminPassword(administratorPassword) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))); + Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses() + .define(virtualMachineName) + .withRegion(network.region()) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(virtualMachineName); + creatableVirtualMachines.add(azureResourceManager.virtualMachines() + .define(virtualMachineName) + .withRegion(network.region()) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(network.subnets().values().iterator().next().name()) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(administratorLogin) + .withAdminPassword(administratorPassword) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))); } HashMap ipAddresses = new HashMap<>(); - for (VirtualMachine virtualMachine: azureResourceManager.virtualMachines().create(creatableVirtualMachines).values()) { + for (VirtualMachine virtualMachine : azureResourceManager.virtualMachines() + .create(creatableVirtualMachines) + .values()) { ipAddresses.put(virtualMachine.name(), virtualMachine.getPrimaryPublicIPAddress().ipAddress()); } @@ -175,24 +180,24 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { sqlServers.add(sqlServerInEurope); sqlServers.add(masterSqlServer); - for (SqlServer sqlServer: sqlServers) { - for (Map.Entry ipAddress: ipAddresses.entrySet()) { + for (SqlServer sqlServer : sqlServers) { + for (Map.Entry ipAddress : ipAddresses.entrySet()) { sqlServer.firewallRules().define(ipAddress.getKey()).withIpAddress(ipAddress.getValue()).create(); } } - for (SqlServer sqlServer: sqlServers) { + for (SqlServer sqlServer : sqlServers) { System.out.println("Print firewall rules in Sql Server in " + sqlServer.regionName()); List firewallRules = sqlServer.firewallRules().list(); - for (SqlFirewallRule firewallRule: firewallRules) { + for (SqlFirewallRule firewallRule : firewallRules) { Utils.print(firewallRule); } } // Delete the SQL Server. System.out.println("Deleting all Sql Servers"); - for (SqlServer sqlServer: sqlServers) { + for (SqlServer sqlServer : sqlServers) { azureResourceManager.sqlServers().deleteById(sqlServer.id()); } return true; @@ -219,8 +224,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java index 6e3be306b9657..6a02342eac9d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java @@ -49,15 +49,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a primary SQL Server with a sample database. System.out.println("Creating a primary SQL Server with a sample database"); - SqlServer sqlPrimaryServer = azureResourceManager.sqlServers().define(sqlPrimaryServerName) + SqlServer sqlPrimaryServer = azureResourceManager.sqlServers() + .define(sqlPrimaryServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() .create(); Utils.print(sqlPrimaryServer); @@ -66,7 +67,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a secondary SQL Server with a sample database. System.out.println("Creating a secondary SQL Server with a sample database"); - SqlServer sqlSecondaryServer = azureResourceManager.sqlServers().define(sqlSecondaryServerName) + SqlServer sqlSecondaryServer = azureResourceManager.sqlServers() + .define(sqlSecondaryServerName) .withRegion(Region.US_EAST2) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) @@ -75,12 +77,12 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(sqlSecondaryServer); - // ============================================================ // Create a Failover Group from the primary SQL server to the secondary SQL server. System.out.println("Creating a Failover Group from the primary SQL server to the secondary SQL server"); - SqlFailoverGroup failoverGroup = sqlPrimaryServer.failoverGroups().define(failoverGroupName) + SqlFailoverGroup failoverGroup = sqlPrimaryServer.failoverGroups() + .define(failoverGroupName) .withManualReadWriteEndpointPolicy() .withPartnerServerId(sqlSecondaryServer.id()) .withReadOnlyEndpointPolicyDisabled() @@ -96,7 +98,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(failoverGroup); - // ============================================================ // Update the Failover Group Endpoint policies and tags. System.out.println("Updating the Failover Group Endpoint policies and tags"); @@ -109,10 +110,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(failoverGroup); - // ============================================================ // Update the Failover Group to add database and change read-write endpoint's failover policy. - System.out.println("Updating the Failover Group to add database and change read-write endpoint's failover policy"); + System.out.println( + "Updating the Failover Group to add database and change read-write endpoint's failover policy"); SqlDatabase db = sqlPrimaryServer.databases().get(dbName); @@ -126,7 +127,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(failoverGroup); - // ============================================================ // List the Failover Group on the secondary server. System.out.println("Listing the Failover Group on the secondary server"); @@ -150,8 +150,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { sqlPrimaryServer.failoverGroups().delete(failoverGroup.name()); - - // Delete the SQL Servers. System.out.println("Deleting the Sql Servers"); azureResourceManager.sqlServers().deleteById(sqlPrimaryServer.id()); @@ -179,8 +177,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java index 64a97ce582882..34590fc30888a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -52,17 +51,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a SQL Server, with 2 firewall rules. - System.out.println("Create a SQL server with 2 firewall rules adding a single IP Address and a range of IP Addresses"); - - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() - .defineFirewallRule("filewallRule2") - .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() - .create(); + System.out.println( + "Create a SQL server with 2 firewall rules adding a single IP Address and a range of IP Addresses"); + + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("filewallRule1") + .withIpAddress(firewallRuleIPAddress) + .attach() + .defineFirewallRule("filewallRule2") + .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress) + .attach() + .create(); Utils.print(sqlServer); @@ -71,7 +75,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Listing all firewall rules in SQL Server."); List firewallRules = sqlServer.firewallRules().list(); - for (SqlFirewallRule firewallRule: firewallRules) { + for (SqlFirewallRule firewallRule : firewallRules) { // Print information of the firewall rule. Utils.print(firewallRule); @@ -83,9 +87,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Add new firewall rules. System.out.println("Creating a firewall rule in existing SQL Server"); - SqlFirewallRule firewallRule = sqlServer.firewallRules().define(myFirewallName) - .withIpAddress(myFirewallRuleIPAddress) - .create(); + SqlFirewallRule firewallRule + = sqlServer.firewallRules().define(myFirewallName).withIpAddress(myFirewallRuleIPAddress).create(); Utils.print(firewallRule); @@ -96,13 +99,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Deleting and adding new firewall rules as part of SQL Server update."); sqlServer.update() - .withoutFirewallRule(myFirewallName) - .defineFirewallRule("filewallRule2") - .withIpAddressRange(otherFirewallRuleStartIPAddress, otherFirewallRuleEndIPAddress) - .attach() - .apply(); + .withoutFirewallRule(myFirewallName) + .defineFirewallRule("filewallRule2") + .withIpAddressRange(otherFirewallRuleStartIPAddress, otherFirewallRuleEndIPAddress) + .attach() + .apply(); - for (SqlFirewallRule sqlFirewallRule: sqlServer.firewallRules().list()) { + for (SqlFirewallRule sqlFirewallRule : sqlServer.firewallRules().list()) { // Print information of the firewall rule. Utils.print(sqlFirewallRule); } @@ -133,8 +136,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java index e784b4bca0246..20ab86c4e999c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -43,25 +42,26 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a SQL Server with one database from a sample. - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbFromSampleName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withBasicEdition() - .attach() + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withBasicEdition() + .attach() .create(); Utils.print(sqlServer); - SqlDatabase dbFromSample = sqlServer.databases() - .get(dbFromSampleName); + SqlDatabase dbFromSample = sqlServer.databases().get(dbFromSampleName); Utils.print(dbFromSample); // ============================================================ // Export a database from a SQL server created above to a new storage account within the same resource group. - System.out.println("Exporting a database from a SQL server created above to a new storage account within the same resource group."); + System.out.println( + "Exporting a database from a SQL server created above to a new storage account within the same resource group."); Creatable storageAccountCreatable = azureResourceManager.storageAccounts() .define(storageName) @@ -71,20 +71,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { dbFromSample.exportTo(storageAccountCreatable, "container-name", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) .execute(); - StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); + StorageAccount storageAccount + = azureResourceManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); // ============================================================ // Import a database within a new elastic pool from a storage account container created above. - System.out.println("Importing a database within a new elastic pool from a storage account container created above."); + System.out.println( + "Importing a database within a new elastic pool from a storage account container created above."); SqlDatabase dbFromImport = sqlServer.databases() .define("db-from-import1") - .defineElasticPool("epi") - .withStandardPool() - .attach() - .importFrom(storageAccount, "container-name", "dbfromsample.bacpac") - .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) - .create(); + .defineElasticPool("epi") + .withStandardPool() + .attach() + .importFrom(storageAccount, "container-name", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) + .create(); Utils.print(dbFromImport); // Delete the database. @@ -93,17 +95,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create an empty database within an elastic pool. - SqlDatabase dbEmpty = sqlServer.databases() - .define("db-from-import2") - .withExistingElasticPool("epi") - .create(); + SqlDatabase dbEmpty + = sqlServer.databases().define("db-from-import2").withExistingElasticPool("epi").create(); // ============================================================ // Import data from a BACPAC to an empty database within an elastic pool. System.out.println("Importing data from a BACPAC to an empty database within an elastic pool."); - dbEmpty - .importBacpac(storageAccount, "container-name", "dbfromsample.bacpac") + dbEmpty.importBacpac(storageAccount, "container-name", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) .execute(); Utils.print(dbFromImport); @@ -136,7 +135,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } - /** * Main entry point. * @param args the parameters @@ -149,8 +147,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java index 86873a4a71d6d..8cdc5d77d220a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -39,7 +38,8 @@ public class ManageSqlServerDnsAliases { * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(AzureResourceManager azureResourceManager) throws ClassNotFoundException, SQLException { + public static boolean runSample(AzureResourceManager azureResourceManager) + throws ClassNotFoundException, SQLException { final String sqlServerForTestName = Utils.randomResourceName(azureResourceManager, "sqltest", 20); final String sqlServerForProdName = Utils.randomResourceName(azureResourceManager, "sqlprod", 20); final String sqlServerDnsAlias = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); @@ -55,17 +55,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Create a "test" SQL Server. System.out.println("Creating a SQL server for test related activities"); - SqlServer sqlServerForTest = azureResourceManager.sqlServers().define(sqlServerForTestName) + SqlServer sqlServerForTest = azureResourceManager.sqlServers() + .define(sqlServerForTestName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineFirewallRule("allowAll") - .withIpAddressRange("0.0.0.1", "255.255.255.255") - .attach() + .withIpAddressRange("0.0.0.1", "255.255.255.255") + .attach() .defineDatabase(dbName) - .withBasicEdition() - .attach() + .withBasicEdition() + .attach() .create(); Utils.print(sqlServerForTest); @@ -74,15 +75,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Create a connection to the "test" SQL Server. System.out.println("Creating a connection to the \"test\" SQL Server"); String connectionToSqlTestUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", - sqlServerForTest.fullyQualifiedDomainName(), - dbName, - administratorLogin, - administratorPassword); + sqlServerForTest.fullyQualifiedDomainName(), dbName, administratorLogin, administratorPassword); // Establish the connection. try (Connection conTest = DriverManager.getConnection(connectionToSqlTestUrl); - Statement stmt = conTest.createStatement();) { - + Statement stmt = conTest.createStatement();) { // ============================================================ // Create a new table into the "test" SQL Server database and insert one value. @@ -95,22 +92,22 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw stmt.execute(sqlCommand); } - // ============================================================ // Create a "production" SQL Server. System.out.println("Creating a SQL server for production related activities"); - SqlServer sqlServerForProd = azureResourceManager.sqlServers().define(sqlServerForProdName) + SqlServer sqlServerForProd = azureResourceManager.sqlServers() + .define(sqlServerForProdName) .withRegion(Region.US_EAST2) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineFirewallRule("allowAll") - .withIpAddressRange("0.0.0.1", "255.255.255.255") - .attach() + .withIpAddressRange("0.0.0.1", "255.255.255.255") + .attach() .defineDatabase(dbName) - .withBasicEdition() - .attach() + .withBasicEdition() + .attach() .create(); Utils.print(sqlServerForProd); @@ -120,20 +117,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a connection to the \"production\" SQL Server"); String connectionToSqlProdUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", - sqlServerForProd.fullyQualifiedDomainName(), - dbName, - administratorLogin, - administratorPassword); + sqlServerForProd.fullyQualifiedDomainName(), dbName, administratorLogin, administratorPassword); // Establish the connection. try (Connection conProd = DriverManager.getConnection(connectionToSqlProdUrl); - Statement stmt1 = conProd.createStatement();) { - + Statement stmt1 = conProd.createStatement();) { // ============================================================ // Create a new table into the "production" SQL Server database and insert one value. - System.out.println("Creating a new table into the \"production\" SQL Server database and insert one value"); - + System.out + .println("Creating a new table into the \"production\" SQL Server database and insert one value"); String sqlCommand = "CREATE TABLE [Dns_Alias_Sample_Prod] ([Name] [varchar](30) NOT NULL)"; stmt1.execute(sqlCommand); @@ -142,25 +135,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw stmt1.execute(sqlCommand); } - // ============================================================ // Create a SQL Server DNS alias and use it to query the "test" database. System.out.println("Creating a SQL Server DNS alias and use it to query the \"test\" database"); - SqlServerDnsAlias dnsAlias = sqlServerForTest.dnsAliases() - .define(sqlServerDnsAlias) - .create(); + SqlServerDnsAlias dnsAlias = sqlServerForTest.dnsAliases().define(sqlServerDnsAlias).create(); ResourceManagerUtils.sleep(Duration.ofMinutes(5)); String connectionUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", - dnsAlias.azureDnsRecord(), - dbName, - administratorLogin, - administratorPassword); + dnsAlias.azureDnsRecord(), dbName, administratorLogin, administratorPassword); // Establish the connection. try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); - Statement stmt2 = conDnsAlias.createStatement();) { + Statement stmt2 = conDnsAlias.createStatement();) { String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Test;"; try (ResultSet resultSet = stmt2.executeQuery(sqlCommand);) { @@ -172,10 +159,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } - // ============================================================ // Use the "production" SQL Server to acquire the SQL Server DNS Alias and use it to query the "production" database. - System.out.println("Using the \"production\" SQL Server to acquire the SQL Server DNS Alias and use it to query the \"production\" database"); + System.out.println( + "Using the \"production\" SQL Server to acquire the SQL Server DNS Alias and use it to query the \"production\" database"); sqlServerForProd.dnsAliases().acquire(sqlServerDnsAlias, sqlServerForTest.id()); @@ -184,7 +171,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Re-establish the connection. try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); - Statement stmt = conDnsAlias.createStatement();) { + Statement stmt = conDnsAlias.createStatement();) { String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Prod;"; try (ResultSet resultSet = stmt.executeQuery(sqlCommand);) { @@ -223,8 +210,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java index ad0c203bcf26c..b5064b1d8ee29 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -56,7 +55,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create a SQL Server with system assigned managed service identity. System.out.println("Creating a SQL Server with system assigned managed service identity"); - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) @@ -70,17 +70,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Create an Azure Key Vault and set the access policies. System.out.println("Creating an Azure Key Vault and set the access policies"); - Vault vault = azureResourceManager.vaults().define(vaultName) + Vault vault = azureResourceManager.vaults() + .define(vaultName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .defineAccessPolicy() - .forObjectId(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY, KeyPermissions.GET, KeyPermissions.LIST) - .attach() + .forObjectId(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY, KeyPermissions.GET, + KeyPermissions.LIST) + .attach() .defineAccessPolicy() - .forServicePrincipal(objectId) - .allowKeyAllPermissions() - .attach() + .forServicePrincipal(objectId) + .allowKeyAllPermissions() + .attach() .withSku(SkuName.PREMIUM) .create(); @@ -93,7 +95,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin } } - Key keyBundle = vault.keys().define(keyName) + Key keyBundle = vault.keys() + .define(keyName) .withKeyTypeToCreate(KeyType.RSA_HSM) .withKeyOperations(keyOperations) .create(); @@ -105,16 +108,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin String keyUri = keyBundle.getJsonWebKey().getId(); // Work around for SQL server key name must be formatted as "vault_key_version" - String serverKeyName = String.format("%s_%s_%s", vaultName, keyName, - keyUri.substring(keyUri.lastIndexOf("/") + 1)); + String serverKeyName + = String.format("%s_%s_%s", vaultName, keyName, keyUri.substring(keyUri.lastIndexOf("/") + 1)); - SqlServerKey sqlServerKey = sqlServer.serverKeys().define() - .withAzureKeyVaultKey(keyUri) - .create(); + SqlServerKey sqlServerKey = sqlServer.serverKeys().define().withAzureKeyVaultKey(keyUri).create(); Utils.print(sqlServerKey); - // Validate key exists by getting key System.out.println("Validating key exists by getting the key"); @@ -122,7 +122,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin Utils.print(sqlServerKey); - // Validate key exists by listing keys System.out.println("Validating key exists by listing keys"); @@ -131,13 +130,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin Utils.print(item); } - // Delete key System.out.println("Deleting the key"); azureResourceManager.sqlServers().serverKeys().deleteBySqlServer(rgName, sqlServerName, serverKeyName); - // Delete the SQL Server. System.out.println("Deleting a Sql Server"); azureResourceManager.sqlServers().deleteById(sqlServer.id()); @@ -165,8 +162,7 @@ public static void main(String[] args) { .build(); final Configuration configuration = Configuration.getGlobalConfiguration(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java index 5e20ea526e6c0..f50883f9efc2b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java @@ -47,15 +47,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a primary SQL Server with a sample database. System.out.println("Creating a primary SQL Server with a sample database"); - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) .withRegion(region) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() .create(); Utils.print(sqlServer); @@ -63,7 +64,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create an Azure Storage Account and get the storage account blob entry point. System.out.println("Creating an Azure Storage Account and a storage account blob"); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); @@ -73,7 +75,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a Server Security Alert Policy. System.out.println("Creating a Server Security Alert Policy"); - sqlServer.serverSecurityAlertPolicies().define() + sqlServer.serverSecurityAlertPolicies() + .define() .withState(SecurityAlertPolicyState.ENABLED) .withEmailAccountAdmins() .withStorageEndpoint(blobEntrypoint, accountKey) @@ -81,13 +84,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { .withRetentionDays(5) .create(); - // ============================================================ // Get the Server Security Alert Policy. System.out.println("Getting the Server Security Alert Policy"); SqlServerSecurityAlertPolicy sqlSecurityAlertPolicy = sqlServer.serverSecurityAlertPolicies().get(); - // ============================================================ // Update the Server Security Alert Policy. System.out.println("Updating the Server Security Alert Policy"); @@ -97,7 +98,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { .withRetentionDays(1) .apply(); - // Delete the SQL Servers. System.out.println("Deleting the Sql Servers"); azureResourceManager.sqlServers().deleteById(sqlServer.id()); @@ -124,8 +124,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java index fe86584c9ebc6..9eb552460259e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -49,14 +48,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a virtual network with two subnets. System.out.println("Create a virtual network with two subnets: subnet1 and subnet2"); - Network virtualNetwork = azureResourceManager.networks().define(vnetName) + Network virtualNetwork = azureResourceManager.networks() + .define(vnetName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAddressSpace("192.168.0.0/16") .defineSubnet("subnet1") - .withAddressPrefix("192.168.1.0/24") - .withAccessFromService(ServiceEndpointType.MICROSOFT_SQL) - .attach() + .withAddressPrefix("192.168.1.0/24") + .withAccessFromService(ServiceEndpointType.MICROSOFT_SQL) + .attach() .withSubnet("subnet2", "192.168.2.0/24") .create(); @@ -68,28 +68,28 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create a SQL Server, with one virtual network rule. System.out.println("Create a SQL server with one virtual network rule"); - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .withoutAccessFromAzureServices() .defineVirtualNetworkRule("virtualNetworkRule1") - .withSubnet(virtualNetwork.id(), "subnet1") - .attach() + .withSubnet(virtualNetwork.id(), "subnet1") + .attach() .create(); Utils.print(sqlServer); - // ============================================================ // Get the virtual network rule created above. - SqlVirtualNetworkRule virtualNetworkRule = azureResourceManager.sqlServers().virtualNetworkRules() + SqlVirtualNetworkRule virtualNetworkRule = azureResourceManager.sqlServers() + .virtualNetworkRules() .getBySqlServer(rgName, sqlServerName, "virtualNetworkRule1"); Utils.print(virtualNetworkRule); - // ============================================================ // Add new virtual network rules. System.out.println("adding another virtual network rule in existing SQL Server"); @@ -101,17 +101,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(virtualNetworkRule); - // ============================================================ // Update a virtual network rules. System.out.println("Updating an existing virtual network rules in SQL Server."); - virtualNetworkRule.update() - .withSubnet(virtualNetwork.id(), "subnet1") - .apply(); + virtualNetworkRule.update().withSubnet(virtualNetwork.id(), "subnet1").apply(); Utils.print(virtualNetworkRule); - // ============================================================ // List and delete all virtual network rules. System.out.println("Listing all virtual network rules in SQL Server."); @@ -123,7 +119,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { vnetRule.delete(); } - // Delete the SQL Server. System.out.println("Deleting a Sql Server"); azureResourceManager.sqlServers().deleteById(sqlServer.id()); @@ -150,8 +145,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java index a290c6aa2c90b..c9b7b178ce6a9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.sql.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -48,30 +47,29 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Create a SQL Server with two databases from a sample. System.out.println("Creating a SQL Server with two databases from a sample."); - SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = azureResourceManager.sqlServers() + .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbToDeleteName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() .defineDatabase(dbToRestoreName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() .create(); Utils.print(sqlServer); // Sleep for 5 minutes to allow for the service to be aware of the new server and databases ResourceManagerUtils.sleep(Duration.ofMinutes(5)); - SqlDatabase dbToBeDeleted = sqlServer.databases() - .get(dbToDeleteName); + SqlDatabase dbToBeDeleted = sqlServer.databases().get(dbToDeleteName); Utils.print(dbToBeDeleted); - SqlDatabase dbToRestore = sqlServer.databases() - .get(dbToRestoreName); + SqlDatabase dbToRestore = sqlServer.databases().get(dbToRestoreName); Utils.print(dbToRestore); // ============================================================ @@ -91,17 +89,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { RestorePoint restorePointInTime = dbToRestore.listRestorePoints().get(0); // Restore point might not be ready right away and we will have to wait for it. OffsetDateTime currentTime = OffsetDateTime.now(); - long waitForRestoreToBeReady = ChronoUnit.MILLIS.between(currentTime, restorePointInTime.earliestRestoreDate()) - + 5 * 60 * 1000; + long waitForRestoreToBeReady + = ChronoUnit.MILLIS.between(currentTime, restorePointInTime.earliestRestoreDate()) + 5 * 60 * 1000; System.out.printf("waitForRestoreToBeReady %d%n", waitForRestoreToBeReady); if (waitForRestoreToBeReady > 0) { ResourceManagerUtils.sleep(Duration.ofMillis(waitForRestoreToBeReady)); } - SqlDatabase dbRestorePointInTime = sqlServer.databases() - .define("db-restore-pit") - .fromRestorePoint(restorePointInTime) - .create(); + SqlDatabase dbRestorePointInTime + = sqlServer.databases().define("db-restore-pit").fromRestorePoint(restorePointInTime).create(); Utils.print(dbRestorePointInTime); dbRestorePointInTime.delete(); @@ -116,7 +112,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Delete the database than loop until the restorable dropped database backup is available. - System.out.println("Deleting the database than loop until the restorable dropped database backup is available."); + System.out + .println("Deleting the database than loop until the restorable dropped database backup is available."); dbToBeDeleted.delete(); retries = 24; @@ -163,8 +160,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java index 4d80eeb9575bd..684489d0d39d5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java @@ -47,15 +47,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Storage Account"); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount); - // ============================================================ // Get | regenerate storage account access keys @@ -71,16 +71,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { Utils.print(storageAccountKeys); - // ============================================================ // Create another storage account System.out.println("Creating a 2nd Storage Account"); - StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(storageAccountName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount2 = azureResourceManager.storageAccounts() + .define(storageAccountName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount2); @@ -89,7 +89,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a V2 Storage Account"); - azureResourceManager.storageAccounts().define(storageAccountName3) + azureResourceManager.storageAccounts() + .define(storageAccountName3) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() @@ -106,15 +107,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { PagedIterable accounts = storageAccounts.listByResourceGroup(rgName); for (StorageAccount sa : accounts) { - System.out.println("Storage Account " + sa.name() - + " created @ " + sa.creationTime()); + System.out.println("Storage Account " + sa.name() + " created @ " + sa.creationTime()); } // ============================================================ // Delete a storage account - System.out.println("Deleting a storage account - " + storageAccount.name() - + " created @ " + storageAccount.creationTime()); + System.out.println("Deleting a storage account - " + storageAccount.name() + " created @ " + + storageAccount.creationTime()); azureResourceManager.storageAccounts().deleteById(storageAccount.id()); @@ -143,8 +143,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java index 7562c81b8ae2b..e64e082f721d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.storage.samples; - import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; @@ -41,19 +40,22 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) System.out.println("Creating a Storage Accounts"); Flux.merge( - azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .createAsync(), - azureResourceManager.storageAccounts().define(storageAccountName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .createAsync()) - .map(storageAccount -> { - System.out.println("Created a Storage Account:"); - Utils.print(storageAccount); - return storageAccount; - }).blockLast(); + azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .createAsync(), + azureResourceManager.storageAccounts() + .define(storageAccountName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .createAsync()) + .map(storageAccount -> { + System.out.println("Created a Storage Account:"); + Utils.print(storageAccount); + return storageAccount; + }) + .blockLast(); // ============================================================ // List storage accounts and regenerate storage account access keys @@ -62,31 +64,27 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) StorageAccounts storageAccounts = azureResourceManager.storageAccounts(); - storageAccounts.listByResourceGroupAsync(rgName) - .flatMap(storageAccount -> { - System.out.println("Getting storage account access keys for Storage Account " - + storageAccount.name() + " created @ " + storageAccount.creationTime()); - - return storageAccount.getKeysAsync() - .flatMap(storageAccountKeys -> { - System.out.println("Regenerating first storage account access key"); - return storageAccount.regenerateKeyAsync(storageAccountKeys.get(0).keyName()); - }); - }) - .map(storageAccountKeys -> { - Utils.print(storageAccountKeys); - return storageAccountKeys; - }).blockLast(); + storageAccounts.listByResourceGroupAsync(rgName).flatMap(storageAccount -> { + System.out.println("Getting storage account access keys for Storage Account " + storageAccount.name() + + " created @ " + storageAccount.creationTime()); + + return storageAccount.getKeysAsync().flatMap(storageAccountKeys -> { + System.out.println("Regenerating first storage account access key"); + return storageAccount.regenerateKeyAsync(storageAccountKeys.get(0).keyName()); + }); + }).map(storageAccountKeys -> { + Utils.print(storageAccountKeys); + return storageAccountKeys; + }).blockLast(); // ============================================================ // Delete storage accounts - storageAccounts.listByResourceGroupAsync(rgName) - .flatMap(storageAccount -> { - System.out.println("Deleting a storage account - " + storageAccount.name() - + " created @ " + storageAccount.creationTime()); - return azureResourceManager.storageAccounts().deleteByIdAsync(storageAccount.id()); - }).blockLast(); + storageAccounts.listByResourceGroupAsync(rgName).flatMap(storageAccount -> { + System.out.println("Deleting a storage account - " + storageAccount.name() + " created @ " + + storageAccount.creationTime()); + return azureResourceManager.storageAccounts().deleteByIdAsync(storageAccount.id()); + }).blockLast(); return true; } finally { @@ -112,8 +110,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java index 7799eec803d0e..22bf4dc628ea4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java @@ -61,7 +61,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Create a storage account with system assigned managed service identity - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) .withRegion(region) .withNewResourceGroup(rgName) .withInfrastructureEncryption() @@ -73,17 +74,18 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Create a key vault with purge protection enabled and access policy for managed service identity of storage account - Vault vault = azureResourceManager.vaults().define(vaultName) + Vault vault = azureResourceManager.vaults() + .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() // access policy for this sample client to generate key - .forServicePrincipal(clientId) - .allowKeyAllPermissions() - .attach() + .forServicePrincipal(clientId) + .allowKeyAllPermissions() + .attach() .defineAccessPolicy() // access policy for storage account managed service identity - .forObjectId(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .withPurgeProtectionEnabled() .create(); @@ -92,21 +94,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Create a key for storage account, RSA 2048, 3072 or 4096 - vault.keys().define("sakey") - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + vault.keys().define("sakey").withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); //============================================================ // Create a diagnostic setting on key vault and save audit logs to storage account - StorageAccount auditStorageAccount = azureResourceManager.storageAccounts().define(auditStorageAccountName) + StorageAccount auditStorageAccount = azureResourceManager.storageAccounts() + .define(auditStorageAccountName) .withRegion(region) .withExistingResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); - azureResourceManager.diagnosticSettings().define(diagnosticSettingName) + azureResourceManager.diagnosticSettings() + .define(diagnosticSettingName) .withResource(vault.id()) .withStorageAccount(auditStorageAccount.id()) .withLog("AuditEvent", 90) @@ -115,9 +116,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Enable customer-managed key in storage account - storageAccount.update() - .withEncryptionKeyFromKeyVault(vault.vaultUri(), "sakey", null) - .apply(); + storageAccount.update().withEncryptionKeyFromKeyVault(vault.vaultUri(), "sakey", null).apply(); Utils.print(storageAccount); @@ -126,16 +125,15 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin //============================================================ // Create a container and upload a blob - azureResourceManager.storageBlobContainers().defineContainer(containerName) + azureResourceManager.storageBlobContainers() + .defineContainer(containerName) .withExistingStorageAccount(rgName, storageAccountName) .withPublicAccess(PublicAccess.NONE) .create(); BlobClient blobClient = new BlobClientBuilder() - .connectionString( - ResourceManagerUtils.getStorageConnectionString( - storageAccountName, storageAccountKey, - azureResourceManager.storageAccounts().manager().environment())) + .connectionString(ResourceManagerUtils.getStorageConnectionString(storageAccountName, storageAccountKey, + azureResourceManager.storageAccounts().manager().environment())) .containerName(containerName) .blobName("data.txt") .buildClient(); @@ -172,10 +170,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Browse audit logs saved in storage account BlobContainerClient containerClient = new BlobContainerClientBuilder() - .connectionString( - ResourceManagerUtils.getStorageConnectionString( - auditStorageAccountName, auditStorageAccount.getKeys().iterator().next().value(), - azureResourceManager.storageAccounts().manager().environment())) + .connectionString(ResourceManagerUtils.getStorageConnectionString(auditStorageAccountName, + auditStorageAccount.getKeys().iterator().next().value(), + azureResourceManager.storageAccounts().manager().environment())) .containerName("insights-logs-auditevent") .buildClient(); @@ -207,8 +204,7 @@ public static void main(String[] args) { .build(); final Configuration configuration = Configuration.getGlobalConfiguration(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java index c519d87573a4a..c1874ca44fab2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java @@ -49,15 +49,16 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Virtual network and subnet with storage service subnet access enabled:"); - final Network network = azureResourceManager.networks().define(networkName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .defineSubnet(subnetName) - .withAddressPrefix("10.0.0.8/29") - .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) - .attach() - .create(); + final Network network = azureResourceManager.networks() + .define(networkName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .defineSubnet(subnetName) + .withAddressPrefix("10.0.0.8/29") + .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) + .attach() + .create(); System.out.println("Created a Virtual network with subnet:"); Utils.print(network); @@ -69,12 +70,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a storage account with access allowed only from the subnet :" + subnetId); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withAccessFromSelectedNetworks() - .withAccessFromNetworkSubnet(subnetId) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withAccessFromSelectedNetworks() + .withAccessFromNetworkSubnet(subnetId) + .create(); System.out.println("Created storage account:"); Utils.print(storageAccount); @@ -85,11 +87,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a Public IP address"); final PublicIpAddress publicIPAddress = azureResourceManager.publicIpAddresses() - .define(publicIpName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(publicIpName) - .create(); + .define(publicIpName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(publicIpName) + .create(); System.out.println("Created Public IP address:"); Utils.print(publicIPAddress); @@ -100,17 +102,17 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating a VM with the Public IP address"); VirtualMachine linuxVM = azureResourceManager.virtualMachines() - .define(vmName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withNewPrimaryNetwork("10.1.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIPAddress) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tirekicker") - .withRootPassword(Utils.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + .define(vmName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withNewPrimaryNetwork("10.1.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIPAddress) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tirekicker") + .withRootPassword(Utils.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); System.out.println("Created the VM: " + linuxVM.id()); Utils.print(linuxVM); @@ -120,11 +122,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // ============================================================ // Update the storage account so that it can also be accessed from the PublicIP address - System.out.println("Updating storage account with access also allowed from publicIP :" + publicIPAddress.ipAddress()); + System.out.println( + "Updating storage account with access also allowed from publicIP :" + publicIPAddress.ipAddress()); - storageAccount.update() - .withAccessFromIpAddress(publicIPAddress.ipAddress()) - .apply(); + storageAccount.update().withAccessFromIpAddress(publicIPAddress.ipAddress()).apply(); System.out.println("Updated storage account:"); Utils.print(storageAccount); @@ -134,9 +135,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Restricting access to storage account only via HTTPS"); - storageAccount.update() - .withOnlyHttpsTraffic() - .apply(); + storageAccount.update().withOnlyHttpsTraffic().apply(); System.out.println("Updated the storage account:"); Utils.print(storageAccount); @@ -165,8 +164,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java index 3b42887036876..14bc6a6902563 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java @@ -42,21 +42,17 @@ public final class ManageSimpleTrafficManager { public static boolean runSample(AzureResourceManager azureResourceManager) { final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOPD", 24); final String userName = "tirekicker"; - final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final String sshKey + = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; final int vmCountPerRegion = 2; - Set regions = new HashSet<>(Arrays.asList( - Region.US_EAST2, - Region.ASIA_SOUTHEAST - )); + Set regions = new HashSet<>(Arrays.asList(Region.US_EAST2, Region.ASIA_SOUTHEAST)); try { //============================================================= // Create a shared resource group for all the resources so they can all be deleted together // - ResourceGroup resourceGroup = azureResourceManager.resourceGroups() - .define(rgName) - .withRegion(Region.US_EAST2) - .create(); + ResourceGroup resourceGroup + = azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create(); System.out.println("Created a new resource group - " + resourceGroup.id()); @@ -70,21 +66,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { //============================================================= // Create a virtual machine in its own virtual network String vmName = String.format("%s-%d", linuxVMNamePrefix, i); - Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork("10.0.0.0/29") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(vmName) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername(userName) - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable vmDefinition = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/29") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(vmName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); creatableVirtualMachines.add(vmDefinition); } } - //============================================================= // Create the VMs !! @@ -92,7 +88,8 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { System.out.println("Creating the virtual machines..."); stopwatch.start(); - Collection virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); + Collection virtualMachines + = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); stopwatch.stop(); System.out.println(String.format("Created virtual machines in %d seconds.", stopwatch.getTime() / 1000)); @@ -101,20 +98,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { // Create 1 traffic manager profile // String trafficManagerName = Utils.randomResourceName(azureResourceManager, "tra", 15); - TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azureResourceManager.trafficManagerProfiles() + TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint + = azureResourceManager.trafficManagerProfiles() .define(trafficManagerName) - .withExistingResourceGroup(resourceGroup) - .withLeafDomainLabel(trafficManagerName) - .withPerformanceBasedRouting(); + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(trafficManagerName) + .withPerformanceBasedRouting(); TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null; int routingPriority = 1; for (VirtualMachine vm : virtualMachines) { String endpointName = Utils.randomResourceName(azureResourceManager, "ep", 15); profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName) - .toResourceId(vm.getPrimaryPublicIPAddressId()) - .withRoutingPriority(routingPriority++) - .attach(); + .toResourceId(vm.getPrimaryPublicIPAddressId()) + .withRoutingPriority(routingPriority++) + .attach(); } stopwatch.reset(); @@ -123,15 +121,14 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { TrafficManagerProfile trafficManagerProfile = profileWithCreate.create(); stopwatch.stop(); - System.out.printf("Created a traffic manager profile %s in %d seconds.%n", trafficManagerProfile.id(), stopwatch.getTime() / 1000); + System.out.printf("Created a traffic manager profile %s in %d seconds.%n", trafficManagerProfile.id(), + stopwatch.getTime() / 1000); //============================================================= // Modify the traffic manager to use priority based routing // - trafficManagerProfile.update() - .withPriorityBasedRouting() - .apply(); + trafficManagerProfile.update().withPriorityBasedRouting().apply(); System.out.println("Modified the traffic manager to use priority-based routing."); return true; @@ -148,6 +145,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { } } } + /** * Main entry point. * @param args the parameters @@ -162,8 +160,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java index f1bba3cbba6be..aead2f5aee404 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java @@ -42,21 +42,20 @@ */ public final class ManageTrafficManager { - /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { - final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); - final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")] - final String certPassword = "StrongPass!12"; - final String appServicePlanNamePrefix = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); - final String webAppNamePrefix = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); - final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); - final List regions = new ArrayList<>(); + final String certPassword = "StrongPass!12"; + final String appServicePlanNamePrefix = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); + final String webAppNamePrefix = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); + final List regions = new ArrayList<>(); // The regions in which web app needs to be created // regions.add(Region.US_WEST2); @@ -65,31 +64,30 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw regions.add(Region.US_CENTRAL); try { - azureResourceManager.resourceGroups().define(rgName) - .withRegion(Region.US_WEST) - .create(); + azureResourceManager.resourceGroups().define(rgName).withRegion(Region.US_WEST).create(); //============================================================ // Purchase a domain (will be canceled for a full refund) System.out.println("Purchasing a domain " + domainName + "..."); - AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) - .withExistingResourceGroup(rgName) - .defineRegistrantContact() - .withFirstName("Jon") - .withLastName("Doe") - .withEmail("jondoe@contoso.com") - .withAddressLine1("123 4th Ave") - .withCity("Redmond") - .withStateOrProvince("WA") - .withCountry(CountryIsoCode.UNITED_STATES) - .withPostalCode("98052") - .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) - .withPhoneNumber("4258828080") - .attach() - .withDomainPrivacyEnabled(true) - .withAutoRenewEnabled(false) - .create(); + AppServiceDomain domain = azureResourceManager.appServiceDomains() + .define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); @@ -111,12 +109,13 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw for (Region region : regions) { String planName = appServicePlanNamePrefix + id; System.out.println("Creating an app service plan " + planName + " in region " + region + "..."); - AppServicePlan appServicePlan = azureResourceManager.appServicePlans().define(planName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withPricingTier(PricingTier.BASIC_B1) - .withOperatingSystem(OperatingSystem.WINDOWS) - .create(); + AppServicePlan appServicePlan = azureResourceManager.appServicePlans() + .define(planName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.BASIC_B1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); System.out.println("Created app service plan " + planName); Utils.print(appServicePlan); appServicePlans.add(appServicePlan); @@ -129,21 +128,23 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw id = 0; for (AppServicePlan appServicePlan : appServicePlans) { String webAppName = webAppNamePrefix + id; - System.out.println("Creating a web app " + webAppName + " using the plan " + appServicePlan.name() + "..."); - WebApp webApp = azureResourceManager.webApps().define(webAppName) - .withExistingWindowsPlan(appServicePlan) - .withExistingResourceGroup(rgName) - .withManagedHostnameBindings(domain, webAppName) - .defineSslBinding() - .forHostname(webAppName + "." + domain.name()) - .withPfxCertificateToUpload(new File(pfxPath), certPassword) - .withSniBasedSsl() - .attach() - .defineSourceControl() - .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") - .withBranch("master") - .attach() - .create(); + System.out + .println("Creating a web app " + webAppName + " using the plan " + appServicePlan.name() + "..."); + WebApp webApp = azureResourceManager.webApps() + .define(webAppName) + .withExistingWindowsPlan(appServicePlan) + .withExistingResourceGroup(rgName) + .withManagedHostnameBindings(domain, webAppName) + .defineSslBinding() + .forHostname(webAppName + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); System.out.println("Created web app " + webAppName); Utils.print(webApp); webApps.add(webApp); @@ -154,18 +155,19 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Creates a traffic manager profile System.out.println("Creating a traffic manager profile " + tmName + " for the web apps..."); - TrafficManagerProfile.DefinitionStages.WithEndpoint tmDefinition = azureResourceManager.trafficManagerProfiles() + TrafficManagerProfile.DefinitionStages.WithEndpoint tmDefinition + = azureResourceManager.trafficManagerProfiles() .define(tmName) - .withExistingResourceGroup(rgName) - .withLeafDomainLabel(tmName) - .withPriorityBasedRouting(); + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(tmName) + .withPriorityBasedRouting(); Creatable tmCreatable = null; int priority = 1; for (WebApp webApp : webApps) { tmCreatable = tmDefinition.defineAzureTargetEndpoint("endpoint-" + priority) - .toResourceId(webApp.id()) - .withRoutingPriority(priority) - .attach(); + .toResourceId(webApp.id()) + .withRoutingPriority(priority) + .attach(); priority++; } TrafficManagerProfile trafficManagerProfile = tmCreatable.create(); @@ -177,11 +179,11 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Disabling and removing endpoint..."); trafficManagerProfile = trafficManagerProfile.update() - .updateAzureTargetEndpoint("endpoint-1") - .withTrafficDisabled() - .parent() - .withoutEndpoint("endpoint-2") - .apply(); + .updateAzureTargetEndpoint("endpoint-1") + .withTrafficDisabled() + .parent() + .withoutEndpoint("endpoint-2") + .apply(); System.out.println("Endpoints updated"); //============================================================ @@ -189,10 +191,10 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Enabling endpoint..."); trafficManagerProfile = trafficManagerProfile.update() - .updateAzureTargetEndpoint("endpoint-1") - .withTrafficEnabled() - .parent() - .apply(); + .updateAzureTargetEndpoint("endpoint-1") + .withTrafficEnabled() + .parent() + .apply(); System.out.println("Endpoint updated"); Utils.print(trafficManagerProfile); @@ -200,27 +202,21 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw // Change/configure traffic manager routing method System.out.println("Changing traffic manager profile routing method..."); - trafficManagerProfile = trafficManagerProfile.update() - .withPerformanceBasedRouting() - .apply(); + trafficManagerProfile = trafficManagerProfile.update().withPerformanceBasedRouting().apply(); System.out.println("Changed traffic manager profile routing method"); //============================================================ // Disables the traffic manager profile System.out.println("Disabling traffic manager profile..."); - trafficManagerProfile.update() - .withProfileStatusDisabled() - .apply(); + trafficManagerProfile.update().withProfileStatusDisabled().apply(); System.out.println("Traffic manager profile disabled"); //============================================================ // Enables the traffic manager profile System.out.println("Enabling traffic manager profile..."); - trafficManagerProfile.update() - .withProfileStatusDisabled() - .apply(); + trafficManagerProfile.update().withProfileStatusDisabled().apply(); System.out.println("Traffic manager profile enabled"); //============================================================ @@ -242,6 +238,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw } } } + /** * Main entry point. * @param args the parameters @@ -256,8 +253,7 @@ public static void main(String[] args) { .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureResourceManager azureResourceManager = AzureResourceManager - .configure() + AzureResourceManager azureResourceManager = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java index 15032516f6a3f..d347b3c25f8c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.resourcemanager.samples; - import com.azure.core.test.annotation.DoNotRecord; import com.azure.resourcemanager.appplatform.samples.ManageSpringCloud; import org.junit.jupiter.api.Assertions; @@ -18,7 +17,8 @@ public class AppPlatformLiveOnlyTests extends SamplesTestBase { @Test @DoNotRecord(skipInPlayback = true) - public void testSpringCloud() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { + public void testSpringCloud() + throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { if (skipInPlayback()) { return; } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java index e3e3fab39cd50..cd34707cec157 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java @@ -71,11 +71,10 @@ public void testManageWebAppCosmosDbThroughKeyVault() { @Test @DoNotRecord(skipInPlayback = true) public void testManageFunctionAppLogs() throws IOException { - azureResourceManager = buildManager( - AzureResourceManager.class, + azureResourceManager = buildManager(AzureResourceManager.class, setReadTimeout(azureResourceManager.storageAccounts().manager().httpPipeline(), Duration.ofMinutes(10)), - new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), AzureEnvironment.AZURE) - ); + new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), + AzureEnvironment.AZURE)); Assertions.assertTrue(ManageFunctionAppLogs.runSample(azureResourceManager)); } @@ -85,11 +84,10 @@ public void testManageWebAppLogs() throws IOException { if (skipInPlayback()) { return; } - azureResourceManager = buildManager( - AzureResourceManager.class, + azureResourceManager = buildManager(AzureResourceManager.class, setReadTimeout(azureResourceManager.storageAccounts().manager().httpPipeline(), Duration.ofMinutes(10)), - new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), AzureEnvironment.AZURE) - ); + new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), + AzureEnvironment.AZURE)); Assertions.assertTrue(ManageWebAppLogs.runSample(azureResourceManager)); } @@ -99,12 +97,7 @@ private HttpPipeline setReadTimeout(HttpPipeline httpPipeline, Duration timeout) builder.policies(httpPipeline.getPolicy(i)); } builder.httpClient( - super.generateHttpClientWithProxy( - new NettyAsyncHttpClientBuilder() - .readTimeout(timeout), - null - ) - ); + super.generateHttpClientWithProxy(new NettyAsyncHttpClientBuilder().readTimeout(timeout), null)); return builder.build(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ComputeSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ComputeSampleTests.java index cd7bd80e7e5ba..0bc8de0340dc2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ComputeSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ComputeSampleTests.java @@ -164,7 +164,8 @@ public void testManageStorageFromMSIEnabledVirtualMachine() { @Test public void testManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup() { - Assertions.assertTrue(ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.runSample(azureResourceManager)); + Assertions + .assertTrue(ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.runSample(azureResourceManager)); } @Test @@ -197,7 +198,8 @@ public void testCreateVirtualMachineEncryptedUsingCustomerManagedKey() { final Configuration configuration = Configuration.getGlobalConfiguration(); String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); Assertions.assertNotNull(clientId); - Assertions.assertTrue(CreateVirtualMachineEncryptedUsingCustomerManagedKey.runSample(azureResourceManager, clientId)); + Assertions + .assertTrue(CreateVirtualMachineEncryptedUsingCustomerManagedKey.runSample(azureResourceManager, clientId)); } @DoNotRecord(skipInPlayback = true) @@ -213,6 +215,7 @@ public void testCreateVirtualMachineWithTrustedLaunchFromGalleryImage() { @Test public void testCreateMultipleVirtualMachinesAndBatchQueryStatus() { - Assertions.assertTrue(CreateMultipleVirtualMachinesAndBatchQueryStatus.runSample(azureResourceManager, resourceGraphManager)); + Assertions.assertTrue( + CreateMultipleVirtualMachinesAndBatchQueryStatus.runSample(azureResourceManager, resourceGraphManager)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java index dc68ba20b2028..cc1ec9d603db4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java @@ -27,7 +27,8 @@ public void testManageContainerInstanceWithAzureFileShareMount() { public void testManageContainerInstanceWithManualAzureFileShareMountCreation() { // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time if (!isPlaybackMode()) { - Assertions.assertTrue(ManageContainerInstanceWithManualAzureFileShareMountCreation.runSample(azureResourceManager)); + Assertions.assertTrue( + ManageContainerInstanceWithManualAzureFileShareMountCreation.runSample(azureResourceManager)); } } @@ -40,10 +41,12 @@ public void testManageContainerInstanceWithMultipleContainerImages() { } @Test - public void testManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator() throws InterruptedException, JSchException, IOException { + public void testManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator() + throws InterruptedException, JSchException, IOException { // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time if (!isPlaybackMode()) { - Assertions.assertTrue(ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.runSample(azureResourceManager, "", "")); + Assertions.assertTrue(ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator + .runSample(azureResourceManager, "", "")); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/GraphRbacTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/GraphRbacTests.java index cee28b95644cb..23cdf76c85f79 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/GraphRbacTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/GraphRbacTests.java @@ -37,10 +37,10 @@ public void testManageUsersGroupsAndRoles() { Assertions.assertTrue(ManageUsersGroupsAndRoles.runSample(azureResourceManager, profile)); } -// @Test -// public void testManageServicePrincipal() { -// Assertions.assertTrue(ManageServicePrincipal.runSample(authenticated, defaultSubscription)); -// } + // @Test + // public void testManageServicePrincipal() { + // Assertions.assertTrue(ManageServicePrincipal.runSample(authenticated, defaultSubscription)); + // } @Test @DoNotRecord(skipInPlayback = true) @@ -53,21 +53,10 @@ public void testManageServicePrincipalCredentials() throws IOException { } @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -80,4 +69,3 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile protected void cleanUpResources() { } } - diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java index 45504aafc5327..b954348e2cdd2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java @@ -26,7 +26,8 @@ public void testManageKubernetesClusterWithAdvancedNetworking() { } @Test - public void testDeployImageFromContainerRegistryToKubernetes() throws JSchException, IOException, InterruptedException { + public void testDeployImageFromContainerRegistryToKubernetes() + throws JSchException, IOException, InterruptedException { if (!isPlaybackMode()) { Assertions.assertTrue(DeployImageFromContainerRegistryToKubernetes.runSample(azureResourceManager, "", "")); } @@ -35,6 +36,7 @@ public void testDeployImageFromContainerRegistryToKubernetes() throws JSchExcept @Test @DoNotRecord(skipInPlayback = true) public void testManagedKubernetesClusterWithCustomerManagedKey() { - Assertions.assertTrue(ManageKubernetesClusterWithCustomerManagedKey.runSample(azureResourceManager, clientIdFromFile())); + Assertions.assertTrue( + ManageKubernetesClusterWithCustomerManagedKey.runSample(azureResourceManager, clientIdFromFile())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ManagedHsmTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ManagedHsmTests.java index 054175631beeb..8ee6a4f639e82 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ManagedHsmTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ManagedHsmTests.java @@ -70,21 +70,10 @@ public class ManagedHsmTests extends SamplesTestBase { private KeyVaultManager keyVaultManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -124,34 +113,41 @@ public void canOperateManagedHsmAndKeys() throws Exception { activateManagedHsm(managedHsm); // getByResourceGroup - ManagedHsm hsm = keyVaultManager.managedHsms() - .getByResourceGroup(rgName, managedHsm.name()); + ManagedHsm hsm = keyVaultManager.managedHsms().getByResourceGroup(rgName, managedHsm.name()); - KeyVaultAccessControlAsyncClient accessControlAsyncClient = - new KeyVaultAccessControlClientBuilder() - .pipeline(keyVaultManager.httpPipeline()) + KeyVaultAccessControlAsyncClient accessControlAsyncClient + = new KeyVaultAccessControlClientBuilder().pipeline(keyVaultManager.httpPipeline()) .vaultUrl(managedHsm.hsmUri()) .buildAsyncClient(); // create role assignments // cryptoUser for key operations - KeyVaultRoleDefinition cryptoUser = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto User"); - accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.KEYS, cryptoUser.getId(), managedHsm.initialAdminObjectIds().get(0)).block(); + KeyVaultRoleDefinition cryptoUser + = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto User"); + accessControlAsyncClient + .createRoleAssignment(KeyVaultRoleScope.KEYS, cryptoUser.getId(), + managedHsm.initialAdminObjectIds().get(0)) + .block(); // key operations, same interface as the key vault Keys keys = hsm.keys(); String keyName = generateRandomResourceName("key", 10); - Key key = keys.define(keyName) - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key key = keys.define(keyName).withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); // cryptoUser for managing individual key - KeyVaultRoleDefinition cryptoUserForKey = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto User"); - accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.fromString(String.format("/keys/%s", keyName)), cryptoUserForKey.getId(), managedHsm.initialAdminObjectIds().get(0)).block(); + KeyVaultRoleDefinition cryptoUserForKey + = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto User"); + accessControlAsyncClient + .createRoleAssignment(KeyVaultRoleScope.fromString(String.format("/keys/%s", keyName)), + cryptoUserForKey.getId(), managedHsm.initialAdminObjectIds().get(0)) + .block(); // cryptoOfficer for polling deleted key status - KeyVaultRoleDefinition cryptoOfficer = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto Officer"); - accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.KEYS, cryptoOfficer.getId(), managedHsm.initialAdminObjectIds().get(0)).block(); + KeyVaultRoleDefinition cryptoOfficer + = getRoleDefinitionByName(accessControlAsyncClient, "Managed HSM Crypto Officer"); + accessControlAsyncClient + .createRoleAssignment(KeyVaultRoleScope.KEYS, cryptoOfficer.getId(), + managedHsm.initialAdminObjectIds().get(0)) + .block(); keys.deleteById(key.id()); } finally { @@ -160,8 +156,13 @@ public void canOperateManagedHsmAndKeys() throws Exception { } } - private KeyVaultRoleDefinition getRoleDefinitionByName(KeyVaultAccessControlAsyncClient accessControlAsyncClient, String roleName) { - return accessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.KEYS).toStream().filter(rd -> rd.getRoleName().equals(roleName)).findFirst().get(); + private KeyVaultRoleDefinition getRoleDefinitionByName(KeyVaultAccessControlAsyncClient accessControlAsyncClient, + String roleName) { + return accessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.KEYS) + .toStream() + .filter(rd -> rd.getRoleName().equals(roleName)) + .findFirst() + .get(); } /* @@ -174,9 +175,9 @@ private void activateManagedHsm(ManagedHsm managedHsm) throws Exception { keyPairGenerator.initialize(4096); // 1. generate ssl certificates - JsonWebKey key1 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); - JsonWebKey key2 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); - JsonWebKey key3 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); + JsonWebKey key1 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); + JsonWebKey key2 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); + JsonWebKey key3 = JsonWebKey.fromRsa(keyPairGenerator.generateKeyPair()); // 2. download security domain downloadSecurityDomain(managedHsm, key1, key2, key3); @@ -185,7 +186,8 @@ private void activateManagedHsm(ManagedHsm managedHsm) throws Exception { pollDownlaodStatusUntilSuccess(managedHsm); } - private void downloadSecurityDomain(ManagedHsm managedHsm, JsonWebKey key1, JsonWebKey key2, JsonWebKey key3) throws IOException { + private void downloadSecurityDomain(ManagedHsm managedHsm, JsonWebKey key1, JsonWebKey key2, JsonWebKey key3) + throws IOException { String url = String.format("%ssecuritydomain/download?api-version=7.2", managedHsm.hsmUri()); HttpRequest request = new HttpRequest(HttpMethod.POST, url); request.setHeader("Content-Type", "application/json charset=utf-8"); @@ -199,7 +201,8 @@ private void downloadSecurityDomain(ManagedHsm managedHsm, JsonWebKey key1, Json if (response.getStatusCode() != 202) { throw new RuntimeException("Failed to activate managed hsm"); } - Map responseBody = SerializerFactory.createDefaultManagementSerializerAdapter().deserialize(response.getBodyAsString().block(), Map.class, SerializerEncoding.JSON); + Map responseBody = SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize(response.getBodyAsString().block(), Map.class, SerializerEncoding.JSON); String securityDomainDownloadToken = (String) responseBody.get("value"); Assertions.assertNotNull(securityDomainDownloadToken); } @@ -208,29 +211,31 @@ private void pollDownlaodStatusUntilSuccess(ManagedHsm managedHsm) { String url = String.format("%ssecuritydomain/download/pending?api-version=7.2", managedHsm.hsmUri()); HttpRequest request = new HttpRequest(HttpMethod.GET, url); request.setHeader("Content-Type", "application/json charset=utf-8"); - Flux.interval(Duration.ZERO, ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(keyVaultManager.serviceClient().getDefaultPollInterval())) + Flux.interval(Duration.ZERO, + ResourceManagerUtils.InternalRuntimeContext + .getDelayDuration(keyVaultManager.serviceClient().getDefaultPollInterval())) .flatMap(ignored -> keyVaultManager.httpPipeline().send(request)) .flatMap(httpResponse -> { if (httpResponse.getStatusCode() != 200) { return Mono.error(new RuntimeException("Failed to poll security domain status")); } - return httpResponse.getBodyAsString() - .flatMap(bodyString -> { - try { - Map body = SerializerFactory.createDefaultManagementSerializerAdapter() - .deserialize(bodyString, Map.class, SerializerEncoding.JSON); - String status = (String) body.get("status"); - if (status == null) { - return Mono.error(new NullPointerException("status null")); - } - if (status.equals("Failed")) { - return Mono.error(new RuntimeException(String.format("Download security domain failed, message:%s", body.get("status_details")))); - } - return Mono.just(status); - } catch (IOException e) { - return Mono.error(e); + return httpResponse.getBodyAsString().flatMap(bodyString -> { + try { + Map body = SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize(bodyString, Map.class, SerializerEncoding.JSON); + String status = (String) body.get("status"); + if (status == null) { + return Mono.error(new NullPointerException("status null")); } - }); + if (status.equals("Failed")) { + return Mono.error(new RuntimeException(String + .format("Download security domain failed, message:%s", body.get("status_details")))); + } + return Mono.just(status); + } catch (IOException e) { + return Mono.error(e); + } + }); }) .takeUntil(status -> status.equals("Success")) .blockLast(); @@ -240,35 +245,28 @@ private void pollDownlaodStatusUntilSuccess(ManagedHsm managedHsm) { * create or get managed hsm instance */ private ManagedHsm createManagedHsm(String mhsmName) { - String objectId = azureResourceManager - .accessManagement() + String objectId = azureResourceManager.accessManagement() .servicePrincipals() .getByNameAsync(clientIdFromFile()) .block() .id(); keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create(); - ManagedHsmInner inner = keyVaultManager.serviceClient() - .getManagedHsms() - .createOrUpdate( - rgName, - mhsmName, - new ManagedHsmInner() - .withLocation(Region.US_EAST2.name()) + ManagedHsmInner inner + = keyVaultManager.serviceClient() + .getManagedHsms() + .createOrUpdate(rgName, mhsmName, new ManagedHsmInner().withLocation(Region.US_EAST2.name()) .withSku( new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1)) .withProperties( - new ManagedHsmProperties() - .withTenantId(UUID.fromString(azureResourceManager.tenantId())) + new ManagedHsmProperties().withTenantId(UUID.fromString(azureResourceManager.tenantId())) .withInitialAdminObjectIds(Arrays.asList(objectId)) .withEnableSoftDelete(true) .withSoftDeleteRetentionInDays(7) .withEnablePurgeProtection(false)), - Context.NONE); + Context.NONE); - keyVaultManager.serviceClient() - .getManagedHsms() - .createOrUpdate(rgName, inner.name(), inner); + keyVaultManager.serviceClient().getManagedHsms().createOrUpdate(rgName, inner.name(), inner); return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name()); } @@ -311,7 +309,9 @@ private static String base64X5c(byte[] publicBytes) throws Exception { } private static String base64Encode(byte[] digest) throws Exception { - return new String(Base64.getEncoder().encode(digest), "ascii").trim().replaceAll("\\+", "-").replaceAll("/", "_"); + return new String(Base64.getEncoder().encode(digest), "ascii").trim() + .replaceAll("\\+", "-") + .replaceAll("/", "_"); } public Collection getX5c() { diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/MonitorTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/MonitorTests.java index f16cee42058a0..72aba42feb400 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/MonitorTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/MonitorTests.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.samples; - import com.azure.core.test.annotation.DoNotRecord; import com.azure.resourcemanager.monitor.samples.AutoscaleSettingsBasedOnPerformanceOrSchedule; import com.azure.resourcemanager.monitor.samples.QueryMetricsAndActivityLogs; diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ResourceSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ResourceSampleTests.java index 127860e2b7696..28ba7af4d010a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ResourceSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ResourceSampleTests.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.samples; - import com.azure.resourcemanager.resources.samples.DeployUsingARMTemplate; import com.azure.resourcemanager.resources.samples.DeployUsingARMTemplateAsync; import com.azure.resourcemanager.resources.samples.DeployUsingARMTemplateWithDeploymentOperations; diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SamplesTestBase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SamplesTestBase.java index f64573425dacb..e2b319ed3099f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SamplesTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SamplesTestBase.java @@ -31,26 +31,14 @@ public SamplesTestBase() { addSanitizers( // Search key new TestProxySanitizer("$.key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$.value[*].key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) - ); + new TestProxySanitizer("$.value[*].key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)); } @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java index a28e55133b66c..e2ddb9e181763 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java @@ -95,7 +95,9 @@ public void testManageSqlServerKeysWithAzureKeyVaultKey() { if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); - if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + if (envSecondaryServicePrincipal == null + || !envSecondaryServicePrincipal.isEmpty() + || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } try { @@ -105,7 +107,8 @@ public void testManageSqlServerKeysWithAzureKeyVaultKey() { } } - Assertions.assertTrue(ManageSqlServerKeysWithAzureKeyVaultKey.runSample(azureResourceManager, servicePrincipalClientId)); + Assertions.assertTrue( + ManageSqlServerKeysWithAzureKeyVaultKey.runSample(azureResourceManager, servicePrincipalClientId)); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/StorageSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/StorageSampleTests.java index fea1a3049837f..757499fb4a868 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/StorageSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/StorageSampleTests.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.samples; - import com.azure.core.test.annotation.DoNotRecord; import com.azure.resourcemanager.storage.samples.ManageStorageAccount; import com.azure.resourcemanager.storage.samples.ManageStorageAccountAsync; @@ -31,6 +30,7 @@ public void testManageStorageAccountNetworkRules() { @Test @DoNotRecord(skipInPlayback = true) // requires generate a key public void testManageStorageAccountCustomerManagedKey() { - Assertions.assertTrue(ManageStorageAccountCustomerManagedKey.runSample(azureResourceManager, clientIdFromFile())); + Assertions + .assertTrue(ManageStorageAccountCustomerManagedKey.runSample(azureResourceManager, clientIdFromFile())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml index b730254f95dcf..4702150c5e9f2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml @@ -46,6 +46,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/SearchServiceManager.java b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/SearchServiceManager.java index 42a7ea4107f21..66342a64ac7c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/SearchServiceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/SearchServiceManager.java @@ -85,18 +85,13 @@ public SearchServiceManager authenticate(TokenCredential credential, AzureProfil } private SearchServiceManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new SearchManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new SearchManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) - .buildClient() - ); + .buildClient()); } - /** * @return the availability set resource management API entry point */ diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServiceImpl.java b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServiceImpl.java index c50c128bf67e4..86668950de8f4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServiceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServiceImpl.java @@ -26,15 +26,8 @@ * Implementation for Search service and its create and update interfaces. */ class SearchServiceImpl - extends GroupableParentResourceImpl< - SearchService, - SearchServiceInner, - SearchServiceImpl, - SearchServiceManager> - implements - SearchService, - SearchService.Definition, - SearchService.Update { + extends GroupableParentResourceImpl + implements SearchService, SearchService.Definition, SearchService.Update { SearchServiceImpl(String name, final SearchServiceInner innerModel, final SearchServiceManager searchManager) { super(name, innerModel, searchManager); @@ -42,10 +35,14 @@ class SearchServiceImpl @Override protected Mono createInner() { - return this.manager().serviceClient().getServices() + return this.manager() + .serviceClient() + .getServices() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) // TODO: remove this after azure-core-management upgrade to 1.0.1 - .switchIfEmpty(this.manager().serviceClient().getServices() + .switchIfEmpty(this.manager() + .serviceClient() + .getServices() .getByResourceGroupAsync(this.resourceGroupName(), this.name())); } @@ -55,7 +52,9 @@ protected void initializeChildrenFromInner() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getServices() + return this.manager() + .serviceClient() + .getServices() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @@ -101,7 +100,10 @@ public AdminKeys getAdminKeys() { @Override public Mono getAdminKeysAsync() { - return this.manager().serviceClient().getAdminKeys().getAsync(this.resourceGroupName(), this.name()) + return this.manager() + .serviceClient() + .getAdminKeys() + .getAsync(this.resourceGroupName(), this.name()) .map(AdminKeysImpl::new); } @@ -112,9 +114,10 @@ public PagedIterable listQueryKeys() { @Override public PagedFlux listQueryKeysAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getQueryKeys() - .listBySearchServiceAsync(this.resourceGroupName(), this.name()), - QueryKeyImpl::new); + return PagedConverter.mapPage(this.manager() + .serviceClient() + .getQueryKeys() + .listBySearchServiceAsync(this.resourceGroupName(), this.name()), QueryKeyImpl::new); } @Override @@ -124,7 +127,9 @@ public AdminKeys regenerateAdminKeys(AdminKeyKind keyKind) { @Override public Mono regenerateAdminKeysAsync(AdminKeyKind keyKind) { - return this.manager().serviceClient().getAdminKeys() + return this.manager() + .serviceClient() + .getAdminKeys() .regenerateAsync(this.resourceGroupName(), this.name(), keyKind) .map(AdminKeysImpl::new); } @@ -136,7 +141,9 @@ public QueryKey createQueryKey(String name) { @Override public Mono createQueryKeyAsync(String name) { - return this.manager().serviceClient().getQueryKeys() + return this.manager() + .serviceClient() + .getQueryKeys() .createAsync(this.resourceGroupName(), this.name(), name) .map(QueryKeyImpl::new); } @@ -148,8 +155,7 @@ public void deleteQueryKey(String key) { @Override public Mono deleteQueryKeyAsync(String key) { - return this.manager().serviceClient().getQueryKeys() - .deleteAsync(this.resourceGroupName(), this.name(), key); + return this.manager().serviceClient().getQueryKeys().deleteAsync(this.resourceGroupName(), this.name(), key); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServicesImpl.java b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServicesImpl.java index 0968e0bdcdf7c..85efed04e57f5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServicesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/implementation/SearchServicesImpl.java @@ -23,13 +23,8 @@ /** * Implementation for SearchServices. */ -public class SearchServicesImpl - extends GroupableResourcesImpl< - SearchService, - SearchServiceImpl, - SearchServiceInner, - SearchManagementClient, - SearchServiceManager> +public class SearchServicesImpl extends + GroupableResourcesImpl implements SearchServices { public SearchServicesImpl(final SearchServiceManager searchManager) { @@ -77,8 +72,7 @@ public AdminKeys getAdminKeys(String resourceGroupName, String searchServiceName @Override public Mono getAdminKeysAsync(String resourceGroupName, String searchServiceName) { - return this.inner().getAdminKeys().getAsync(resourceGroupName, searchServiceName) - .map(AdminKeysImpl::new); + return this.inner().getAdminKeys().getAsync(resourceGroupName, searchServiceName).map(AdminKeysImpl::new); } @Override @@ -88,7 +82,8 @@ public PagedIterable listQueryKeys(String resourceGroupName, String se @Override public PagedFlux listQueryKeysAsync(String resourceGroupName, String searchServiceName) { - return PagedConverter.mapPage(this.inner().getQueryKeys().listBySearchServiceAsync(resourceGroupName, searchServiceName), + return PagedConverter.mapPage( + this.inner().getQueryKeys().listBySearchServiceAsync(resourceGroupName, searchServiceName), QueryKeyImpl::new); } @@ -98,10 +93,11 @@ public AdminKeys regenerateAdminKeys(String resourceGroupName, String searchServ } @Override - public Mono regenerateAdminKeysAsync(String resourceGroupName, - String searchServiceName, - AdminKeyKind keyKind) { - return this.inner().getAdminKeys().regenerateAsync(resourceGroupName, searchServiceName, keyKind) + public Mono regenerateAdminKeysAsync(String resourceGroupName, String searchServiceName, + AdminKeyKind keyKind) { + return this.inner() + .getAdminKeys() + .regenerateAsync(resourceGroupName, searchServiceName, keyKind) .map(AdminKeysImpl::new); } @@ -112,7 +108,9 @@ public QueryKey createQueryKey(String resourceGroupName, String searchServiceNam @Override public Mono createQueryKeyAsync(String resourceGroupName, String searchServiceName, String name) { - return this.inner().getQueryKeys().createAsync(resourceGroupName, searchServiceName, name) + return this.inner() + .getQueryKeys() + .createAsync(resourceGroupName, searchServiceName, name) .map(QueryKeyImpl::new); } @@ -134,8 +132,8 @@ public PagedIterable listByResourceGroup(String resourceGroupName @Override public PagedFlux listByResourceGroupAsync(String resourceGroupName) { if (CoreUtils.isNullOrEmpty(resourceGroupName)) { - return new PagedFlux<>(() -> Mono.error( - new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); + return new PagedFlux<>(() -> Mono + .error(new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null."))); } return PagedConverter.mapPage(this.inner().getServices().listByResourceGroupAsync(resourceGroupName), this::wrapModel); @@ -153,7 +151,6 @@ public PagedIterable list() { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.inner().getServices().listAsync(), - this::wrapModel); + return PagedConverter.mapPage(this.inner().getServices().listAsync(), this::wrapModel); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchService.java b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchService.java index 6c52bd7ce4f56..8286618e5789e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchService.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchService.java @@ -21,10 +21,8 @@ * An immutable client-side representation of an Azure Cognitive Search service. */ @Fluent -public interface SearchService extends - GroupableResource, - Refreshable, - Updatable { +public interface SearchService extends GroupableResource, + Refreshable, Updatable { /** * The hosting mode value. @@ -207,18 +205,12 @@ public interface SearchService extends */ PublicNetworkAccess publicNetworkAccess(); - /** * The entirety of the Search service definition. */ - interface Definition extends - DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithSku, - DefinitionStages.WithPublicNetworkAccess, - DefinitionStages.WithPartitionsAndCreate, - DefinitionStages.WithReplicasAndCreate, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithSku, + DefinitionStages.WithPublicNetworkAccess, DefinitionStages.WithPartitionsAndCreate, + DefinitionStages.WithReplicasAndCreate, DefinitionStages.WithCreate { } /** @@ -228,15 +220,13 @@ interface DefinitionStages { /** * The first stage of the Search service definition. */ - interface Blank - extends GroupableResource.DefinitionWithRegion { + interface Blank extends GroupableResource.DefinitionWithRegion { } /** * The stage of the Search service definition allowing to specify the resource group. */ - interface WithGroup - extends GroupableResource.DefinitionStages.WithGroup { + interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { } /** @@ -313,22 +303,16 @@ interface WithPartitionsAndCreate extends WithReplicasAndCreate { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Resource.DefinitionWithTags, - WithPublicNetworkAccess { + interface WithCreate + extends Creatable, Resource.DefinitionWithTags, WithPublicNetworkAccess { } } /** * The template for a Search service update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - Resource.UpdateWithTags, - UpdateStages.WithReplicaCount, - UpdateStages.WithPartitionCount, - UpdateStages.WithPublicNetworkAccess { + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithReplicaCount, + UpdateStages.WithPartitionCount, UpdateStages.WithPublicNetworkAccess { } /** @@ -372,6 +356,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the search service. * diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchServices.java b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchServices.java index 26f7d2a385f74..b2a3f267d7b95 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchServices.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/main/java/com/azure/resourcemanager/search/models/SearchServices.java @@ -23,16 +23,10 @@ * Entry point to Cognitive Search service management API in Azure. */ @Fluent -public interface SearchServices extends - SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - HasManager { +public interface SearchServices extends SupportsCreating, + SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, SupportsBatchCreation, HasManager { /** * Checks if the specified Search service name is valid and available. diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchManagementTest.java index 9813e6664c041..7912e830a5d3f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchManagementTest.java @@ -25,21 +25,10 @@ public abstract class SearchManagementTest extends ResourceManagerTestProxyTestB protected SearchServiceManager searchManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchServiceOperationTests.java b/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchServiceOperationTests.java index b3790f3fe634e..f26925f317c08 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchServiceOperationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-search/src/test/java/com/azure/resourcemanager/search/SearchServiceOperationTests.java @@ -33,14 +33,13 @@ protected void cleanUpResources() { public void canCreateUpdateSearchService() { String searchServiceName = generateRandomResourceName("search", 15); - resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + resourceManager.resourceGroups().define(rgName).withRegion(region).create(); CheckNameAvailabilityOutput result = searchManager.searchServices().checkNameAvailability(searchServiceName); Assertions.assertTrue(result.isNameAvailable()); - SearchService searchService = searchManager.searchServices().define(searchServiceName) + SearchService searchService = searchManager.searchServices() + .define(searchServiceName) .withRegion(region) .withExistingResourceGroup(rgName) .withFreeSku() @@ -60,11 +59,10 @@ public void canCreateUpdateSearchService() { Assertions.assertTrue(foundSearchService); if (!isPlaybackMode()) { - searchService.update() - .withTag("key1", "value1") - .apply(); + searchService.update().withTag("key1", "value1").apply(); - SearchService updatedSearchService = searchManager.searchServices().getByResourceGroup(rgName, searchServiceName); + SearchService updatedSearchService + = searchManager.searchServices().getByResourceGroup(rgName, searchServiceName); Assertions.assertNotNull(updatedSearchService); Assertions.assertEquals(SkuName.FREE, updatedSearchService.sku().name()); Assertions.assertEquals(1, updatedSearchService.tags().size()); @@ -76,9 +74,7 @@ public void canCreateUpdateSearchService() { public void canCreateAndUpdatePublicNetworkAccess() { String searchServiceName = generateRandomResourceName("search", 15); - resourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + resourceManager.resourceGroups().define(rgName).withRegion(region).create(); SearchService searchService = searchManager.searchServices() .define(searchServiceName) diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml index cb44875c211fd..2f6bde5c4adf9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml @@ -46,6 +46,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/ServiceBusManager.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/ServiceBusManager.java index f047dc4df791a..34f91c3e3c3a9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/ServiceBusManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/ServiceBusManager.java @@ -23,6 +23,7 @@ public final class ServiceBusManager extends Manager { // Collections private ServiceBusNamespaces namespaces; + /** * Get a Configurable instance that can be used to create {@link ServiceBusManager} * with optional configuration. @@ -76,9 +77,7 @@ public interface Configurable extends AzureConfigurable { /** * The implementation for Configurable interface. */ - private static class ConfigurableImpl - extends AzureConfigurableImpl - implements Configurable { + private static class ConfigurableImpl extends AzureConfigurableImpl implements Configurable { public ServiceBusManager authenticate(TokenCredential credential, AzureProfile profile) { return ServiceBusManager.authenticate(buildHttpPipeline(credential, profile), profile); @@ -86,11 +85,8 @@ public ServiceBusManager authenticate(TokenCredential credential, AzureProfile p } private ServiceBusManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new ServiceBusManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new ServiceBusManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationKeysImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationKeysImpl.java index d19850777f860..f9a0070f535a0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationKeysImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationKeysImpl.java @@ -10,9 +10,7 @@ /** * Implementation for AuthorizationKeys. */ -class AuthorizationKeysImpl - extends WrapperImpl - implements AuthorizationKeys { +class AuthorizationKeysImpl extends WrapperImpl implements AuthorizationKeys { AuthorizationKeysImpl(AccessKeysInner inner) { super(inner); diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationRuleBaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationRuleBaseImpl.java index c98db157038bf..90d8975e0f91e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationRuleBaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/AuthorizationRuleBaseImpl.java @@ -28,21 +28,8 @@ * @param the parent fluent implementation * @param the manager */ -abstract class AuthorizationRuleBaseImpl< - FluentModelT extends IndependentChildResource, - FluentParentModelT extends Resource & HasResourceGroup, - InnerModelT extends SBAuthorizationRuleInner, - FluentModelImplT extends IndependentChildResourceImpl< - FluentModelT, - FluentParentModelT, - InnerModelT, - FluentModelImplT, - ManagerT>, - ManagerT> extends IndependentChildResourceImpl { +abstract class AuthorizationRuleBaseImpl, FluentParentModelT extends Resource & HasResourceGroup, InnerModelT extends SBAuthorizationRuleInner, FluentModelImplT extends IndependentChildResourceImpl, ManagerT> + extends IndependentChildResourceImpl { protected AuthorizationRuleBaseImpl(String name, InnerModelT innerObject, ManagerT manager) { super(name, innerObject, manager); } @@ -51,8 +38,7 @@ protected AuthorizationRuleBaseImpl(String name, InnerModelT innerObject, Manage * @return stream that emits primary, secondary keys and connection strings */ public Mono getKeysAsync() { - return this.getKeysInnerAsync() - .map(inner -> new AuthorizationKeysImpl(inner)); + return this.getKeysInnerAsync().map(inner -> new AuthorizationKeysImpl(inner)); } /** @@ -63,8 +49,7 @@ public AuthorizationKeys getKeys() { } public Mono regenerateKeyAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { - return this.regenerateKeysInnerAsync(regenerateAccessKeyParameters) - .map(AuthorizationKeysImpl::new); + return this.regenerateKeysInnerAsync(regenerateAccessKeyParameters).map(AuthorizationKeysImpl::new); } public AuthorizationKeys regenerateKey(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { @@ -120,5 +105,7 @@ public FluentModelImplT withManagementEnabled() { } protected abstract Mono getKeysInnerAsync(); - protected abstract Mono regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters); + + protected abstract Mono + regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters); } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/CheckNameAvailabilityResultImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/CheckNameAvailabilityResultImpl.java index 2ba86bb124a08..e06a875990949 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/CheckNameAvailabilityResultImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/CheckNameAvailabilityResultImpl.java @@ -11,9 +11,8 @@ /** * Implementation for CheckNameAvailabilityResult. */ -class CheckNameAvailabilityResultImpl - extends WrapperImpl - implements CheckNameAvailabilityResult { +class CheckNameAvailabilityResultImpl extends WrapperImpl + implements CheckNameAvailabilityResult { /** * Creates an instance of the check name availability result object. * @@ -38,4 +37,3 @@ public String unavailabilityMessage() { return innerModel().message(); } } - diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRuleImpl.java index ec0f9b58a3266..9f89f80df79a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRuleImpl.java @@ -13,21 +13,12 @@ /** * Implementation for NamespaceAuthorizationRule. */ -class NamespaceAuthorizationRuleImpl extends AuthorizationRuleBaseImpl - implements - NamespaceAuthorizationRule, - NamespaceAuthorizationRule.Definition, - NamespaceAuthorizationRule.Update { +class NamespaceAuthorizationRuleImpl extends + AuthorizationRuleBaseImpl + implements NamespaceAuthorizationRule, NamespaceAuthorizationRule.Definition, NamespaceAuthorizationRule.Update { - NamespaceAuthorizationRuleImpl(String resourceGroupName, - String namespaceName, - String name, - SBAuthorizationRuleInner inner, - ServiceBusManager manager) { + NamespaceAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String name, + SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.withExistingParentResource(resourceGroupName, namespaceName); } @@ -39,20 +30,19 @@ public String namespaceName() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getNamespaces() - .getAuthorizationRuleAsync(this.resourceGroupName(), - this.namespaceName(), - this.name()); + return this.manager() + .serviceClient() + .getNamespaces() + .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.name()); } @Override protected Mono createChildResourceAsync() { final NamespaceAuthorizationRule self = this; - return this.manager().serviceClient().getNamespaces() - .createOrUpdateAuthorizationRuleAsync( - this.resourceGroupName(), - this.namespaceName(), - this.name(), + return this.manager() + .serviceClient() + .getNamespaces() + .createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); @@ -62,18 +52,19 @@ protected Mono createChildResourceAsync() { @Override protected Mono getKeysInnerAsync() { - return this.manager().serviceClient().getNamespaces() - .listKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.name()); + return this.manager() + .serviceClient() + .getNamespaces() + .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.name()); } @Override - protected Mono regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { - return this.manager().serviceClient().getNamespaces() - .regenerateKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.name(), - regenerateAccessKeyParameters); + protected Mono + regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { + return this.manager() + .serviceClient() + .getNamespaces() + .regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.name(), + regenerateAccessKeyParameters); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRulesImpl.java index e9814709dbc6c..d7d73093fddb3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/NamespaceAuthorizationRulesImpl.java @@ -18,14 +18,8 @@ /** * Implementation for NamespaceAuthorizationRules. */ -class NamespaceAuthorizationRulesImpl - extends ServiceBusChildResourcesImpl< - NamespaceAuthorizationRule, - NamespaceAuthorizationRuleImpl, - SBAuthorizationRuleInner, - NamespacesClient, - ServiceBusManager, - ServiceBusNamespace> +class NamespaceAuthorizationRulesImpl extends + ServiceBusChildResourcesImpl implements NamespaceAuthorizationRules { private final String resourceGroupName; private final String namespaceName; @@ -33,10 +27,8 @@ class NamespaceAuthorizationRulesImpl private final ClientLogger logger = new ClientLogger(NamespaceAuthorizationRulesImpl.class); - NamespaceAuthorizationRulesImpl(String resourceGroupName, - String namespaceName, - Region region, - ServiceBusManager manager) { + NamespaceAuthorizationRulesImpl(String resourceGroupName, String namespaceName, Region region, + ServiceBusManager manager) { super(manager.serviceClient().getNamespaces(), manager); this.resourceGroupName = resourceGroupName; this.namespaceName = namespaceName; @@ -65,33 +57,24 @@ protected PagedFlux listInnerAsync() { @Override protected PagedIterable listInner() { - return this.innerModel().listAuthorizationRules(this.resourceGroupName, - this.namespaceName); + return this.innerModel().listAuthorizationRules(this.resourceGroupName, this.namespaceName); } @Override protected NamespaceAuthorizationRuleImpl wrapModel(String name) { - return new NamespaceAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - name, - new SBAuthorizationRuleInner(), - this.manager()); + return new NamespaceAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, name, + new SBAuthorizationRuleInner(), this.manager()); } - @Override protected NamespaceAuthorizationRuleImpl wrapModel(SBAuthorizationRuleInner inner) { if (inner == null) { return null; } - return new NamespaceAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - inner.name(), - inner, - this.manager()); + return new NamespaceAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, inner.name(), inner, + this.manager()); } - @Override public PagedIterable listByParent(String resourceGroupName, String parentName) { // 'IndependentChildResourcesImpl' will be refactoring to remove all 'ByParent' methods diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRuleImpl.java index 5be14669e9079..0958f59c67ee0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRuleImpl.java @@ -13,23 +13,13 @@ /** * Implementation for QueueAuthorizationRule. */ -class QueueAuthorizationRuleImpl extends AuthorizationRuleBaseImpl - implements - QueueAuthorizationRule, - QueueAuthorizationRule.Definition, - QueueAuthorizationRule.Update { +class QueueAuthorizationRuleImpl extends + AuthorizationRuleBaseImpl + implements QueueAuthorizationRule, QueueAuthorizationRule.Definition, QueueAuthorizationRule.Update { private final String namespaceName; - QueueAuthorizationRuleImpl(String resourceGroupName, - String namespaceName, - String queueName, - String name, - SBAuthorizationRuleInner inner, - ServiceBusManager manager) { + QueueAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String queueName, String name, + SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, queueName); @@ -47,21 +37,20 @@ public String queueName() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getQueues() - .getAuthorizationRuleAsync(this.resourceGroupName(), - this.namespaceName(), - this.queueName(), - this.name()); + return this.manager() + .serviceClient() + .getQueues() + .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.queueName(), this.name()); } @Override protected Mono createChildResourceAsync() { final QueueAuthorizationRule self = this; - return this.manager().serviceClient().getQueues().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), - this.namespaceName(), - this.queueName(), - this.name(), - this.innerModel()) + return this.manager() + .serviceClient() + .getQueues() + .createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.queueName(), + this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; @@ -70,20 +59,19 @@ protected Mono createChildResourceAsync() { @Override protected Mono getKeysInnerAsync() { - return this.manager().serviceClient().getQueues() - .listKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.queueName(), - this.name()); + return this.manager() + .serviceClient() + .getQueues() + .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.queueName(), this.name()); } @Override - protected Mono regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { - return this.manager().serviceClient().getQueues() - .regenerateKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.queueName(), - this.name(), - regenerateAccessKeyParameters); + protected Mono + regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { + return this.manager() + .serviceClient() + .getQueues() + .regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.queueName(), this.name(), + regenerateAccessKeyParameters); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRulesImpl.java index dceca3ed02f2a..88a9d1f2c6685 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueAuthorizationRulesImpl.java @@ -18,14 +18,8 @@ /** * Implementation for QueueAuthorizationRules. */ -class QueueAuthorizationRulesImpl - extends ServiceBusChildResourcesImpl< - QueueAuthorizationRule, - QueueAuthorizationRuleImpl, - SBAuthorizationRuleInner, - QueuesClient, - ServiceBusManager, - Queue> +class QueueAuthorizationRulesImpl extends + ServiceBusChildResourcesImpl implements QueueAuthorizationRules { private final String resourceGroupName; private final String namespaceName; @@ -34,11 +28,8 @@ class QueueAuthorizationRulesImpl private final ClientLogger logger = new ClientLogger(QueueAuthorizationRulesImpl.class); - QueueAuthorizationRulesImpl(String resourceGroupName, - String namespaceName, - String queueName, - Region region, - ServiceBusManager manager) { + QueueAuthorizationRulesImpl(String resourceGroupName, String namespaceName, String queueName, Region region, + ServiceBusManager manager) { super(manager.serviceClient().getQueues(), manager); this.resourceGroupName = resourceGroupName; this.namespaceName = namespaceName; @@ -53,41 +44,31 @@ public QueueAuthorizationRuleImpl define(String name) { @Override public Mono deleteByNameAsync(String name) { - return this.innerModel().deleteAuthorizationRuleAsync(this.resourceGroupName, - this.namespaceName, - this.queueName, - name); + return this.innerModel() + .deleteAuthorizationRuleAsync(this.resourceGroupName, this.namespaceName, this.queueName, name); } @Override protected Mono getInnerByNameAsync(String name) { - return this.innerModel().getAuthorizationRuleAsync(this.resourceGroupName, - this.namespaceName, - this.queueName, - name); + return this.innerModel() + .getAuthorizationRuleAsync(this.resourceGroupName, this.namespaceName, this.queueName, name); } @Override protected PagedFlux listInnerAsync() { - return this.innerModel().listAuthorizationRulesAsync( - this.resourceGroupName, this.namespaceName, this.queueName); + return this.innerModel() + .listAuthorizationRulesAsync(this.resourceGroupName, this.namespaceName, this.queueName); } @Override protected PagedIterable listInner() { - return this.innerModel().listAuthorizationRules(this.resourceGroupName, - this.namespaceName, - this.queueName); + return this.innerModel().listAuthorizationRules(this.resourceGroupName, this.namespaceName, this.queueName); } @Override protected QueueAuthorizationRuleImpl wrapModel(String name) { - return new QueueAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - this.queueName, - name, - new SBAuthorizationRuleInner(), - this.manager()); + return new QueueAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, this.queueName, name, + new SBAuthorizationRuleInner(), this.manager()); } @Override @@ -95,12 +76,8 @@ protected QueueAuthorizationRuleImpl wrapModel(SBAuthorizationRuleInner inner) { if (inner == null) { return null; } - return new QueueAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - this.queueName, - inner.name(), - inner, - this.manager()); + return new QueueAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, this.queueName, inner.name(), + inner, this.manager()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueImpl.java index d87db7a06ecf4..425d2f5aec72c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueueImpl.java @@ -24,25 +24,13 @@ * Implementation for Queue. */ class QueueImpl - extends IndependentChildResourceImpl< - Queue, - ServiceBusNamespaceImpl, - SBQueueInner, - QueueImpl, - ServiceBusManager> - implements - Queue, - Queue.Definition, - Queue.Update { + extends IndependentChildResourceImpl + implements Queue, Queue.Definition, Queue.Update { private List> rulesToCreate; private List rulesToDelete; - QueueImpl(String resourceGroupName, - String namespaceName, - String name, - Region region, - SBQueueInner inner, - ServiceBusManager manager) { + QueueImpl(String resourceGroupName, String namespaceName, String name, Region region, SBQueueInner inner, + ServiceBusManager manager) { super(name, inner, manager); this.withExistingParentResource(resourceGroupName, namespaceName); initChildrenOperationsCache(); @@ -147,8 +135,7 @@ public long messageCount() { @Override public long activeMessageCount() { - if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().activeMessageCount() == null) { + if (this.innerModel().countDetails() == null || this.innerModel().countDetails().activeMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().activeMessageCount()); @@ -157,7 +144,7 @@ public long activeMessageCount() { @Override public long deadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().deadLetterMessageCount() == null) { + || this.innerModel().countDetails().deadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().deadLetterMessageCount()); @@ -166,7 +153,7 @@ public long deadLetterMessageCount() { @Override public long scheduledMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().scheduledMessageCount() == null) { + || this.innerModel().countDetails().scheduledMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().scheduledMessageCount()); @@ -175,7 +162,7 @@ public long scheduledMessageCount() { @Override public long transferDeadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { + || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferDeadLetterMessageCount()); @@ -184,7 +171,7 @@ public long transferDeadLetterMessageCount() { @Override public long transferMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferMessageCount() == null) { + || this.innerModel().countDetails().transferMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferMessageCount()); @@ -197,11 +184,8 @@ public EntityStatus status() { @Override public QueueAuthorizationRulesImpl authorizationRules() { - return new QueueAuthorizationRulesImpl(this.resourceGroupName(), - this.parentName, - this.name(), - this.region(), - manager()); + return new QueueAuthorizationRulesImpl(this.resourceGroupName(), this.parentName, this.name(), this.region(), + manager()); } @Override @@ -338,20 +322,19 @@ public QueueImpl withoutAuthorizationRule(String name) { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getQueues() - .getAsync(this.resourceGroupName(), - this.parentName, - this.name()); + return this.manager() + .serviceClient() + .getQueues() + .getAsync(this.resourceGroupName(), this.parentName, this.name()); } @Override protected Mono createChildResourceAsync() { - Mono createTask = this.manager().serviceClient().getQueues() - .createOrUpdateAsync(this.resourceGroupName(), - this.parentName, - this.name(), - this.innerModel()) + Mono createTask = this.manager() + .serviceClient() + .getQueues() + .createOrUpdateAsync(this.resourceGroupName(), this.parentName, this.name(), this.innerModel()) .map(inner -> { setInner(inner); return inner; @@ -377,7 +360,6 @@ private Flux submitChildrenOperationsAsync() { if (this.rulesToDelete.size() > 0) { rulesDeleteStream = this.authorizationRules().deleteByNameAsync(this.rulesToDelete); } - return Flux.mergeDelayError(32, rulesCreateStream, - rulesDeleteStream); + return Flux.mergeDelayError(32, rulesCreateStream, rulesDeleteStream); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueuesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueuesImpl.java index 60c0eede14202..ad7e8c964fc2f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueuesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/QueuesImpl.java @@ -18,14 +18,8 @@ /** * Implementation for Queues. */ -class QueuesImpl - extends ServiceBusChildResourcesImpl< - Queue, - QueueImpl, - SBQueueInner, - QueuesClient, - ServiceBusManager, - ServiceBusNamespace> +class QueuesImpl extends + ServiceBusChildResourcesImpl implements Queues { private final String resourceGroupName; private final String namespaceName; @@ -47,9 +41,7 @@ public QueueImpl define(String name) { @Override public Mono deleteByNameAsync(String name) { - return this.innerModel().deleteAsync(this.resourceGroupName, - this.namespaceName, - name); + return this.innerModel().deleteAsync(this.resourceGroupName, this.namespaceName, name); } @Override @@ -69,12 +61,8 @@ protected PagedIterable listInner() { @Override protected QueueImpl wrapModel(String name) { - return new QueueImpl(this.resourceGroupName, - this.namespaceName, - name, - this.region, - new SBQueueInner(), - this.manager()); + return new QueueImpl(this.resourceGroupName, this.namespaceName, name, this.region, new SBQueueInner(), + this.manager()); } @Override @@ -82,12 +70,8 @@ protected QueueImpl wrapModel(SBQueueInner inner) { if (inner == null) { return null; } - return new QueueImpl(this.resourceGroupName, - this.namespaceName, - inner.name(), - this.region, - inner, - this.manager()); + return new QueueImpl(this.resourceGroupName, this.namespaceName, inner.name(), this.region, inner, + this.manager()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusChildResourcesImpl.java index 5006b73c7e356..d155c966e963f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusChildResourcesImpl.java @@ -31,23 +31,16 @@ * @param the manager * @param the parent model interface type */ -abstract class ServiceBusChildResourcesImpl< - T extends IndependentChildResource, - ImplT extends T, - InnerT, - InnerCollectionT, - ManagerT extends Manager, - ParentT extends Resource & HasResourceGroup> - extends IndependentChildResourcesImpl - implements SupportsGettingByName, SupportsListing, SupportsDeletingByName { +abstract class ServiceBusChildResourcesImpl, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends Manager, ParentT extends Resource & HasResourceGroup> + extends IndependentChildResourcesImpl + implements SupportsGettingByName, SupportsListing, SupportsDeletingByName { protected ServiceBusChildResourcesImpl(InnerCollectionT innerCollection, ManagerT manager) { super(innerCollection, manager); } @Override public Mono getByNameAsync(String name) { - return getInnerByNameAsync(name) - .map(this::wrapModel); + return getInnerByNameAsync(name).map(this::wrapModel); } @Override @@ -57,8 +50,7 @@ public T getByName(String name) { @Override public PagedFlux listAsync() { - return PagedConverter.mapPage(this.listInnerAsync(), - this::wrapModel); + return PagedConverter.mapPage(this.listInnerAsync(), this::wrapModel); } @Override @@ -75,11 +67,12 @@ public Flux deleteByNameAsync(List names) { if (names == null) { return Flux.empty(); } - return Flux.fromIterable(names) - .flatMapDelayError(name -> deleteByNameAsync(name), 32, 32); + return Flux.fromIterable(names).flatMapDelayError(name -> deleteByNameAsync(name), 32, 32); } protected abstract Mono getInnerByNameAsync(String name); + protected abstract PagedFlux listInnerAsync(); + protected abstract PagedIterable listInner(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespaceImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespaceImpl.java index 288f6d0ef2cb6..c19cace0e81c6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespaceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespaceImpl.java @@ -24,15 +24,8 @@ * Implementation for ServiceBusNamespace. */ class ServiceBusNamespaceImpl - extends GroupableResourceImpl< - ServiceBusNamespace, - SBNamespaceInner, - ServiceBusNamespaceImpl, - ServiceBusManager> - implements - ServiceBusNamespace, - ServiceBusNamespace.Definition, - ServiceBusNamespace.Update { + extends GroupableResourceImpl + implements ServiceBusNamespace, ServiceBusNamespace.Definition, ServiceBusNamespace.Update { private List> queuesToCreate; private List> topicsToCreate; private List> rulesToCreate; @@ -72,32 +65,23 @@ public OffsetDateTime updatedAt() { @Override public QueuesImpl queues() { - return new QueuesImpl(this.resourceGroupName(), - this.name(), - this.region(), - this.manager()); + return new QueuesImpl(this.resourceGroupName(), this.name(), this.region(), this.manager()); } @Override public TopicsImpl topics() { - return new TopicsImpl(this.resourceGroupName(), - this.name(), - this.region(), - this.manager()); + return new TopicsImpl(this.resourceGroupName(), this.name(), this.region(), this.manager()); } @Override public NamespaceAuthorizationRulesImpl authorizationRules() { - return new NamespaceAuthorizationRulesImpl(this.resourceGroupName(), - this.name(), - this.region(), - manager()); + return new NamespaceAuthorizationRulesImpl(this.resourceGroupName(), this.name(), this.region(), manager()); } @Override public ServiceBusNamespaceImpl withSku(NamespaceSku namespaceSku) { - this.innerModel().withSku(new SBSku() - .withName(namespaceSku.name()) + this.innerModel() + .withSku(new SBSku().withName(namespaceSku.name()) .withTier(namespaceSku.tier()) .withCapacity(namespaceSku.capacity())); return this; @@ -153,16 +137,18 @@ public ServiceBusNamespaceImpl withoutAuthorizationRule(String name) { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getNamespaces().getByResourceGroupAsync(this.resourceGroupName(), - this.name()); + return this.manager() + .serviceClient() + .getNamespaces() + .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public Mono createResourceAsync() { - Mono createTask = this.manager().serviceClient().getNamespaces() - .createOrUpdateAsync(this.resourceGroupName(), - this.name(), - this.innerModel()) + Mono createTask = this.manager() + .serviceClient() + .getNamespaces() + .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); return inner; @@ -209,12 +195,7 @@ private Flux submitChildrenOperationsAsync() { if (this.rulesToDelete.size() > 0) { rulesDeleteStream = this.authorizationRules().deleteByNameAsync(this.rulesToDelete); } - return Flux.mergeDelayError(32, - queuesCreateStream, - topicsCreateStream, - rulesCreateStream, - queuesDeleteStream, - topicsDeleteStream, - rulesDeleteStream); + return Flux.mergeDelayError(32, queuesCreateStream, topicsCreateStream, rulesCreateStream, queuesDeleteStream, + topicsDeleteStream, rulesDeleteStream); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespacesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespacesImpl.java index 6dea872490281..354834ee812e0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespacesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusNamespacesImpl.java @@ -16,12 +16,8 @@ /** * Implementation for ServiceBusNamespaces. */ -public final class ServiceBusNamespacesImpl extends TopLevelModifiableResourcesImpl< - ServiceBusNamespace, - ServiceBusNamespaceImpl, - SBNamespaceInner, - NamespacesClient, - ServiceBusManager> +public final class ServiceBusNamespacesImpl extends + TopLevelModifiableResourcesImpl implements ServiceBusNamespaces { public ServiceBusNamespacesImpl(NamespacesClient innerCollection, ServiceBusManager manager) { @@ -40,21 +36,18 @@ public CheckNameAvailabilityResult checkNameAvailability(String name) { @Override public Mono checkNameAvailabilityAsync(String name) { - return this.inner().checkNameAvailabilityAsync(new CheckNameAvailability().withName(name)) + return this.inner() + .checkNameAvailabilityAsync(new CheckNameAvailability().withName(name)) .map(inner -> new CheckNameAvailabilityResultImpl(inner)); } @Override protected ServiceBusNamespaceImpl wrapModel(String name) { - return new ServiceBusNamespaceImpl(name, - new SBNamespaceInner(), - this.manager()); + return new ServiceBusNamespaceImpl(name, new SBNamespaceInner(), this.manager()); } @Override protected ServiceBusNamespaceImpl wrapModel(SBNamespaceInner inner) { - return new ServiceBusNamespaceImpl(inner.name(), - inner, - this.manager()); + return new ServiceBusNamespaceImpl(inner.name(), inner, this.manager()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionImpl.java index 2e345adb0f772..50736ad3a38e8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionImpl.java @@ -19,24 +19,12 @@ * Implementation for Subscription. */ class ServiceBusSubscriptionImpl extends - IndependentChildResourceImpl< - ServiceBusSubscription, - Topic, - SBSubscriptionInner, - ServiceBusSubscriptionImpl, - ServiceBusManager> - implements - ServiceBusSubscription, - ServiceBusSubscription.Definition, - ServiceBusSubscription.Update { + IndependentChildResourceImpl + implements ServiceBusSubscription, ServiceBusSubscription.Definition, ServiceBusSubscription.Update { private final String namespaceName; - ServiceBusSubscriptionImpl(String resourceGroupName, - String namespaceName, - String topicName, - String name, - SBSubscriptionInner inner, - ServiceBusManager manager) { + ServiceBusSubscriptionImpl(String resourceGroupName, String namespaceName, String topicName, String name, + SBSubscriptionInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); @@ -108,8 +96,7 @@ public long messageCount() { @Override public long activeMessageCount() { - if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().activeMessageCount() == null) { + if (this.innerModel().countDetails() == null || this.innerModel().countDetails().activeMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().activeMessageCount()); @@ -118,7 +105,7 @@ public long activeMessageCount() { @Override public long deadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().deadLetterMessageCount() == null) { + || this.innerModel().countDetails().deadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().deadLetterMessageCount()); @@ -127,7 +114,7 @@ public long deadLetterMessageCount() { @Override public long scheduledMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().scheduledMessageCount() == null) { + || this.innerModel().countDetails().scheduledMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().scheduledMessageCount()); @@ -136,7 +123,7 @@ public long scheduledMessageCount() { @Override public long transferDeadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { + || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferDeadLetterMessageCount()); @@ -145,7 +132,7 @@ public long transferDeadLetterMessageCount() { @Override public long transferMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferMessageCount() == null) { + || this.innerModel().countDetails().transferMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferMessageCount()); @@ -241,22 +228,20 @@ public ServiceBusSubscriptionImpl withMessageMovedToDeadLetterQueueOnMaxDelivery @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getSubscriptions() - .getAsync(this.resourceGroupName(), - this.namespaceName, - this.parentName, - this.name()); + return this.manager() + .serviceClient() + .getSubscriptions() + .getAsync(this.resourceGroupName(), this.namespaceName, this.parentName, this.name()); } @Override protected Mono createChildResourceAsync() { final ServiceBusSubscription self = this; - return this.manager().serviceClient().getSubscriptions() - .createOrUpdateAsync(this.resourceGroupName(), - this.namespaceName, - this.parentName, - this.name(), - this.innerModel()) + return this.manager() + .serviceClient() + .getSubscriptions() + .createOrUpdateAsync(this.resourceGroupName(), this.namespaceName, this.parentName, this.name(), + this.innerModel()) .map(inner -> { setInner(inner); return self; diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionsImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionsImpl.java index 320ac6d41b352..8525ce14bf057 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/ServiceBusSubscriptionsImpl.java @@ -18,14 +18,8 @@ /** * Implementation for Subscriptions. */ -class ServiceBusSubscriptionsImpl - extends ServiceBusChildResourcesImpl< - ServiceBusSubscription, - ServiceBusSubscriptionImpl, - SBSubscriptionInner, - SubscriptionsClient, - ServiceBusManager, - Topic> +class ServiceBusSubscriptionsImpl extends + ServiceBusChildResourcesImpl implements ServiceBusSubscriptions { private final String resourceGroupName; private final String namespaceName; @@ -34,11 +28,8 @@ class ServiceBusSubscriptionsImpl private final ClientLogger logger = new ClientLogger(ServiceBusSubscriptionsImpl.class); - protected ServiceBusSubscriptionsImpl(String resourceGroupName, - String namespaceName, - String topicName, - Region region, - ServiceBusManager manager) { + protected ServiceBusSubscriptionsImpl(String resourceGroupName, String namespaceName, String topicName, + Region region, ServiceBusManager manager) { super(manager.serviceClient().getSubscriptions(), manager); this.resourceGroupName = resourceGroupName; this.namespaceName = namespaceName; @@ -53,10 +44,7 @@ public ServiceBusSubscriptionImpl define(String name) { @Override public Mono deleteByNameAsync(String name) { - return this.innerModel().deleteAsync(this.resourceGroupName, - this.namespaceName, - this.topicName, - name); + return this.innerModel().deleteAsync(this.resourceGroupName, this.namespaceName, this.topicName, name); } @Override @@ -76,22 +64,14 @@ protected PagedIterable listInner() { @Override protected ServiceBusSubscriptionImpl wrapModel(String name) { - return new ServiceBusSubscriptionImpl(this.resourceGroupName, - this.namespaceName, - this.topicName, - name, - new SBSubscriptionInner(), - this.manager()); + return new ServiceBusSubscriptionImpl(this.resourceGroupName, this.namespaceName, this.topicName, name, + new SBSubscriptionInner(), this.manager()); } @Override protected ServiceBusSubscriptionImpl wrapModel(SBSubscriptionInner inner) { - return new ServiceBusSubscriptionImpl(this.resourceGroupName, - this.namespaceName, - this.topicName, - inner.name(), - inner, - this.manager()); + return new ServiceBusSubscriptionImpl(this.resourceGroupName, this.namespaceName, this.topicName, inner.name(), + inner, this.manager()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRuleImpl.java index 6557935c9c84e..6dd0ff79a6061 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRuleImpl.java @@ -13,24 +13,13 @@ /** * Implementation for TopicAuthorizationRule. */ -class TopicAuthorizationRuleImpl - extends AuthorizationRuleBaseImpl - implements - TopicAuthorizationRule, - TopicAuthorizationRule.Definition, - TopicAuthorizationRule.Update { +class TopicAuthorizationRuleImpl extends + AuthorizationRuleBaseImpl + implements TopicAuthorizationRule, TopicAuthorizationRule.Definition, TopicAuthorizationRule.Update { private final String namespaceName; - TopicAuthorizationRuleImpl(String resourceGroupName, - String namespaceName, - String topicName, - String name, - SBAuthorizationRuleInner inner, - ServiceBusManager manager) { + TopicAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String topicName, String name, + SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); @@ -48,21 +37,20 @@ public String topicName() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getTopics() - .getAuthorizationRuleAsync(this.resourceGroupName(), - this.namespaceName(), - this.topicName(), - this.name()); + return this.manager() + .serviceClient() + .getTopics() + .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override protected Mono createChildResourceAsync() { final TopicAuthorizationRule self = this; - return this.manager().serviceClient().getTopics().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), - this.namespaceName(), - this.topicName(), - this.name(), - this.innerModel()) + return this.manager() + .serviceClient() + .getTopics() + .createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), + this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; @@ -71,19 +59,19 @@ protected Mono createChildResourceAsync() { @Override protected Mono getKeysInnerAsync() { - return this.manager().serviceClient().getTopics() - .listKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.topicName(), - this.name()); + return this.manager() + .serviceClient() + .getTopics() + .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override - protected Mono regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { - return this.manager().serviceClient().getTopics().regenerateKeysAsync(this.resourceGroupName(), - this.namespaceName(), - this.topicName(), - this.name(), - regenerateAccessKeyParameters); + protected Mono + regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { + return this.manager() + .serviceClient() + .getTopics() + .regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), + regenerateAccessKeyParameters); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRulesImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRulesImpl.java index cffcf084413eb..7fc102c197d15 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRulesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicAuthorizationRulesImpl.java @@ -18,14 +18,8 @@ /** * Implementation for TopicAuthorizationRules. */ -class TopicAuthorizationRulesImpl - extends ServiceBusChildResourcesImpl< - TopicAuthorizationRule, - TopicAuthorizationRuleImpl, - SBAuthorizationRuleInner, - TopicsClient, - ServiceBusManager, - Topic> +class TopicAuthorizationRulesImpl extends + ServiceBusChildResourcesImpl implements TopicAuthorizationRules { private final String resourceGroupName; private final String namespaceName; @@ -34,11 +28,8 @@ class TopicAuthorizationRulesImpl private final ClientLogger logger = new ClientLogger(TopicAuthorizationRulesImpl.class); - TopicAuthorizationRulesImpl(String resourceGroupName, - String namespaceName, - String topicName, - Region region, - ServiceBusManager manager) { + TopicAuthorizationRulesImpl(String resourceGroupName, String namespaceName, String topicName, Region region, + ServiceBusManager manager) { super(manager.serviceClient().getTopics(), manager); this.resourceGroupName = resourceGroupName; this.namespaceName = namespaceName; @@ -53,41 +44,31 @@ public TopicAuthorizationRuleImpl define(String name) { @Override public Mono deleteByNameAsync(String name) { - return this.innerModel().deleteAuthorizationRuleAsync(this.resourceGroupName, - this.namespaceName, - this.topicName, - name); + return this.innerModel() + .deleteAuthorizationRuleAsync(this.resourceGroupName, this.namespaceName, this.topicName, name); } @Override protected Mono getInnerByNameAsync(String name) { - return this.innerModel().getAuthorizationRuleAsync(this.resourceGroupName, - this.namespaceName, - this.topicName, - name); + return this.innerModel() + .getAuthorizationRuleAsync(this.resourceGroupName, this.namespaceName, this.topicName, name); } @Override protected PagedFlux listInnerAsync() { - return this.innerModel().listAuthorizationRulesAsync( - this.resourceGroupName, this.namespaceName, this.topicName); + return this.innerModel() + .listAuthorizationRulesAsync(this.resourceGroupName, this.namespaceName, this.topicName); } @Override protected PagedIterable listInner() { - return this.innerModel().listAuthorizationRules(this.resourceGroupName, - this.namespaceName, - this.topicName); + return this.innerModel().listAuthorizationRules(this.resourceGroupName, this.namespaceName, this.topicName); } @Override protected TopicAuthorizationRuleImpl wrapModel(String name) { - return new TopicAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - this.topicName, - name, - new SBAuthorizationRuleInner(), - this.manager()); + return new TopicAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, this.topicName, name, + new SBAuthorizationRuleInner(), this.manager()); } @Override @@ -95,12 +76,8 @@ protected TopicAuthorizationRuleImpl wrapModel(SBAuthorizationRuleInner inner) { if (inner == null) { return null; } - return new TopicAuthorizationRuleImpl(this.resourceGroupName, - this.namespaceName, - this.topicName, - inner.name(), - inner, - this.manager()); + return new TopicAuthorizationRuleImpl(this.resourceGroupName, this.namespaceName, this.topicName, inner.name(), + inner, this.manager()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicImpl.java index 7d30700c82b61..5a1091c41596e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicImpl.java @@ -25,27 +25,15 @@ * Implementation for Topic. */ class TopicImpl - extends IndependentChildResourceImpl< - Topic, - ServiceBusNamespaceImpl, - SBTopicInner, - TopicImpl, - ServiceBusManager> - implements - Topic, - Topic.Definition, - Topic.Update { + extends IndependentChildResourceImpl + implements Topic, Topic.Definition, Topic.Update { private List> subscriptionsToCreate; private List> rulesToCreate; private List subscriptionsToDelete; private List rulesToDelete; - TopicImpl(String resourceGroupName, - String namespaceName, - String name, - Region region, - SBTopicInner inner, - ServiceBusManager manager) { + TopicImpl(String resourceGroupName, String namespaceName, String name, Region region, SBTopicInner inner, + ServiceBusManager manager) { super(name, inner, manager); this.withExistingParentResource(resourceGroupName, namespaceName); initChildrenOperationsCache(); @@ -122,8 +110,7 @@ public Duration duplicateMessageDetectionHistoryDuration() { @Override public long activeMessageCount() { - if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().activeMessageCount() == null) { + if (this.innerModel().countDetails() == null || this.innerModel().countDetails().activeMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().activeMessageCount()); @@ -132,7 +119,7 @@ public long activeMessageCount() { @Override public long deadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().deadLetterMessageCount() == null) { + || this.innerModel().countDetails().deadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().deadLetterMessageCount()); @@ -141,7 +128,7 @@ public long deadLetterMessageCount() { @Override public long scheduledMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().scheduledMessageCount() == null) { + || this.innerModel().countDetails().scheduledMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().scheduledMessageCount()); @@ -150,7 +137,7 @@ public long scheduledMessageCount() { @Override public long transferDeadLetterMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { + || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferDeadLetterMessageCount()); @@ -159,7 +146,7 @@ public long transferDeadLetterMessageCount() { @Override public long transferMessageCount() { if (this.innerModel().countDetails() == null - || this.innerModel().countDetails().transferMessageCount() == null) { + || this.innerModel().countDetails().transferMessageCount() == null) { return 0; } return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferMessageCount()); @@ -180,20 +167,14 @@ public EntityStatus status() { @Override public ServiceBusSubscriptionsImpl subscriptions() { - return new ServiceBusSubscriptionsImpl(this.resourceGroupName(), - this.parentName, - this.name(), - this.region(), - manager()); + return new ServiceBusSubscriptionsImpl(this.resourceGroupName(), this.parentName, this.name(), this.region(), + manager()); } @Override public TopicAuthorizationRulesImpl authorizationRules() { - return new TopicAuthorizationRulesImpl(this.resourceGroupName(), - this.parentName, - this.name(), - this.region(), - manager()); + return new TopicAuthorizationRulesImpl(this.resourceGroupName(), this.parentName, this.name(), this.region(), + manager()); } @Override @@ -310,19 +291,18 @@ public TopicImpl withoutSubscription(String name) { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getTopics() - .getAsync(this.resourceGroupName(), - this.parentName, - this.name()); + return this.manager() + .serviceClient() + .getTopics() + .getAsync(this.resourceGroupName(), this.parentName, this.name()); } @Override protected Mono createChildResourceAsync() { - Mono createTask = this.manager().serviceClient().getTopics() - .createOrUpdateAsync(this.resourceGroupName(), - this.parentName, - this.name(), - this.innerModel()) + Mono createTask = this.manager() + .serviceClient() + .getTopics() + .createOrUpdateAsync(this.resourceGroupName(), this.parentName, this.name(), this.innerModel()) .map(inner -> { setInner(inner); return inner; @@ -358,10 +338,7 @@ private Flux submitChildrenOperationsAsync() { if (this.rulesToDelete.size() > 0) { rulesDeleteStream = this.authorizationRules().deleteByNameAsync(this.rulesToDelete); } - return Flux.mergeDelayError(32, - subscriptionsCreateStream, - rulesCreateStream, - subscriptionsDeleteStream, + return Flux.mergeDelayError(32, subscriptionsCreateStream, rulesCreateStream, subscriptionsDeleteStream, rulesDeleteStream); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicsImpl.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicsImpl.java index 9ee42dbed2337..d30c60421b263 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/implementation/TopicsImpl.java @@ -18,14 +18,8 @@ /** * Implementation for Topics. */ -class TopicsImpl - extends ServiceBusChildResourcesImpl< - Topic, - TopicImpl, - SBTopicInner, - TopicsClient, - ServiceBusManager, - ServiceBusNamespace> +class TopicsImpl extends + ServiceBusChildResourcesImpl implements Topics { private final String resourceGroupName; private final String namespaceName; @@ -47,9 +41,7 @@ public TopicImpl define(String name) { @Override public Mono deleteByNameAsync(String name) { - return this.innerModel().deleteAsync(this.resourceGroupName, - this.namespaceName, - name); + return this.innerModel().deleteAsync(this.resourceGroupName, this.namespaceName, name); } @Override @@ -64,18 +56,13 @@ protected PagedFlux listInnerAsync() { @Override protected PagedIterable listInner() { - return this.innerModel().listByNamespace(this.resourceGroupName, - this.namespaceName); + return this.innerModel().listByNamespace(this.resourceGroupName, this.namespaceName); } @Override protected TopicImpl wrapModel(String name) { - return new TopicImpl(this.resourceGroupName, - this.namespaceName, - name, - this.region, - new SBTopicInner(), - this.manager()); + return new TopicImpl(this.resourceGroupName, this.namespaceName, name, this.region, new SBTopicInner(), + this.manager()); } @Override @@ -83,12 +70,8 @@ protected TopicImpl wrapModel(SBTopicInner inner) { if (inner == null) { return null; } - return new TopicImpl(this.resourceGroupName, - this.namespaceName, - inner.name(), - this.region, - inner, - this.manager()); + return new TopicImpl(this.resourceGroupName, this.namespaceName, inner.name(), this.region, inner, + this.manager()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationKeys.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationKeys.java index 22cd0dd98f0cd..a0478c13ad7de 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationKeys.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationKeys.java @@ -16,14 +16,17 @@ public interface AuthorizationKeys extends HasInnerModel { * @return primary key associated with the rule */ String primaryKey(); + /** * @return secondary key associated with the rule */ String secondaryKey(); + /** * @return primary connection string */ String primaryConnectionString(); + /** * @return secondary connection string */ diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRule.java index bf45875bd1d99..5c4708511ff92 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRule.java @@ -18,9 +18,8 @@ * @param the specific rule type */ @Fluent -public interface AuthorizationRule> extends - IndependentChildResource, - Refreshable { +public interface AuthorizationRule> + extends IndependentChildResource, Refreshable { /** * @return rights associated with the rule diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRules.java index a3f942526c909..83c252c7c4ae7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/AuthorizationRules.java @@ -16,9 +16,6 @@ * @param the specific rule type */ @Fluent -public interface AuthorizationRules extends - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName, - HasManager { +public interface AuthorizationRules extends SupportsListing, SupportsGettingByName, + SupportsDeletingByName, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/CheckNameAvailabilityResult.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/CheckNameAvailabilityResult.java index 3ae659bcdc46d..1ce248b915cbc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/CheckNameAvailabilityResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/CheckNameAvailabilityResult.java @@ -18,11 +18,13 @@ public interface CheckNameAvailabilityResult extends HasInnerModel, - Updatable { +public interface NamespaceAuthorizationRule + extends AuthorizationRule, Updatable { /** * @return the name of the parent namespace name */ @@ -42,16 +41,14 @@ interface WithCreate extends Creatable { /** * The entirety of the namespace authorization rule definition. */ - interface Definition extends - NamespaceAuthorizationRule.DefinitionStages.Blank, - NamespaceAuthorizationRule.DefinitionStages.WithCreate { + interface Definition extends NamespaceAuthorizationRule.DefinitionStages.Blank, + NamespaceAuthorizationRule.DefinitionStages.WithCreate { } /** * The entirety of the namespace authorization rule update. */ - interface Update extends - Appliable, - AuthorizationRule.UpdateStages.WithListenOrSendOrManage { + interface Update + extends Appliable, AuthorizationRule.UpdateStages.WithListenOrSendOrManage { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceAuthorizationRules.java index 315323189a2e9..c0a95baf6f93c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceAuthorizationRules.java @@ -10,7 +10,6 @@ * Entry point to namespace authorization rules management API. */ @Fluent -public interface NamespaceAuthorizationRules extends - AuthorizationRules, +public interface NamespaceAuthorizationRules extends AuthorizationRules, SupportsCreating { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceSku.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceSku.java index 19c5f514a6177..cfc689c9160a2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceSku.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/NamespaceSku.java @@ -10,20 +10,20 @@ */ public final class NamespaceSku { /** Static value NamespaceSku for BASIC. */ - public static final NamespaceSku BASIC = new NamespaceSku( - new SBSku().withName(SkuName.BASIC).withTier(SkuTier.BASIC)); + public static final NamespaceSku BASIC + = new NamespaceSku(new SBSku().withName(SkuName.BASIC).withTier(SkuTier.BASIC)); /** Static value NamespaceSku for STANDARD. */ - public static final NamespaceSku STANDARD = new NamespaceSku( - new SBSku().withName(SkuName.STANDARD).withTier(SkuTier.STANDARD)); + public static final NamespaceSku STANDARD + = new NamespaceSku(new SBSku().withName(SkuName.STANDARD).withTier(SkuTier.STANDARD)); /** Static value NamespaceSku for PREMIUM_CAPACITY1. */ - public static final NamespaceSku PREMIUM_CAPACITY1 = new NamespaceSku( - new SBSku().withCapacity(1).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); + public static final NamespaceSku PREMIUM_CAPACITY1 + = new NamespaceSku(new SBSku().withCapacity(1).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); /** Static value NamespaceSku for PREMIUM_CAPACITY2. */ - public static final NamespaceSku PREMIUM_CAPACITY2 = new NamespaceSku( - new SBSku().withCapacity(2).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); + public static final NamespaceSku PREMIUM_CAPACITY2 + = new NamespaceSku(new SBSku().withCapacity(2).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); /** Static value NamespaceSku for PREMIUM_CAPACITY4. */ - public static final NamespaceSku PREMIUM_CAPACITY4 = new NamespaceSku( - new SBSku().withCapacity(4).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); + public static final NamespaceSku PREMIUM_CAPACITY4 + = new NamespaceSku(new SBSku().withCapacity(4).withName(SkuName.PREMIUM).withTier(SkuTier.PREMIUM)); private final SBSku sku; @@ -34,10 +34,7 @@ public final class NamespaceSku { * @param tier sku tier */ public NamespaceSku(String name, String tier) { - this(new SBSku() - .withCapacity(null) - .withName(SkuName.fromString(name)) - .withTier(SkuTier.fromString(tier))); + this(new SBSku().withCapacity(null).withName(SkuName.fromString(name)).withTier(SkuTier.fromString(tier))); } /** @@ -48,10 +45,7 @@ public NamespaceSku(String name, String tier) { * @param capacity factor of resources allocated to host Service Bus */ public NamespaceSku(String name, String tier, int capacity) { - this(new SBSku() - .withCapacity(capacity) - .withName(SkuName.fromString(name)) - .withTier(SkuTier.fromString(tier))); + this(new SBSku().withCapacity(capacity).withName(SkuName.fromString(name)).withTier(SkuTier.fromString(tier))); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queue.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queue.java index 92835b313f93b..0be31026bf98f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queue.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queue.java @@ -19,103 +19,124 @@ * Type representing Service Bus queue. */ @Fluent -public interface Queue extends - IndependentChildResource, - Refreshable, - Updatable { +public interface Queue + extends IndependentChildResource, Refreshable, Updatable { /** * @return the exact time the queue was created */ OffsetDateTime createdAt(); + /** * @return last time a message was sent, or the last time there was a receive request to this queue */ OffsetDateTime accessedAt(); + /** * @return the exact time the queue was updated */ OffsetDateTime updatedAt(); + /** * @return the maximum size of memory allocated for the queue in megabytes */ long maxSizeInMB(); + /** * @return current size of the queue, in bytes */ long currentSizeInBytes(); + /** * @return indicates whether server-side batched operations are enabled */ boolean isBatchedOperationsEnabled(); + /** * @return indicates whether this queue has dead letter support when a message expires */ boolean isDeadLetteringEnabledForExpiredMessages(); + /** * @return indicates whether express entities are enabled */ boolean isExpressEnabled(); + /** * @return indicates whether the queue is to be partitioned across multiple message brokers */ boolean isPartitioningEnabled(); + /** * @return indicates whether the queue supports sessions */ boolean isSessionEnabled(); + /** * @return indicates if this queue requires duplicate detection */ boolean isDuplicateDetectionEnabled(); + /** * @return the duration of peek-lock which is the amount of time that the message is locked for other receivers */ long lockDurationInSeconds(); + /** * @return the idle duration after which the queue is automatically deleted */ long deleteOnIdleDurationInMinutes(); + /** * @return the duration after which the message expires, starting from when the message is sent to queue */ Duration defaultMessageTtlDuration(); + /** * @return the duration of the duplicate detection history */ Duration duplicateMessageDetectionHistoryDuration(); + /** * @return the maximum number of a message delivery before marking it as dead-lettered */ int maxDeliveryCountBeforeDeadLetteringMessage(); + /** * @return the number of messages in the queue */ long messageCount(); + /** * @return number of active messages in the queue */ long activeMessageCount(); + /** * @return number of messages in the dead-letter queue */ long deadLetterMessageCount(); + /** * @return number of messages sent to the queue that are yet to be released * for consumption */ long scheduledMessageCount(); + /** * @return number of messages transferred into dead letters */ long transferDeadLetterMessageCount(); + /** * @return number of messages transferred to another queue, topic, or subscription */ long transferMessageCount(); + /** * @return the current status of the queue */ EntityStatus status(); + /** * @return entry point to manage authorization rules for the Service Bus queue */ @@ -124,9 +145,7 @@ public interface Queue extends /** * The entirety of the Service Bus queue definition. */ - interface Definition extends - Queue.DefinitionStages.Blank, - Queue.DefinitionStages.WithCreate { + interface Definition extends Queue.DefinitionStages.Blank, Queue.DefinitionStages.WithCreate { } /** @@ -311,6 +330,7 @@ interface WithAuthorizationRule { * @return next stage of the queue definition */ WithCreate withNewSendRule(String name); + /** * Creates a listen authorization rule for the queue. * @@ -318,6 +338,7 @@ interface WithAuthorizationRule { * @return next stage of the queue definition */ WithCreate withNewListenRule(String name); + /** * Creates a manage authorization rule for the queue. * @@ -332,17 +353,11 @@ interface WithAuthorizationRule { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Queue.DefinitionStages.WithSize, - Queue.DefinitionStages.WithPartitioning, - Queue.DefinitionStages.WithDeleteOnIdle, - Queue.DefinitionStages.WithMessageLockDuration, - Queue.DefinitionStages.WithDefaultMessageTTL, - Queue.DefinitionStages.WithSession, - Queue.DefinitionStages.WithExpressMessage, - Queue.DefinitionStages.WithMessageBatching, - Queue.DefinitionStages.WithDuplicateMessageDetection, + interface WithCreate extends Creatable, Queue.DefinitionStages.WithSize, + Queue.DefinitionStages.WithPartitioning, Queue.DefinitionStages.WithDeleteOnIdle, + Queue.DefinitionStages.WithMessageLockDuration, Queue.DefinitionStages.WithDefaultMessageTTL, + Queue.DefinitionStages.WithSession, Queue.DefinitionStages.WithExpressMessage, + Queue.DefinitionStages.WithMessageBatching, Queue.DefinitionStages.WithDuplicateMessageDetection, Queue.DefinitionStages.WithExpiredMessageMovedToDeadLetterQueue, Queue.DefinitionStages.WithMessageMovedToDeadLetterQueueOnMaxDeliveryCount, Queue.DefinitionStages.WithAuthorizationRule { @@ -352,17 +367,10 @@ interface WithCreate extends /** * The template for Service Bus queue update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - Queue.UpdateStages.WithSize, - Queue.UpdateStages.WithDeleteOnIdle, - Queue.UpdateStages.WithMessageLockDuration, - Queue.UpdateStages.WithDefaultMessageTTL, - Queue.UpdateStages.WithSession, - Queue.UpdateStages.WithExpressMessage, - Queue.UpdateStages.WithMessageBatching, - Queue.UpdateStages.WithDuplicateMessageDetection, - Queue.UpdateStages.WithExpiredMessageMovedToDeadLetterQueue, + interface Update extends Appliable, Queue.UpdateStages.WithSize, Queue.UpdateStages.WithDeleteOnIdle, + Queue.UpdateStages.WithMessageLockDuration, Queue.UpdateStages.WithDefaultMessageTTL, + Queue.UpdateStages.WithSession, Queue.UpdateStages.WithExpressMessage, Queue.UpdateStages.WithMessageBatching, + Queue.UpdateStages.WithDuplicateMessageDetection, Queue.UpdateStages.WithExpiredMessageMovedToDeadLetterQueue, Queue.UpdateStages.WithMessageMovedToDeadLetterQueueOnMaxDeliveryCount, Queue.UpdateStages.WithAuthorizationRule { } @@ -552,6 +560,7 @@ interface WithAuthorizationRule { * @return next stage of the queue update */ Update withNewSendRule(String name); + /** * Creates a listen authorization rule for the queue. * @@ -559,6 +568,7 @@ interface WithAuthorizationRule { * @return next stage of the queue update */ Update withNewListenRule(String name); + /** * Creates a manage authorization rule for the queue. * diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRule.java index bcffb5b0488c2..f6cd71dda46fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRule.java @@ -12,9 +12,8 @@ * Type representing authorization rule defined for queue. */ @Fluent -public interface QueueAuthorizationRule extends - AuthorizationRule, - Updatable { +public interface QueueAuthorizationRule + extends AuthorizationRule, Updatable { /** * @return the name of the namespace that the parent queue belongs to */ @@ -32,8 +31,8 @@ interface DefinitionStages { /** * The first stage of queue authorization rule definition. */ - interface Blank extends AuthorizationRule.DefinitionStages.WithListenOrSendOrManage< - QueueAuthorizationRule.DefinitionStages.WithCreate> { + interface Blank extends + AuthorizationRule.DefinitionStages.WithListenOrSendOrManage { } /** @@ -48,16 +47,14 @@ interface WithCreate extends Creatable { /** * The entirety of the queue authorization rule definition. */ - interface Definition extends - QueueAuthorizationRule.DefinitionStages.Blank, - QueueAuthorizationRule.DefinitionStages.WithCreate { + interface Definition + extends QueueAuthorizationRule.DefinitionStages.Blank, QueueAuthorizationRule.DefinitionStages.WithCreate { } /** * The entirety of the queue authorization rule update. */ - interface Update extends - Appliable, + interface Update extends Appliable, AuthorizationRule.UpdateStages.WithListenOrSendOrManage { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRules.java index 3549c917d2d54..97afe1e9daf03 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/QueueAuthorizationRules.java @@ -10,7 +10,6 @@ * Entry point to queue authorization rules management API. */ @Fluent -public interface QueueAuthorizationRules extends - AuthorizationRules, +public interface QueueAuthorizationRules extends AuthorizationRules, SupportsCreating { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queues.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queues.java index ad15e87e8491c..755e2fa58e277 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queues.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Queues.java @@ -11,15 +11,10 @@ import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; import com.azure.resourcemanager.servicebus.ServiceBusManager; - /** * Entry point to service bus queue management API in Azure. */ @Fluent -public interface Queues extends - SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName, - HasManager { +public interface Queues extends SupportsCreating, SupportsListing, + SupportsGettingByName, SupportsDeletingByName, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespace.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespace.java index 9a7159b20b7af..852fb862367e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespace.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespace.java @@ -19,26 +19,28 @@ * An immutable client-side representation of an Azure Service Bus namespace. */ @Fluent -public interface ServiceBusNamespace extends - GroupableResource, - Refreshable, - Updatable { +public interface ServiceBusNamespace extends GroupableResource, + Refreshable, Updatable { /** * @return the relative DNS name of the Service Bus namespace */ String dnsLabel(); + /** * @return fully qualified domain name (FQDN) of the Service Bus namespace */ String fqdn(); + /** * @return sku value */ NamespaceSku sku(); + /** * @return time the namespace was created */ OffsetDateTime createdAt(); + /** * @return time the namespace was updated */ @@ -48,10 +50,12 @@ public interface ServiceBusNamespace extends * @return entry point to manage queue entities in the Service Bus namespace */ Queues queues(); + /** * @return entry point to manage topics entities in the Service Bus namespace */ Topics topics(); + /** * @return entry point to manage authorization rules for the Service Bus namespace */ @@ -60,10 +64,8 @@ public interface ServiceBusNamespace extends /** * The entirety of the Service Bus namespace definition. */ - interface Definition extends - ServiceBusNamespace.DefinitionStages.Blank, - ServiceBusNamespace.DefinitionStages.WithGroup, - ServiceBusNamespace.DefinitionStages.WithCreate { + interface Definition extends ServiceBusNamespace.DefinitionStages.Blank, + ServiceBusNamespace.DefinitionStages.WithGroup, ServiceBusNamespace.DefinitionStages.WithCreate { } /** @@ -135,6 +137,7 @@ interface WithAuthorizationRule { * @return next stage of the Service Bus namespace definition */ WithCreate withNewSendRule(String name); + /** * Creates a listen authorization rule for the Service Bus namespace. * @@ -142,6 +145,7 @@ interface WithAuthorizationRule { * @return next stage of the Service Bus namespace definition */ WithCreate withNewListenRule(String name); + /** * Creates a manage authorization rule for the Service Bus namespace. * @@ -156,26 +160,18 @@ interface WithAuthorizationRule { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Resource.DefinitionWithTags, - ServiceBusNamespace.DefinitionStages.WithSku, - ServiceBusNamespace.DefinitionStages.WithQueue, - ServiceBusNamespace.DefinitionStages.WithTopic, - ServiceBusNamespace.DefinitionStages.WithAuthorizationRule { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + ServiceBusNamespace.DefinitionStages.WithSku, ServiceBusNamespace.DefinitionStages.WithQueue, + ServiceBusNamespace.DefinitionStages.WithTopic, ServiceBusNamespace.DefinitionStages.WithAuthorizationRule { } } /** * The template for a Service Bus namespace update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - Resource.UpdateWithTags, - ServiceBusNamespace.UpdateStages.WithSku, - ServiceBusNamespace.UpdateStages.WithQueue, - ServiceBusNamespace.UpdateStages.WithTopic, - ServiceBusNamespace.UpdateStages.WithAuthorizationRule { + interface Update extends Appliable, Resource.UpdateWithTags, + ServiceBusNamespace.UpdateStages.WithSku, ServiceBusNamespace.UpdateStages.WithQueue, + ServiceBusNamespace.UpdateStages.WithTopic, ServiceBusNamespace.UpdateStages.WithAuthorizationRule { } /** @@ -251,6 +247,7 @@ interface WithAuthorizationRule { * @return next stage of the Service Bus namespace update */ Update withNewSendRule(String name); + /** * Creates a listen authorization rule for the Service Bus namespace. * @@ -258,6 +255,7 @@ interface WithAuthorizationRule { * @return next stage of the Service Bus namespace update */ Update withNewListenRule(String name); + /** * Creates a manage authorization rule for the Service Bus namespace. * @@ -265,6 +263,7 @@ interface WithAuthorizationRule { * @return next stage of the Service Bus namespace update */ Update withNewManageRule(String name); + /** * Removes an authorization rule from the Service Bus namespace. * diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespaces.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespaces.java index d5de17fa908e8..7d9f17ae5a8e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespaces.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusNamespaces.java @@ -20,17 +20,11 @@ * Entry point to Service Bus namespace API in Azure. */ @Fluent -public interface ServiceBusNamespaces extends - SupportsCreating, - SupportsBatchCreation, - SupportsBatchDeletion, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - HasManager { +public interface ServiceBusNamespaces + extends SupportsCreating, SupportsBatchCreation, + SupportsBatchDeletion, SupportsListing, SupportsListingByResourceGroup, + SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, + SupportsDeletingByResourceGroup, HasManager { /** * Checks if namespace name is valid and is not in use. * diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscription.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscription.java index 16be555ded0f8..40a624f9ccb1a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscription.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscription.java @@ -19,79 +19,94 @@ * Type representing service bus topic subscription. */ @Fluent -public interface ServiceBusSubscription extends - IndependentChildResource, - Refreshable, - Updatable { +public interface ServiceBusSubscription extends IndependentChildResource, + Refreshable, Updatable { /** * @return the exact time the message was created */ OffsetDateTime createdAt(); + /** * @return last time there was a receive request to this subscription */ OffsetDateTime accessedAt(); + /** * @return the exact time the message was updated */ OffsetDateTime updatedAt(); + /** * @return indicates whether server-side batched operations are enabled */ boolean isBatchedOperationsEnabled(); + /** * @return indicates whether this subscription has dead letter support when a message expires */ boolean isDeadLetteringEnabledForExpiredMessages(); + /** * @return indicates whether the subscription supports sessions */ boolean isSessionEnabled(); + /** * @return the duration of peek-lock which is the amount of time that the message is locked for other receivers */ long lockDurationInSeconds(); + /** * @return the idle duration after which the subscription is automatically deleted. */ long deleteOnIdleDurationInMinutes(); + /** * @return the duration after which the message expires, starting from when the message is sent to subscription. */ Duration defaultMessageTtlDuration(); + /** * @return the maximum number of a message delivery before marking it as dead-lettered */ int maxDeliveryCountBeforeDeadLetteringMessage(); + /** * @return the number of messages in the subscription */ long messageCount(); + /** * @return number of active messages in the subscription */ long activeMessageCount(); + /** * @return number of messages in the dead-letter subscription */ long deadLetterMessageCount(); + /** * @return number of messages sent to the subscription that are yet to be released * for consumption */ long scheduledMessageCount(); + /** * @return number of messages transferred into dead letters */ long transferDeadLetterMessageCount(); + /** * @return number of messages transferred to another queue, topic, or subscription */ long transferMessageCount(); + /** * @return the current status of the subscription */ EntityStatus status(); + /** * @return indicates whether subscription has dead letter support on filter evaluation exceptions */ @@ -100,9 +115,8 @@ public interface ServiceBusSubscription extends /** * The entirety of the subscription definition. */ - interface Definition extends - ServiceBusSubscription.DefinitionStages.Blank, - ServiceBusSubscription.DefinitionStages.WithCreate { + interface Definition + extends ServiceBusSubscription.DefinitionStages.Blank, ServiceBusSubscription.DefinitionStages.WithCreate { } /** @@ -253,29 +267,24 @@ interface WithAuthorizationRule { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - ServiceBusSubscription.DefinitionStages.WithDeleteOnIdle, + interface WithCreate + extends Creatable, ServiceBusSubscription.DefinitionStages.WithDeleteOnIdle, ServiceBusSubscription.DefinitionStages.WithMessageLockDuration, ServiceBusSubscription.DefinitionStages.WithDefaultMessageTTL, ServiceBusSubscription.DefinitionStages.WithSession, ServiceBusSubscription.DefinitionStages.WithMessageBatching, ServiceBusSubscription.DefinitionStages.WithExpiredMessageMovedToDeadLetterSubscription, ServiceBusSubscription.DefinitionStages.WithMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount, - ServiceBusSubscription.DefinitionStages. - WithMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException { + ServiceBusSubscription.DefinitionStages.WithMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException { } } /** * The template for a subscription update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - ServiceBusSubscription.UpdateStages.WithDeleteOnIdle, + interface Update extends Appliable, ServiceBusSubscription.UpdateStages.WithDeleteOnIdle, ServiceBusSubscription.UpdateStages.WithMessageLockDuration, - ServiceBusSubscription.UpdateStages.WithDefaultMessageTTL, - ServiceBusSubscription.UpdateStages.WithSession, + ServiceBusSubscription.UpdateStages.WithDefaultMessageTTL, ServiceBusSubscription.UpdateStages.WithSession, ServiceBusSubscription.UpdateStages.WithMessageBatching, ServiceBusSubscription.UpdateStages.WithExpiredMessageMovedToDeadLetterSubscription, ServiceBusSubscription.UpdateStages.WithMessageMovedToDeadLetterQueueOnMaxDeliveryCount, diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscriptions.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscriptions.java index b5c9149147dff..172454cd26dac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscriptions.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/ServiceBusSubscriptions.java @@ -15,10 +15,7 @@ * Entry point to service bus queue management API in Azure. */ @Fluent -public interface ServiceBusSubscriptions extends - SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName, - HasManager { +public interface ServiceBusSubscriptions + extends SupportsCreating, SupportsListing, + SupportsGettingByName, SupportsDeletingByName, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topic.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topic.java index f158d7b53e4e6..51e2761e0d7c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topic.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topic.java @@ -20,93 +20,110 @@ * Type representing Service Bus topic. */ @Fluent -public interface Topic extends - IndependentChildResource, - Refreshable, - Updatable, - HasInnerModel { +public interface Topic extends IndependentChildResource, Refreshable, + Updatable, HasInnerModel { /** * @return the exact time the topic was created */ OffsetDateTime createdAt(); + /** * @return last time a message was sent, or the last time there was a receive request to this topic */ OffsetDateTime accessedAt(); + /** * @return the exact time the topic was updated */ OffsetDateTime updatedAt(); + /** * @return the maximum size of memory allocated for the topic in megabytes */ long maxSizeInMB(); + /** * @return current size of the topic, in bytes */ long currentSizeInBytes(); + /** * @return indicates whether server-side batched operations are enabled */ boolean isBatchedOperationsEnabled(); + /** * @return indicates whether express entities are enabled */ boolean isExpressEnabled(); + /** * @return indicates whether the topic is to be partitioned across multiple message brokers */ boolean isPartitioningEnabled(); + /** * @return indicates if this topic requires duplicate detection */ boolean isDuplicateDetectionEnabled(); + /** * @return the idle duration after which the topic is automatically deleted */ long deleteOnIdleDurationInMinutes(); + /** * @return the duration after which the message expires, starting from when the message is sent to topic */ Duration defaultMessageTtlDuration(); + /** * @return the duration of the duplicate detection history */ Duration duplicateMessageDetectionHistoryDuration(); + /** * @return number of active messages in the topic */ long activeMessageCount(); + /** * @return number of messages in the dead-letter topic */ long deadLetterMessageCount(); + /** * @return number of messages sent to the topic that are yet to be released * for consumption */ long scheduledMessageCount(); + /** * @return number of messages transferred into dead letters */ long transferDeadLetterMessageCount(); + /** * @return number of messages transferred to another topic, topic, or subscription */ long transferMessageCount(); + /** * @return number of subscriptions for the topic */ int subscriptionCount(); + /** * @return the current status of the topic */ EntityStatus status(); + /** * @return entry point to manage subscriptions associated with the topic */ ServiceBusSubscriptions subscriptions(); + /** * @return entry point to manage authorization rules for the Service Bus topic */ @@ -115,9 +132,7 @@ public interface Topic extends /** * The entirety of the Service Bus topic definition. */ - interface Definition extends - Topic.DefinitionStages.Blank, - Topic.DefinitionStages.WithCreate { + interface Definition extends Topic.DefinitionStages.Blank, Topic.DefinitionStages.WithCreate { } /** @@ -260,6 +275,7 @@ interface WithAuthorizationRule { * @return next stage of the topic definition */ WithCreate withNewSendRule(String name); + /** * Creates a listen authorization rule for the topic. * @@ -267,6 +283,7 @@ interface WithAuthorizationRule { * @return next stage of the topic definition */ WithCreate withNewListenRule(String name); + /** * Creates a manage authorization rule for the topic. * @@ -281,33 +298,21 @@ interface WithAuthorizationRule { * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ - interface WithCreate extends - Creatable, - Topic.DefinitionStages.WithSize, - Topic.DefinitionStages.WithPartitioning, - Topic.DefinitionStages.WithDeleteOnIdle, - Topic.DefinitionStages.WithDefaultMessageTTL, - Topic.DefinitionStages.WithExpressMessage, - Topic.DefinitionStages.WithMessageBatching, - Topic.DefinitionStages.WithDuplicateMessageDetection, - Topic.DefinitionStages.WithSubscription, - Topic.DefinitionStages.WithAuthorizationRule { + interface WithCreate extends Creatable, Topic.DefinitionStages.WithSize, + Topic.DefinitionStages.WithPartitioning, Topic.DefinitionStages.WithDeleteOnIdle, + Topic.DefinitionStages.WithDefaultMessageTTL, Topic.DefinitionStages.WithExpressMessage, + Topic.DefinitionStages.WithMessageBatching, Topic.DefinitionStages.WithDuplicateMessageDetection, + Topic.DefinitionStages.WithSubscription, Topic.DefinitionStages.WithAuthorizationRule { } } /** * The template for a Service Bus topic update operation, containing all the settings that can be modified. */ - interface Update extends - Appliable, - Topic.UpdateStages.WithSize, - Topic.UpdateStages.WithDeleteOnIdle, - Topic.UpdateStages.WithDefaultMessageTTL, - Topic.UpdateStages.WithExpressMessage, - Topic.UpdateStages.WithMessageBatching, - Topic.UpdateStages.WithDuplicateMessageDetection, - Topic.UpdateStages.WithSubscription, - Topic.UpdateStages.WithAuthorizationRule { + interface Update extends Appliable, Topic.UpdateStages.WithSize, Topic.UpdateStages.WithDeleteOnIdle, + Topic.UpdateStages.WithDefaultMessageTTL, Topic.UpdateStages.WithExpressMessage, + Topic.UpdateStages.WithMessageBatching, Topic.UpdateStages.WithDuplicateMessageDetection, + Topic.UpdateStages.WithSubscription, Topic.UpdateStages.WithAuthorizationRule { } /** @@ -449,6 +454,7 @@ interface WithAuthorizationRule { * @return next stage of the topic update */ Update withNewSendRule(String name); + /** * Creates a listen authorization rule for the topic. * @@ -456,6 +462,7 @@ interface WithAuthorizationRule { * @return next stage of the topic update */ Update withNewListenRule(String name); + /** * Creates a manage authorization rule for the topic. * diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRule.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRule.java index 94f2358d84c2b..c28fc04e5abdf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRule.java @@ -12,9 +12,8 @@ * Type representing authorization rule defined for topic. */ @Fluent -public interface TopicAuthorizationRule extends - AuthorizationRule, - Updatable { +public interface TopicAuthorizationRule + extends AuthorizationRule, Updatable { /** * @return the name of the namespace that the parent topic belongs to */ @@ -32,9 +31,8 @@ interface DefinitionStages { /** * The first stage of topic authorization rule definition. */ - interface Blank extends AuthorizationRule - .DefinitionStages - .WithListenOrSendOrManage { + interface Blank extends + AuthorizationRule.DefinitionStages.WithListenOrSendOrManage { } /** @@ -49,16 +47,14 @@ interface WithCreate extends Creatable { /** * The entirety of the topic authorization rule definition. */ - interface Definition extends - TopicAuthorizationRule.DefinitionStages.Blank, - TopicAuthorizationRule.DefinitionStages.WithCreate { + interface Definition + extends TopicAuthorizationRule.DefinitionStages.Blank, TopicAuthorizationRule.DefinitionStages.WithCreate { } /** * The entirety of the topic authorization rule update. */ - interface Update extends - Appliable, + interface Update extends Appliable, AuthorizationRule.UpdateStages.WithListenOrSendOrManage { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRules.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRules.java index 2144fe0ce9bd3..c6e3a7065de08 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/TopicAuthorizationRules.java @@ -10,7 +10,6 @@ * Entry point to topic authorization rules management API. */ @Fluent -public interface TopicAuthorizationRules extends - AuthorizationRules, +public interface TopicAuthorizationRules extends AuthorizationRules, SupportsCreating { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topics.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topics.java index 0d1aa54108d9d..82a2120de9651 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topics.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/main/java/com/azure/resourcemanager/servicebus/models/Topics.java @@ -15,10 +15,6 @@ * Entry point to Service Bus topic management API in Azure. */ @Fluent -public interface Topics extends - SupportsCreating, - SupportsListing, - SupportsGettingByName, - SupportsDeletingByName, - HasManager { +public interface Topics extends SupportsCreating, SupportsListing, + SupportsGettingByName, SupportsDeletingByName, HasManager { } diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/ServiceBusOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/ServiceBusOperationsTests.java index d80c86974e1fb..b9b02b0031042 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/ServiceBusOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/ServiceBusOperationsTests.java @@ -45,21 +45,10 @@ public class ServiceBusOperationsTests extends ResourceManagerTestProxyTestBase private String rgName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -81,20 +70,17 @@ protected void cleanUpResources() { @Test public void canCRUDOnSimpleNamespace() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.BASIC) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.BASIC) + .create(); - ServiceBusNamespace namespace = serviceBusManager.namespaces() - .getByResourceGroup(rgName, namespaceDNSLabel); + ServiceBusNamespace namespace = serviceBusManager.namespaces().getByResourceGroup(rgName, namespaceDNSLabel); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); @@ -135,9 +121,7 @@ public void canCRUDOnSimpleNamespace() { Assertions.assertTrue(defaultNsRule.namespaceName().equalsIgnoreCase(namespaceDNSLabel)); Assertions.assertNotNull(defaultNsRule.resourceGroupName()); Assertions.assertTrue(defaultNsRule.resourceGroupName().equalsIgnoreCase(rgName)); - namespace.update() - .withSku(NamespaceSku.STANDARD) - .apply(); + namespace.update().withSku(NamespaceSku.STANDARD).apply(); Assertions.assertTrue(namespace.sku().name().equals(NamespaceSku.STANDARD.name())); serviceBusManager.namespaces().deleteByResourceGroup(rgName, namespace.name()); } @@ -145,24 +129,20 @@ public void canCRUDOnSimpleNamespace() { @Test public void canCreateNamespaceThenCRUDOnQueue() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); String queueName = generateRandomResourceName("queue1-", 15); - Queue queue = namespace.queues() - .define(queueName) - .create(); + Queue queue = namespace.queues().define(queueName).create(); Assertions.assertNotNull(queue); Assertions.assertNotNull(queue.innerModel()); @@ -203,11 +183,11 @@ public void canCreateNamespaceThenCRUDOnQueue() { // Assertions.assertFalse(foundQueue.isDeadLetteringEnabledForExpiredMessages()); foundQueue = foundQueue.update() - .withMessageLockDurationInSeconds(120) - .withDefaultMessageTTL(Duration.ofMinutes(20)) - .withExpiredMessageMovedToDeadLetterQueue() - .withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(25) - .apply(); + .withMessageLockDurationInSeconds(120) + .withDefaultMessageTTL(Duration.ofMinutes(20)) + .withExpiredMessageMovedToDeadLetterQueue() + .withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(25) + .apply(); Assertions.assertEquals(120, foundQueue.lockDurationInSeconds()); Assertions.assertTrue(foundQueue.isDeadLetteringEnabledForExpiredMessages()); Assertions.assertEquals(25, foundQueue.maxDeliveryCountBeforeDeadLetteringMessage()); @@ -217,21 +197,19 @@ public void canCreateNamespaceThenCRUDOnQueue() { @Test public void canCreateDeleteQueueWithNamespace() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); String queueName = generateRandomResourceName("queue1-", 15); // Create NS with Queue // ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .withNewQueue(queueName, 1024) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .withNewQueue(queueName, 1024) + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); // Lookup queue @@ -249,9 +227,7 @@ public void canCreateDeleteQueueWithNamespace() { Assertions.assertNotNull(foundQueue); // Remove Queue // - namespace.update() - .withoutQueue(queueName) - .apply(); + namespace.update().withoutQueue(queueName).apply(); queuesInNamespace = namespace.queues().list(); Assertions.assertNotNull(queuesInNamespace); Assertions.assertEquals(0, TestUtilities.getSize(queuesInNamespace)); @@ -260,24 +236,20 @@ public void canCreateDeleteQueueWithNamespace() { @Test public void canCreateNamespaceThenCRUDOnTopic() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); String topicName = generateRandomResourceName("topic1-", 15); - Topic topic = namespace.topics() - .define(topicName) - .create(); + Topic topic = namespace.topics().define(topicName).create(); Assertions.assertNotNull(topic); Assertions.assertNotNull(topic.innerModel()); @@ -311,10 +283,10 @@ public void canCreateNamespaceThenCRUDOnTopic() { } Assertions.assertNotNull(foundTopic); foundTopic = foundTopic.update() - .withDefaultMessageTTL(Duration.ofMinutes(20)) - .withDuplicateMessageDetectionHistoryDuration(Duration.ofMinutes(15)) - .withDeleteOnIdleDurationInMinutes(25) - .apply(); + .withDefaultMessageTTL(Duration.ofMinutes(20)) + .withDuplicateMessageDetectionHistoryDuration(Duration.ofMinutes(15)) + .withDeleteOnIdleDurationInMinutes(25) + .apply(); Duration ttlDuration = foundTopic.defaultMessageTtlDuration(); Assertions.assertNotNull(ttlDuration); Assertions.assertEquals(20, ttlDuration.toMinutes()); @@ -329,21 +301,19 @@ public void canCreateNamespaceThenCRUDOnTopic() { @Test public void canCreateDeleteTopicWithNamespace() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); String topicName = generateRandomResourceName("topic1-", 15); // Create NS with Topic // ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .withNewTopic(topicName, 1024) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .withNewTopic(topicName, 1024) + .create(); Assertions.assertNotNull(namespace); Assertions.assertNotNull(namespace.innerModel()); // Lookup topic @@ -361,9 +331,7 @@ public void canCreateDeleteTopicWithNamespace() { Assertions.assertNotNull(foundTopic); // Remove Topic // - namespace.update() - .withoutTopic(topicName) - .apply(); + namespace.update().withoutTopic(topicName).apply(); topicsInNamespace = namespace.topics().list(); Assertions.assertNotNull(topicsInNamespace); Assertions.assertEquals(0, TestUtilities.getSize(topicsInNamespace)); @@ -372,9 +340,7 @@ public void canCreateDeleteTopicWithNamespace() { @Test public void canOperateOnAuthorizationRules() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); String queueName = generateRandomResourceName("queue1-", 15); @@ -383,14 +349,14 @@ public void canOperateOnAuthorizationRules() { // Create NS with Queue, Topic and authorization rule // ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .withNewQueue(queueName, 1024) - .withNewTopic(topicName, 1024) - .withNewManageRule(nsRuleName) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .withNewQueue(queueName, 1024) + .withNewTopic(topicName, 1024) + .withNewManageRule(nsRuleName) + .create(); // Lookup ns authorization rule // PagedIterable rulesInNamespace = namespace.authorizationRules().list(); @@ -426,15 +392,10 @@ public void canOperateOnAuthorizationRules() { Assertions.assertNotNull(queue); Assertions.assertNotNull(queue.innerModel()); - QueueAuthorizationRule qRule = queue.authorizationRules() - .define("rule1") - .withListeningEnabled() - .create(); + QueueAuthorizationRule qRule = queue.authorizationRules().define("rule1").withListeningEnabled().create(); Assertions.assertNotNull(qRule); Assertions.assertNotNull(qRule.rights().contains(AccessRights.LISTEN)); - qRule = qRule.update() - .withManagementEnabled() - .apply(); + qRule = qRule.update().withManagementEnabled().apply(); Assertions.assertNotNull(qRule.rights().contains(AccessRights.MANAGE)); PagedIterable rulesInQueue = queue.authorizationRules().list(); Assertions.assertTrue(TestUtilities.getSize(rulesInQueue) > 0); @@ -455,15 +416,10 @@ public void canOperateOnAuthorizationRules() { Topic topic = topicsInNamespace.iterator().next(); Assertions.assertNotNull(topic); Assertions.assertNotNull(topic.innerModel()); - TopicAuthorizationRule tRule = topic.authorizationRules() - .define("rule2") - .withSendingEnabled() - .create(); + TopicAuthorizationRule tRule = topic.authorizationRules().define("rule2").withSendingEnabled().create(); Assertions.assertNotNull(tRule); Assertions.assertNotNull(tRule.rights().contains(AccessRights.SEND)); - tRule = tRule.update() - .withManagementEnabled() - .apply(); + tRule = tRule.update().withManagementEnabled().apply(); Assertions.assertNotNull(tRule.rights().contains(AccessRights.MANAGE)); PagedIterable rulesInTopic = topic.authorizationRules().list(); Assertions.assertTrue(TestUtilities.getSize(rulesInTopic) > 0); @@ -482,9 +438,8 @@ public void canOperateOnAuthorizationRules() { public void canPerformOnNamespaceActions() { rgName = null; String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); - CheckNameAvailabilityResult availabilityResult = serviceBusManager - .namespaces() - .checkNameAvailability(namespaceDNSLabel); + CheckNameAvailabilityResult availabilityResult + = serviceBusManager.namespaces().checkNameAvailability(namespaceDNSLabel); Assertions.assertNotNull(availabilityResult); if (!availabilityResult.isAvailable()) { Assertions.assertNotNull(availabilityResult.unavailabilityReason()); @@ -495,9 +450,7 @@ public void canPerformOnNamespaceActions() { @Test public void canPerformCRUDOnSubscriptions() { Region region = Region.US_EAST; - Creatable rgCreatable = resourceManager.resourceGroups() - .define(rgName) - .withRegion(region); + Creatable rgCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15); String topicName = generateRandomResourceName("topic1-", 15); @@ -505,18 +458,17 @@ public void canPerformCRUDOnSubscriptions() { // Create NS with Topic // ServiceBusNamespace namespace = serviceBusManager.namespaces() - .define(namespaceDNSLabel) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withSku(NamespaceSku.STANDARD) - .withNewTopic(topicName, 1024) - .create(); + .define(namespaceDNSLabel) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withSku(NamespaceSku.STANDARD) + .withNewTopic(topicName, 1024) + .create(); // Create Topic subscriptions and list it // Topic topic = namespace.topics().getByName(topicName); - ServiceBusSubscription subscription = topic.subscriptions().define(subscriptionName) - .withDefaultMessageTTL(Duration.ofMinutes(20)) - .create(); + ServiceBusSubscription subscription + = topic.subscriptions().define(subscriptionName).withDefaultMessageTTL(Duration.ofMinutes(20)).create(); Assertions.assertNotNull(subscription); Assertions.assertNotNull(subscription.innerModel()); Assertions.assertEquals(20, subscription.defaultMessageTtlDuration().toMinutes()); @@ -560,8 +512,7 @@ public void canCRUDQueryWithSlashInName() { .withSku(NamespaceSku.BASIC) .create(); - Queue queue = serviceBusNamespace.queues().define(queueName) - .create(); + Queue queue = serviceBusNamespace.queues().define(queueName).create(); Assertions.assertEquals(1, serviceBusNamespace.queues().list().stream().count()); diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/TypeSerializationTests.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/TypeSerializationTests.java index 9396a77c2422f..c10fdcee82b40 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/TypeSerializationTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/test/java/com/azure/resourcemanager/servicebus/TypeSerializationTests.java @@ -18,7 +18,8 @@ public class TypeSerializationTests { public void testQueueDurationSerialization() throws Exception { SerializerAdapter adapter = SerializerFactory.createDefaultManagementSerializerAdapter(); - String queueJson = "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/javasb759933551/providers/Microsoft.ServiceBus/namespaces/jvsbns56571ea/queues/queue1-39374a\",\"name\":\"queue1-39374a\",\"type\":\"Microsoft.ServiceBus/Namespaces/Queues\",\"location\":\"East US\",\"properties\":{\"lockDuration\":\"PT1M\",\"maxSizeInMegabytes\":1024,\"requiresDuplicateDetection\":false,\"requiresSession\":false,\"defaultMessageTimeToLive\":\"P10675199DT2H48M5.4775807S\",\"deadLetteringOnMessageExpiration\":false,\"enableBatchedOperations\":true,\"duplicateDetectionHistoryTimeWindow\":\"PT10M\",\"maxDeliveryCount\":10,\"sizeInBytes\":0,\"messageCount\":0,\"status\":\"Active\",\"autoDeleteOnIdle\":\"P10675199DT2H48M5.4775807S\",\"enablePartitioning\":false,\"enableExpress\":false,\"countDetails\":{\"activeMessageCount\":0,\"deadLetterMessageCount\":0,\"scheduledMessageCount\":0,\"transferMessageCount\":0,\"transferDeadLetterMessageCount\":0},\"createdAt\":\"2021-03-24T07:16:45.943Z\",\"updatedAt\":\"2021-03-24T07:16:45.973Z\",\"accessedAt\":\"0001-01-01T00:00:00\"}}"; + String queueJson + = "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/javasb759933551/providers/Microsoft.ServiceBus/namespaces/jvsbns56571ea/queues/queue1-39374a\",\"name\":\"queue1-39374a\",\"type\":\"Microsoft.ServiceBus/Namespaces/Queues\",\"location\":\"East US\",\"properties\":{\"lockDuration\":\"PT1M\",\"maxSizeInMegabytes\":1024,\"requiresDuplicateDetection\":false,\"requiresSession\":false,\"defaultMessageTimeToLive\":\"P10675199DT2H48M5.4775807S\",\"deadLetteringOnMessageExpiration\":false,\"enableBatchedOperations\":true,\"duplicateDetectionHistoryTimeWindow\":\"PT10M\",\"maxDeliveryCount\":10,\"sizeInBytes\":0,\"messageCount\":0,\"status\":\"Active\",\"autoDeleteOnIdle\":\"P10675199DT2H48M5.4775807S\",\"enablePartitioning\":false,\"enableExpress\":false,\"countDetails\":{\"activeMessageCount\":0,\"deadLetterMessageCount\":0,\"scheduledMessageCount\":0,\"transferMessageCount\":0,\"transferDeadLetterMessageCount\":0},\"createdAt\":\"2021-03-24T07:16:45.943Z\",\"updatedAt\":\"2021-03-24T07:16:45.973Z\",\"accessedAt\":\"0001-01-01T00:00:00\"}}"; SBQueueInner queue = adapter.deserialize(queueJson, SBQueueInner.class, SerializerEncoding.JSON); Duration autoDeleteOnIdle = queue.autoDeleteOnIdle(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml index 138025abeb93b..4b14d8e9a0b2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml @@ -51,6 +51,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/SqlServerManager.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/SqlServerManager.java index d83fe642f1278..647300a419ac8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/SqlServerManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/SqlServerManager.java @@ -32,11 +32,8 @@ public class SqlServerManager extends Manager { * @param profile The AzureProfile to use. */ protected SqlServerManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new SqlManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new SqlManagementClientBuilder().pipeline(httpPipeline) .subscriptionId(profile.getSubscriptionId()) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/LongTermRetentionBackupsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/LongTermRetentionBackupsClientImpl.java index ab62411938b66..d0a33804ca132 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/LongTermRetentionBackupsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/LongTermRetentionBackupsClientImpl.java @@ -3165,7 +3165,7 @@ public Mono copyByResourceGroupAsyn String backupName, CopyLongTermRetentionBackupParameters parameters) { return beginCopyByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, parameters).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -3190,7 +3190,7 @@ private Mono copyByResourceGroupAsy String backupName, CopyLongTermRetentionBackupParameters parameters, Context context) { return beginCopyByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, parameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -3494,7 +3494,7 @@ public Mono updateByResourceGroupAs String backupName, UpdateLongTermRetentionBackupParameters parameters) { return beginUpdateByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, parameters).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** @@ -3519,7 +3519,7 @@ private Mono updateByResourceGroupA String backupName, UpdateLongTermRetentionBackupParameters parameters, Context context) { return beginUpdateByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, parameters, context).last() - .flatMap(this.client::getLroFinalResultOrError); + .flatMap(this.client::getLroFinalResultOrError); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientImpl.java index da9c94e6aa70f..43c65137f6207 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientImpl.java @@ -456,7 +456,7 @@ public Mono createOrUpdateAsyn DatabaseVulnerabilityAssessmentRuleBaselineInner parameters) { return createOrUpdateWithResponseAsync(resourceGroupName, managedInstanceName, databaseName, vulnerabilityAssessmentName, ruleId, baselineName, parameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ReplicationLinkImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ReplicationLinkImpl.java index a8f7301a0439a..deab8ad821389 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ReplicationLinkImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/ReplicationLinkImpl.java @@ -22,10 +22,7 @@ class ReplicationLinkImpl extends RefreshableWrapperImpl getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getReplicationLinks() .getAsync(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()); } @@ -105,27 +100,21 @@ public String replicationMode() { @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getReplicationLinks() .delete(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()); } @Override public void failover() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getReplicationLinks() .failover(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()); } @Override public Mono failoverAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getReplicationLinks() .failoverAsync(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()) .then(); @@ -133,18 +122,14 @@ public Mono failoverAsync() { @Override public void forceFailoverAllowDataLoss() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getReplicationLinks() .failoverAllowDataLoss(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()); } @Override public Mono forceFailoverAllowDataLossAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getReplicationLinks() .failoverAllowDataLossAsync(this.resourceGroupName, this.sqlServerName, this.databaseName(), this.name()) .then(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlChildrenOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlChildrenOperationsImpl.java index 5b20c15672575..c467106877612 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlChildrenOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlChildrenOperationsImpl.java @@ -47,21 +47,17 @@ public Mono getAsync(String name) { @Override public FluentModelT getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -82,21 +78,17 @@ public Mono deleteAsync(String name) { @Override public void deleteById(String id) { Objects.requireNonNull(id); - this - .deleteBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + this.deleteBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); - return this - .deleteBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.deleteBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseAutomaticTuningImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseAutomaticTuningImpl.java index 38fe2f2c79d60..130e5bb2182af 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseAutomaticTuningImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseAutomaticTuningImpl.java @@ -32,20 +32,12 @@ public class SqlDatabaseAutomaticTuningImpl private Map automaticTuningOptionsMap; SqlDatabaseAutomaticTuningImpl(SqlDatabaseImpl database, DatabaseAutomaticTuningInner innerObject) { - this( - database.resourceGroupName, - database.sqlServerName, - database.name(), - innerObject, + this(database.resourceGroupName, database.sqlServerName, database.name(), innerObject, database.sqlServerManager); } - SqlDatabaseAutomaticTuningImpl( - String resourceGroupName, - String sqlServerName, - String sqlDatabaseName, - DatabaseAutomaticTuningInner innerObject, - SqlServerManager sqlServerManager) { + SqlDatabaseAutomaticTuningImpl(String resourceGroupName, String sqlServerName, String sqlDatabaseName, + DatabaseAutomaticTuningInner innerObject, SqlServerManager sqlServerManager) { super(innerObject); Objects.requireNonNull(innerObject); Objects.requireNonNull(sqlServerManager); @@ -70,11 +62,9 @@ public AutomaticTuningMode actualState() { @Override public Map tuningOptions() { - return Collections - .unmodifiableMap( - this.innerModel().options() != null - ? this.innerModel().options() - : new HashMap()); + return Collections.unmodifiableMap(this.innerModel().options() != null + ? this.innerModel().options() + : new HashMap()); } @Override @@ -84,20 +74,19 @@ public SqlDatabaseAutomaticTuningImpl withAutomaticTuningMode(AutomaticTuningMod } @Override - public SqlDatabaseAutomaticTuningImpl withAutomaticTuningOption( - String tuningOptionName, AutomaticTuningOptionModeDesired desiredState) { + public SqlDatabaseAutomaticTuningImpl withAutomaticTuningOption(String tuningOptionName, + AutomaticTuningOptionModeDesired desiredState) { if (this.automaticTuningOptionsMap == null) { this.automaticTuningOptionsMap = new HashMap(); } - this - .automaticTuningOptionsMap - .put(tuningOptionName, new AutomaticTuningOptions().withDesiredState(desiredState)); + this.automaticTuningOptionsMap.put(tuningOptionName, + new AutomaticTuningOptions().withDesiredState(desiredState)); return this; } @Override - public SqlDatabaseAutomaticTuningImpl withAutomaticTuningOptions( - Map tuningOptions) { + public SqlDatabaseAutomaticTuningImpl + withAutomaticTuningOptions(Map tuningOptions) { if (tuningOptions != null) { for (Map.Entry option : tuningOptions.entrySet()) { this.withAutomaticTuningOption(option.getKey(), option.getValue()); @@ -113,9 +102,7 @@ public SqlDatabaseAutomaticTuningImpl update() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabaseAutomaticTunings() .getAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName); } @@ -139,18 +126,15 @@ public SqlDatabaseAutomaticTuning apply(Context context) { public Mono applyAsync(Context context) { final SqlDatabaseAutomaticTuningImpl self = this; this.innerModel().withOptions(this.automaticTuningOptionsMap); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabaseAutomaticTunings() .updateAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.innerModel()) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map( - databaseAutomaticTuningInner -> { - self.setInner(databaseAutomaticTuningInner); - self.automaticTuningOptionsMap.clear(); - return self; - }); + .map(databaseAutomaticTuningInner -> { + self.setInner(databaseAutomaticTuningInner); + self.automaticTuningOptionsMap.clear(); + return self; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseExportRequestImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseExportRequestImpl.java index c97ec995183d4..55f1c3eb69925 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseExportRequestImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseExportRequestImpl.java @@ -47,14 +47,9 @@ public ExportDatabaseDefinition innerModel() { @Override public Mono executeWorkAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() - .exportAsync( - this.sqlDatabase.resourceGroupName, - this.sqlDatabase.sqlServerName, - this.sqlDatabase.name(), + .exportAsync(this.sqlDatabase.resourceGroupName, this.sqlDatabase.sqlServerName, this.sqlDatabase.name(), this.innerModel()) .map(SqlDatabaseImportExportResponseImpl::new); } @@ -68,74 +63,55 @@ public SqlDatabaseExportRequestImpl exportTo(String storageUri) { return this; } - private Mono getOrCreateStorageAccountContainer( - final StorageAccount storageAccount, - final String containerName, - final String fileName, - final FunctionalTaskItem.Context context) { + private Mono getOrCreateStorageAccountContainer(final StorageAccount storageAccount, + final String containerName, final String fileName, final FunctionalTaskItem.Context context) { final SqlDatabaseExportRequestImpl self = this; - return storageAccount - .getKeysAsync() + return storageAccount.getKeysAsync() .flatMap(storageAccountKeys -> Mono.justOrEmpty(storageAccountKeys.stream().findFirst())) - .flatMap( - storageAccountKey -> { - self - .inner - .withStorageUri( - String - .format( - "%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName)); - self.inner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); - self.inner.withStorageKey(storageAccountKey.value()); - BlobContainers blobContainers = this.sqlServerManager.storageManager().blobContainers(); - return blobContainers - .getAsync(parent().resourceGroupName(), storageAccount.name(), containerName) - .onErrorResume( - error -> { - if (error instanceof ManagementException) { - if (((ManagementException) error).getResponse().getStatusCode() == 404) { - return blobContainers - .defineContainer(containerName) - .withExistingStorageAccount( - parent().resourceGroupName(), storageAccount.name()) - .withPublicAccess(PublicAccess.NONE) - .createAsync(); - } - } - return Mono.error(error); - }); - }); + .flatMap(storageAccountKey -> { + self.inner.withStorageUri( + String.format("%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName)); + self.inner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); + self.inner.withStorageKey(storageAccountKey.value()); + BlobContainers blobContainers = this.sqlServerManager.storageManager().blobContainers(); + return blobContainers.getAsync(parent().resourceGroupName(), storageAccount.name(), containerName) + .onErrorResume(error -> { + if (error instanceof ManagementException) { + if (((ManagementException) error).getResponse().getStatusCode() == 404) { + return blobContainers.defineContainer(containerName) + .withExistingStorageAccount(parent().resourceGroupName(), storageAccount.name()) + .withPublicAccess(PublicAccess.NONE) + .createAsync(); + } + } + return Mono.error(error); + }); + }); } @Override - public SqlDatabaseExportRequestImpl exportTo( - final StorageAccount storageAccount, final String containerName, final String fileName) { + public SqlDatabaseExportRequestImpl exportTo(final StorageAccount storageAccount, final String containerName, + final String fileName) { Objects.requireNonNull(storageAccount); Objects.requireNonNull(containerName); Objects.requireNonNull(fileName); if (this.inner == null) { this.inner = new ExportDatabaseDefinition(); } - this - .addDependency( - context -> getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, context)); + this.addDependency( + context -> getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, context)); return this; } @Override - public SqlDatabaseExportRequestImpl exportTo( - final Creatable storageAccountCreatable, final String containerName, final String fileName) { + public SqlDatabaseExportRequestImpl exportTo(final Creatable storageAccountCreatable, + final String containerName, final String fileName) { if (this.inner == null) { this.inner = new ExportDatabaseDefinition(); } - this - .addDependency( - context -> - storageAccountCreatable - .createAsync() - .flatMap( - storageAccount -> - getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, context))); + this.addDependency(context -> storageAccountCreatable.createAsync() + .flatMap(storageAccount -> getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, + context))); return this; } @@ -169,15 +145,15 @@ SqlDatabaseExportRequestImpl withAuthenticationType(AuthenticationType authentic } @Override - public SqlDatabaseExportRequestImpl withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseExportRequestImpl withSqlAdministratorLoginAndPassword(String administratorLogin, + String administratorPassword) { this.inner.withAuthenticationType(AuthenticationType.SQL.toString()); return this.withLoginAndPassword(administratorLogin, administratorPassword); } @Override - public SqlDatabaseExportRequestImpl withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseExportRequestImpl withActiveDirectoryLoginAndPassword(String administratorLogin, + String administratorPassword) { this.inner.withAuthenticationType(AuthenticationType.ADPASSWORD.toString()); return this.withLoginAndPassword(administratorLogin, administratorPassword); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseForElasticPoolImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseForElasticPoolImpl.java index f1e5fe85def5c..301e9aeb3fc10 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseForElasticPoolImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseForElasticPoolImpl.java @@ -13,16 +13,12 @@ import java.util.Objects; /** Implementation for SqlDatabase as inline definition inside a SqlElasticPool definition. */ -public class SqlDatabaseForElasticPoolImpl - implements SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool< - SqlElasticPoolOperations.DefinitionStages.WithCreate>, - SqlDatabase.DefinitionStages.WithStorageKeyAfterElasticPool< - SqlElasticPoolOperations.DefinitionStages.WithCreate>, - SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool< - SqlElasticPoolOperations.DefinitionStages.WithCreate>, - SqlDatabase.DefinitionStages.WithCreateMode, - SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions< - SqlElasticPoolOperations.DefinitionStages.WithCreate> { +public class SqlDatabaseForElasticPoolImpl implements + SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool, + SqlDatabase.DefinitionStages.WithStorageKeyAfterElasticPool, + SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool, + SqlDatabase.DefinitionStages.WithCreateMode, + SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions { private SqlDatabaseImpl sqlDatabase; private SqlElasticPoolImpl sqlElasticPool; @@ -80,8 +76,8 @@ public SqlDatabaseForElasticPoolImpl importFrom(String storageUri) { } @Override - public SqlDatabaseForElasticPoolImpl importFrom( - StorageAccount storageAccount, String containerName, String fileName) { + public SqlDatabaseForElasticPoolImpl importFrom(StorageAccount storageAccount, String containerName, + String fileName) { this.sqlDatabase.importFrom(storageAccount, containerName, fileName); return this; } @@ -99,15 +95,15 @@ public SqlDatabaseForElasticPoolImpl withSharedAccessKey(String sharedAccessKey) } @Override - public SqlDatabaseForElasticPoolImpl withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseForElasticPoolImpl withSqlAdministratorLoginAndPassword(String administratorLogin, + String administratorPassword) { this.sqlDatabase.withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword); return this; } @Override - public SqlDatabaseForElasticPoolImpl withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseForElasticPoolImpl withActiveDirectoryLoginAndPassword(String administratorLogin, + String administratorPassword) { this.sqlDatabase.withActiveDirectoryLoginAndPassword(administratorLogin, administratorPassword); return this; } @@ -119,8 +115,8 @@ public SqlDatabaseForElasticPoolImpl fromRestorePoint(RestorePoint restorePoint) } @Override - public SqlDatabaseForElasticPoolImpl fromRestorePoint( - RestorePoint restorePoint, OffsetDateTime restorePointDateTime) { + public SqlDatabaseForElasticPoolImpl fromRestorePoint(RestorePoint restorePoint, + OffsetDateTime restorePointDateTime) { this.sqlDatabase.fromRestorePoint(restorePoint, restorePointDateTime); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImpl.java index 75372f7103823..075702b38c3ba 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImpl.java @@ -65,19 +65,17 @@ /** Implementation for SqlDatabase and its parent interfaces. */ class SqlDatabaseImpl extends ExternalChildResourceImpl - implements SqlDatabase, - SqlDatabase.SqlDatabaseDefinition, - SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool, - SqlDatabase.DefinitionStages.WithStorageKeyAfterElasticPool, - SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool, - SqlDatabase.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, - SqlDatabase.Update, - SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithStorageKeyAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions, - SqlDatabaseOperations.SqlDatabaseOperationsDefinition { + implements SqlDatabase, SqlDatabase.SqlDatabaseDefinition, + SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool, + SqlDatabase.DefinitionStages.WithStorageKeyAfterElasticPool, + SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool, + SqlDatabase.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, SqlDatabase.Update, + SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithStorageKeyAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions, + SqlDatabaseOperations.SqlDatabaseOperationsDefinition { private SqlElasticPoolsAsExternalChildResourcesImpl sqlElasticPools; @@ -123,13 +121,8 @@ class SqlDatabaseImpl extends ExternalChildResourceImpl listRestorePoints() { List restorePoints = new ArrayList<>(); - PagedIterable restorePointInners = - this - .sqlServerManager - .serviceClient() - .getRestorePoints() - .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); + PagedIterable restorePointInners = this.sqlServerManager.serviceClient() + .getRestorePoints() + .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); for (RestorePointInner inner : restorePointInners) { restorePoints.add(new RestorePointImpl(this.resourceGroupName, this.sqlServerName, inner)); } @@ -282,29 +264,22 @@ public List listRestorePoints() { @Override public PagedFlux listRestorePointsAsync() { final SqlDatabaseImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getRestorePoints() - .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), - restorePointInner -> - new RestorePointImpl(self.resourceGroupName, self.sqlServerName, restorePointInner)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getRestorePoints() + .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), + restorePointInner -> new RestorePointImpl(self.resourceGroupName, self.sqlServerName, restorePointInner)); } @Override public Map listReplicationLinks() { Map replicationLinkMap = new HashMap<>(); - PagedIterable replicationLinkInners = - this - .sqlServerManager - .serviceClient() - .getReplicationLinks() - .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); + PagedIterable replicationLinkInners = this.sqlServerManager.serviceClient() + .getReplicationLinks() + .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); for (ReplicationLinkInner inner : replicationLinkInners) { - replicationLinkMap - .put( - inner.name(), - new ReplicationLinkImpl(this.resourceGroupName, this.sqlServerName, inner, this.sqlServerManager)); + replicationLinkMap.put(inner.name(), + new ReplicationLinkImpl(this.resourceGroupName, this.sqlServerName, inner, this.sqlServerManager)); } return Collections.unmodifiableMap(replicationLinkMap); } @@ -312,14 +287,12 @@ public Map listReplicationLinks() { @Override public PagedFlux listReplicationLinksAsync() { final SqlDatabaseImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getReplicationLinks() - .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), - replicationLinkInner -> - new ReplicationLinkImpl( - self.resourceGroupName, self.sqlServerName, replicationLinkInner, self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getReplicationLinks() + .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), + replicationLinkInner -> new ReplicationLinkImpl(self.resourceGroupName, self.sqlServerName, + replicationLinkInner, self.sqlServerManager)); } @Override @@ -330,16 +303,16 @@ public SqlDatabaseExportRequestImpl exportTo(String storageUri) { @Override public SqlDatabaseExportRequestImpl exportTo(StorageAccount storageAccount, String containerName, String fileName) { Objects.requireNonNull(storageAccount); - return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager) - .exportTo(storageAccount, containerName, fileName); + return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager).exportTo(storageAccount, containerName, + fileName); } @Override - public SqlDatabaseExportRequestImpl exportTo( - Creatable storageAccountCreatable, String containerName, String fileName) { + public SqlDatabaseExportRequestImpl exportTo(Creatable storageAccountCreatable, + String containerName, String fileName) { Objects.requireNonNull(storageAccountCreatable); - return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager) - .exportTo(storageAccountCreatable, containerName, fileName); + return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager).exportTo(storageAccountCreatable, + containerName, fileName); } @Override @@ -348,40 +321,36 @@ public SqlDatabaseImportRequestImpl importBacpac(String storageUri) { } @Override - public SqlDatabaseImportRequestImpl importBacpac( - StorageAccount storageAccount, String containerName, String fileName) { + public SqlDatabaseImportRequestImpl importBacpac(StorageAccount storageAccount, String containerName, + String fileName) { Objects.requireNonNull(storageAccount); - return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager) - .importFrom(storageAccount, containerName, fileName); + return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager).importFrom(storageAccount, containerName, + fileName); } @Override public SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank defineThreatDetectionPolicy(String policyName) { - SqlDatabaseThreatDetectionPolicyImpl result = new SqlDatabaseThreatDetectionPolicyImpl( - policyName, this, new DatabaseSecurityAlertPolicyInner(), this.sqlServerManager); + SqlDatabaseThreatDetectionPolicyImpl result = new SqlDatabaseThreatDetectionPolicyImpl(policyName, this, + new DatabaseSecurityAlertPolicyInner(), this.sqlServerManager); result.setPendingOperation(ExternalChildResourceImpl.PendingOperation.ToBeCreated); return result; } @Override - public SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank defineThreatDetectionPolicy(SecurityAlertPolicyName policyName) { + public SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank + defineThreatDetectionPolicy(SecurityAlertPolicyName policyName) { SqlDatabaseThreatDetectionPolicyImpl result = new SqlDatabaseThreatDetectionPolicyImpl( - policyName == null ? SecurityAlertPolicyName.DEFAULT.toString() : policyName.toString(), - this, - new DatabaseSecurityAlertPolicyInner(), - this.sqlServerManager); + policyName == null ? SecurityAlertPolicyName.DEFAULT.toString() : policyName.toString(), this, + new DatabaseSecurityAlertPolicyInner(), this.sqlServerManager); result.setPendingOperation(ExternalChildResourceImpl.PendingOperation.ToBeCreated); return result; } @Override public SqlDatabaseThreatDetectionPolicy getThreatDetectionPolicy() { - DatabaseSecurityAlertPolicyInner policyInner = - this - .sqlServerManager - .serviceClient() - .getDatabaseSecurityAlertPolicies() - .get(this.resourceGroupName, this.sqlServerName, this.name(), SecurityAlertPolicyName.DEFAULT); + DatabaseSecurityAlertPolicyInner policyInner = this.sqlServerManager.serviceClient() + .getDatabaseSecurityAlertPolicies() + .get(this.resourceGroupName, this.sqlServerName, this.name(), SecurityAlertPolicyName.DEFAULT); return policyInner != null ? new SqlDatabaseThreatDetectionPolicyImpl(policyInner.name(), this, policyInner, this.sqlServerManager) : null; @@ -389,12 +358,9 @@ public SqlDatabaseThreatDetectionPolicy getThreatDetectionPolicy() { @Override public SqlDatabaseAutomaticTuning getDatabaseAutomaticTuning() { - DatabaseAutomaticTuningInner databaseAutomaticTuningInner = - this - .sqlServerManager - .serviceClient() - .getDatabaseAutomaticTunings() - .get(this.resourceGroupName, this.sqlServerName, this.name()); + DatabaseAutomaticTuningInner databaseAutomaticTuningInner = this.sqlServerManager.serviceClient() + .getDatabaseAutomaticTunings() + .get(this.resourceGroupName, this.sqlServerName, this.name()); return databaseAutomaticTuningInner != null ? new SqlDatabaseAutomaticTuningImpl(this, databaseAutomaticTuningInner) : null; @@ -403,12 +369,9 @@ public SqlDatabaseAutomaticTuning getDatabaseAutomaticTuning() { @Override public List listUsageMetrics() { List databaseUsageMetrics = new ArrayList<>(); - PagedIterable databaseUsageInners = - this - .sqlServerManager - .serviceClient() - .getDatabaseUsages() - .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); + PagedIterable databaseUsageInners = this.sqlServerManager.serviceClient() + .getDatabaseUsages() + .listByDatabase(this.resourceGroupName, this.sqlServerName, this.name()); for (DatabaseUsageInner inner : databaseUsageInners) { databaseUsageMetrics.add(new SqlDatabaseUsageMetricImpl(inner)); } @@ -417,11 +380,10 @@ public List listUsageMetrics() { @Override public PagedFlux listUsageMetricsAsync() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getDatabaseUsages() - .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getDatabaseUsages() + .listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name()), SqlDatabaseUsageMetricImpl::new); } @@ -429,15 +391,11 @@ public PagedFlux listUsageMetricsAsync() { public SqlDatabase rename(String newDatabaseName) { ResourceId resourceId = ResourceId.fromString(this.id()); String newId = resourceId.parent().id() + "/databases/" + newDatabaseName; - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getDatabases() .rename(this.resourceGroupName, this.sqlServerName, this.name(), new ResourceMoveDefinition().withId(newId)); - return this - .sqlServerManager - .sqlServers() + return this.sqlServerManager.sqlServers() .databases() .getBySqlServer(this.resourceGroupName, this.sqlServerName, newDatabaseName); } @@ -447,50 +405,35 @@ public Mono renameAsync(final String newDatabaseName) { final SqlDatabaseImpl self = this; ResourceId resourceId = ResourceId.fromString(this.id()); String newId = resourceId.parent().id() + "/databases/" + newDatabaseName; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .renameAsync(this.resourceGroupName, this.sqlServerName, self.name(), new ResourceMoveDefinition().withId(newId)) - .flatMap( - aVoid -> - self - .sqlServerManager - .sqlServers() - .databases() - .getBySqlServerAsync(self.resourceGroupName, self.sqlServerName, newDatabaseName)); + .flatMap(aVoid -> self.sqlServerManager.sqlServers() + .databases() + .getBySqlServerAsync(self.resourceGroupName, self.sqlServerName, newDatabaseName)); } @Override public TransparentDataEncryption getTransparentDataEncryption() { - LogicalDatabaseTransparentDataEncryptionInner transparentDataEncryptionInner = - this - .sqlServerManager - .serviceClient() + LogicalDatabaseTransparentDataEncryptionInner transparentDataEncryptionInner + = this.sqlServerManager.serviceClient() .getTransparentDataEncryptions() .get(this.resourceGroupName, this.sqlServerName, this.name(), TransparentDataEncryptionName.CURRENT); return (transparentDataEncryptionInner == null) ? null - : new TransparentDataEncryptionImpl( - this.resourceGroupName, this.sqlServerName, transparentDataEncryptionInner, this.sqlServerManager); + : new TransparentDataEncryptionImpl(this.resourceGroupName, this.sqlServerName, + transparentDataEncryptionInner, this.sqlServerManager); } @Override public Mono getTransparentDataEncryptionAsync() { final SqlDatabaseImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getTransparentDataEncryptions() .getAsync(this.resourceGroupName, this.sqlServerName, this.name(), TransparentDataEncryptionName.CURRENT) - .map( - transparentDataEncryptionInner -> - new TransparentDataEncryptionImpl( - self.resourceGroupName, - self.sqlServerName, - transparentDataEncryptionInner, - self.sqlServerManager)); + .map(transparentDataEncryptionInner -> new TransparentDataEncryptionImpl(self.resourceGroupName, + self.sqlServerName, transparentDataEncryptionInner, self.sqlServerManager)); } @Override @@ -524,9 +467,7 @@ SqlDatabaseImpl withPatchUpdate() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -540,13 +481,11 @@ public void beforeGroupCreateOrUpdate() { if (this.importRequestInner != null && this.elasticPoolId() != null) { final SqlDatabaseImpl self = this; final String epId = this.elasticPoolId(); - this - .addPostRunDependent( - context -> { - self.importRequestInner = null; - self.withExistingElasticPoolId(epId); - return self.createResourceAsync().flatMap(sqlDatabase -> context.voidMono()); - }); + this.addPostRunDependent(context -> { + self.importRequestInner = null; + self.withExistingElasticPoolId(epId); + return self.createResourceAsync().flatMap(sqlDatabase -> context.voidMono()); + }); } } @@ -560,44 +499,34 @@ public Mono createResourceAsync() { this.importRequestInner.withEdition(this.edition().toString()); } if (this.importRequestInner.serviceObjectiveName() == null) { - this - .importRequestInner - .withServiceObjectiveName(this.innerModel().sku().name()); + this.importRequestInner.withServiceObjectiveName(this.innerModel().sku().name()); } if (this.importRequestInner.maxSizeBytes() == null) { this.importRequestInner.withMaxSizeBytes(String.valueOf(this.innerModel().maxSizeBytes())); } - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServers() .importDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.importRequestInner) - .then( - Mono - .defer( - () -> { - if (self.elasticPoolId() != null) { - self.importRequestInner = null; - return self.withExistingElasticPool(ResourceUtils.nameFromResourceId(self.elasticPoolId())) - .withPatchUpdate() - .updateResourceAsync(); - } else { - return self.refreshAsync(); - } - })); + .then(Mono.defer(() -> { + if (self.elasticPoolId() != null) { + self.importRequestInner = null; + return self.withExistingElasticPool(ResourceUtils.nameFromResourceId(self.elasticPoolId())) + .withPatchUpdate() + .updateResourceAsync(); + } else { + return self.refreshAsync(); + } + })); } else { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } } @@ -605,26 +534,21 @@ public Mono createResourceAsync() { public Mono updateResourceAsync() { if (this.isPatchUpdate) { final SqlDatabaseImpl self = this; - DatabaseUpdate databaseUpdateInner = - new DatabaseUpdate() - .withTags(self.innerModel().tags()) - .withCollation(self.innerModel().collation()) - .withSourceDatabaseId(self.innerModel().sourceDatabaseId()) - .withCreateMode(self.innerModel().createMode()) - .withSku(self.innerModel().sku()) - .withMaxSizeBytes(this.innerModel().maxSizeBytes()) - .withElasticPoolId(this.innerModel().elasticPoolId()); - return this - .sqlServerManager - .serviceClient() + DatabaseUpdate databaseUpdateInner = new DatabaseUpdate().withTags(self.innerModel().tags()) + .withCollation(self.innerModel().collation()) + .withSourceDatabaseId(self.innerModel().sourceDatabaseId()) + .withCreateMode(self.innerModel().createMode()) + .withSku(self.innerModel().sku()) + .withMaxSizeBytes(this.innerModel().maxSizeBytes()) + .withElasticPoolId(this.innerModel().elasticPoolId()); + return this.sqlServerManager.serviceClient() .getDatabases() .updateAsync(this.resourceGroupName, this.sqlServerName, this.name(), databaseUpdateInner) - .map( - inner -> { - self.setInner(inner); - self.isPatchUpdate = false; - return self; - }); + .map(inner -> { + self.setInner(inner); + self.isPatchUpdate = false; + return self; + }); } else { return this.createResourceAsync(); @@ -649,18 +573,14 @@ public Mono afterPostRunAsync(boolean isGroupFaulted) { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getDatabases() .delete(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -671,8 +591,8 @@ public Mono deleteAsync() { } @Override - public SqlDatabaseImpl withExistingSqlServer( - String resourceGroupName, String sqlServerName, String sqlServerLocation) { + public SqlDatabaseImpl withExistingSqlServer(String resourceGroupName, String sqlServerName, + String sqlServerLocation) { this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.sqlServerLocation = sqlServerLocation; @@ -704,14 +624,8 @@ public SqlDatabaseImpl withoutElasticPool() { private String generateElasticPoolIdFromName(String elasticPoolName) { if (this.parentId() == null) { - return ResourceUtils - .constructResourceId( - this.sqlServerManager.subscriptionId(), - this.resourceGroupName, - "Microsoft.Sql", - "elasticPools", - elasticPoolName, - String.format("servers/%s", this.sqlServerName)); + return ResourceUtils.constructResourceId(this.sqlServerManager.subscriptionId(), this.resourceGroupName, + "Microsoft.Sql", "elasticPools", elasticPoolName, String.format("servers/%s", this.sqlServerName)); } return String.format("%s/elasticPools/%s", this.parentId(), elasticPoolName); } @@ -754,26 +668,21 @@ public SqlDatabaseImpl withNewElasticPool(final Creatable sqlEla @Override public SqlElasticPoolForDatabaseImpl defineElasticPool(String elasticPoolName) { if (this.sqlElasticPools == null) { - this.sqlElasticPools = - new SqlElasticPoolsAsExternalChildResourcesImpl( - this.taskGroup(), this.sqlServerManager, "SqlElasticPool"); + this.sqlElasticPools = new SqlElasticPoolsAsExternalChildResourcesImpl(this.taskGroup(), + this.sqlServerManager, "SqlElasticPool"); } this.innerModel().withSku(null); this.innerModel().withElasticPoolId(generateElasticPoolIdFromName(elasticPoolName)); - return new SqlElasticPoolForDatabaseImpl( - this, - this - .sqlElasticPools - .defineIndependentElasticPool(elasticPoolName) + return new SqlElasticPoolForDatabaseImpl(this, + this.sqlElasticPools.defineIndependentElasticPool(elasticPoolName) .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)); } @Override public SqlDatabaseImpl fromRestorableDroppedDatabase(SqlRestorableDroppedDatabase restorableDroppedDatabase) { Objects.requireNonNull(restorableDroppedDatabase); - this - .innerModel() + this.innerModel() .withRestorableDroppedDatabaseId(restorableDroppedDatabase.id()) .withCreateMode(CreateMode.RESTORE); return this; @@ -798,30 +707,20 @@ public SqlDatabaseImpl importFrom(String storageUri) { } @Override - public SqlDatabaseImpl importFrom( - final StorageAccount storageAccount, final String containerName, final String fileName) { + public SqlDatabaseImpl importFrom(final StorageAccount storageAccount, final String containerName, + final String fileName) { final SqlDatabaseImpl self = this; Objects.requireNonNull(storageAccount); this.initializeImportRequestInner(); - this - .addDependency( - context -> - storageAccount - .getKeysAsync() - .flatMap(storageAccountKeys -> Mono.justOrEmpty(storageAccountKeys.stream().findFirst())) - .flatMap( - storageAccountKey -> { - self - .importRequestInner - .withStorageUri( - String - .format( - "%s%s/%s", - storageAccount.endPoints().primary().blob(), containerName, fileName)); - self.importRequestInner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); - self.importRequestInner.withStorageKey(storageAccountKey.value()); - return context.voidMono(); - })); + this.addDependency(context -> storageAccount.getKeysAsync() + .flatMap(storageAccountKeys -> Mono.justOrEmpty(storageAccountKeys.stream().findFirst())) + .flatMap(storageAccountKey -> { + self.importRequestInner.withStorageUri( + String.format("%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName)); + self.importRequestInner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); + self.importRequestInner.withStorageKey(storageAccountKey.value()); + return context.voidMono(); + })); return this; } @@ -840,8 +739,8 @@ public SqlDatabaseImpl withSharedAccessKey(String sharedAccessKey) { } @Override - public SqlDatabaseImpl withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseImpl withSqlAdministratorLoginAndPassword(String administratorLogin, + String administratorPassword) { this.importRequestInner.withAuthenticationType(AuthenticationType.SQL.toString()); this.importRequestInner.withAdministratorLogin(administratorLogin); this.importRequestInner.withAdministratorLoginPassword(administratorPassword); @@ -849,8 +748,8 @@ public SqlDatabaseImpl withSqlAdministratorLoginAndPassword( } @Override - public SqlDatabaseImpl withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseImpl withActiveDirectoryLoginAndPassword(String administratorLogin, + String administratorPassword) { this.importRequestInner.withAuthenticationType(AuthenticationType.ADPASSWORD.toString()); this.importRequestInner.withAdministratorLogin(administratorLogin); this.importRequestInner.withAdministratorLoginPassword(administratorPassword); @@ -923,8 +822,8 @@ public SqlDatabaseImpl withStandardEdition(SqlDatabaseStandardServiceObjective s } @Override - public SqlDatabaseImpl withStandardEdition( - SqlDatabaseStandardServiceObjective serviceObjective, SqlDatabaseStandardStorage maxStorageCapacity) { + public SqlDatabaseImpl withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective, + SqlDatabaseStandardStorage maxStorageCapacity) { Sku sku = new Sku().withName(serviceObjective.toString()).withTier(DatabaseEdition.STANDARD.toString()); this.innerModel().withSku(sku); @@ -939,8 +838,8 @@ public SqlDatabaseImpl withPremiumEdition(SqlDatabasePremiumServiceObjective ser } @Override - public SqlDatabaseImpl withPremiumEdition( - SqlDatabasePremiumServiceObjective serviceObjective, SqlDatabasePremiumStorage maxStorageCapacity) { + public SqlDatabaseImpl withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective, + SqlDatabasePremiumStorage maxStorageCapacity) { Sku sku = new Sku().withName(serviceObjective.toString()).withTier(DatabaseEdition.PREMIUM.toString()); this.innerModel().withSku(sku); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImportRequestImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImportRequestImpl.java index 8fe55bc447110..4865c33a2586e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImportRequestImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseImportRequestImpl.java @@ -44,44 +44,26 @@ public ImportExistingDatabaseDefinition innerModel() { @Override public Mono executeWorkAsync() { final SqlDatabaseImportRequestImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() - .importMethodAsync( - this.sqlDatabase.resourceGroupName, - this.sqlDatabase.sqlServerName, - this.sqlDatabase.name(), - this.innerModel()) - .flatMap( - importExportResponseInner -> - self - .sqlDatabase - .refreshAsync() - .map(sqlDatabase -> new SqlDatabaseImportExportResponseImpl(importExportResponseInner))); + .importMethodAsync(this.sqlDatabase.resourceGroupName, this.sqlDatabase.sqlServerName, + this.sqlDatabase.name(), this.innerModel()) + .flatMap(importExportResponseInner -> self.sqlDatabase.refreshAsync() + .map(sqlDatabase -> new SqlDatabaseImportExportResponseImpl(importExportResponseInner))); } - private Mono getOrCreateStorageAccountContainer( - final StorageAccount storageAccount, - final String containerName, - final String fileName, - final FunctionalTaskItem.Context context) { + private Mono getOrCreateStorageAccountContainer(final StorageAccount storageAccount, + final String containerName, final String fileName, final FunctionalTaskItem.Context context) { final SqlDatabaseImportRequestImpl self = this; - return storageAccount - .getKeysAsync() + return storageAccount.getKeysAsync() .flatMap(storageAccountKeys -> Mono.justOrEmpty(storageAccountKeys.stream().findFirst())) - .flatMap( - storageAccountKey -> { - self - .inner - .withStorageUri( - String - .format( - "%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName)); - self.inner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); - self.inner.withStorageKey(storageAccountKey.value()); - return context.voidMono(); - }); + .flatMap(storageAccountKey -> { + self.inner.withStorageUri( + String.format("%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName)); + self.inner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY); + self.inner.withStorageKey(storageAccountKey.value()); + return context.voidMono(); + }); } @Override @@ -94,17 +76,16 @@ public SqlDatabaseImportRequestImpl importFrom(String storageUri) { } @Override - public SqlDatabaseImportRequestImpl importFrom( - final StorageAccount storageAccount, final String containerName, final String fileName) { + public SqlDatabaseImportRequestImpl importFrom(final StorageAccount storageAccount, final String containerName, + final String fileName) { Objects.requireNonNull(storageAccount); Objects.requireNonNull(containerName); Objects.requireNonNull(fileName); if (this.inner == null) { this.inner = new ImportExistingDatabaseDefinition(); } - this - .addDependency( - context -> getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, context)); + this.addDependency( + context -> getOrCreateStorageAccountContainer(storageAccount, containerName, fileName, context)); return this; } @@ -123,15 +104,15 @@ public SqlDatabaseImportRequestImpl withSharedAccessKey(String sharedAccessKey) } @Override - public SqlDatabaseImportRequestImpl withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseImportRequestImpl withSqlAdministratorLoginAndPassword(String administratorLogin, + String administratorPassword) { this.inner.withAuthenticationType(AuthenticationType.SQL.toString()); return this.withLoginAndPassword(administratorLogin, administratorPassword); } @Override - public SqlDatabaseImportRequestImpl withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword) { + public SqlDatabaseImportRequestImpl withActiveDirectoryLoginAndPassword(String administratorLogin, + String administratorPassword) { this.inner.withAuthenticationType(AuthenticationType.ADPASSWORD.toString()); return this.withLoginAndPassword(administratorLogin, administratorPassword); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseOperationsImpl.java index df95d68ee24f8..74fe9943dc59c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseOperationsImpl.java @@ -28,8 +28,8 @@ public class SqlDatabaseOperationsImpl Objects.requireNonNull(manager); this.sqlServer = parent; this.manager = manager; - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.sqlServer.taskGroup(), manager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.sqlServer.taskGroup(), manager, "SqlDatabase"); } SqlDatabaseOperationsImpl(SqlServerManager manager) { @@ -47,17 +47,13 @@ public SqlDatabase getBySqlServer(String resourceGroupName, String sqlServerName } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { - return this - .manager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { + return this.manager.serviceClient() .getDatabases() .getAsync(resourceGroupName, sqlServerName, name) - .map( - inner -> - new SqlDatabaseImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + .map(inner -> new SqlDatabaseImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, + manager)); } @Override @@ -65,16 +61,15 @@ public SqlDatabase getBySqlServer(SqlServer sqlServer, String name) { if (sqlServer == null) { return null; } - DatabaseInner inner = - this.manager.serviceClient().getDatabases().get(sqlServer.resourceGroupName(), sqlServer.name(), name); + DatabaseInner inner + = this.manager.serviceClient().getDatabases().get(sqlServer.resourceGroupName(), sqlServer.name(), name); return (inner != null) ? new SqlDatabaseImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager) : null; } @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getDatabases() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) @@ -100,21 +95,17 @@ public Mono getAsync(String name) { @Override public SqlDatabase getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -130,21 +121,17 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public void deleteById(String id) { Objects.requireNonNull(id); - this - .deleteBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + this.deleteBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); - return this - .deleteBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.deleteBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -165,38 +152,30 @@ public Mono deleteAsync(String name) { @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List databasesSet = new ArrayList<>(); - for (DatabaseInner inner - : this.manager.serviceClient().getDatabases().listByServer(resourceGroupName, sqlServerName)) { - databasesSet - .add( - new SqlDatabaseImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + for (DatabaseInner inner : this.manager.serviceClient() + .getDatabases() + .listByServer(resourceGroupName, sqlServerName)) { + databasesSet.add( + new SqlDatabaseImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); } return Collections.unmodifiableList(databasesSet); } @Override public PagedFlux listBySqlServerAsync(final String resourceGroupName, final String sqlServerName) { - return PagedConverter.mapPage(this - .manager - .serviceClient() - .getDatabases() - .listByServerAsync(resourceGroupName, sqlServerName), - inner -> - new SqlDatabaseImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + return PagedConverter.mapPage( + this.manager.serviceClient().getDatabases().listByServerAsync(resourceGroupName, sqlServerName), + inner -> new SqlDatabaseImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, + manager)); } @Override public List listBySqlServer(SqlServer sqlServer) { List firewallRuleSet = new ArrayList<>(); if (sqlServer != null) { - for (DatabaseInner inner - : this - .manager - .serviceClient() - .getDatabases() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { + for (DatabaseInner inner : this.manager.serviceClient() + .getDatabases() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { firewallRuleSet.add(new SqlDatabaseImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager)); } } @@ -205,11 +184,11 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getDatabases() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getDatabases() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), inner -> new SqlDatabaseImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseThreatDetectionPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseThreatDetectionPolicyImpl.java index 0b2cdf231302c..b2b952e5f34ca 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseThreatDetectionPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabaseThreatDetectionPolicyImpl.java @@ -22,22 +22,18 @@ import java.util.stream.Stream; /** Implementation for SQL database threat detection policy. */ -public class SqlDatabaseThreatDetectionPolicyImpl - extends ExternalChildResourceImpl< - SqlDatabaseThreatDetectionPolicy, DatabaseSecurityAlertPolicyInner, SqlDatabaseImpl, SqlDatabase> +public class SqlDatabaseThreatDetectionPolicyImpl extends + ExternalChildResourceImpl implements SqlDatabaseThreatDetectionPolicy, - SqlDatabaseThreatDetectionPolicy.SqlDatabaseThreatDetectionPolicyDefinition, - SqlDatabaseThreatDetectionPolicy.Update { + SqlDatabaseThreatDetectionPolicy.SqlDatabaseThreatDetectionPolicyDefinition, + SqlDatabaseThreatDetectionPolicy.Update { private SqlServerManager sqlServerManager; private String resourceGroupName; private String sqlServerName; private String policyName; - protected SqlDatabaseThreatDetectionPolicyImpl( - String name, - SqlDatabaseImpl parent, - DatabaseSecurityAlertPolicyInner innerObject, - SqlServerManager sqlServerManager) { + protected SqlDatabaseThreatDetectionPolicyImpl(String name, SqlDatabaseImpl parent, + DatabaseSecurityAlertPolicyInner innerObject, SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); Objects.requireNonNull(innerObject); @@ -75,7 +71,9 @@ public String kind() { @Override public SecurityAlertPolicyState currentState() { - return this.innerModel().state() == null ? null : SecurityAlertPolicyState.fromString(this.innerModel().state().toString()); + return this.innerModel().state() == null + ? null + : SecurityAlertPolicyState.fromString(this.innerModel().state().toString()); } @Override @@ -137,33 +135,24 @@ public boolean isDefaultSecurityAlertPolicy() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabaseSecurityAlertPolicies() - .getAsync( - this.resourceGroupName, this.sqlServerName, this.parent().name(), SecurityAlertPolicyName.fromString(this.name())); + .getAsync(this.resourceGroupName, this.sqlServerName, this.parent().name(), + SecurityAlertPolicyName.fromString(this.name())); } @Override public Mono createResourceAsync() { final SqlDatabaseThreatDetectionPolicyImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabaseSecurityAlertPolicies() - .createOrUpdateAsync( - this.resourceGroupName, - this.sqlServerName, - this.parent().name(), - SecurityAlertPolicyName.fromString(this.policyName), - this.innerModel()) - .map( - databaseSecurityAlertPolicyInner -> { - self.setInner(databaseSecurityAlertPolicyInner); - this.policyName = databaseSecurityAlertPolicyInner.name(); - return self; - }); + .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.parent().name(), + SecurityAlertPolicyName.fromString(this.policyName), this.innerModel()) + .map(databaseSecurityAlertPolicyInner -> { + self.setInner(databaseSecurityAlertPolicyInner); + this.policyName = databaseSecurityAlertPolicyInner.name(); + return self; + }); } @Override @@ -214,7 +203,8 @@ public SqlDatabaseThreatDetectionPolicyImpl withStorageAccountAccessKey(String s @Override public SqlDatabaseThreatDetectionPolicyImpl withAlertsFilter(String alertsFilter) { if (alertsFilter != null) { - this.innerModel().withDisabledAlerts(Stream.of(alertsFilter.split(Pattern.quote(";"))).collect(Collectors.toList())); + this.innerModel() + .withDisabledAlerts(Stream.of(alertsFilter.split(Pattern.quote(";"))).collect(Collectors.toList())); } return this; } @@ -230,7 +220,8 @@ public SqlDatabaseThreatDetectionPolicyImpl withAlertsFilter(List alerts @Override public SqlDatabaseThreatDetectionPolicyImpl withEmailAddresses(String addresses) { if (addresses != null) { - this.innerModel().withEmailAddresses(Stream.of(addresses.split(Pattern.quote(";"))).collect(Collectors.toList())); + this.innerModel() + .withEmailAddresses(Stream.of(addresses.split(Pattern.quote(";"))).collect(Collectors.toList())); } return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabasesAsExternalChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabasesAsExternalChildResourcesImpl.java index 360e3563be378..4ab8e10a00bc0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabasesAsExternalChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlDatabasesAsExternalChildResourcesImpl.java @@ -52,8 +52,8 @@ protected SqlDatabasesAsExternalChildResourcesImpl(SqlServerManager sqlServerMan * @param sqlServerManager the manager * @param childResourceName the child resource name (for logging) */ - protected SqlDatabasesAsExternalChildResourcesImpl( - TaskGroup parentTaskGroup, SqlServerManager sqlServerManager, String childResourceName) { + protected SqlDatabasesAsExternalChildResourcesImpl(TaskGroup parentTaskGroup, SqlServerManager sqlServerManager, + String childResourceName) { super(null, parentTaskGroup, childResourceName); Objects.requireNonNull(sqlServerManager); @@ -82,12 +82,12 @@ SqlDatabaseImpl patchUpdateDatabase(String name) { if (this.getParent() == null) { // resource group and server name will be set by the next method in the Fluent flow return prepareInlineUpdate( - new SqlDatabaseImpl(null, null, null, name, new DatabaseInner(), this.sqlServerManager)) - .withPatchUpdate(); + new SqlDatabaseImpl(null, null, null, name, new DatabaseInner(), this.sqlServerManager)) + .withPatchUpdate(); } else { return prepareInlineUpdate( - new SqlDatabaseImpl(name, this.getParent(), new DatabaseInner(), this.getParent().manager())) - .withPatchUpdate(); + new SqlDatabaseImpl(name, this.getParent(), new DatabaseInner(), this.getParent().manager())) + .withPatchUpdate(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolForDatabaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolForDatabaseImpl.java index 9f36c69b575d6..9b85d70a30c78 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolForDatabaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolForDatabaseImpl.java @@ -20,9 +20,8 @@ import com.azure.resourcemanager.sql.models.SqlElasticPoolStandardStorage; /** Implementation for SqlElasticPool as inline definition inside a SqlDatabase definition. */ -public class SqlElasticPoolForDatabaseImpl - implements SqlElasticPool.SqlElasticPoolDefinition< - SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool> { +public class SqlElasticPoolForDatabaseImpl implements + SqlElasticPool.SqlElasticPoolDefinition { private SqlElasticPoolImpl sqlElasticPool; private SqlDatabaseImpl sqlDatabase; diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolImpl.java index 125fb0655b7b0..499c548956f13 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolImpl.java @@ -46,13 +46,10 @@ import java.util.Objects; /** Implementation for SqlElasticPool. */ -public class SqlElasticPoolImpl - extends ExternalChildResourceImpl - implements SqlElasticPool, - SqlElasticPool.SqlElasticPoolDefinition, - SqlElasticPoolOperations.DefinitionStages.WithCreate, - SqlElasticPool.Update, - SqlElasticPoolOperations.SqlElasticPoolOperationsDefinition { +public class SqlElasticPoolImpl extends + ExternalChildResourceImpl implements SqlElasticPool, + SqlElasticPool.SqlElasticPoolDefinition, SqlElasticPoolOperations.DefinitionStages.WithCreate, + SqlElasticPool.Update, SqlElasticPoolOperations.SqlElasticPoolOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; @@ -69,8 +66,8 @@ public class SqlElasticPoolImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlElasticPoolImpl( - String name, SqlServerImpl parent, ElasticPoolInner innerObject, SqlServerManager sqlServerManager) { + SqlElasticPoolImpl(String name, SqlServerImpl parent, ElasticPoolInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -93,13 +90,8 @@ public class SqlElasticPoolImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlElasticPoolImpl( - String resourceGroupName, - String sqlServerName, - String sqlServerLocation, - String name, - ElasticPoolInner innerObject, - SqlServerManager sqlServerManager) { + SqlElasticPoolImpl(String resourceGroupName, String sqlServerName, String sqlServerLocation, String name, + ElasticPoolInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -107,8 +99,8 @@ public class SqlElasticPoolImpl this.sqlServerName = sqlServerName; this.sqlServerLocation = sqlServerLocation; - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } /** @@ -123,8 +115,8 @@ public class SqlElasticPoolImpl Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } @Override @@ -195,12 +187,9 @@ public Region region() { @Override public List listActivities() { List elasticPoolActivities = new ArrayList<>(); - PagedIterable elasticPoolActivityInners = - this - .sqlServerManager - .serviceClient() - .getElasticPoolOperations() - .listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); + PagedIterable elasticPoolActivityInners = this.sqlServerManager.serviceClient() + .getElasticPoolOperations() + .listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); for (ElasticPoolOperationInner inner : elasticPoolActivityInners) { elasticPoolActivities.add(new ElasticPoolActivityImpl(inner)); } @@ -209,33 +198,22 @@ public List listActivities() { @Override public PagedFlux listActivitiesAsync() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getElasticPoolOperations() - .listByElasticPoolAsync(this.resourceGroupName, this.sqlServerName, this.name()), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getElasticPoolOperations() + .listByElasticPoolAsync(this.resourceGroupName, this.sqlServerName, this.name()), ElasticPoolActivityImpl::new); } @Override public List listDatabases() { List databases = new ArrayList<>(); - PagedIterable databaseInners = - this - .sqlServerManager - .serviceClient() - .getDatabases() - .listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); + PagedIterable databaseInners = this.sqlServerManager.serviceClient() + .getDatabases() + .listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); for (DatabaseInner inner : databaseInners) { - databases - .add( - new SqlDatabaseImpl( - this.resourceGroupName, - this.sqlServerName, - this.sqlServerLocation, - inner.name(), - inner, - this.sqlServerManager)); + databases.add(new SqlDatabaseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, + inner.name(), inner, this.sqlServerManager)); } return Collections.unmodifiableList(databases); } @@ -243,46 +221,29 @@ public List listDatabases() { @Override public PagedFlux listDatabasesAsync() { final SqlElasticPoolImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getDatabases() - .listByElasticPoolAsync(self.resourceGroupName, self.sqlServerName, this.name()), - databaseInner -> - new SqlDatabaseImpl( - self.resourceGroupName, - self.sqlServerName, - self.sqlServerLocation, - databaseInner.name(), - databaseInner, - self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getDatabases() + .listByElasticPoolAsync(self.resourceGroupName, self.sqlServerName, this.name()), + databaseInner -> new SqlDatabaseImpl(self.resourceGroupName, self.sqlServerName, self.sqlServerLocation, + databaseInner.name(), databaseInner, self.sqlServerManager)); } @Override public SqlDatabase getDatabase(String databaseName) { - DatabaseInner databaseInner = - this - .sqlServerManager - .serviceClient() - .getDatabases() - .get(this.resourceGroupName, this.sqlServerName, databaseName); + DatabaseInner databaseInner = this.sqlServerManager.serviceClient() + .getDatabases() + .get(this.resourceGroupName, this.sqlServerName, databaseName); return databaseInner != null - ? new SqlDatabaseImpl( - this.resourceGroupName, - this.sqlServerName, - this.sqlServerLocation, - databaseName, - databaseInner, - this.sqlServerManager) + ? new SqlDatabaseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, databaseName, + databaseInner, this.sqlServerManager) : null; } @Override public SqlDatabase addNewDatabase(String databaseName) { - return this - .sqlServerManager - .sqlServers() + return this.sqlServerManager.sqlServers() .databases() .define(databaseName) .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation) @@ -302,8 +263,7 @@ public SqlDatabase addExistingDatabase(SqlDatabase database) { @Override public SqlDatabase removeDatabase(String databaseName) { - return this - .getDatabase(databaseName) + return this.getDatabase(databaseName) .update() .withoutElasticPool() .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) @@ -312,9 +272,7 @@ public SqlDatabase removeDatabase(String databaseName) { @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getElasticPools() .delete(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -326,9 +284,7 @@ public Mono deleteAsync() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getElasticPools() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -337,31 +293,25 @@ protected Mono getInnerAsync() { public Mono createResourceAsync() { final SqlElasticPoolImpl self = this; this.innerModel().withLocation(this.sqlServerLocation); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getElasticPools() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } @Override public Mono updateResourceAsync() { final SqlElasticPoolImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getElasticPools() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } void addParentDependency(TaskGroup.HasTaskGroup parentDependency) { @@ -383,9 +333,7 @@ public Mono afterPostRunAsync(boolean isGroupFaulted) { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getElasticPools() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -543,64 +491,45 @@ public SqlElasticPoolImpl withStorageCapacity(Long maxSizeBytes) { @Override public SqlElasticPoolImpl withNewDatabase(String databaseName) { if (this.sqlDatabases == null) { - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } - return new SqlDatabaseForElasticPoolImpl( - this, - this - .sqlDatabases - .defineInlineDatabase(databaseName) - .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) - .attach(); + return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases.defineInlineDatabase(databaseName) + .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)).attach(); } @Override public SqlElasticPoolImpl withExistingDatabase(String databaseName) { if (this.sqlDatabases == null) { - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } - return new SqlDatabaseForElasticPoolImpl( - this, - this - .sqlDatabases - .patchUpdateDatabase(databaseName) - .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) - .attach(); + return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases.patchUpdateDatabase(databaseName) + .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)).attach(); } @Override public SqlElasticPoolImpl withExistingDatabase(SqlDatabase database) { if (this.sqlDatabases == null) { - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } - return new SqlDatabaseForElasticPoolImpl( - this, - this - .sqlDatabases - .patchUpdateDatabase(database.name()) - .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) - .attach(); + return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases.patchUpdateDatabase(database.name()) + .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)).attach(); } @Override public SqlDatabaseForElasticPoolImpl defineDatabase(String databaseName) { if (this.sqlDatabases == null) { - this.sqlDatabases = - new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); + this.sqlDatabases + = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } - return new SqlDatabaseForElasticPoolImpl( - this, - this - .sqlDatabases - .defineInlineDatabase(databaseName) - .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)); + return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases.defineInlineDatabase(databaseName) + .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolOperationsImpl.java index 29e463b80ef5c..4e2db379cad9c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolOperationsImpl.java @@ -39,25 +39,21 @@ public class SqlElasticPoolOperationsImpl @Override public SqlElasticPool getBySqlServer(String resourceGroupName, String sqlServerName, String name) { - ElasticPoolInner inner = - this.manager.serviceClient().getElasticPools().get(resourceGroupName, sqlServerName, name); + ElasticPoolInner inner + = this.manager.serviceClient().getElasticPools().get(resourceGroupName, sqlServerName, name); return (inner != null) ? new SqlElasticPoolImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { - return this - .manager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { + return this.manager.serviceClient() .getElasticPools() .getAsync(resourceGroupName, sqlServerName, name) - .map( - inner -> - new SqlElasticPoolImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + .map(inner -> new SqlElasticPoolImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), + inner, manager)); } @Override @@ -65,16 +61,15 @@ public SqlElasticPool getBySqlServer(SqlServer sqlServer, String name) { if (sqlServer == null) { return null; } - ElasticPoolInner inner = - this.manager.serviceClient().getElasticPools().get(sqlServer.resourceGroupName(), sqlServer.name(), name); + ElasticPoolInner inner + = this.manager.serviceClient().getElasticPools().get(sqlServer.resourceGroupName(), sqlServer.name(), name); return (inner != null) ? new SqlElasticPoolImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager) : null; } @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getElasticPools() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) @@ -100,21 +95,17 @@ public Mono getAsync(String name) { @Override public SqlElasticPool getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -145,21 +136,17 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public void deleteById(String id) { Objects.requireNonNull(id); - this - .deleteBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + this.deleteBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); - return this - .deleteBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.deleteBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -181,38 +168,30 @@ public PagedFlux listAsync() { @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List elasticPoolSet = new ArrayList<>(); - for (ElasticPoolInner inner - : this.manager.serviceClient().getElasticPools().listByServer(resourceGroupName, sqlServerName)) { - elasticPoolSet - .add( - new SqlElasticPoolImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + for (ElasticPoolInner inner : this.manager.serviceClient() + .getElasticPools() + .listByServer(resourceGroupName, sqlServerName)) { + elasticPoolSet.add(new SqlElasticPoolImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), + inner, manager)); } return Collections.unmodifiableList(elasticPoolSet); } @Override public PagedFlux listBySqlServerAsync(final String resourceGroupName, final String sqlServerName) { - return PagedConverter.mapPage(this - .manager - .serviceClient() - .getElasticPools() - .listByServerAsync(resourceGroupName, sqlServerName), - inner -> - new SqlElasticPoolImpl( - resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager)); + return PagedConverter.mapPage( + this.manager.serviceClient().getElasticPools().listByServerAsync(resourceGroupName, sqlServerName), + inner -> new SqlElasticPoolImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, + manager)); } @Override public List listBySqlServer(SqlServer sqlServer) { List elasticPoolSet = new ArrayList<>(); if (sqlServer != null) { - for (ElasticPoolInner inner - : this - .manager - .serviceClient() - .getElasticPools() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { + for (ElasticPoolInner inner : this.manager.serviceClient() + .getElasticPools() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { elasticPoolSet.add(new SqlElasticPoolImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager)); } } @@ -222,11 +201,11 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getElasticPools() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getElasticPools() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), inner -> new SqlElasticPoolImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolsAsExternalChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolsAsExternalChildResourcesImpl.java index 12343c90fc994..964244ed083f9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolsAsExternalChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlElasticPoolsAsExternalChildResourcesImpl.java @@ -13,9 +13,8 @@ import java.util.List; /** Represents a SQL Elastic Pool collection associated with an Azure SQL server. */ -public class SqlElasticPoolsAsExternalChildResourcesImpl - extends ExternalChildResourcesNonCachedImpl< - SqlElasticPoolImpl, SqlElasticPool, ElasticPoolInner, SqlServerImpl, SqlServer> { +public class SqlElasticPoolsAsExternalChildResourcesImpl extends + ExternalChildResourcesNonCachedImpl { SqlServerManager sqlServerManager; @@ -48,8 +47,8 @@ protected SqlElasticPoolsAsExternalChildResourcesImpl(SqlServerManager sqlServer * @param sqlServerManager the manager * @param childResourceName the child resource name (for logging) */ - protected SqlElasticPoolsAsExternalChildResourcesImpl( - TaskGroup parentTaskGroup, SqlServerManager sqlServerManager, String childResourceName) { + protected SqlElasticPoolsAsExternalChildResourcesImpl(TaskGroup parentTaskGroup, SqlServerManager sqlServerManager, + String childResourceName) { super(null, parentTaskGroup, childResourceName); this.sqlServerManager = sqlServerManager; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorImpl.java index 9cbaa972de5d1..b545c1579baf0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorImpl.java @@ -34,8 +34,8 @@ public class SqlEncryptionProtectorImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlEncryptionProtectorImpl( - SqlServerImpl parent, EncryptionProtectorInner innerObject, SqlServerManager sqlServerManager) { + SqlEncryptionProtectorImpl(SqlServerImpl parent, EncryptionProtectorInner innerObject, + SqlServerManager sqlServerManager) { super("", parent, innerObject); Objects.requireNonNull(parent); @@ -56,10 +56,7 @@ public class SqlEncryptionProtectorImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlEncryptionProtectorImpl( - String resourceGroupName, - String sqlServerName, - EncryptionProtectorInner innerObject, + SqlEncryptionProtectorImpl(String resourceGroupName, String sqlServerName, EncryptionProtectorInner innerObject, SqlServerManager sqlServerManager) { super("", null, innerObject); Objects.requireNonNull(sqlServerManager); @@ -161,17 +158,14 @@ public SqlEncryptionProtectorImpl withServiceManagedServerKey() { @Override public Mono createResourceAsync() { final SqlEncryptionProtectorImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getEncryptionProtectors() - .createOrUpdateAsync( - this.resourceGroupName, this.sqlServerName, EncryptionProtectorName.CURRENT, this.innerModel()) - .map( - encryptionProtectorInner -> { - self.setInner(encryptionProtectorInner); - return self; - }); + .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, EncryptionProtectorName.CURRENT, + this.innerModel()) + .map(encryptionProtectorInner -> { + self.setInner(encryptionProtectorInner); + return self; + }); } @Override @@ -191,9 +185,7 @@ public Mono deleteResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getEncryptionProtectors() .getAsync(this.resourceGroupName, this.sqlServerName, EncryptionProtectorName.CURRENT); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorOperationsImpl.java index 021b9d14372cb..3938f03aad8d6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlEncryptionProtectorOperationsImpl.java @@ -19,9 +19,8 @@ import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** Implementation for SQL Encryption Protector operations. */ -public class SqlEncryptionProtectorOperationsImpl - implements SqlEncryptionProtectorOperations, - SqlEncryptionProtectorOperations.SqlEncryptionProtectorActionsDefinition { +public class SqlEncryptionProtectorOperationsImpl implements SqlEncryptionProtectorOperations, + SqlEncryptionProtectorOperations.SqlEncryptionProtectorActionsDefinition { protected SqlServerManager sqlServerManager; protected SqlServer sqlServer; @@ -40,42 +39,33 @@ public class SqlEncryptionProtectorOperationsImpl @Override public SqlEncryptionProtector getBySqlServer(String resourceGroupName, String sqlServerName) { - EncryptionProtectorInner encryptionProtectorInner = - this - .sqlServerManager - .serviceClient() - .getEncryptionProtectors() - .get(resourceGroupName, sqlServerName, EncryptionProtectorName.CURRENT); + EncryptionProtectorInner encryptionProtectorInner = this.sqlServerManager.serviceClient() + .getEncryptionProtectors() + .get(resourceGroupName, sqlServerName, EncryptionProtectorName.CURRENT); return encryptionProtectorInner != null - ? new SqlEncryptionProtectorImpl( - resourceGroupName, sqlServerName, encryptionProtectorInner, this.sqlServerManager) + ? new SqlEncryptionProtectorImpl(resourceGroupName, sqlServerName, encryptionProtectorInner, + this.sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { + public Mono getBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { final SqlEncryptionProtectorOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getEncryptionProtectors() .getAsync(resourceGroupName, sqlServerName, EncryptionProtectorName.CURRENT) - .map( - encryptionProtectorInner -> - new SqlEncryptionProtectorImpl( - resourceGroupName, sqlServerName, encryptionProtectorInner, self.sqlServerManager)); + .map(encryptionProtectorInner -> new SqlEncryptionProtectorImpl(resourceGroupName, sqlServerName, + encryptionProtectorInner, self.sqlServerManager)); } @Override public SqlEncryptionProtector getBySqlServer(SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - EncryptionProtectorInner encryptionProtectorInner = - sqlServer - .manager() - .serviceClient() - .getEncryptionProtectors() - .get(sqlServer.resourceGroupName(), sqlServer.name(), EncryptionProtectorName.CURRENT); + EncryptionProtectorInner encryptionProtectorInner = sqlServer.manager() + .serviceClient() + .getEncryptionProtectors() + .get(sqlServer.resourceGroupName(), sqlServer.name(), EncryptionProtectorName.CURRENT); return encryptionProtectorInner != null ? new SqlEncryptionProtectorImpl((SqlServerImpl) sqlServer, encryptionProtectorInner, sqlServer.manager()) : null; @@ -84,15 +74,12 @@ public SqlEncryptionProtector getBySqlServer(SqlServer sqlServer) { @Override public Mono getBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getEncryptionProtectors() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), EncryptionProtectorName.CURRENT) - .map( - encryptionProtectorInner -> - new SqlEncryptionProtectorImpl( - (SqlServerImpl) sqlServer, encryptionProtectorInner, sqlServer.manager())); + .map(encryptionProtectorInner -> new SqlEncryptionProtectorImpl((SqlServerImpl) sqlServer, + encryptionProtectorInner, sqlServer.manager())); } @Override @@ -114,19 +101,15 @@ public Mono getAsync() { @Override public SqlEncryptionProtector getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); } @Override @@ -148,12 +131,9 @@ public PagedFlux listAsync() { @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List encryptionProtectors = new ArrayList<>(); - PagedIterable encryptionProtectorInners = - this - .sqlServerManager - .serviceClient() - .getEncryptionProtectors() - .listByServer(resourceGroupName, sqlServerName); + PagedIterable encryptionProtectorInners = this.sqlServerManager.serviceClient() + .getEncryptionProtectors() + .listByServer(resourceGroupName, sqlServerName); for (EncryptionProtectorInner inner : encryptionProtectorInners) { encryptionProtectors .add(new SqlEncryptionProtectorImpl(resourceGroupName, sqlServerName, inner, this.sqlServerManager)); @@ -162,29 +142,25 @@ public List listBySqlServer(String resourceGroupName, St } @Override - public PagedFlux listBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { + public PagedFlux listBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { final SqlEncryptionProtectorOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getEncryptionProtectors() - .listByServerAsync(resourceGroupName, sqlServerName), - encryptionProtectorInner -> - new SqlEncryptionProtectorImpl( - resourceGroupName, sqlServerName, encryptionProtectorInner, self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getEncryptionProtectors() + .listByServerAsync(resourceGroupName, sqlServerName), + encryptionProtectorInner -> new SqlEncryptionProtectorImpl(resourceGroupName, sqlServerName, + encryptionProtectorInner, self.sqlServerManager)); } @Override public List listBySqlServer(SqlServer sqlServer) { Objects.requireNonNull(sqlServer); List encryptionProtectors = new ArrayList<>(); - PagedIterable encryptionProtectorInners = - sqlServer - .manager() - .serviceClient() - .getEncryptionProtectors() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); + PagedIterable encryptionProtectorInners = sqlServer.manager() + .serviceClient() + .getEncryptionProtectors() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); for (EncryptionProtectorInner inner : encryptionProtectorInners) { encryptionProtectors .add(new SqlEncryptionProtectorImpl((SqlServerImpl) sqlServer, inner, sqlServer.manager())); @@ -195,13 +171,12 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getEncryptionProtectors() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - encryptionProtectorInner -> - new SqlEncryptionProtectorImpl( - (SqlServerImpl) sqlServer, encryptionProtectorInner, sqlServer.manager())); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getEncryptionProtectors() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + encryptionProtectorInner -> new SqlEncryptionProtectorImpl((SqlServerImpl) sqlServer, + encryptionProtectorInner, sqlServer.manager())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupImpl.java index 0fc35ff39d0eb..f89141c15997d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupImpl.java @@ -27,10 +27,8 @@ /** Implementation for SqlFailoverGroup. */ public class SqlFailoverGroupImpl - extends ExternalChildResourceImpl - implements SqlFailoverGroup, - SqlFailoverGroup.Update, - SqlFailoverGroupOperations.SqlFailoverGroupOperationsDefinition { + extends ExternalChildResourceImpl implements + SqlFailoverGroup, SqlFailoverGroup.Update, SqlFailoverGroupOperations.SqlFailoverGroupOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; @@ -45,8 +43,8 @@ public class SqlFailoverGroupImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses failover group operations */ - SqlFailoverGroupImpl( - String name, SqlServerImpl parent, FailoverGroupInner innerObject, SqlServerManager sqlServerManager) { + SqlFailoverGroupImpl(String name, SqlServerImpl parent, FailoverGroupInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -66,13 +64,8 @@ public class SqlFailoverGroupImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses failover group operations */ - SqlFailoverGroupImpl( - String resourceGroupName, - String sqlServerName, - String sqlServerLocation, - String name, - FailoverGroupInner innerObject, - SqlServerManager sqlServerManager) { + SqlFailoverGroupImpl(String resourceGroupName, String sqlServerName, String sqlServerLocation, String name, + FailoverGroupInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -137,9 +130,9 @@ public ReadWriteEndpointFailoverPolicy readWriteEndpointPolicy() { @Override public int readWriteEndpointDataLossGracePeriodMinutes() { return this.innerModel().readWriteEndpoint() != null - && this.innerModel().readWriteEndpoint().failoverWithDataLossGracePeriodMinutes() != null - ? this.innerModel().readWriteEndpoint().failoverWithDataLossGracePeriodMinutes() - : 0; + && this.innerModel().readWriteEndpoint().failoverWithDataLossGracePeriodMinutes() != null + ? this.innerModel().readWriteEndpoint().failoverWithDataLossGracePeriodMinutes() + : 0; } @Override @@ -161,25 +154,20 @@ public String replicationState() { @Override public List partnerServers() { - return Collections - .unmodifiableList( - this.innerModel().partnerServers() != null - ? this.innerModel().partnerServers() - : new ArrayList()); + return Collections.unmodifiableList(this.innerModel().partnerServers() != null + ? this.innerModel().partnerServers() + : new ArrayList()); } @Override public List databases() { - return Collections - .unmodifiableList( - this.innerModel().databases() != null ? this.innerModel().databases() : new ArrayList()); + return Collections.unmodifiableList( + this.innerModel().databases() != null ? this.innerModel().databases() : new ArrayList()); } @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getFailoverGroups() .delete(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -190,8 +178,8 @@ public Mono deleteAsync() { } @Override - public SqlFailoverGroupImpl withExistingSqlServer( - String resourceGroupName, String sqlServerName, String sqlServerLocation) { + public SqlFailoverGroupImpl withExistingSqlServer(String resourceGroupName, String sqlServerName, + String sqlServerLocation) { this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.sqlServerLocation = sqlServerLocation; @@ -216,16 +204,13 @@ public SqlFailoverGroupImpl update() { @Override public Mono createResourceAsync() { final SqlFailoverGroupImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .createOrUpdateAsync(self.resourceGroupName, self.sqlServerName, self.name(), self.innerModel()) - .map( - failoverGroupInner -> { - self.setInner(failoverGroupInner); - return self; - }); + .map(failoverGroupInner -> { + self.setInner(failoverGroupInner); + return self; + }); } @Override @@ -235,18 +220,14 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupOperationsImpl.java index afaba55bf2283..4d5213eeb9e25 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFailoverGroupOperationsImpl.java @@ -32,20 +32,18 @@ public class SqlFailoverGroupOperationsImpl extends SqlChildrenOperationsImpl getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { final SqlFailoverGroupOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .getAsync(resourceGroupName, sqlServerName, name) .map(failoverGroupInner -> new SqlFailoverGroupImpl(name, failoverGroupInner, self.sqlServerManager)); @@ -54,12 +52,10 @@ public Mono getBySqlServerAsync( @Override public SqlFailoverGroup getBySqlServer(SqlServer sqlServer, String name) { Objects.requireNonNull(sqlServer); - FailoverGroupInner failoverGroupInner = - sqlServer - .manager() - .serviceClient() - .getFailoverGroups() - .get(sqlServer.resourceGroupName(), sqlServer.name(), name); + FailoverGroupInner failoverGroupInner = sqlServer.manager() + .serviceClient() + .getFailoverGroups() + .get(sqlServer.resourceGroupName(), sqlServer.name(), name); return failoverGroupInner != null ? new SqlFailoverGroupImpl(name, (SqlServerImpl) sqlServer, failoverGroupInner, sqlServer.manager()) : null; @@ -68,14 +64,12 @@ public SqlFailoverGroup getBySqlServer(SqlServer sqlServer, String name) { @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getFailoverGroups() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) - .map( - failoverGroupInner -> - new SqlFailoverGroupImpl(name, (SqlServerImpl) sqlServer, failoverGroupInner, sqlServer.manager())); + .map(failoverGroupInner -> new SqlFailoverGroupImpl(name, (SqlServerImpl) sqlServer, failoverGroupInner, + sqlServer.manager())); } @Override @@ -85,9 +79,7 @@ public void deleteBySqlServer(String resourceGroupName, String sqlServerName, St @Override public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlServerName, String name) { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .deleteAsync(resourceGroupName, sqlServerName, name); } @@ -95,8 +87,8 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List failoverGroups = new ArrayList<>(); - PagedIterable failoverGroupInners = - this.sqlServerManager.serviceClient().getFailoverGroups().listByServer(resourceGroupName, sqlServerName); + PagedIterable failoverGroupInners + = this.sqlServerManager.serviceClient().getFailoverGroups().listByServer(resourceGroupName, sqlServerName); for (FailoverGroupInner inner : failoverGroupInners) { failoverGroups.add(new SqlFailoverGroupImpl(inner.name(), inner, this.sqlServerManager)); } @@ -104,27 +96,24 @@ public List listBySqlServer(String resourceGroupName, String s } @Override - public PagedFlux listBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { + public PagedFlux listBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { final SqlFailoverGroupOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getFailoverGroups() - .listByServerAsync(resourceGroupName, sqlServerName), - failoverGroupInner -> - new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getFailoverGroups() + .listByServerAsync(resourceGroupName, sqlServerName), + failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, + self.sqlServerManager)); } @Override public List listBySqlServer(final SqlServer sqlServer) { List failoverGroups = new ArrayList<>(); - PagedIterable failoverGroupInners = - sqlServer - .manager() - .serviceClient() - .getFailoverGroups() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); + PagedIterable failoverGroupInners = sqlServer.manager() + .serviceClient() + .getFailoverGroups() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); for (FailoverGroupInner inner : failoverGroupInners) { failoverGroups .add(new SqlFailoverGroupImpl(inner.name(), (SqlServerImpl) sqlServer, inner, this.sqlServerManager)); @@ -134,14 +123,13 @@ public List listBySqlServer(final SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getFailoverGroups() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - failoverGroupInner -> - new SqlFailoverGroupImpl( - failoverGroupInner.name(), (SqlServerImpl) sqlServer, failoverGroupInner, sqlServer.manager())); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getFailoverGroups() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), (SqlServerImpl) sqlServer, + failoverGroupInner, sqlServer.manager())); } @Override @@ -154,113 +142,91 @@ public SqlFailoverGroupImpl define(String name) { @Override public SqlFailoverGroup failover(String failoverGroupName) { Objects.requireNonNull(this.sqlServer); - FailoverGroupInner failoverGroupInner = - sqlServer - .manager() - .serviceClient() - .getFailoverGroups() - .failover(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName); + FailoverGroupInner failoverGroupInner = sqlServer.manager() + .serviceClient() + .getFailoverGroups() + .failover(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName); return failoverGroupInner != null - ? new SqlFailoverGroupImpl( - failoverGroupInner.name(), (SqlServerImpl) this.sqlServer, failoverGroupInner, sqlServer.manager()) + ? new SqlFailoverGroupImpl(failoverGroupInner.name(), (SqlServerImpl) this.sqlServer, failoverGroupInner, + sqlServer.manager()) : null; } @Override public Mono failoverAsync(String failoverGroupName) { Objects.requireNonNull(this.sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getFailoverGroups() .failoverAsync(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName) - .map( - failoverGroupInner -> - new SqlFailoverGroupImpl( - failoverGroupInner.name(), (SqlServerImpl) sqlServer, failoverGroupInner, sqlServer.manager())); + .map(failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), (SqlServerImpl) sqlServer, + failoverGroupInner, sqlServer.manager())); } @Override public SqlFailoverGroup forceFailoverAllowDataLoss(String failoverGroupName) { Objects.requireNonNull(this.sqlServer); - FailoverGroupInner failoverGroupInner = - sqlServer - .manager() - .serviceClient() - .getFailoverGroups() - .forceFailoverAllowDataLoss(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName); + FailoverGroupInner failoverGroupInner = sqlServer.manager() + .serviceClient() + .getFailoverGroups() + .forceFailoverAllowDataLoss(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName); return failoverGroupInner != null - ? new SqlFailoverGroupImpl( - failoverGroupInner.name(), (SqlServerImpl) this.sqlServer, failoverGroupInner, sqlServer.manager()) + ? new SqlFailoverGroupImpl(failoverGroupInner.name(), (SqlServerImpl) this.sqlServer, failoverGroupInner, + sqlServer.manager()) : null; } @Override public Mono forceFailoverAllowDataLossAsync(String failoverGroupName) { Objects.requireNonNull(this.sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getFailoverGroups() .forceFailoverAllowDataLossAsync(sqlServer.resourceGroupName(), sqlServer.name(), failoverGroupName) - .map( - failoverGroupInner -> - new SqlFailoverGroupImpl( - failoverGroupInner.name(), (SqlServerImpl) sqlServer, failoverGroupInner, sqlServer.manager())); + .map(failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), (SqlServerImpl) sqlServer, + failoverGroupInner, sqlServer.manager())); } @Override public SqlFailoverGroup failover(String resourceGroupName, String serverName, String failoverGroupName) { - FailoverGroupInner failoverGroupInner = - this - .sqlServerManager - .serviceClient() - .getFailoverGroups() - .failover(resourceGroupName, serverName, failoverGroupName); + FailoverGroupInner failoverGroupInner = this.sqlServerManager.serviceClient() + .getFailoverGroups() + .failover(resourceGroupName, serverName, failoverGroupName); return failoverGroupInner != null ? new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, this.sqlServerManager) : null; } @Override - public Mono failoverAsync( - final String resourceGroupName, final String serverName, final String failoverGroupName) { + public Mono failoverAsync(final String resourceGroupName, final String serverName, + final String failoverGroupName) { final SqlFailoverGroupOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .failoverAsync(resourceGroupName, serverName, failoverGroupName) - .map( - failoverGroupInner -> - new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, self.sqlServerManager)); + .map(failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, + self.sqlServerManager)); } @Override - public SqlFailoverGroup forceFailoverAllowDataLoss( - String resourceGroupName, String serverName, String failoverGroupName) { - FailoverGroupInner failoverGroupInner = - this - .sqlServerManager - .serviceClient() - .getFailoverGroups() - .forceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName); + public SqlFailoverGroup forceFailoverAllowDataLoss(String resourceGroupName, String serverName, + String failoverGroupName) { + FailoverGroupInner failoverGroupInner = this.sqlServerManager.serviceClient() + .getFailoverGroups() + .forceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName); return failoverGroupInner != null ? new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, this.sqlServerManager) : null; } @Override - public Mono forceFailoverAllowDataLossAsync( - final String resourceGroupName, final String serverName, String failoverGroupName) { + public Mono forceFailoverAllowDataLossAsync(final String resourceGroupName, + final String serverName, String failoverGroupName) { final SqlFailoverGroupOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFailoverGroups() .forceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName) - .map( - failoverGroupInner -> - new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, self.sqlServerManager)); + .map(failoverGroupInner -> new SqlFailoverGroupImpl(failoverGroupInner.name(), failoverGroupInner, + self.sqlServerManager)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleImpl.java index 144511b7d6f51..620b43a00a66d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleImpl.java @@ -18,10 +18,8 @@ /** Implementation for SqlFirewallRule. */ public class SqlFirewallRuleImpl extends ExternalChildResourceImpl - implements SqlFirewallRule, - SqlFirewallRule.SqlFirewallRuleDefinition, - SqlFirewallRule.Update, - SqlFirewallRuleOperations.SqlFirewallRuleOperationsDefinition { + implements SqlFirewallRule, SqlFirewallRule.SqlFirewallRuleDefinition, SqlFirewallRule.Update, + SqlFirewallRuleOperations.SqlFirewallRuleOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; @@ -35,8 +33,8 @@ public class SqlFirewallRuleImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlFirewallRuleImpl( - String name, SqlServerImpl parent, FirewallRuleInner innerObject, SqlServerManager sqlServerManager) { + SqlFirewallRuleImpl(String name, SqlServerImpl parent, FirewallRuleInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -55,11 +53,7 @@ public class SqlFirewallRuleImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlFirewallRuleImpl( - String resourceGroupName, - String sqlServerName, - String name, - FirewallRuleInner innerObject, + SqlFirewallRuleImpl(String resourceGroupName, String sqlServerName, String name, FirewallRuleInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); @@ -83,9 +77,7 @@ public class SqlFirewallRuleImpl @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -158,38 +150,30 @@ public String parentId() { @Override public Mono createResourceAsync() { final SqlFirewallRuleImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } @Override public Mono updateResourceAsync() { final SqlFirewallRuleImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleOperationsImpl.java index 27aa3e9a949a8..500abb4f9bc96 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRuleOperationsImpl.java @@ -40,35 +40,29 @@ public class SqlFirewallRuleOperationsImpl @Override public SqlFirewallRule getBySqlServer(String resourceGroupName, String sqlServerName, String name) { - FirewallRuleInner inner = - this.sqlServerManager.serviceClient().getFirewallRules().get(resourceGroupName, sqlServerName, name); + FirewallRuleInner inner + = this.sqlServerManager.serviceClient().getFirewallRules().get(resourceGroupName, sqlServerName, name); return (inner != null) ? new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { - return this - .sqlServerManager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { + return this.sqlServerManager.serviceClient() .getFirewallRules() .getAsync(resourceGroupName, sqlServerName, name) - .map( - inner -> - new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager)); + .map(inner -> new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, + sqlServerManager)); } @Override public SqlFirewallRule getBySqlServer(SqlServer sqlServer, String name) { Objects.requireNonNull(sqlServer); - FirewallRuleInner inner = - this - .sqlServerManager - .serviceClient() - .getFirewallRules() - .get(sqlServer.resourceGroupName(), sqlServer.name(), name); + FirewallRuleInner inner = this.sqlServerManager.serviceClient() + .getFirewallRules() + .get(sqlServer.resourceGroupName(), sqlServer.name(), name); return (inner != null) ? new SqlFirewallRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager()) : null; @@ -77,9 +71,7 @@ public SqlFirewallRule getBySqlServer(SqlServer sqlServer, String name) { @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) .map(inner -> new SqlFirewallRuleImpl(name, (SqlServerImpl) sqlServer, inner, sqlServer.manager())); @@ -104,21 +96,17 @@ public Mono getAsync(String name) { @Override public SqlFirewallRule getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -128,9 +116,7 @@ public void deleteBySqlServer(String resourceGroupName, String sqlServerName, St @Override public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlServerName, String name) { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getFirewallRules() .deleteAsync(resourceGroupName, sqlServerName, name); } @@ -138,21 +124,17 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public void deleteById(String id) { Objects.requireNonNull(id); - this - .deleteBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + this.deleteBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override public Mono deleteByIdAsync(String id) { Objects.requireNonNull(id); - return this - .deleteBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), - ResourceUtils.nameFromResourceId(id)); + return this.deleteBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)), + ResourceUtils.nameFromResourceId(id)); } @Override @@ -173,38 +155,32 @@ public Mono deleteAsync(String name) { @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List firewallRuleSet = new ArrayList<>(); - PagedIterable firewallRuleInners = - this.sqlServerManager.serviceClient().getFirewallRules().listByServer(resourceGroupName, sqlServerName); + PagedIterable firewallRuleInners + = this.sqlServerManager.serviceClient().getFirewallRules().listByServer(resourceGroupName, sqlServerName); for (FirewallRuleInner inner : firewallRuleInners) { - firewallRuleSet - .add( - new SqlFirewallRuleImpl( - resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); + firewallRuleSet.add( + new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); } return Collections.unmodifiableList(firewallRuleSet); } @Override public PagedFlux listBySqlServerAsync(final String resourceGroupName, final String sqlServerName) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getFirewallRules() - .listByServerAsync(resourceGroupName, sqlServerName), - inner -> - new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getFirewallRules() + .listByServerAsync(resourceGroupName, sqlServerName), + inner -> new SqlFirewallRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager)); } @Override public List listBySqlServer(SqlServer sqlServer) { Objects.requireNonNull(sqlServer); List firewallRuleSet = new ArrayList<>(); - for (FirewallRuleInner inner - : sqlServer - .manager() - .serviceClient() - .getFirewallRules() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { + for (FirewallRuleInner inner : sqlServer.manager() + .serviceClient() + .getFirewallRules() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { firewallRuleSet .add(new SqlFirewallRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); } @@ -214,12 +190,12 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getFirewallRules() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - inner -> new SqlFirewallRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getFirewallRules() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + inner -> new SqlFirewallRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRulesAsExternalChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRulesAsExternalChildResourcesImpl.java index 7c70e88372f0a..0b43bab99b849 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRulesAsExternalChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlFirewallRulesAsExternalChildResourcesImpl.java @@ -9,9 +9,8 @@ import com.azure.resourcemanager.sql.fluent.models.FirewallRuleInner; /** Represents a SQL Firewall rules collection associated with an Azure SQL server. */ -public class SqlFirewallRulesAsExternalChildResourcesImpl - extends ExternalChildResourcesNonCachedImpl< - SqlFirewallRuleImpl, SqlFirewallRule, FirewallRuleInner, SqlServerImpl, SqlServer> { +public class SqlFirewallRulesAsExternalChildResourcesImpl extends + ExternalChildResourcesNonCachedImpl { SqlServerManager sqlServerManager; @@ -32,8 +31,8 @@ protected SqlFirewallRulesAsExternalChildResourcesImpl(SqlServerImpl parent, Str * @param sqlServerManager the manager * @param childResourceName the child resource name (for logging) */ - protected SqlFirewallRulesAsExternalChildResourcesImpl( - SqlServerManager sqlServerManager, String childResourceName) { + protected SqlFirewallRulesAsExternalChildResourcesImpl(SqlServerManager sqlServerManager, + String childResourceName) { super(null, null, childResourceName); this.sqlServerManager = sqlServerManager; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlRestorableDroppedDatabaseImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlRestorableDroppedDatabaseImpl.java index 66f1706b902b2..0cae513221cfb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlRestorableDroppedDatabaseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlRestorableDroppedDatabaseImpl.java @@ -19,11 +19,8 @@ public class SqlRestorableDroppedDatabaseImpl private final String resourceGroupName; private final SqlServerManager sqlServerManager; - protected SqlRestorableDroppedDatabaseImpl( - String resourceGroupName, - String sqlServerName, - RestorableDroppedDatabaseInner innerObject, - SqlServerManager sqlServerManager) { + protected SqlRestorableDroppedDatabaseImpl(String resourceGroupName, String sqlServerName, + RestorableDroppedDatabaseInner innerObject, SqlServerManager sqlServerManager) { super(innerObject); this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; @@ -67,9 +64,7 @@ public OffsetDateTime earliestRestoreDate() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getRestorableDroppedDatabases() .getAsync(this.resourceGroupName, this.sqlServerName, this.innerModel().id()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerAutomaticTuningImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerAutomaticTuningImpl.java index c6a957ac6465a..f5aa26106f0d5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerAutomaticTuningImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerAutomaticTuningImpl.java @@ -32,10 +32,7 @@ public class SqlServerAutomaticTuningImpl this(server.resourceGroupName(), server.name(), innerObject, server.manager()); } - SqlServerAutomaticTuningImpl( - String resourceGroupName, - String sqlServerName, - ServerAutomaticTuningInner innerObject, + SqlServerAutomaticTuningImpl(String resourceGroupName, String sqlServerName, ServerAutomaticTuningInner innerObject, SqlServerManager sqlServerManager) { super(innerObject); Objects.requireNonNull(innerObject); @@ -64,11 +61,9 @@ public AutomaticTuningServerMode actualState() { @Override public Map tuningOptions() { - return Collections - .unmodifiableMap( - this.innerModel().options() != null - ? this.innerModel().options() - : new HashMap()); + return Collections.unmodifiableMap(this.innerModel().options() != null + ? this.innerModel().options() + : new HashMap()); } @Override @@ -78,17 +73,15 @@ public SqlServerAutomaticTuningImpl withAutomaticTuningMode(AutomaticTuningServe } @Override - public SqlServerAutomaticTuningImpl withAutomaticTuningOption( - String tuningOptionName, AutomaticTuningOptionModeDesired desiredState) { + public SqlServerAutomaticTuningImpl withAutomaticTuningOption(String tuningOptionName, + AutomaticTuningOptionModeDesired desiredState) { if (this.innerModel().options() == null) { this.innerModel().withOptions(new HashMap()); } AutomaticTuningServerOptions item = this.innerModel().options().get(tuningOptionName); - this - .innerModel() + this.innerModel() .options() - .put( - tuningOptionName, + .put(tuningOptionName, item != null ? item.withDesiredState(desiredState) : new AutomaticTuningServerOptions().withDesiredState(desiredState)); @@ -96,8 +89,8 @@ public SqlServerAutomaticTuningImpl withAutomaticTuningOption( } @Override - public SqlServerAutomaticTuningImpl withAutomaticTuningOptions( - Map tuningOptions) { + public SqlServerAutomaticTuningImpl + withAutomaticTuningOptions(Map tuningOptions) { if (tuningOptions != null) { for (Map.Entry option : tuningOptions.entrySet()) { this.withAutomaticTuningOption(option.getKey(), option.getValue()); @@ -108,9 +101,7 @@ public SqlServerAutomaticTuningImpl withAutomaticTuningOptions( @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerAutomaticTunings() .getAsync(this.resourceGroupName, this.sqlServerName); } @@ -133,17 +124,14 @@ public SqlServerAutomaticTuning apply(Context context) { @Override public Mono applyAsync(Context context) { final SqlServerAutomaticTuningImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerAutomaticTunings() .updateAsync(this.resourceGroupName, this.sqlServerName, this.innerModel()) .contextWrite(c -> c.putAll(FluxUtil.toReactorContext(context).readOnly())) - .map( - serverAutomaticTuningInner -> { - self.setInner(serverAutomaticTuningInner); - return self; - }); + .map(serverAutomaticTuningInner -> { + self.setInner(serverAutomaticTuningInner); + return self; + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasImpl.java index 1da8c8326246f..c3df9f5081a4b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasImpl.java @@ -30,8 +30,8 @@ public class SqlServerDnsAliasImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlServerDnsAliasImpl( - String name, SqlServerImpl parent, ServerDnsAliasInner innerObject, SqlServerManager sqlServerManager) { + SqlServerDnsAliasImpl(String name, SqlServerImpl parent, ServerDnsAliasInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -50,11 +50,7 @@ public class SqlServerDnsAliasImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlServerDnsAliasImpl( - String resourceGroupName, - String sqlServerName, - String name, - ServerDnsAliasInner innerObject, + SqlServerDnsAliasImpl(String resourceGroupName, String sqlServerName, String name, ServerDnsAliasInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); @@ -111,9 +107,7 @@ public String parentId() { @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getServerDnsAliases() .delete(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -150,16 +144,13 @@ public SqlServerDnsAliasImpl withExistingSqlServer(SqlServer sqlServer) { @Override public Mono createResourceAsync() { final SqlServerDnsAliasImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .createOrUpdateAsync(self.resourceGroupName, self.sqlServerName, self.name()) - .map( - serverDnsAliasInner -> { - self.setInner(serverDnsAliasInner); - return self; - }); + .map(serverDnsAliasInner -> { + self.setInner(serverDnsAliasInner); + return self; + }); } @Override @@ -169,18 +160,14 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasOperationsImpl.java index a2354638d0e76..b43918223f492 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerDnsAliasOperationsImpl.java @@ -36,38 +36,32 @@ public class SqlServerDnsAliasOperationsImpl extends SqlChildrenOperationsImpl getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { final SqlServerDnsAliasOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .getAsync(resourceGroupName, sqlServerName, name) - .map( - serverDnsAliasInner -> - new SqlServerDnsAliasImpl( - resourceGroupName, sqlServerName, name, serverDnsAliasInner, self.sqlServerManager)); + .map(serverDnsAliasInner -> new SqlServerDnsAliasImpl(resourceGroupName, sqlServerName, name, + serverDnsAliasInner, self.sqlServerManager)); } @Override public SqlServerDnsAlias getBySqlServer(SqlServer sqlServer, String name) { Objects.requireNonNull(sqlServer); - ServerDnsAliasInner serverDnsAliasInner = - sqlServer - .manager() - .serviceClient() - .getServerDnsAliases() - .get(sqlServer.resourceGroupName(), sqlServer.name(), name); + ServerDnsAliasInner serverDnsAliasInner = sqlServer.manager() + .serviceClient() + .getServerDnsAliases() + .get(sqlServer.resourceGroupName(), sqlServer.name(), name); return serverDnsAliasInner != null ? new SqlServerDnsAliasImpl(name, (SqlServerImpl) sqlServer, serverDnsAliasInner, sqlServer.manager()) : null; @@ -76,15 +70,12 @@ public SqlServerDnsAlias getBySqlServer(SqlServer sqlServer, String name) { @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getServerDnsAliases() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) - .map( - serverDnsAliasInner -> - new SqlServerDnsAliasImpl( - name, (SqlServerImpl) sqlServer, serverDnsAliasInner, sqlServer.manager())); + .map(serverDnsAliasInner -> new SqlServerDnsAliasImpl(name, (SqlServerImpl) sqlServer, serverDnsAliasInner, + sqlServer.manager())); } @Override @@ -94,9 +85,7 @@ public void deleteBySqlServer(String resourceGroupName, String sqlServerName, St @Override public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlServerName, String name) { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .deleteAsync(resourceGroupName, sqlServerName, name); } @@ -104,44 +93,35 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List serverDnsAliases = new ArrayList<>(); - PagedIterable serverDnsAliasInners = - this.sqlServerManager.serviceClient().getServerDnsAliases().listByServer(resourceGroupName, sqlServerName); + PagedIterable serverDnsAliasInners = this.sqlServerManager.serviceClient() + .getServerDnsAliases() + .listByServer(resourceGroupName, sqlServerName); for (ServerDnsAliasInner inner : serverDnsAliasInners) { - serverDnsAliases - .add( - new SqlServerDnsAliasImpl( - resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); + serverDnsAliases.add(new SqlServerDnsAliasImpl(resourceGroupName, sqlServerName, inner.name(), inner, + this.sqlServerManager)); } return Collections.unmodifiableList(serverDnsAliases); } @Override - public PagedFlux listBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { + public PagedFlux listBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { final SqlServerDnsAliasOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getServerDnsAliases() - .listByServerAsync(resourceGroupName, sqlServerName), - serverDnsAliasInner -> - new SqlServerDnsAliasImpl( - resourceGroupName, - sqlServerName, - serverDnsAliasInner.name(), - serverDnsAliasInner, - self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getServerDnsAliases() + .listByServerAsync(resourceGroupName, sqlServerName), + serverDnsAliasInner -> new SqlServerDnsAliasImpl(resourceGroupName, sqlServerName, + serverDnsAliasInner.name(), serverDnsAliasInner, self.sqlServerManager)); } @Override public List listBySqlServer(SqlServer sqlServer) { List serverDnsAliases = new ArrayList<>(); - PagedIterable serverDnsAliasInners = - sqlServer - .manager() - .serviceClient() - .getServerDnsAliases() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); + PagedIterable serverDnsAliasInners = sqlServer.manager() + .serviceClient() + .getServerDnsAliases() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); for (ServerDnsAliasInner inner : serverDnsAliasInners) { serverDnsAliases .add(new SqlServerDnsAliasImpl(inner.name(), (SqlServerImpl) sqlServer, inner, this.sqlServerManager)); @@ -151,35 +131,27 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getServerDnsAliases() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - serverDnsAliasInner -> - new SqlServerDnsAliasImpl( - serverDnsAliasInner.name(), - (SqlServerImpl) sqlServer, - serverDnsAliasInner, - sqlServer.manager())); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getServerDnsAliases() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + serverDnsAliasInner -> new SqlServerDnsAliasImpl(serverDnsAliasInner.name(), (SqlServerImpl) sqlServer, + serverDnsAliasInner, sqlServer.manager())); } @Override public void acquire(String resourceGroupName, String serverName, String dnsAliasName, String sqlServerId) { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getServerDnsAliases() .acquire(resourceGroupName, serverName, dnsAliasName, new ServerDnsAliasAcquisition().withOldServerDnsAliasId(sqlServerId + DNS_ALIASES + dnsAliasName)); } @Override - public Mono acquireAsync( - String resourceGroupName, String serverName, String dnsAliasName, String sqlServerId) { - return this - .sqlServerManager - .serviceClient() + public Mono acquireAsync(String resourceGroupName, String serverName, String dnsAliasName, + String sqlServerId) { + return this.sqlServerManager.serviceClient() .getServerDnsAliases() .acquireAsync(resourceGroupName, serverName, dnsAliasName, new ServerDnsAliasAcquisition().withOldServerDnsAliasId(sqlServerId + DNS_ALIASES + dnsAliasName)) @@ -190,14 +162,9 @@ public Mono acquireAsync( public void acquire(String dnsAliasName, String oldSqlServerId, String newSqlServerId) { Objects.requireNonNull(oldSqlServerId); ResourceId resourceId = ResourceId.fromString(oldSqlServerId); - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getServerDnsAliases() - .acquire( - resourceId.resourceGroupName(), - resourceId.name(), - dnsAliasName, + .acquire(resourceId.resourceGroupName(), resourceId.name(), dnsAliasName, new ServerDnsAliasAcquisition().withOldServerDnsAliasId(newSqlServerId + DNS_ALIASES + dnsAliasName)); } @@ -205,22 +172,17 @@ public void acquire(String dnsAliasName, String oldSqlServerId, String newSqlSer public Mono acquireAsync(String dnsAliasName, String oldSqlServerId, String newSqlServerId) { Objects.requireNonNull(oldSqlServerId); ResourceId resourceId = ResourceId.fromString(oldSqlServerId); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerDnsAliases() - .acquireAsync( - resourceId.resourceGroupName(), - resourceId.name(), - dnsAliasName, + .acquireAsync(resourceId.resourceGroupName(), resourceId.name(), dnsAliasName, new ServerDnsAliasAcquisition().withOldServerDnsAliasId(newSqlServerId + DNS_ALIASES + dnsAliasName)) .then(); } @Override public SqlServerDnsAliasImpl define(String name) { - SqlServerDnsAliasImpl result = - new SqlServerDnsAliasImpl(name, new ServerDnsAliasInner(), this.sqlServerManager); + SqlServerDnsAliasImpl result + = new SqlServerDnsAliasImpl(name, new ServerDnsAliasInner(), this.sqlServerManager); result.setPendingOperation(ExternalChildResourceImpl.PendingOperation.ToBeCreated); return (this.sqlServer != null) ? result.withExistingSqlServer(this.sqlServer) : result; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerImpl.java index a020ed0cf7415..dd6a86864e177 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerImpl.java @@ -72,16 +72,15 @@ protected SqlServerImpl(String name, ServerInner innerObject, SqlServerManager m this.sqlADAdminCreator = null; this.allowAzureServicesAccess = true; this.sqlFirewallRules = new SqlFirewallRulesAsExternalChildResourcesImpl(this, "SqlFirewallRule"); - this.sqlVirtualNetworkRules = - new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(this, "SqlVirtualNetworkRule"); + this.sqlVirtualNetworkRules + = new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(this, "SqlVirtualNetworkRule"); this.sqlElasticPools = new SqlElasticPoolsAsExternalChildResourcesImpl(this, "SqlElasticPool"); this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this, "SqlDatabase"); } @Override protected Mono getInnerAsync() { - return this - .manager() + return this.manager() .serviceClient() .getServers() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); @@ -89,25 +88,21 @@ protected Mono getInnerAsync() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getServers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) - .map( - serverInner -> { - setInner(serverInner); - return this; - }); + .map(serverInner -> { + setInner(serverInner); + return this; + }); } @Override public void beforeGroupCreateOrUpdate() { if (this.isInCreateMode()) { if (allowAzureServicesAccess) { - this - .sqlFirewallRules - .defineInlineFirewallRule("AllowAllWindowsAzureIps") + this.sqlFirewallRules.defineInlineFirewallRule("AllowAllWindowsAzureIps") .withStartIpAddress("0.0.0.0") .withEndIpAddress("0.0.0.0"); } @@ -117,10 +112,10 @@ public void beforeGroupCreateOrUpdate() { } if (this.sqlElasticPools != null && this.sqlDatabases != null) { // Databases must be deleted before the Elastic Pools (only an empty Elastic Pool can be deleted) - List dbToBeRemoved = - this.sqlDatabases.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeRemoved); - List epToBeRemoved = - this.sqlElasticPools.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeRemoved); + List dbToBeRemoved + = this.sqlDatabases.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeRemoved); + List epToBeRemoved + = this.sqlElasticPools.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeRemoved); for (SqlElasticPoolImpl epItem : epToBeRemoved) { for (SqlDatabaseImpl dbItem : dbToBeRemoved) { epItem.addParentDependency(dbItem); @@ -128,10 +123,10 @@ public void beforeGroupCreateOrUpdate() { } // Databases in a new Elastic Pool should be created after the Elastic Pool - List dbToBeCreated = - this.sqlDatabases.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeCreated); - List epToBeCreated = - this.sqlElasticPools.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeCreated); + List dbToBeCreated + = this.sqlDatabases.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeCreated); + List epToBeCreated + = this.sqlElasticPools.getChildren(ExternalChildResourceImpl.PendingOperation.ToBeCreated); for (SqlElasticPoolImpl epItem : epToBeCreated) { for (SqlDatabaseImpl dbItem : dbToBeCreated) { if (dbItem.elasticPoolId() != null @@ -196,8 +191,8 @@ public IdentityType managedServiceIdentityType() { @Override public List listUsageMetrics() { List serverMetrics = new ArrayList<>(); - PagedIterable serverUsageInners = - this.manager().serviceClient().getServerUsages().listByServer(this.resourceGroupName(), this.name()); + PagedIterable serverUsageInners + = this.manager().serviceClient().getServerUsages().listByServer(this.resourceGroupName(), this.name()); for (ServerUsageInner serverUsageInner : serverUsageInners) { serverMetrics.add(new ServerMetricImpl(serverUsageInner)); } @@ -207,17 +202,13 @@ public List listUsageMetrics() { @Override public List listRestorableDroppedDatabases() { List sqlRestorableDroppedDatabases = new ArrayList<>(); - PagedIterable restorableDroppedDatabasesInners = - this - .manager() - .serviceClient() - .getRestorableDroppedDatabases() - .listByServer(this.resourceGroupName(), this.name()); + PagedIterable restorableDroppedDatabasesInners = this.manager() + .serviceClient() + .getRestorableDroppedDatabases() + .listByServer(this.resourceGroupName(), this.name()); for (RestorableDroppedDatabaseInner restorableDroppedDatabaseInner : restorableDroppedDatabasesInners) { - sqlRestorableDroppedDatabases - .add( - new SqlRestorableDroppedDatabaseImpl( - this.resourceGroupName(), this.name(), restorableDroppedDatabaseInner, this.manager())); + sqlRestorableDroppedDatabases.add(new SqlRestorableDroppedDatabaseImpl(this.resourceGroupName(), + this.name(), restorableDroppedDatabaseInner, this.manager())); } return Collections.unmodifiableList(sqlRestorableDroppedDatabases); } @@ -225,14 +216,13 @@ public List listRestorableDroppedDatabases() { @Override public PagedFlux listRestorableDroppedDatabasesAsync() { final SqlServerImpl self = this; - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getRestorableDroppedDatabases() - .listByServerAsync(this.resourceGroupName(), this.name()), - restorableDroppedDatabaseInner -> - new SqlRestorableDroppedDatabaseImpl( - self.resourceGroupName(), self.name(), restorableDroppedDatabaseInner, self.manager())); + return PagedConverter.mapPage( + this.manager() + .serviceClient() + .getRestorableDroppedDatabases() + .listByServerAsync(this.resourceGroupName(), this.name()), + restorableDroppedDatabaseInner -> new SqlRestorableDroppedDatabaseImpl(self.resourceGroupName(), + self.name(), restorableDroppedDatabaseInner, self.manager())); } @Override @@ -244,12 +234,10 @@ public String version() { public SqlFirewallRule enableAccessFromAzureServices() { SqlFirewallRule firewallRule = null; try { - firewallRule = - this - .manager() - .sqlServers() - .firewallRules() - .getBySqlServer(this.resourceGroupName(), this.name(), "AllowAllWindowsAzureIps"); + firewallRule = this.manager() + .sqlServers() + .firewallRules() + .getBySqlServer(this.resourceGroupName(), this.name(), "AllowAllWindowsAzureIps"); } catch (ManagementException e) { if (e.getResponse().getStatusCode() != 404) { throw logger.logExceptionAsError(e); @@ -257,15 +245,13 @@ public SqlFirewallRule enableAccessFromAzureServices() { } if (firewallRule == null) { - firewallRule = - this - .manager() - .sqlServers() - .firewallRules() - .define("AllowAllWindowsAzureIps") - .withExistingSqlServer(this.resourceGroupName(), this.name()) - .withIpAddress("0.0.0.0") - .create(); + firewallRule = this.manager() + .sqlServers() + .firewallRules() + .define("AllowAllWindowsAzureIps") + .withExistingSqlServer(this.resourceGroupName(), this.name()) + .withIpAddress("0.0.0.0") + .create(); } return firewallRule; @@ -280,12 +266,10 @@ public ServerNetworkAccessFlag publicNetworkAccess() { public void removeAccessFromAzureServices() { SqlFirewallRule firewallRule = null; try { - firewallRule = - this - .manager() - .sqlServers() - .firewallRules() - .getBySqlServer(this.resourceGroupName(), this.name(), "AllowAllWindowsAzureIps"); + firewallRule = this.manager() + .sqlServers() + .firewallRules() + .getBySqlServer(this.resourceGroupName(), this.name(), "AllowAllWindowsAzureIps"); } catch (ManagementException e) { if (e.getResponse().getStatusCode() != 404) { throw logger.logExceptionAsError(e); @@ -293,8 +277,7 @@ public void removeAccessFromAzureServices() { } if (firewallRule == null) { - this - .manager() + this.manager() .sqlServers() .firewallRules() .deleteBySqlServer(this.resourceGroupName(), this.name(), "AllowAllWindowsAzureIps"); @@ -303,33 +286,25 @@ public void removeAccessFromAzureServices() { @Override public SqlActiveDirectoryAdministratorImpl setActiveDirectoryAdministrator(String userLogin, String objectId) { - ServerAzureADAdministratorInner serverAzureADAdministratorInner = - new ServerAzureADAdministratorInner() - .withAdministratorType(AdministratorType.ACTIVE_DIRECTORY) + ServerAzureADAdministratorInner serverAzureADAdministratorInner + = new ServerAzureADAdministratorInner().withAdministratorType(AdministratorType.ACTIVE_DIRECTORY) .withLogin(userLogin) .withSid(UUID.fromString(objectId)) .withTenantId(UUID.fromString(this.manager().tenantId())); - return new SqlActiveDirectoryAdministratorImpl( - this - .manager() - .serviceClient() - .getServerAzureADAdministrators() - .createOrUpdate( - this.resourceGroupName(), - this.name(), - AdministratorName.ACTIVE_DIRECTORY, - serverAzureADAdministratorInner)); + return new SqlActiveDirectoryAdministratorImpl(this.manager() + .serviceClient() + .getServerAzureADAdministrators() + .createOrUpdate(this.resourceGroupName(), this.name(), AdministratorName.ACTIVE_DIRECTORY, + serverAzureADAdministratorInner)); } @Override public SqlActiveDirectoryAdministratorImpl getActiveDirectoryAdministrator() { - ServerAzureADAdministratorInner serverAzureADAdministratorInner = - this - .manager() - .serviceClient() - .getServerAzureADAdministrators() - .get(this.resourceGroupName(), this.name(), AdministratorName.ACTIVE_DIRECTORY); + ServerAzureADAdministratorInner serverAzureADAdministratorInner = this.manager() + .serviceClient() + .getServerAzureADAdministrators() + .get(this.resourceGroupName(), this.name(), AdministratorName.ACTIVE_DIRECTORY); return serverAzureADAdministratorInner != null ? new SqlActiveDirectoryAdministratorImpl(serverAzureADAdministratorInner) @@ -338,8 +313,7 @@ public SqlActiveDirectoryAdministratorImpl getActiveDirectoryAdministrator() { @Override public void removeActiveDirectoryAdministrator() { - this - .manager() + this.manager() .serviceClient() .getServerAzureADAdministrators() .deleteAsync(this.resourceGroupName(), this.name(), AdministratorName.ACTIVE_DIRECTORY) @@ -349,8 +323,8 @@ public void removeActiveDirectoryAdministrator() { @Override public SqlServerAutomaticTuning getServerAutomaticTuning() { - ServerAutomaticTuningInner serverAutomaticTuningInner = - this.manager().serviceClient().getServerAutomaticTunings().get(this.resourceGroupName(), this.name()); + ServerAutomaticTuningInner serverAutomaticTuningInner + = this.manager().serviceClient().getServerAutomaticTunings().get(this.resourceGroupName(), this.name()); return serverAutomaticTuningInner != null ? new SqlServerAutomaticTuningImpl(this, serverAutomaticTuningInner) : null; @@ -391,29 +365,23 @@ public SqlServerImpl withoutAccessFromAzureServices() { } @Override - public SqlServer.DefinitionStages.WithCreate withActiveDirectoryAdministrator( - final String userLogin, final String objectId) { + public SqlServer.DefinitionStages.WithCreate withActiveDirectoryAdministrator(final String userLogin, + final String objectId) { final SqlServerImpl self = this; - sqlADAdminCreator = - context -> { - ServerAzureADAdministratorInner serverAzureADAdministratorInner = - new ServerAzureADAdministratorInner() - .withAdministratorType(AdministratorType.ACTIVE_DIRECTORY) - .withLogin(userLogin) - .withSid(UUID.fromString(objectId)) - .withTenantId(UUID.fromString(self.manager().tenantId())); - - return self - .manager() - .serviceClient() - .getServerAzureADAdministrators() - .createOrUpdateAsync( - self.resourceGroupName(), - self.name(), - AdministratorName.ACTIVE_DIRECTORY, - serverAzureADAdministratorInner) - .flatMap(serverAzureADAdministratorInner1 -> context.voidMono()); - }; + sqlADAdminCreator = context -> { + ServerAzureADAdministratorInner serverAzureADAdministratorInner + = new ServerAzureADAdministratorInner().withAdministratorType(AdministratorType.ACTIVE_DIRECTORY) + .withLogin(userLogin) + .withSid(UUID.fromString(objectId)) + .withTenantId(UUID.fromString(self.manager().tenantId())); + + return self.manager() + .serviceClient() + .getServerAzureADAdministrators() + .createOrUpdateAsync(self.resourceGroupName(), self.name(), AdministratorName.ACTIVE_DIRECTORY, + serverAzureADAdministratorInner) + .flatMap(serverAzureADAdministratorInner1 -> context.voidMono()); + }; return this; } @@ -429,8 +397,8 @@ public SqlServerImpl withoutFirewallRule(String firewallRuleName) { } @Override - public SqlVirtualNetworkRule.DefinitionStages.Blank defineVirtualNetworkRule( - String virtualNetworkRuleName) { + public SqlVirtualNetworkRule.DefinitionStages.Blank + defineVirtualNetworkRule(String virtualNetworkRuleName) { return this.sqlVirtualNetworkRules.defineInlineVirtualNetworkRule(virtualNetworkRuleName); } @@ -486,8 +454,8 @@ public SqlEncryptionProtectorOperations.SqlEncryptionProtectorActionsDefinition public SqlServerSecurityAlertPolicyOperations.SqlServerSecurityAlertPolicyActionsDefinition serverSecurityAlertPolicies() { if (this.sqlServerSecurityAlertPolicyOperations == null) { - this.sqlServerSecurityAlertPolicyOperations = - new SqlServerSecurityAlertPolicyOperationsImpl(this, this.manager()); + this.sqlServerSecurityAlertPolicyOperations + = new SqlServerSecurityAlertPolicyOperationsImpl(this, this.manager()); } return this.sqlServerSecurityAlertPolicyOperations; } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyImpl.java index c3d42dcdb18e9..70753f22029dc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyImpl.java @@ -55,11 +55,7 @@ public class SqlServerKeyImpl extends ExternalChildResourceImpl createResourceAsync() { final SqlServerKeyImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerKeys() .createOrUpdateAsync(self.resourceGroupName, self.sqlServerName, self.serverKeyName, self.innerModel()) - .map( - serverKeyInner -> { - self.setInner(serverKeyInner); - return self; - }); + .map(serverKeyInner -> { + self.setInner(serverKeyInner); + return self; + }); } @Override @@ -162,18 +155,14 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerKeys() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerKeys() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @@ -225,9 +214,7 @@ public OffsetDateTime creationDate() { @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getServerKeys() .delete(this.resourceGroupName, this.sqlServerName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyOperationsImpl.java index 45137c5f6d8a0..b04428a75b38f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerKeyOperationsImpl.java @@ -32,37 +32,31 @@ public class SqlServerKeyOperationsImpl extends SqlChildrenOperationsImpl getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { final SqlServerKeyOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerKeys() .getAsync(resourceGroupName, sqlServerName, name) - .map( - serverKeyInner -> - new SqlServerKeyImpl( - resourceGroupName, sqlServerName, name, serverKeyInner, self.sqlServerManager)); + .map(serverKeyInner -> new SqlServerKeyImpl(resourceGroupName, sqlServerName, name, serverKeyInner, + self.sqlServerManager)); } @Override public SqlServerKey getBySqlServer(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - ServerKeyInner serverKeyInner = - sqlServer - .manager() - .serviceClient() - .getServerKeys() - .get(sqlServer.resourceGroupName(), sqlServer.name(), name); + ServerKeyInner serverKeyInner = sqlServer.manager() + .serviceClient() + .getServerKeys() + .get(sqlServer.resourceGroupName(), sqlServer.name(), name); return serverKeyInner != null ? new SqlServerKeyImpl(name, (SqlServerImpl) sqlServer, serverKeyInner, sqlServer.manager()) : null; @@ -71,14 +65,12 @@ public SqlServerKey getBySqlServer(final SqlServer sqlServer, final String name) @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getServerKeys() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) - .map( - serverKeyInner -> - new SqlServerKeyImpl(name, (SqlServerImpl) sqlServer, serverKeyInner, sqlServer.manager())); + .map(serverKeyInner -> new SqlServerKeyImpl(name, (SqlServerImpl) sqlServer, serverKeyInner, + sqlServer.manager())); } @Override @@ -88,9 +80,7 @@ public void deleteBySqlServer(String resourceGroupName, String sqlServerName, St @Override public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlServerName, String name) { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerKeys() .deleteAsync(resourceGroupName, sqlServerName, name); } @@ -98,12 +88,11 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List serverKeys = new ArrayList<>(); - PagedIterable serverKeyInners = - this.sqlServerManager.serviceClient().getServerKeys().listByServer(resourceGroupName, sqlServerName); + PagedIterable serverKeyInners + = this.sqlServerManager.serviceClient().getServerKeys().listByServer(resourceGroupName, sqlServerName); for (ServerKeyInner inner : serverKeyInners) { - serverKeys - .add( - new SqlServerKeyImpl(resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); + serverKeys.add( + new SqlServerKeyImpl(resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); } return Collections.unmodifiableList(serverKeys); } @@ -111,30 +100,20 @@ public List listBySqlServer(String resourceGroupName, String sqlSe @Override public PagedFlux listBySqlServerAsync(final String resourceGroupName, final String sqlServerName) { final SqlServerKeyOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getServerKeys() - .listByServerAsync(resourceGroupName, sqlServerName), - serverKeyInner -> - new SqlServerKeyImpl( - resourceGroupName, - sqlServerName, - serverKeyInner.name(), - serverKeyInner, - self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient().getServerKeys().listByServerAsync(resourceGroupName, sqlServerName), + serverKeyInner -> new SqlServerKeyImpl(resourceGroupName, sqlServerName, serverKeyInner.name(), + serverKeyInner, self.sqlServerManager)); } @Override public List listBySqlServer(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); List serverKeys = new ArrayList<>(); - PagedIterable serverKeyInners = - sqlServer - .manager() - .serviceClient() - .getServerKeys() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); + PagedIterable serverKeyInners = sqlServer.manager() + .serviceClient() + .getServerKeys() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name()); for (ServerKeyInner inner : serverKeyInners) { serverKeys.add(new SqlServerKeyImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); } @@ -144,14 +123,13 @@ public List listBySqlServer(final SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getServerKeys() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - serverKeyInner -> - new SqlServerKeyImpl( - serverKeyInner.name(), (SqlServerImpl) sqlServer, serverKeyInner, sqlServer.manager())); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getServerKeys() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + serverKeyInner -> new SqlServerKeyImpl(serverKeyInner.name(), (SqlServerImpl) sqlServer, serverKeyInner, + sqlServer.manager())); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyImpl.java index 41631a39b085b..84c34b0caf090 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyImpl.java @@ -19,12 +19,10 @@ import reactor.core.publisher.Mono; /** Implementation for SQL Server Security Alert Policy interface. */ -public class SqlServerSecurityAlertPolicyImpl - extends ExternalChildResourceImpl< - SqlServerSecurityAlertPolicy, ServerSecurityAlertPolicyInner, SqlServerImpl, SqlServer> - implements SqlServerSecurityAlertPolicy, - SqlServerSecurityAlertPolicy.Update, - SqlServerSecurityAlertPolicyOperations.SqlServerSecurityAlertPolicyOperationsDefinition { +public class SqlServerSecurityAlertPolicyImpl extends + ExternalChildResourceImpl + implements SqlServerSecurityAlertPolicy, SqlServerSecurityAlertPolicy.Update, + SqlServerSecurityAlertPolicyOperations.SqlServerSecurityAlertPolicyOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; @@ -37,8 +35,8 @@ public class SqlServerSecurityAlertPolicyImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlServerSecurityAlertPolicyImpl( - SqlServerImpl parent, ServerSecurityAlertPolicyInner innerObject, SqlServerManager sqlServerManager) { + SqlServerSecurityAlertPolicyImpl(SqlServerImpl parent, ServerSecurityAlertPolicyInner innerObject, + SqlServerManager sqlServerManager) { super("Default", parent, innerObject); Objects.requireNonNull(parent); @@ -56,11 +54,8 @@ public class SqlServerSecurityAlertPolicyImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ - SqlServerSecurityAlertPolicyImpl( - String resourceGroupName, - String sqlServerName, - ServerSecurityAlertPolicyInner innerObject, - SqlServerManager sqlServerManager) { + SqlServerSecurityAlertPolicyImpl(String resourceGroupName, String sqlServerName, + ServerSecurityAlertPolicyInner innerObject, SqlServerManager sqlServerManager) { super("Default", null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -115,7 +110,9 @@ public String parentId() { @Override public SecurityAlertPolicyState state() { - return this.innerModel().state() == null ? null : SecurityAlertPolicyState.fromString(this.innerModel().state().toString()); + return this.innerModel().state() == null + ? null + : SecurityAlertPolicyState.fromString(this.innerModel().state().toString()); } @Override @@ -183,20 +180,14 @@ public SqlServerSecurityAlertPolicyImpl update() { @Override public Mono createResourceAsync() { final SqlServerSecurityAlertPolicyImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerSecurityAlertPolicies() - .createOrUpdateAsync( - self.resourceGroupName, - self.sqlServerName, - SecurityAlertPolicyNameAutoGenerated.DEFAULT, - self.innerModel()) - .map( - serverSecurityAlertPolicyInner -> { - self.setInner(serverSecurityAlertPolicyInner); - return self; - }); + .createOrUpdateAsync(self.resourceGroupName, self.sqlServerName, + SecurityAlertPolicyNameAutoGenerated.DEFAULT, self.innerModel()) + .map(serverSecurityAlertPolicyInner -> { + self.setInner(serverSecurityAlertPolicyInner); + return self; + }); } @Override @@ -212,9 +203,7 @@ public Mono deleteResourceAsync() { @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerSecurityAlertPolicies() .getAsync(this.resourceGroupName, this.sqlServerName, SecurityAlertPolicyNameAutoGenerated.DEFAULT); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyOperationsImpl.java index 70de600c0e9c7..d311de6952caf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServerSecurityAlertPolicyOperationsImpl.java @@ -14,9 +14,8 @@ import reactor.core.publisher.Mono; /** Implementation for SQL Server Security Alert Policy operations. */ -public class SqlServerSecurityAlertPolicyOperationsImpl - implements SqlServerSecurityAlertPolicyOperations, - SqlServerSecurityAlertPolicyOperations.SqlServerSecurityAlertPolicyActionsDefinition { +public class SqlServerSecurityAlertPolicyOperationsImpl implements SqlServerSecurityAlertPolicyOperations, + SqlServerSecurityAlertPolicyOperations.SqlServerSecurityAlertPolicyActionsDefinition { protected SqlServerManager sqlServerManager; protected SqlServer sqlServer; @@ -35,8 +34,8 @@ public class SqlServerSecurityAlertPolicyOperationsImpl @Override public SqlServerSecurityAlertPolicyImpl define() { - SqlServerSecurityAlertPolicyImpl result = - new SqlServerSecurityAlertPolicyImpl(new ServerSecurityAlertPolicyInner(), this.sqlServerManager); + SqlServerSecurityAlertPolicyImpl result + = new SqlServerSecurityAlertPolicyImpl(new ServerSecurityAlertPolicyInner(), this.sqlServerManager); result.setPendingOperation(ExternalChildResourceImpl.PendingOperation.ToBeCreated); return (this.sqlServer != null) ? result.withExistingSqlServer(this.sqlServer) : result; } @@ -59,77 +58,61 @@ public Mono getAsync() { @Override public SqlServerSecurityAlertPolicy getBySqlServer(String resourceGroupName, String sqlServerName) { - ServerSecurityAlertPolicyInner serverSecurityAlertPolicyInner = - this - .sqlServerManager - .serviceClient() - .getServerSecurityAlertPolicies() - .get(resourceGroupName, sqlServerName, SecurityAlertPolicyNameAutoGenerated.DEFAULT); + ServerSecurityAlertPolicyInner serverSecurityAlertPolicyInner = this.sqlServerManager.serviceClient() + .getServerSecurityAlertPolicies() + .get(resourceGroupName, sqlServerName, SecurityAlertPolicyNameAutoGenerated.DEFAULT); return serverSecurityAlertPolicyInner != null - ? new SqlServerSecurityAlertPolicyImpl( - resourceGroupName, sqlServerName, serverSecurityAlertPolicyInner, this.sqlServerManager) + ? new SqlServerSecurityAlertPolicyImpl(resourceGroupName, sqlServerName, serverSecurityAlertPolicyInner, + this.sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { + public Mono getBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { final SqlServerSecurityAlertPolicyOperationsImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getServerSecurityAlertPolicies() .getAsync(resourceGroupName, sqlServerName, SecurityAlertPolicyNameAutoGenerated.DEFAULT) - .map( - serverSecurityAlertPolicyInner -> - new SqlServerSecurityAlertPolicyImpl( - resourceGroupName, sqlServerName, serverSecurityAlertPolicyInner, self.sqlServerManager)); + .map(serverSecurityAlertPolicyInner -> new SqlServerSecurityAlertPolicyImpl(resourceGroupName, + sqlServerName, serverSecurityAlertPolicyInner, self.sqlServerManager)); } @Override public SqlServerSecurityAlertPolicy getBySqlServer(SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - ServerSecurityAlertPolicyInner serverSecurityAlertPolicyInner = - sqlServer - .manager() - .serviceClient() - .getServerSecurityAlertPolicies() - .get(sqlServer.resourceGroupName(), sqlServer.name(), SecurityAlertPolicyNameAutoGenerated.DEFAULT); + ServerSecurityAlertPolicyInner serverSecurityAlertPolicyInner = sqlServer.manager() + .serviceClient() + .getServerSecurityAlertPolicies() + .get(sqlServer.resourceGroupName(), sqlServer.name(), SecurityAlertPolicyNameAutoGenerated.DEFAULT); return serverSecurityAlertPolicyInner != null - ? new SqlServerSecurityAlertPolicyImpl( - (SqlServerImpl) sqlServer, serverSecurityAlertPolicyInner, sqlServer.manager()) + ? new SqlServerSecurityAlertPolicyImpl((SqlServerImpl) sqlServer, serverSecurityAlertPolicyInner, + sqlServer.manager()) : null; } @Override public Mono getBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getServerSecurityAlertPolicies() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), SecurityAlertPolicyNameAutoGenerated.DEFAULT) - .map( - serverSecurityAlertPolicyInner -> - new SqlServerSecurityAlertPolicyImpl( - (SqlServerImpl) sqlServer, serverSecurityAlertPolicyInner, sqlServer.manager())); + .map(serverSecurityAlertPolicyInner -> new SqlServerSecurityAlertPolicyImpl((SqlServerImpl) sqlServer, + serverSecurityAlertPolicyInner, sqlServer.manager())); } @Override public SqlServerSecurityAlertPolicy getById(String id) { Objects.requireNonNull(id); - return this - .getBySqlServer( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); + return this.getBySqlServer(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); } @Override public Mono getByIdAsync(String id) { Objects.requireNonNull(id); - return this - .getBySqlServerAsync( - ResourceUtils.groupFromResourceId(id), - ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); + return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id), + ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id))); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServersImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServersImpl.java index 602374df20aa9..c1d8c4d0f8543 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlServersImpl.java @@ -177,27 +177,27 @@ public SqlDatabaseOperations databases() { @Override public CheckNameAvailabilityResult checkNameAvailability(String name) { - return new CheckNameAvailabilityResultImpl(this.inner().checkNameAvailability( - new CheckNameAvailabilityRequest().withName(name))); + return new CheckNameAvailabilityResultImpl( + this.inner().checkNameAvailability(new CheckNameAvailabilityRequest().withName(name))); } @Override public Mono checkNameAvailabilityAsync(String name) { - return this.inner().checkNameAvailabilityAsync(new CheckNameAvailabilityRequest().withName(name)) + return this.inner() + .checkNameAvailabilityAsync(new CheckNameAvailabilityRequest().withName(name)) .map(CheckNameAvailabilityResultImpl::new); } @Override public RegionCapabilities getCapabilitiesByRegion(Region region) { - LocationCapabilitiesInner capabilitiesInner = - this.manager().serviceClient().getCapabilities().listByLocation(region.name()); + LocationCapabilitiesInner capabilitiesInner + = this.manager().serviceClient().getCapabilities().listByLocation(region.name()); return capabilitiesInner != null ? new RegionCapabilitiesImpl(capabilitiesInner) : null; } @Override public Mono getCapabilitiesByRegionAsync(Region region) { - return this - .manager() + return this.manager() .serviceClient() .getCapabilities() .listByLocationAsync(region.name()) @@ -208,8 +208,8 @@ public Mono getCapabilitiesByRegionAsync(Region region) { public List listUsageByRegion(Region region) { Objects.requireNonNull(region); List subscriptionUsages = new ArrayList<>(); - PagedIterable subscriptionUsageInners = - this.manager().serviceClient().getSubscriptionUsages().listByLocation(region.name()); + PagedIterable subscriptionUsageInners + = this.manager().serviceClient().getSubscriptionUsages().listByLocation(region.name()); for (SubscriptionUsageInner inner : subscriptionUsageInners) { subscriptionUsages.add(new SqlSubscriptionUsageMetricImpl(region.name(), inner, this.manager())); } @@ -220,12 +220,9 @@ public List listUsageByRegion(Region region) { public PagedFlux listUsageByRegionAsync(final Region region) { Objects.requireNonNull(region); final SqlServers self = this; - return PagedConverter.mapPage(this - .manager() - .serviceClient() - .getSubscriptionUsages() - .listByLocationAsync(region.name()), - subscriptionUsageInner -> - new SqlSubscriptionUsageMetricImpl(region.name(), subscriptionUsageInner, self.manager())); + return PagedConverter.mapPage( + this.manager().serviceClient().getSubscriptionUsages().listByLocationAsync(region.name()), + subscriptionUsageInner -> new SqlSubscriptionUsageMetricImpl(region.name(), subscriptionUsageInner, + self.manager())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSubscriptionUsageMetricImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSubscriptionUsageMetricImpl.java index 5caffbed927e9..fa6f8343e39d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSubscriptionUsageMetricImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSubscriptionUsageMetricImpl.java @@ -10,15 +10,14 @@ import reactor.core.publisher.Mono; /** Implementation for Azure SQL subscription usage. */ -public class SqlSubscriptionUsageMetricImpl - extends RefreshableWrapperImpl - implements SqlSubscriptionUsageMetric { +public class SqlSubscriptionUsageMetricImpl extends + RefreshableWrapperImpl implements SqlSubscriptionUsageMetric { private final SqlServerManager sqlServerManager; private final String location; - protected SqlSubscriptionUsageMetricImpl( - String location, SubscriptionUsageInner innerObject, SqlServerManager sqlServerManager) { + protected SqlSubscriptionUsageMetricImpl(String location, SubscriptionUsageInner innerObject, + SqlServerManager sqlServerManager) { super(innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncFullSchemaPropertyImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncFullSchemaPropertyImpl.java index 5501fcf5d082d..e2899bab98018 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncFullSchemaPropertyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncFullSchemaPropertyImpl.java @@ -21,9 +21,8 @@ protected SqlSyncFullSchemaPropertyImpl(SyncFullSchemaPropertiesInner innerObjec @Override public List tables() { - return Collections - .unmodifiableList( - this.innerModel().tables() != null ? this.innerModel().tables() : new ArrayList()); + return Collections.unmodifiableList( + this.innerModel().tables() != null ? this.innerModel().tables() : new ArrayList()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupImpl.java index e6ce4704ed11d..14e02dddbc9c7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupImpl.java @@ -44,8 +44,8 @@ public class SqlSyncGroupImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlSyncGroupImpl( - String name, SqlDatabaseImpl parent, SyncGroupInner innerObject, SqlServerManager sqlServerManager) { + SqlSyncGroupImpl(String name, SqlDatabaseImpl parent, SyncGroupInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -66,13 +66,8 @@ public class SqlSyncGroupImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlSyncGroupImpl( - String resourceGroupName, - String sqlServerName, - String sqlDatabaseName, - String name, - SyncGroupInner innerObject, - SqlServerManager sqlServerManager) { + SqlSyncGroupImpl(String resourceGroupName, String sqlServerName, String sqlDatabaseName, String name, + SyncGroupInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -165,108 +160,79 @@ public SyncGroupSchema schema() { @Override public void refreshHubSchema() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() .refreshHubSchema(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public Mono refreshHubSchemaAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() .refreshHubSchemaAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public PagedIterable listHubSchemas() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listHubSchemas(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncGroups() + .listHubSchemas(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()), inner -> new SqlSyncFullSchemaPropertyImpl(inner)); } @Override public PagedFlux listHubSchemasAsync() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listHubSchemasAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncGroups() + .listHubSchemasAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()), syncFullSchemaPropertiesInner -> new SqlSyncFullSchemaPropertyImpl(syncFullSchemaPropertiesInner)); } @Override public PagedIterable listLogs(String startTime, String endTime, String type) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() + return PagedConverter.mapPage(this.sqlServerManager.serviceClient() .getSyncGroups() - .listLogs( - this.resourceGroupName, - this.sqlServerName, - this.sqlDatabaseName, - this.name(), - startTime, - endTime, + .listLogs(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name(), startTime, endTime, SyncGroupsType.fromString(type)), inner -> new SqlSyncGroupLogPropertyImpl(inner)); } @Override public PagedFlux listLogsAsync(String startTime, String endTime, String type) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listLogsAsync( - this.resourceGroupName, - this.sqlServerName, - this.sqlDatabaseName, - this.name(), - startTime, - endTime, - SyncGroupsType.fromString(type)), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncGroups() + .listLogsAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name(), startTime, + endTime, SyncGroupsType.fromString(type)), syncGroupLogPropertiesInner -> new SqlSyncGroupLogPropertyImpl(syncGroupLogPropertiesInner)); } @Override public void triggerSynchronization() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() .triggerSync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public Mono triggerSynchronizationAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() .triggerSyncAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public void cancelSynchronization() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() .cancelSync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public Mono cancelSynchronizationAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() .cancelSyncAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @@ -343,17 +309,14 @@ public Update update() { @Override public Mono createResourceAsync() { final SqlSyncGroupImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() - .createOrUpdateAsync( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name(), this.innerModel()) - .map( - syncGroupInner -> { - self.setInner(syncGroupInner); - return self; - }); + .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name(), + this.innerModel()) + .map(syncGroupInner -> { + self.setInner(syncGroupInner); + return self; + }); } @Override @@ -363,27 +326,21 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() .getAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() .delete(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupOperationsImpl.java index a5b8beb5eb5ad..6d608302b47c3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncGroupOperationsImpl.java @@ -40,51 +40,38 @@ public class SqlSyncGroupOperationsImpl } @Override - public SqlSyncGroup getBySqlServer( - String resourceGroupName, String sqlServerName, String databaseName, String name) { - SyncGroupInner syncGroupInner = - this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .get(resourceGroupName, sqlServerName, databaseName, name); + public SqlSyncGroup getBySqlServer(String resourceGroupName, String sqlServerName, String databaseName, + String name) { + SyncGroupInner syncGroupInner = this.sqlServerManager.serviceClient() + .getSyncGroups() + .get(resourceGroupName, sqlServerName, databaseName, name); return syncGroupInner != null - ? new SqlSyncGroupImpl( - resourceGroupName, sqlServerName, databaseName, name, syncGroupInner, this.sqlServerManager) + ? new SqlSyncGroupImpl(resourceGroupName, sqlServerName, databaseName, name, syncGroupInner, + this.sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String databaseName, final String name) { - return this - .sqlServerManager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String databaseName, final String name) { + return this.sqlServerManager.serviceClient() .getSyncGroups() .getAsync(resourceGroupName, sqlServerName, databaseName, name) - .map( - syncGroupInner -> - new SqlSyncGroupImpl( - resourceGroupName, sqlServerName, databaseName, name, syncGroupInner, sqlServerManager)); + .map(syncGroupInner -> new SqlSyncGroupImpl(resourceGroupName, sqlServerName, databaseName, name, + syncGroupInner, sqlServerManager)); } @Override public PagedIterable listSyncDatabaseIds(String locationName) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listSyncDatabaseIds(locationName), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient().getSyncGroups().listSyncDatabaseIds(locationName), SyncDatabaseIdPropertiesInner::id); } @Override public PagedFlux listSyncDatabaseIdsAsync(String locationName) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listSyncDatabaseIdsAsync(locationName), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient().getSyncGroups().listSyncDatabaseIdsAsync(locationName), SyncDatabaseIdPropertiesInner::id); } @@ -110,9 +97,8 @@ public SqlSyncGroup get(String name) { if (this.sqlDatabase == null) { return null; } - return this - .getBySqlServer( - this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name(), name); + return this.getBySqlServer(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), + this.sqlDatabase.name(), name); } @Override @@ -120,9 +106,8 @@ public Mono getAsync(String name) { if (this.sqlDatabase == null) { return null; } - return this - .getBySqlServerAsync( - this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name(), name); + return this.getBySqlServerAsync(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), + this.sqlDatabase.name(), name); } @Override @@ -130,12 +115,8 @@ public SqlSyncGroup getById(String id) { Objects.requireNonNull(id); try { ResourceId resourceId = ResourceId.fromString(id); - return this - .getBySqlServer( - resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return this.getBySqlServer(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -146,12 +127,8 @@ public Mono getByIdAsync(String id) { Objects.requireNonNull(id); try { ResourceId resourceId = ResourceId.fromString(id); - return this - .getBySqlServerAsync( - resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return this.getBySqlServerAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -162,12 +139,10 @@ public void delete(String name) { if (this.sqlDatabase == null) { return; } - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() - .delete( - this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name(), name); + .delete(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name(), + name); } @Override @@ -175,12 +150,10 @@ public Mono deleteAsync(String name) { if (this.sqlDatabase == null) { return null; } - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() - .deleteAsync( - this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name(), name); + .deleteAsync(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), + this.sqlDatabase.name(), name); } @Override @@ -188,14 +161,9 @@ public void deleteById(String id) { Objects.requireNonNull(id); try { ResourceId resourceId = ResourceId.fromString(id); - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncGroups() - .delete( - resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), + .delete(resourceId.resourceGroupName(), resourceId.parent().parent().name(), resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } @@ -205,15 +173,10 @@ public void deleteById(String id) { public Mono deleteByIdAsync(String id) { try { ResourceId resourceId = ResourceId.fromString(id); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncGroups() - .deleteAsync( - resourceId.resourceGroupName(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + .deleteAsync(resourceId.resourceGroupName(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -223,15 +186,10 @@ public Mono deleteByIdAsync(String id) { public List list() { List sqlSyncGroups = new ArrayList<>(); if (this.sqlDatabase != null) { - PagedIterable syncGroupInners = - this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listByDatabase( - this.sqlDatabase.resourceGroupName(), - this.sqlDatabase.sqlServerName(), - this.sqlDatabase.name()); + PagedIterable syncGroupInners = this.sqlServerManager.serviceClient() + .getSyncGroups() + .listByDatabase(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), + this.sqlDatabase.name()); for (SyncGroupInner groupInner : syncGroupInners) { sqlSyncGroups .add(new SqlSyncGroupImpl(groupInner.name(), this.sqlDatabase, groupInner, this.sqlServerManager)); @@ -243,14 +201,12 @@ public List list() { @Override public PagedFlux listAsync() { final SqlSyncGroupOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncGroups() - .listByDatabaseAsync( - this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), this.sqlDatabase.name()), - syncGroupInner -> - new SqlSyncGroupImpl( - syncGroupInner.name(), self.sqlDatabase, syncGroupInner, self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncGroups() + .listByDatabaseAsync(this.sqlDatabase.resourceGroupName(), this.sqlDatabase.sqlServerName(), + this.sqlDatabase.name()), + syncGroupInner -> new SqlSyncGroupImpl(syncGroupInner.name(), self.sqlDatabase, syncGroupInner, + self.sqlServerManager)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberImpl.java index ecf7eda869ad5..1b8cdc2a680ec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberImpl.java @@ -40,8 +40,8 @@ public class SqlSyncMemberImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlSyncMemberImpl( - String name, SqlSyncGroupImpl parent, SyncMemberInner innerObject, SqlServerManager sqlServerManager) { + SqlSyncMemberImpl(String name, SqlSyncGroupImpl parent, SyncMemberInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -64,14 +64,8 @@ public class SqlSyncMemberImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses DNS alias operations */ - SqlSyncMemberImpl( - String resourceGroupName, - String sqlServerName, - String sqlDatabaseName, - String sqlSyncGroupName, - String name, - SyncMemberInner innerObject, - SqlServerManager sqlServerManager) { + SqlSyncMemberImpl(String resourceGroupName, String sqlServerName, String sqlDatabaseName, String sqlSyncGroupName, + String name, SyncMemberInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -177,22 +171,14 @@ public SyncMemberState syncState() { @Override public Mono createResourceAsync() { final SqlSyncMemberImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .createOrUpdateAsync( - this.resourceGroupName, - this.sqlServerName, - this.sqlDatabaseName, - this.sqlSyncGroupName, - this.name(), - this.innerModel()) - .map( - syncMemberInner -> { - self.setInner(syncMemberInner); - return self; - }); + .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, + this.sqlSyncGroupName, this.name(), this.innerModel()) + .map(syncMemberInner -> { + self.setInner(syncMemberInner); + return self; + }); } @Override @@ -202,32 +188,26 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .deleteAsync( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()); + .deleteAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, + this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .getAsync( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()); + .getAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, + this.name()); } @Override public void delete() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncMembers() - .delete( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()); + .delete(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, + this.name()); } @Override @@ -243,44 +223,37 @@ public Update update() { @Override public PagedIterable listMemberSchemas() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() + return PagedConverter.mapPage(this.sqlServerManager.serviceClient() .getSyncMembers() - .listMemberSchemas( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()), + .listMemberSchemas(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, + this.name()), inner -> new SqlSyncFullSchemaPropertyImpl(inner)); } @Override public PagedFlux listMemberSchemasAsync() { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncMembers() - .listMemberSchemasAsync( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()), + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncMembers() + .listMemberSchemasAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, + this.sqlSyncGroupName, this.name()), syncFullSchemaPropertiesInner -> new SqlSyncFullSchemaPropertyImpl(syncFullSchemaPropertiesInner)); } @Override public void refreshMemberSchema() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncMembers() - .refreshMemberSchema( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()); + .refreshMemberSchema(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, + this.sqlSyncGroupName, this.name()); } @Override public Mono refreshMemberSchemaAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .refreshMemberSchemaAsync( - this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.name()); + .refreshMemberSchemaAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, + this.sqlSyncGroupName, this.name()); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberOperationsImpl.java index 62f1f51d2863f..2c1e55e43d267 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlSyncMemberOperationsImpl.java @@ -37,48 +37,25 @@ public class SqlSyncMemberOperationsImpl } @Override - public SqlSyncMember getBySqlServer( - String resourceGroupName, String sqlServerName, String databaseName, String syncGroupName, String name) { - SyncMemberInner syncMemberInner = - this - .sqlServerManager - .serviceClient() - .getSyncMembers() - .get(resourceGroupName, sqlServerName, databaseName, syncGroupName, name); + public SqlSyncMember getBySqlServer(String resourceGroupName, String sqlServerName, String databaseName, + String syncGroupName, String name) { + SyncMemberInner syncMemberInner = this.sqlServerManager.serviceClient() + .getSyncMembers() + .get(resourceGroupName, sqlServerName, databaseName, syncGroupName, name); return syncMemberInner != null - ? new SqlSyncMemberImpl( - resourceGroupName, - sqlServerName, - databaseName, - syncGroupName, - name, - syncMemberInner, - this.sqlServerManager) + ? new SqlSyncMemberImpl(resourceGroupName, sqlServerName, databaseName, syncGroupName, name, + syncMemberInner, this.sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, - final String sqlServerName, - final String databaseName, - final String syncGroupName, - final String name) { - return this - .sqlServerManager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String databaseName, final String syncGroupName, final String name) { + return this.sqlServerManager.serviceClient() .getSyncMembers() .getAsync(resourceGroupName, sqlServerName, databaseName, syncGroupName, name) - .map( - syncMemberInner -> - new SqlSyncMemberImpl( - resourceGroupName, - sqlServerName, - databaseName, - syncGroupName, - name, - syncMemberInner, - sqlServerManager)); + .map(syncMemberInner -> new SqlSyncMemberImpl(resourceGroupName, sqlServerName, databaseName, syncGroupName, + name, syncMemberInner, sqlServerManager)); } @Override @@ -86,13 +63,8 @@ public SqlSyncMember get(String name) { if (this.sqlSyncGroup == null) { return null; } - return this - .getBySqlServer( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name(), - name); + return this.getBySqlServer(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name(), name); } @Override @@ -100,13 +72,8 @@ public Mono getAsync(String name) { if (this.sqlSyncGroup == null) { return null; } - return this - .getBySqlServerAsync( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name(), - name); + return this.getBySqlServerAsync(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name(), name); } @Override @@ -114,13 +81,8 @@ public SqlSyncMember getById(String id) { Objects.requireNonNull(id); try { ResourceId resourceId = ResourceId.fromString(id); - return this - .getBySqlServer( - resourceId.resourceGroupName(), - resourceId.parent().parent().parent().name(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return this.getBySqlServer(resourceId.resourceGroupName(), resourceId.parent().parent().parent().name(), + resourceId.parent().parent().name(), resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -131,13 +93,9 @@ public Mono getByIdAsync(String id) { Objects.requireNonNull(id); try { ResourceId resourceId = ResourceId.fromString(id); - return this - .getBySqlServerAsync( - resourceId.resourceGroupName(), - resourceId.parent().parent().parent().name(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + return this.getBySqlServerAsync(resourceId.resourceGroupName(), + resourceId.parent().parent().parent().name(), resourceId.parent().parent().name(), + resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -148,16 +106,10 @@ public void delete(String name) { if (this.sqlSyncGroup == null) { return; } - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncMembers() - .delete( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name(), - name); + .delete(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name(), name); } @Override @@ -165,32 +117,20 @@ public Mono deleteAsync(String name) { if (this.sqlSyncGroup == null) { return null; } - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .deleteAsync( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name(), - name); + .deleteAsync(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name(), name); } @Override public void deleteById(String id) { try { ResourceId resourceId = ResourceId.fromString(id); - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getSyncMembers() - .delete( - resourceId.resourceGroupName(), - resourceId.parent().parent().parent().name(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + .delete(resourceId.resourceGroupName(), resourceId.parent().parent().parent().name(), + resourceId.parent().parent().name(), resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } } @@ -199,16 +139,10 @@ public void deleteById(String id) { public Mono deleteByIdAsync(String id) { try { ResourceId resourceId = ResourceId.fromString(id); - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getSyncMembers() - .deleteAsync( - resourceId.resourceGroupName(), - resourceId.parent().parent().parent().name(), - resourceId.parent().parent().name(), - resourceId.parent().name(), - resourceId.name()); + .deleteAsync(resourceId.resourceGroupName(), resourceId.parent().parent().parent().name(), + resourceId.parent().parent().name(), resourceId.parent().name(), resourceId.name()); } catch (NullPointerException e) { } return null; @@ -218,21 +152,13 @@ public Mono deleteByIdAsync(String id) { public List list() { List sqlSyncMembers = new ArrayList<>(); if (this.sqlSyncGroup != null) { - PagedIterable syncMemberInners = - this - .sqlServerManager - .serviceClient() - .getSyncMembers() - .listBySyncGroup( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name()); + PagedIterable syncMemberInners = this.sqlServerManager.serviceClient() + .getSyncMembers() + .listBySyncGroup(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name()); for (SyncMemberInner syncMemberInner : syncMemberInners) { - sqlSyncMembers - .add( - new SqlSyncMemberImpl( - syncMemberInner.name(), this.sqlSyncGroup, syncMemberInner, this.sqlServerManager)); + sqlSyncMembers.add(new SqlSyncMemberImpl(syncMemberInner.name(), this.sqlSyncGroup, syncMemberInner, + this.sqlServerManager)); } } return Collections.unmodifiableList(sqlSyncMembers); @@ -241,18 +167,13 @@ public List list() { @Override public PagedFlux listAsync() { final SqlSyncMemberOperationsImpl self = this; - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getSyncMembers() - .listBySyncGroupAsync( - this.sqlSyncGroup.resourceGroupName(), - this.sqlSyncGroup.sqlServerName(), - this.sqlSyncGroup.sqlDatabaseName(), - this.sqlSyncGroup.name()), - syncMemberInner -> - new SqlSyncMemberImpl( - syncMemberInner.name(), self.sqlSyncGroup, syncMemberInner, self.sqlServerManager)); + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getSyncMembers() + .listBySyncGroupAsync(this.sqlSyncGroup.resourceGroupName(), this.sqlSyncGroup.sqlServerName(), + this.sqlSyncGroup.sqlDatabaseName(), this.sqlSyncGroup.name()), + syncMemberInner -> new SqlSyncMemberImpl(syncMemberInner.name(), self.sqlSyncGroup, syncMemberInner, + self.sqlServerManager)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleImpl.java index 398a9a7ffcae5..1e2d0060f88a8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleImpl.java @@ -14,12 +14,10 @@ import reactor.core.publisher.Mono; /** Implementation for SQL Virtual Network Rule interface. */ -public class SqlVirtualNetworkRuleImpl - extends ExternalChildResourceImpl - implements SqlVirtualNetworkRule, - SqlVirtualNetworkRule.SqlVirtualNetworkRuleDefinition, - SqlVirtualNetworkRule.Update, - SqlVirtualNetworkRuleOperations.SqlVirtualNetworkRuleOperationsDefinition { +public class SqlVirtualNetworkRuleImpl extends + ExternalChildResourceImpl implements + SqlVirtualNetworkRule, SqlVirtualNetworkRule.SqlVirtualNetworkRuleDefinition, + SqlVirtualNetworkRule.Update, SqlVirtualNetworkRuleOperations.SqlVirtualNetworkRuleOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; @@ -33,8 +31,8 @@ public class SqlVirtualNetworkRuleImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses virtual network rule operations */ - SqlVirtualNetworkRuleImpl( - String name, SqlServerImpl parent, VirtualNetworkRuleInner innerObject, SqlServerManager sqlServerManager) { + SqlVirtualNetworkRuleImpl(String name, SqlServerImpl parent, VirtualNetworkRuleInner innerObject, + SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); @@ -53,12 +51,8 @@ public class SqlVirtualNetworkRuleImpl * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses virtual network rule operations */ - SqlVirtualNetworkRuleImpl( - String resourceGroupName, - String sqlServerName, - String name, - VirtualNetworkRuleInner innerObject, - SqlServerManager sqlServerManager) { + SqlVirtualNetworkRuleImpl(String resourceGroupName, String sqlServerName, String name, + VirtualNetworkRuleInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; @@ -82,16 +76,13 @@ public class SqlVirtualNetworkRuleImpl @Override public Mono createResourceAsync() { final SqlVirtualNetworkRuleImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getVirtualNetworkRules() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.innerModel()) - .map( - inner -> { - self.setInner(inner); - return self; - }); + .map(inner -> { + self.setInner(inner); + return self; + }); } @Override @@ -101,18 +92,14 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getVirtualNetworkRules() .deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getVirtualNetworkRules() .getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleOperationsImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleOperationsImpl.java index ec413101fcbf1..79f5e4d0cb30f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleOperationsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRuleOperationsImpl.java @@ -24,37 +24,34 @@ public class SqlVirtualNetworkRuleOperationsImpl extends SqlChildrenOperationsIm SqlVirtualNetworkRuleOperationsImpl(SqlServer parent, SqlServerManager sqlServerManager) { super(parent, sqlServerManager); Objects.requireNonNull(parent); - this.sqlVirtualNetworkRules = - new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(sqlServerManager, "SqlVirtualNetworkRule"); + this.sqlVirtualNetworkRules + = new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(sqlServerManager, "SqlVirtualNetworkRule"); } SqlVirtualNetworkRuleOperationsImpl(SqlServerManager sqlServerManager) { super(null, sqlServerManager); - this.sqlVirtualNetworkRules = - new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(sqlServerManager, "SqlVirtualNetworkRule"); + this.sqlVirtualNetworkRules + = new SqlVirtualNetworkRulesAsExternalChildResourcesImpl(sqlServerManager, "SqlVirtualNetworkRule"); } @Override public SqlVirtualNetworkRule getBySqlServer(String resourceGroupName, String sqlServerName, String name) { - VirtualNetworkRuleInner inner = - this.sqlServerManager.serviceClient().getVirtualNetworkRules().get(resourceGroupName, sqlServerName, name); + VirtualNetworkRuleInner inner = this.sqlServerManager.serviceClient() + .getVirtualNetworkRules() + .get(resourceGroupName, sqlServerName, name); return (inner != null) ? new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager) : null; } @Override - public Mono getBySqlServerAsync( - final String resourceGroupName, final String sqlServerName, final String name) { - return this - .sqlServerManager - .serviceClient() + public Mono getBySqlServerAsync(final String resourceGroupName, final String sqlServerName, + final String name) { + return this.sqlServerManager.serviceClient() .getVirtualNetworkRules() .getAsync(resourceGroupName, sqlServerName, name) - .map( - inner -> - new SqlVirtualNetworkRuleImpl( - resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager)); + .map(inner -> new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, + sqlServerManager)); } @Override @@ -62,12 +59,9 @@ public SqlVirtualNetworkRule getBySqlServer(SqlServer sqlServer, String name) { if (sqlServer == null) { return null; } - VirtualNetworkRuleInner inner = - this - .sqlServerManager - .serviceClient() - .getVirtualNetworkRules() - .get(sqlServer.resourceGroupName(), sqlServer.name(), name); + VirtualNetworkRuleInner inner = this.sqlServerManager.serviceClient() + .getVirtualNetworkRules() + .get(sqlServer.resourceGroupName(), sqlServer.name(), name); return (inner != null) ? new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServerManager) : null; @@ -76,14 +70,12 @@ public SqlVirtualNetworkRule getBySqlServer(SqlServer sqlServer, String name) { @Override public Mono getBySqlServerAsync(final SqlServer sqlServer, final String name) { Objects.requireNonNull(sqlServer); - return sqlServer - .manager() + return sqlServer.manager() .serviceClient() .getVirtualNetworkRules() .getAsync(sqlServer.resourceGroupName(), sqlServer.name(), name) - .map( - inner -> - new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServer.manager())); + .map(inner -> new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, + sqlServer.manager())); } @Override @@ -93,9 +85,7 @@ public void deleteBySqlServer(String resourceGroupName, String sqlServerName, St @Override public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlServerName, String name) { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getVirtualNetworkRules() .deleteAsync(resourceGroupName, sqlServerName, name); } @@ -103,47 +93,35 @@ public Mono deleteBySqlServerAsync(String resourceGroupName, String sqlSer @Override public List listBySqlServer(String resourceGroupName, String sqlServerName) { List virtualNetworkRuleSet = new ArrayList<>(); - for (VirtualNetworkRuleInner inner - : this - .sqlServerManager - .serviceClient() - .getVirtualNetworkRules() - .listByServer(resourceGroupName, sqlServerName)) { - virtualNetworkRuleSet - .add( - new SqlVirtualNetworkRuleImpl( - resourceGroupName, sqlServerName, inner.name(), inner, this.sqlServerManager)); + for (VirtualNetworkRuleInner inner : this.sqlServerManager.serviceClient() + .getVirtualNetworkRules() + .listByServer(resourceGroupName, sqlServerName)) { + virtualNetworkRuleSet.add(new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, inner.name(), + inner, this.sqlServerManager)); } return Collections.unmodifiableList(virtualNetworkRuleSet); } @Override - public PagedFlux listBySqlServerAsync( - final String resourceGroupName, final String sqlServerName) { - return PagedConverter.mapPage(this - .sqlServerManager - .serviceClient() - .getVirtualNetworkRules() - .listByServerAsync(resourceGroupName, sqlServerName), - inner -> - new SqlVirtualNetworkRuleImpl( - resourceGroupName, sqlServerName, inner.name(), inner, sqlServerManager)); + public PagedFlux listBySqlServerAsync(final String resourceGroupName, + final String sqlServerName) { + return PagedConverter.mapPage( + this.sqlServerManager.serviceClient() + .getVirtualNetworkRules() + .listByServerAsync(resourceGroupName, sqlServerName), + inner -> new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, inner.name(), inner, + sqlServerManager)); } @Override public List listBySqlServer(SqlServer sqlServer) { List virtualNetworkRuleSet = new ArrayList<>(); if (sqlServer != null) { - for (VirtualNetworkRuleInner inner - : this - .sqlServerManager - .serviceClient() - .getVirtualNetworkRules() - .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { - virtualNetworkRuleSet - .add( - new SqlVirtualNetworkRuleImpl( - inner.name(), (SqlServerImpl) sqlServer, inner, this.sqlServerManager)); + for (VirtualNetworkRuleInner inner : this.sqlServerManager.serviceClient() + .getVirtualNetworkRules() + .listByServer(sqlServer.resourceGroupName(), sqlServer.name())) { + virtualNetworkRuleSet.add(new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, + this.sqlServerManager)); } } return Collections.unmodifiableList(virtualNetworkRuleSet); @@ -152,13 +130,12 @@ public List listBySqlServer(SqlServer sqlServer) { @Override public PagedFlux listBySqlServerAsync(final SqlServer sqlServer) { Objects.requireNonNull(sqlServer); - return PagedConverter.mapPage(sqlServer - .manager() - .serviceClient() - .getVirtualNetworkRules() - .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), - inner -> - new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServerManager)); + return PagedConverter.mapPage( + sqlServer.manager() + .serviceClient() + .getVirtualNetworkRules() + .listByServerAsync(sqlServer.resourceGroupName(), sqlServer.name()), + inner -> new SqlVirtualNetworkRuleImpl(inner.name(), (SqlServerImpl) sqlServer, inner, sqlServerManager)); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRulesAsExternalChildResourcesImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRulesAsExternalChildResourcesImpl.java index 8ef885d7e6cae..dc5cde3c03bbb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRulesAsExternalChildResourcesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlVirtualNetworkRulesAsExternalChildResourcesImpl.java @@ -9,9 +9,8 @@ import com.azure.resourcemanager.sql.fluent.models.VirtualNetworkRuleInner; /** Represents a SQL Virtual Network Rules collection associated with an Azure SQL server. */ -public class SqlVirtualNetworkRulesAsExternalChildResourcesImpl - extends ExternalChildResourcesNonCachedImpl< - SqlVirtualNetworkRuleImpl, SqlVirtualNetworkRule, VirtualNetworkRuleInner, SqlServerImpl, SqlServer> { +public class SqlVirtualNetworkRulesAsExternalChildResourcesImpl extends + ExternalChildResourcesNonCachedImpl { SqlServerManager sqlServerManager; @@ -32,8 +31,8 @@ protected SqlVirtualNetworkRulesAsExternalChildResourcesImpl(SqlServerImpl paren * @param sqlServerManager the manager * @param childResourceName the child resource name (for logging) */ - protected SqlVirtualNetworkRulesAsExternalChildResourcesImpl( - SqlServerManager sqlServerManager, String childResourceName) { + protected SqlVirtualNetworkRulesAsExternalChildResourcesImpl(SqlServerManager sqlServerManager, + String childResourceName) { super(null, null, childResourceName); this.sqlServerManager = sqlServerManager; } @@ -50,9 +49,8 @@ SqlVirtualNetworkRuleImpl defineInlineVirtualNetworkRule(String name) { return prepareInlineDefine( new SqlVirtualNetworkRuleImpl(name, new VirtualNetworkRuleInner(), this.sqlServerManager)); } else { - return prepareInlineDefine( - new SqlVirtualNetworkRuleImpl( - name, this.getParent(), new VirtualNetworkRuleInner(), this.getParent().manager())); + return prepareInlineDefine(new SqlVirtualNetworkRuleImpl(name, this.getParent(), + new VirtualNetworkRuleInner(), this.getParent().manager())); } } @@ -62,9 +60,8 @@ SqlVirtualNetworkRuleImpl updateInlineVirtualNetworkRule(String name) { return prepareInlineUpdate( new SqlVirtualNetworkRuleImpl(name, new VirtualNetworkRuleInner(), this.sqlServerManager)); } else { - return prepareInlineUpdate( - new SqlVirtualNetworkRuleImpl( - name, this.getParent(), new VirtualNetworkRuleInner(), this.getParent().manager())); + return prepareInlineUpdate(new SqlVirtualNetworkRuleImpl(name, this.getParent(), + new VirtualNetworkRuleInner(), this.getParent().manager())); } } @@ -74,9 +71,8 @@ void removeInlineVirtualNetworkRule(String name) { prepareInlineRemove( new SqlVirtualNetworkRuleImpl(name, new VirtualNetworkRuleInner(), this.sqlServerManager)); } else { - prepareInlineRemove( - new SqlVirtualNetworkRuleImpl( - name, this.getParent(), new VirtualNetworkRuleInner(), this.getParent().manager())); + prepareInlineRemove(new SqlVirtualNetworkRuleImpl(name, this.getParent(), new VirtualNetworkRuleInner(), + this.getParent().manager())); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlWarehouseImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlWarehouseImpl.java index 68564a0bc5585..bbecc46c6df01 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlWarehouseImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/SqlWarehouseImpl.java @@ -15,30 +15,21 @@ class SqlWarehouseImpl extends SqlDatabaseImpl implements SqlWarehouse { super(name, parent, innerObject, sqlServerManager); } - SqlWarehouseImpl( - String resourceGroupName, - String sqlServerName, - String sqlServerLocation, - String name, - DatabaseInner innerObject, - SqlServerManager sqlServerManager) { + SqlWarehouseImpl(String resourceGroupName, String sqlServerName, String sqlServerLocation, String name, + DatabaseInner innerObject, SqlServerManager sqlServerManager) { super(resourceGroupName, sqlServerName, sqlServerLocation, name, innerObject, sqlServerManager); } @Override public void pauseDataWarehouse() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getDatabases() .pause(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public Mono pauseDataWarehouseAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .pauseAsync(this.resourceGroupName, this.sqlServerName, this.name()) .flatMap(databaseInner -> Mono.empty()); @@ -46,18 +37,14 @@ public Mono pauseDataWarehouseAsync() { @Override public void resumeDataWarehouse() { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getDatabases() .resume(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public Mono resumeDataWarehouseAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getDatabases() .resumeAsync(this.resourceGroupName, this.sqlServerName, this.name()) .flatMap(databaseInner -> Mono.empty()); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/TransparentDataEncryptionImpl.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/TransparentDataEncryptionImpl.java index 852b6bc8e1e04..be26307f6ecc9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/TransparentDataEncryptionImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/TransparentDataEncryptionImpl.java @@ -21,11 +21,8 @@ class TransparentDataEncryptionImpl private final SqlServerManager sqlServerManager; private final ResourceId resourceId; - protected TransparentDataEncryptionImpl( - String resourceGroupName, - String sqlServerName, - LogicalDatabaseTransparentDataEncryptionInner innerObject, - SqlServerManager sqlServerManager) { + protected TransparentDataEncryptionImpl(String resourceGroupName, String sqlServerName, + LogicalDatabaseTransparentDataEncryptionInner innerObject, SqlServerManager sqlServerManager) { super(innerObject); this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; @@ -65,14 +62,9 @@ public TransparentDataEncryptionState status() { @Override public TransparentDataEncryption updateStatus(TransparentDataEncryptionState transparentDataEncryptionState) { - this - .sqlServerManager - .serviceClient() + this.sqlServerManager.serviceClient() .getTransparentDataEncryptions() - .createOrUpdate( - this.resourceGroupName, - this.sqlServerName, - this.databaseName(), + .createOrUpdate(this.resourceGroupName, this.sqlServerName, this.databaseName(), TransparentDataEncryptionName.CURRENT, new LogicalDatabaseTransparentDataEncryptionInner().withState(transparentDataEncryptionState)); this.refresh(); @@ -81,17 +73,12 @@ public TransparentDataEncryption updateStatus(TransparentDataEncryptionState tra } @Override - public Mono updateStatusAsync( - TransparentDataEncryptionState transparentDataEncryptionState) { + public Mono + updateStatusAsync(TransparentDataEncryptionState transparentDataEncryptionState) { final TransparentDataEncryptionImpl self = this; - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getTransparentDataEncryptions() - .createOrUpdateAsync( - self.resourceGroupName, - self.sqlServerName, - self.databaseName(), + .createOrUpdateAsync(self.resourceGroupName, self.sqlServerName, self.databaseName(), TransparentDataEncryptionName.CURRENT, new LogicalDatabaseTransparentDataEncryptionInner().withState(transparentDataEncryptionState)) .then(refreshAsync()); @@ -99,11 +86,9 @@ public Mono updateStatusAsync( @Override protected Mono getInnerAsync() { - return this - .sqlServerManager - .serviceClient() + return this.sqlServerManager.serviceClient() .getTransparentDataEncryptions() - .getAsync( - this.resourceGroupName, this.sqlServerName, this.databaseName(), TransparentDataEncryptionName.CURRENT); + .getAsync(this.resourceGroupName, this.sqlServerName, this.databaseName(), + TransparentDataEncryptionName.CURRENT); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/AuthenticationType.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/AuthenticationType.java index 0b84687a616f6..dce6c2bd6f67a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/AuthenticationType.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/AuthenticationType.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.sql.models; - /** Defines values for AuthenticationType. */ public enum AuthenticationType { /** Enum value SQL. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/CheckNameAvailabilityResult.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/CheckNameAvailabilityResult.java index 2d2e69c083205..4b14c41e7ba11 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/CheckNameAvailabilityResult.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/CheckNameAvailabilityResult.java @@ -11,6 +11,7 @@ public interface CheckNameAvailabilityResult extends HasInnerModel { /** @return true if the specified name is valid and available for use, otherwise false */ boolean isAvailable(); + /** @return the reason why the user-provided name for the SQL server could not be used */ String unavailabilityReason(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java index 0f2f12c80a743..1ede4a588e764 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java @@ -16,368 +16,326 @@ public final class DatabaseSku { private static final ConcurrentMap VALUES = new ConcurrentHashMap<>(); /** Free Edition with Free sku. */ - public static final DatabaseSku FREE_FREE = - new DatabaseSku("Free", "Free", null, 5, null); + public static final DatabaseSku FREE_FREE = new DatabaseSku("Free", "Free", null, 5, null); /** Basic Edition with Basic sku. */ - public static final DatabaseSku BASIC_BASIC = - new DatabaseSku("Basic", "Basic", null, 5, null); + public static final DatabaseSku BASIC_BASIC = new DatabaseSku("Basic", "Basic", null, 5, null); /** Standard Edition with S0 sku. */ - public static final DatabaseSku STANDARD_S0 = - new DatabaseSku("Standard", "Standard", null, 10, null); + public static final DatabaseSku STANDARD_S0 = new DatabaseSku("Standard", "Standard", null, 10, null); /** Standard Edition with S1 sku. */ - public static final DatabaseSku STANDARD_S1 = - new DatabaseSku("Standard", "Standard", null, 20, null); + public static final DatabaseSku STANDARD_S1 = new DatabaseSku("Standard", "Standard", null, 20, null); /** Standard Edition with S2 sku. */ - public static final DatabaseSku STANDARD_S2 = - new DatabaseSku("Standard", "Standard", null, 50, null); + public static final DatabaseSku STANDARD_S2 = new DatabaseSku("Standard", "Standard", null, 50, null); /** Standard Edition with S3 sku. */ - public static final DatabaseSku STANDARD_S3 = - new DatabaseSku("Standard", "Standard", null, 100, null); + public static final DatabaseSku STANDARD_S3 = new DatabaseSku("Standard", "Standard", null, 100, null); /** Standard Edition with S4 sku. */ - public static final DatabaseSku STANDARD_S4 = - new DatabaseSku("Standard", "Standard", null, 200, null); + public static final DatabaseSku STANDARD_S4 = new DatabaseSku("Standard", "Standard", null, 200, null); /** Standard Edition with S6 sku. */ - public static final DatabaseSku STANDARD_S6 = - new DatabaseSku("Standard", "Standard", null, 400, null); + public static final DatabaseSku STANDARD_S6 = new DatabaseSku("Standard", "Standard", null, 400, null); /** Standard Edition with S7 sku. */ - public static final DatabaseSku STANDARD_S7 = - new DatabaseSku("Standard", "Standard", null, 800, null); + public static final DatabaseSku STANDARD_S7 = new DatabaseSku("Standard", "Standard", null, 800, null); /** Standard Edition with S9 sku. */ - public static final DatabaseSku STANDARD_S9 = - new DatabaseSku("Standard", "Standard", null, 1600, null); + public static final DatabaseSku STANDARD_S9 = new DatabaseSku("Standard", "Standard", null, 1600, null); /** Standard Edition with S12 sku. */ - public static final DatabaseSku STANDARD_S12 = - new DatabaseSku("Standard", "Standard", null, 3000, null); + public static final DatabaseSku STANDARD_S12 = new DatabaseSku("Standard", "Standard", null, 3000, null); /** Premium Edition with P1 sku. */ - public static final DatabaseSku PREMIUM_P1 = - new DatabaseSku("Premium", "Premium", null, 125, null); + public static final DatabaseSku PREMIUM_P1 = new DatabaseSku("Premium", "Premium", null, 125, null); /** Premium Edition with P2 sku. */ - public static final DatabaseSku PREMIUM_P2 = - new DatabaseSku("Premium", "Premium", null, 250, null); + public static final DatabaseSku PREMIUM_P2 = new DatabaseSku("Premium", "Premium", null, 250, null); /** Premium Edition with P4 sku. */ - public static final DatabaseSku PREMIUM_P4 = - new DatabaseSku("Premium", "Premium", null, 500, null); + public static final DatabaseSku PREMIUM_P4 = new DatabaseSku("Premium", "Premium", null, 500, null); /** Premium Edition with P6 sku. */ - public static final DatabaseSku PREMIUM_P6 = - new DatabaseSku("Premium", "Premium", null, 1000, null); + public static final DatabaseSku PREMIUM_P6 = new DatabaseSku("Premium", "Premium", null, 1000, null); /** Premium Edition with P11 sku. */ - public static final DatabaseSku PREMIUM_P11 = - new DatabaseSku("Premium", "Premium", null, 1750, null); + public static final DatabaseSku PREMIUM_P11 = new DatabaseSku("Premium", "Premium", null, 1750, null); /** Premium Edition with P15 sku. */ - public static final DatabaseSku PREMIUM_P15 = - new DatabaseSku("Premium", "Premium", null, 4000, null); + public static final DatabaseSku PREMIUM_P15 = new DatabaseSku("Premium", "Premium", null, 4000, null); /** DataWarehouse Edition with DW100c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW100C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 900, null); + public static final DatabaseSku DATAWAREHOUSE_DW100C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 900, null); /** DataWarehouse Edition with DW200c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW200C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 1800, null); + public static final DatabaseSku DATAWAREHOUSE_DW200C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 1800, null); /** DataWarehouse Edition with DW300c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW300C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 2700, null); + public static final DatabaseSku DATAWAREHOUSE_DW300C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 2700, null); /** DataWarehouse Edition with DW400c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW400C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 3600, null); + public static final DatabaseSku DATAWAREHOUSE_DW400C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 3600, null); /** DataWarehouse Edition with DW500c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW500C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 4500, null); + public static final DatabaseSku DATAWAREHOUSE_DW500C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 4500, null); /** DataWarehouse Edition with DW1000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW1000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 9000, null); + public static final DatabaseSku DATAWAREHOUSE_DW1000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 9000, null); /** DataWarehouse Edition with DW1500c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW1500C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 13500, null); + public static final DatabaseSku DATAWAREHOUSE_DW1500C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 13500, null); /** DataWarehouse Edition with DW2000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW2000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 18000, null); + public static final DatabaseSku DATAWAREHOUSE_DW2000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 18000, null); /** DataWarehouse Edition with DW2500c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW2500C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 22500, null); + public static final DatabaseSku DATAWAREHOUSE_DW2500C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 22500, null); /** DataWarehouse Edition with DW3000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW3000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 27000, null); + public static final DatabaseSku DATAWAREHOUSE_DW3000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 27000, null); /** DataWarehouse Edition with DW5000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW5000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 45000, null); + public static final DatabaseSku DATAWAREHOUSE_DW5000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 45000, null); /** DataWarehouse Edition with DW6000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW6000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 54000, null); + public static final DatabaseSku DATAWAREHOUSE_DW6000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 54000, null); /** DataWarehouse Edition with DW7500c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW7500C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 67500, null); + public static final DatabaseSku DATAWAREHOUSE_DW7500C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 67500, null); /** DataWarehouse Edition with DW10000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW10000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 90000, null); + public static final DatabaseSku DATAWAREHOUSE_DW10000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 90000, null); /** DataWarehouse Edition with DW15000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW15000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 135000, null); + public static final DatabaseSku DATAWAREHOUSE_DW15000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 135000, null); /** DataWarehouse Edition with DW30000c sku. */ - public static final DatabaseSku DATAWAREHOUSE_DW30000C = - new DatabaseSku("DataWarehouse", "DataWarehouse", null, 270000, null); + public static final DatabaseSku DATAWAREHOUSE_DW30000C + = new DatabaseSku("DataWarehouse", "DataWarehouse", null, 270000, null); /** Stretch Edition with DS100 sku. */ - public static final DatabaseSku STRETCH_DS100 = - new DatabaseSku("Stretch", "Stretch", null, 750, null); + public static final DatabaseSku STRETCH_DS100 = new DatabaseSku("Stretch", "Stretch", null, 750, null); /** Stretch Edition with DS200 sku. */ - public static final DatabaseSku STRETCH_DS200 = - new DatabaseSku("Stretch", "Stretch", null, 1500, null); + public static final DatabaseSku STRETCH_DS200 = new DatabaseSku("Stretch", "Stretch", null, 1500, null); /** Stretch Edition with DS300 sku. */ - public static final DatabaseSku STRETCH_DS300 = - new DatabaseSku("Stretch", "Stretch", null, 2250, null); + public static final DatabaseSku STRETCH_DS300 = new DatabaseSku("Stretch", "Stretch", null, 2250, null); /** Stretch Edition with DS400 sku. */ - public static final DatabaseSku STRETCH_DS400 = - new DatabaseSku("Stretch", "Stretch", null, 3000, null); + public static final DatabaseSku STRETCH_DS400 = new DatabaseSku("Stretch", "Stretch", null, 3000, null); /** Stretch Edition with DS500 sku. */ - public static final DatabaseSku STRETCH_DS500 = - new DatabaseSku("Stretch", "Stretch", null, 3750, null); + public static final DatabaseSku STRETCH_DS500 = new DatabaseSku("Stretch", "Stretch", null, 3750, null); /** Stretch Edition with DS600 sku. */ - public static final DatabaseSku STRETCH_DS600 = - new DatabaseSku("Stretch", "Stretch", null, 4500, null); + public static final DatabaseSku STRETCH_DS600 = new DatabaseSku("Stretch", "Stretch", null, 4500, null); /** Stretch Edition with DS1000 sku. */ - public static final DatabaseSku STRETCH_DS1000 = - new DatabaseSku("Stretch", "Stretch", null, 7500, null); + public static final DatabaseSku STRETCH_DS1000 = new DatabaseSku("Stretch", "Stretch", null, 7500, null); /** Stretch Edition with DS1200 sku. */ - public static final DatabaseSku STRETCH_DS1200 = - new DatabaseSku("Stretch", "Stretch", null, 9000, null); + public static final DatabaseSku STRETCH_DS1200 = new DatabaseSku("Stretch", "Stretch", null, 9000, null); /** Stretch Edition with DS1500 sku. */ - public static final DatabaseSku STRETCH_DS1500 = - new DatabaseSku("Stretch", "Stretch", null, 11250, null); + public static final DatabaseSku STRETCH_DS1500 = new DatabaseSku("Stretch", "Stretch", null, 11250, null); /** Stretch Edition with DS2000 sku. */ - public static final DatabaseSku STRETCH_DS2000 = - new DatabaseSku("Stretch", "Stretch", null, 15000, null); + public static final DatabaseSku STRETCH_DS2000 = new DatabaseSku("Stretch", "Stretch", null, 15000, null); /** GeneralPurpose Edition with GP_S_Gen5_1 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_1 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 1, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_1 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 1, null); /** GeneralPurpose Edition with GP_Gen5_2 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_2 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 2, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_2 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 2, null); /** GeneralPurpose Edition with GP_S_Gen5_2 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_2 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 2, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_2 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 2, null); /** GeneralPurpose Edition with GP_Gen5_4 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_4 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 4, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_4 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 4, null); /** GeneralPurpose Edition with GP_S_Gen5_4 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_4 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 4, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_4 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 4, null); /** GeneralPurpose Edition with GP_Gen5_6 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_6 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 6, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_6 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 6, null); /** GeneralPurpose Edition with GP_S_Gen5_6 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_6 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 6, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_6 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 6, null); /** GeneralPurpose Edition with GP_Gen5_8 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_8 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 8, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_8 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 8, null); /** GeneralPurpose Edition with GP_S_Gen5_8 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_8 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 8, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_8 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 8, null); /** GeneralPurpose Edition with GP_Fsv2_8 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_8 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 8, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_8 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 8, null); /** GeneralPurpose Edition with GP_Gen5_10 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_10 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 10, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_10 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 10, null); /** GeneralPurpose Edition with GP_S_Gen5_10 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_10 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 10, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_10 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 10, null); /** GeneralPurpose Edition with GP_Fsv2_10 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_10 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 10, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_10 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 10, null); /** GeneralPurpose Edition with GP_Gen5_12 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_12 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 12, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_12 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 12, null); /** GeneralPurpose Edition with GP_S_Gen5_12 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_12 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 12, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_12 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 12, null); /** GeneralPurpose Edition with GP_Fsv2_12 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_12 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 12, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_12 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 12, null); /** GeneralPurpose Edition with GP_Gen5_14 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_14 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 14, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_14 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 14, null); /** GeneralPurpose Edition with GP_S_Gen5_14 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_14 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 14, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_14 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 14, null); /** GeneralPurpose Edition with GP_Fsv2_14 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_14 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 14, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_14 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 14, null); /** GeneralPurpose Edition with GP_Gen5_16 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_16 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 16, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_16 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 16, null); /** GeneralPurpose Edition with GP_S_Gen5_16 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_16 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 16, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_16 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 16, null); /** GeneralPurpose Edition with GP_Fsv2_16 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_16 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 16, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_16 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 16, null); /** GeneralPurpose Edition with GP_Gen5_18 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_18 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 18, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_18 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 18, null); /** GeneralPurpose Edition with GP_S_Gen5_18 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_18 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 18, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_18 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 18, null); /** GeneralPurpose Edition with GP_Fsv2_18 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_18 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 18, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_18 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 18, null); /** GeneralPurpose Edition with GP_Gen5_20 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_20 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 20, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_20 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 20, null); /** GeneralPurpose Edition with GP_S_Gen5_20 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_20 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 20, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_20 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 20, null); /** GeneralPurpose Edition with GP_Fsv2_20 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_20 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 20, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_20 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 20, null); /** GeneralPurpose Edition with GP_Gen5_24 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_24 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 24, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_24 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 24, null); /** GeneralPurpose Edition with GP_S_Gen5_24 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_24 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 24, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_24 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 24, null); /** GeneralPurpose Edition with GP_Fsv2_24 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_24 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 24, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_24 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 24, null); /** GeneralPurpose Edition with GP_Gen5_32 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_32 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 32, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_32 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 32, null); /** GeneralPurpose Edition with GP_S_Gen5_32 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_32 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 32, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_32 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 32, null); /** GeneralPurpose Edition with GP_Fsv2_32 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_32 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 32, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_32 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 32, null); /** GeneralPurpose Edition with GP_Fsv2_36 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_36 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 36, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_36 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 36, null); /** GeneralPurpose Edition with GP_Gen5_40 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_40 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 40, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_40 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 40, null); /** GeneralPurpose Edition with GP_S_Gen5_40 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_40 = - new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 40, null); + public static final DatabaseSku GENERALPURPOSE_GP_S_GEN5_40 + = new DatabaseSku("GP_S_Gen5", "GeneralPurpose", "Gen5", 40, null); /** GeneralPurpose Edition with GP_Fsv2_72 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_FSV2_72 = - new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 72, null); + public static final DatabaseSku GENERALPURPOSE_GP_FSV2_72 + = new DatabaseSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 72, null); /** GeneralPurpose Edition with GP_Gen5_80 sku. */ - public static final DatabaseSku GENERALPURPOSE_GP_GEN5_80 = - new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 80, null); + public static final DatabaseSku GENERALPURPOSE_GP_GEN5_80 + = new DatabaseSku("GP_Gen5", "GeneralPurpose", "Gen5", 80, null); /** BusinessCritical Edition with BC_Gen5_2 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_2 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 2, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_2 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 2, null); /** BusinessCritical Edition with BC_Gen5_4 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_4 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 4, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_4 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 4, null); /** BusinessCritical Edition with BC_Gen5_6 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_6 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 6, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_6 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 6, null); /** BusinessCritical Edition with BC_Gen5_8 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_8 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 8, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_8 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 8, null); /** BusinessCritical Edition with BC_M_8 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_8 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 8, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_8 = new DatabaseSku("BC_M", "BusinessCritical", "M", 8, null); /** BusinessCritical Edition with BC_Gen5_10 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_10 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 10, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_10 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 10, null); /** BusinessCritical Edition with BC_M_10 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_10 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 10, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_10 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 10, null); /** BusinessCritical Edition with BC_Gen5_12 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_12 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 12, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_12 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 12, null); /** BusinessCritical Edition with BC_M_12 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_12 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 12, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_12 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 12, null); /** BusinessCritical Edition with BC_Gen5_14 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_14 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 14, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_14 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 14, null); /** BusinessCritical Edition with BC_M_14 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_14 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 14, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_14 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 14, null); /** BusinessCritical Edition with BC_Gen5_16 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_16 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 16, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_16 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 16, null); /** BusinessCritical Edition with BC_M_16 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_16 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 16, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_16 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 16, null); /** BusinessCritical Edition with BC_Gen5_18 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_18 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 18, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_18 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 18, null); /** BusinessCritical Edition with BC_M_18 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_18 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 18, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_18 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 18, null); /** BusinessCritical Edition with BC_Gen5_20 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_20 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 20, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_20 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 20, null); /** BusinessCritical Edition with BC_M_20 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_20 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 20, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_20 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 20, null); /** BusinessCritical Edition with BC_Gen5_24 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_24 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 24, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_24 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 24, null); /** BusinessCritical Edition with BC_M_24 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_24 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 24, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_24 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 24, null); /** BusinessCritical Edition with BC_Gen5_32 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_32 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 32, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_32 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 32, null); /** BusinessCritical Edition with BC_M_32 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_32 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 32, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_32 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 32, null); /** BusinessCritical Edition with BC_Gen5_40 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_40 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 40, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_40 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 40, null); /** BusinessCritical Edition with BC_M_64 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_64 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 64, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_64 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 64, null); /** BusinessCritical Edition with BC_Gen5_80 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_80 = - new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 80, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_GEN5_80 + = new DatabaseSku("BC_Gen5", "BusinessCritical", "Gen5", 80, null); /** BusinessCritical Edition with BC_M_128 sku. */ - public static final DatabaseSku BUSINESSCRITICAL_BC_M_128 = - new DatabaseSku("BC_M", "BusinessCritical", "M", 128, null); + public static final DatabaseSku BUSINESSCRITICAL_BC_M_128 + = new DatabaseSku("BC_M", "BusinessCritical", "M", 128, null); /** Hyperscale Edition with HS_Gen5_2 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_2 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 2, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_2 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 2, null); /** Hyperscale Edition with HS_Gen5_4 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_4 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 4, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_4 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 4, null); /** Hyperscale Edition with HS_Gen5_6 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_6 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 6, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_6 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 6, null); /** Hyperscale Edition with HS_Gen5_8 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_8 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 8, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_8 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 8, null); /** Hyperscale Edition with HS_Gen5_10 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_10 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 10, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_10 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 10, null); /** Hyperscale Edition with HS_Gen5_12 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_12 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 12, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_12 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 12, null); /** Hyperscale Edition with HS_Gen5_14 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_14 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 14, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_14 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 14, null); /** Hyperscale Edition with HS_Gen5_16 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_16 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 16, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_16 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 16, null); /** Hyperscale Edition with HS_Gen5_18 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_18 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 18, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_18 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 18, null); /** Hyperscale Edition with HS_Gen5_20 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_20 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 20, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_20 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 20, null); /** Hyperscale Edition with HS_Gen5_24 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_24 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 24, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_24 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 24, null); /** Hyperscale Edition with HS_Gen5_32 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_32 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 32, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_32 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 32, null); /** Hyperscale Edition with HS_Gen5_40 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_40 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 40, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_40 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 40, null); /** Hyperscale Edition with HS_Gen5_80 sku. */ - public static final DatabaseSku HYPERSCALE_HS_GEN5_80 = - new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 80, null); + public static final DatabaseSku HYPERSCALE_HS_GEN5_80 = new DatabaseSku("HS_Gen5", "Hyperscale", "Gen5", 80, null); private final Sku sku; @@ -425,8 +383,7 @@ public String toString() { /** @return the underneath sku description */ @JsonValue public Sku toSku() { - return new Sku() - .withName(sku.name()) + return new Sku().withName(sku.name()) .withTier(sku.tier()) .withFamily(sku.family()) .withCapacity(sku.capacity()) diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolActivity.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolActivity.java index 553d9eaaeea15..40ce09567931f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolActivity.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolActivity.java @@ -14,7 +14,8 @@ /** An immutable client-side representation of an Azure SQL ElasticPool's Activity. */ @Fluent -public interface ElasticPoolActivity extends HasInnerModel, HasResourceGroup, HasName, HasId { +public interface ElasticPoolActivity + extends HasInnerModel, HasResourceGroup, HasName, HasId { /** @return the time the operation finished (ISO8601 format) */ OffsetDateTime endTime(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java index f77eaa7cc81f1..b9fe45e20a18d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java @@ -16,239 +16,233 @@ public final class ElasticPoolSku { private static final ConcurrentMap VALUES = new ConcurrentHashMap<>(); /** Standard Edition with StandardPool_50 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_50 = - new ElasticPoolSku("StandardPool", "Standard", null, 50, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_50 + = new ElasticPoolSku("StandardPool", "Standard", null, 50, null); /** Standard Edition with StandardPool_100 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_100 = - new ElasticPoolSku("StandardPool", "Standard", null, 100, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_100 + = new ElasticPoolSku("StandardPool", "Standard", null, 100, null); /** Standard Edition with StandardPool_200 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_200 = - new ElasticPoolSku("StandardPool", "Standard", null, 200, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_200 + = new ElasticPoolSku("StandardPool", "Standard", null, 200, null); /** Standard Edition with StandardPool_300 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_300 = - new ElasticPoolSku("StandardPool", "Standard", null, 300, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_300 + = new ElasticPoolSku("StandardPool", "Standard", null, 300, null); /** Standard Edition with StandardPool_400 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_400 = - new ElasticPoolSku("StandardPool", "Standard", null, 400, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_400 + = new ElasticPoolSku("StandardPool", "Standard", null, 400, null); /** Standard Edition with StandardPool_800 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_800 = - new ElasticPoolSku("StandardPool", "Standard", null, 800, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_800 + = new ElasticPoolSku("StandardPool", "Standard", null, 800, null); /** Standard Edition with StandardPool_1200 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_1200 = - new ElasticPoolSku("StandardPool", "Standard", null, 1200, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_1200 + = new ElasticPoolSku("StandardPool", "Standard", null, 1200, null); /** Standard Edition with StandardPool_1600 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_1600 = - new ElasticPoolSku("StandardPool", "Standard", null, 1600, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_1600 + = new ElasticPoolSku("StandardPool", "Standard", null, 1600, null); /** Standard Edition with StandardPool_2000 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_2000 = - new ElasticPoolSku("StandardPool", "Standard", null, 2000, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_2000 + = new ElasticPoolSku("StandardPool", "Standard", null, 2000, null); /** Standard Edition with StandardPool_2500 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_2500 = - new ElasticPoolSku("StandardPool", "Standard", null, 2500, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_2500 + = new ElasticPoolSku("StandardPool", "Standard", null, 2500, null); /** Standard Edition with StandardPool_3000 sku. */ - public static final ElasticPoolSku STANDARD_STANDARDPOOL_3000 = - new ElasticPoolSku("StandardPool", "Standard", null, 3000, null); + public static final ElasticPoolSku STANDARD_STANDARDPOOL_3000 + = new ElasticPoolSku("StandardPool", "Standard", null, 3000, null); /** Premium Edition with PremiumPool_125 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_125 = - new ElasticPoolSku("PremiumPool", "Premium", null, 125, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_125 + = new ElasticPoolSku("PremiumPool", "Premium", null, 125, null); /** Premium Edition with PremiumPool_250 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_250 = - new ElasticPoolSku("PremiumPool", "Premium", null, 250, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_250 + = new ElasticPoolSku("PremiumPool", "Premium", null, 250, null); /** Premium Edition with PremiumPool_500 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_500 = - new ElasticPoolSku("PremiumPool", "Premium", null, 500, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_500 + = new ElasticPoolSku("PremiumPool", "Premium", null, 500, null); /** Premium Edition with PremiumPool_1000 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_1000 = - new ElasticPoolSku("PremiumPool", "Premium", null, 1000, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_1000 + = new ElasticPoolSku("PremiumPool", "Premium", null, 1000, null); /** Premium Edition with PremiumPool_1500 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_1500 = - new ElasticPoolSku("PremiumPool", "Premium", null, 1500, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_1500 + = new ElasticPoolSku("PremiumPool", "Premium", null, 1500, null); /** Premium Edition with PremiumPool_2000 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_2000 = - new ElasticPoolSku("PremiumPool", "Premium", null, 2000, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_2000 + = new ElasticPoolSku("PremiumPool", "Premium", null, 2000, null); /** Premium Edition with PremiumPool_2500 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_2500 = - new ElasticPoolSku("PremiumPool", "Premium", null, 2500, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_2500 + = new ElasticPoolSku("PremiumPool", "Premium", null, 2500, null); /** Premium Edition with PremiumPool_3000 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_3000 = - new ElasticPoolSku("PremiumPool", "Premium", null, 3000, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_3000 + = new ElasticPoolSku("PremiumPool", "Premium", null, 3000, null); /** Premium Edition with PremiumPool_3500 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_3500 = - new ElasticPoolSku("PremiumPool", "Premium", null, 3500, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_3500 + = new ElasticPoolSku("PremiumPool", "Premium", null, 3500, null); /** Premium Edition with PremiumPool_4000 sku. */ - public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_4000 = - new ElasticPoolSku("PremiumPool", "Premium", null, 4000, null); + public static final ElasticPoolSku PREMIUM_PREMIUMPOOL_4000 + = new ElasticPoolSku("PremiumPool", "Premium", null, 4000, null); /** Basic Edition with BasicPool_50 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_50 = - new ElasticPoolSku("BasicPool", "Basic", null, 50, null); + public static final ElasticPoolSku BASIC_BASICPOOL_50 = new ElasticPoolSku("BasicPool", "Basic", null, 50, null); /** Basic Edition with BasicPool_100 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_100 = - new ElasticPoolSku("BasicPool", "Basic", null, 100, null); + public static final ElasticPoolSku BASIC_BASICPOOL_100 = new ElasticPoolSku("BasicPool", "Basic", null, 100, null); /** Basic Edition with BasicPool_200 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_200 = - new ElasticPoolSku("BasicPool", "Basic", null, 200, null); + public static final ElasticPoolSku BASIC_BASICPOOL_200 = new ElasticPoolSku("BasicPool", "Basic", null, 200, null); /** Basic Edition with BasicPool_300 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_300 = - new ElasticPoolSku("BasicPool", "Basic", null, 300, null); + public static final ElasticPoolSku BASIC_BASICPOOL_300 = new ElasticPoolSku("BasicPool", "Basic", null, 300, null); /** Basic Edition with BasicPool_400 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_400 = - new ElasticPoolSku("BasicPool", "Basic", null, 400, null); + public static final ElasticPoolSku BASIC_BASICPOOL_400 = new ElasticPoolSku("BasicPool", "Basic", null, 400, null); /** Basic Edition with BasicPool_800 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_800 = - new ElasticPoolSku("BasicPool", "Basic", null, 800, null); + public static final ElasticPoolSku BASIC_BASICPOOL_800 = new ElasticPoolSku("BasicPool", "Basic", null, 800, null); /** Basic Edition with BasicPool_1200 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_1200 = - new ElasticPoolSku("BasicPool", "Basic", null, 1200, null); + public static final ElasticPoolSku BASIC_BASICPOOL_1200 + = new ElasticPoolSku("BasicPool", "Basic", null, 1200, null); /** Basic Edition with BasicPool_1600 sku. */ - public static final ElasticPoolSku BASIC_BASICPOOL_1600 = - new ElasticPoolSku("BasicPool", "Basic", null, 1600, null); + public static final ElasticPoolSku BASIC_BASICPOOL_1600 + = new ElasticPoolSku("BasicPool", "Basic", null, 1600, null); /** GeneralPurpose Edition with GP_Gen5_2 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_2 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 2, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_2 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 2, null); /** GeneralPurpose Edition with GP_Gen5_4 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_4 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 4, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_4 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 4, null); /** GeneralPurpose Edition with GP_Gen5_6 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_6 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 6, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_6 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 6, null); /** GeneralPurpose Edition with GP_Gen5_8 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_8 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 8, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_8 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 8, null); /** GeneralPurpose Edition with GP_Fsv2_8 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_8 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 8, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_8 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 8, null); /** GeneralPurpose Edition with GP_Gen5_10 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_10 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 10, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_10 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 10, null); /** GeneralPurpose Edition with GP_Fsv2_10 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_10 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 10, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_10 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 10, null); /** GeneralPurpose Edition with GP_Gen5_12 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_12 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 12, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_12 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 12, null); /** GeneralPurpose Edition with GP_Fsv2_12 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_12 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 12, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_12 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 12, null); /** GeneralPurpose Edition with GP_Gen5_14 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_14 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 14, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_14 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 14, null); /** GeneralPurpose Edition with GP_Fsv2_14 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_14 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 14, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_14 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 14, null); /** GeneralPurpose Edition with GP_Gen5_16 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_16 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 16, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_16 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 16, null); /** GeneralPurpose Edition with GP_Fsv2_16 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_16 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 16, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_16 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 16, null); /** GeneralPurpose Edition with GP_Gen5_18 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_18 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 18, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_18 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 18, null); /** GeneralPurpose Edition with GP_Fsv2_18 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_18 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 18, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_18 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 18, null); /** GeneralPurpose Edition with GP_Gen5_20 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_20 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 20, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_20 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 20, null); /** GeneralPurpose Edition with GP_Fsv2_20 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_20 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 20, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_20 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 20, null); /** GeneralPurpose Edition with GP_Gen5_24 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_24 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 24, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_24 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 24, null); /** GeneralPurpose Edition with GP_Fsv2_24 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_24 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 24, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_24 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 24, null); /** GeneralPurpose Edition with GP_Gen5_32 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_32 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 32, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_32 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 32, null); /** GeneralPurpose Edition with GP_Fsv2_32 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_32 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 32, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_32 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 32, null); /** GeneralPurpose Edition with GP_Fsv2_36 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_36 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 36, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_36 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 36, null); /** GeneralPurpose Edition with GP_Gen5_40 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_40 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 40, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_40 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 40, null); /** GeneralPurpose Edition with GP_Fsv2_72 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_72 = - new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 72, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_FSV2_72 + = new ElasticPoolSku("GP_Fsv2", "GeneralPurpose", "Fsv2", 72, null); /** GeneralPurpose Edition with GP_Gen5_80 sku. */ - public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_80 = - new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 80, null); + public static final ElasticPoolSku GENERALPURPOSE_GP_GEN5_80 + = new ElasticPoolSku("GP_Gen5", "GeneralPurpose", "Gen5", 80, null); /** BusinessCritical Edition with BC_Gen5_4 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_4 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 4, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_4 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 4, null); /** BusinessCritical Edition with BC_Gen5_6 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_6 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 6, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_6 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 6, null); /** BusinessCritical Edition with BC_Gen5_8 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_8 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 8, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_8 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 8, null); /** BusinessCritical Edition with BC_M_8 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_8 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 8, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_8 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 8, null); /** BusinessCritical Edition with BC_Gen5_10 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_10 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 10, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_10 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 10, null); /** BusinessCritical Edition with BC_M_10 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_10 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 10, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_10 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 10, null); /** BusinessCritical Edition with BC_Gen5_12 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_12 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 12, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_12 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 12, null); /** BusinessCritical Edition with BC_M_12 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_12 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 12, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_12 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 12, null); /** BusinessCritical Edition with BC_Gen5_14 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_14 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 14, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_14 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 14, null); /** BusinessCritical Edition with BC_M_14 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_14 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 14, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_14 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 14, null); /** BusinessCritical Edition with BC_Gen5_16 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_16 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 16, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_16 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 16, null); /** BusinessCritical Edition with BC_M_16 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_16 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 16, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_16 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 16, null); /** BusinessCritical Edition with BC_Gen5_18 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_18 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 18, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_18 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 18, null); /** BusinessCritical Edition with BC_M_18 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_18 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 18, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_18 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 18, null); /** BusinessCritical Edition with BC_Gen5_20 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_20 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 20, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_20 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 20, null); /** BusinessCritical Edition with BC_M_20 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_20 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 20, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_20 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 20, null); /** BusinessCritical Edition with BC_Gen5_24 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_24 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 24, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_24 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 24, null); /** BusinessCritical Edition with BC_M_24 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_24 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 24, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_24 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 24, null); /** BusinessCritical Edition with BC_Gen5_32 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_32 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 32, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_32 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 32, null); /** BusinessCritical Edition with BC_M_32 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_32 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 32, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_32 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 32, null); /** BusinessCritical Edition with BC_Gen5_40 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_40 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 40, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_40 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 40, null); /** BusinessCritical Edition with BC_M_64 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_64 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 64, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_64 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 64, null); /** BusinessCritical Edition with BC_Gen5_80 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_80 = - new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 80, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_GEN5_80 + = new ElasticPoolSku("BC_Gen5", "BusinessCritical", "Gen5", 80, null); /** BusinessCritical Edition with BC_M_128 sku. */ - public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_128 = - new ElasticPoolSku("BC_M", "BusinessCritical", "M", 128, null); + public static final ElasticPoolSku BUSINESSCRITICAL_BC_M_128 + = new ElasticPoolSku("BC_M", "BusinessCritical", "M", 128, null); private final Sku sku; @@ -296,8 +290,7 @@ public String toString() { /** @return the underneath sku description */ @JsonValue public Sku toSku() { - return new Sku() - .withName(sku.name()) + return new Sku().withName(sku.name()) .withTier(sku.tier()) .withFamily(sku.family()) .withCapacity(sku.capacity()) diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabase.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabase.java index 988ae5fe8f1a4..472ccac005b47 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabase.java @@ -24,12 +24,8 @@ /** An immutable client-side representation of an Azure SQL Server Database. */ @Fluent -public interface SqlDatabase - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { +public interface SqlDatabase extends ExternalChildResource, HasInnerModel, + HasResourceGroup, Refreshable, Updatable { /** @return name of the SQL Server to which this database belongs */ String sqlServerName(); @@ -139,8 +135,8 @@ public interface SqlDatabase * @param fileName the exported database file name * @return response object */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword exportTo( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + exportTo(StorageAccount storageAccount, String containerName, String fileName); /** * Exports the current database to a new storage account and relative path. @@ -150,8 +146,8 @@ SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword * @param fileName the exported database file name * @return response object */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword exportTo( - Creatable storageAccountCreatable, String containerName, String fileName); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + exportTo(Creatable storageAccountCreatable, String containerName, String fileName); /** * Imports into the current database from a specified URI path; the current database must be empty. @@ -170,8 +166,8 @@ SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword * @param fileName the exported database file name * @return response object */ - SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword importBacpac( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + importBacpac(StorageAccount storageAccount, String containerName, String fileName); /** * Begins a definition for a security alert policy. @@ -189,7 +185,8 @@ SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword * @param policyName the name of the security alert policy * @return the first stage of the SqlDatabaseThreatDetectionPolicy definition */ - SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank defineThreatDetectionPolicy(SecurityAlertPolicyName policyName); + SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank + defineThreatDetectionPolicy(SecurityAlertPolicyName policyName); /** * Gets a SQL database threat detection policy. @@ -257,19 +254,17 @@ SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword * * @param the stage of the parent definition to return to after attaching this definition */ - interface SqlDatabaseDefinition - extends SqlDatabase.DefinitionStages.Blank, - SqlDatabase.DefinitionStages.WithAllDifferentOptions, - SqlDatabase.DefinitionStages.WithElasticPoolName, - SqlDatabase.DefinitionStages.WithRestorableDroppedDatabase, - SqlDatabase.DefinitionStages.WithImportFrom, - SqlDatabase.DefinitionStages.WithStorageKey, - SqlDatabase.DefinitionStages.WithAuthentication, - SqlDatabase.DefinitionStages.WithRestorePointDatabase, - SqlDatabase.DefinitionStages.WithSourceDatabaseId, - SqlDatabase.DefinitionStages.WithCreateMode, - SqlDatabase.DefinitionStages.WithAttachAllOptions, - SqlDatabase.DefinitionStages.WithAttachFinal { + interface SqlDatabaseDefinition extends SqlDatabase.DefinitionStages.Blank, + SqlDatabase.DefinitionStages.WithAllDifferentOptions, + SqlDatabase.DefinitionStages.WithElasticPoolName, + SqlDatabase.DefinitionStages.WithRestorableDroppedDatabase, + SqlDatabase.DefinitionStages.WithImportFrom, SqlDatabase.DefinitionStages.WithStorageKey, + SqlDatabase.DefinitionStages.WithAuthentication, + SqlDatabase.DefinitionStages.WithRestorePointDatabase, + SqlDatabase.DefinitionStages.WithSourceDatabaseId, + SqlDatabase.DefinitionStages.WithCreateMode, + SqlDatabase.DefinitionStages.WithAttachAllOptions, + SqlDatabase.DefinitionStages.WithAttachFinal { } /** Grouping of all the SQL Database definition stages. */ @@ -287,15 +282,14 @@ interface Blank extends SqlDatabase.DefinitionStages.WithAllDifferentOp * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAllDifferentOptions - extends SqlDatabase.DefinitionStages.WithElasticPoolName, - SqlDatabase.DefinitionStages.WithRestorableDroppedDatabase, - SqlDatabase.DefinitionStages.WithImportFrom, - SqlDatabase.DefinitionStages.WithRestorePointDatabase, - SqlDatabase.DefinitionStages.WithSampleDatabase, - SqlDatabase.DefinitionStages.WithSourceDatabaseId, - SqlDatabase.DefinitionStages.WithEditionDefaults, - SqlDatabase.DefinitionStages.WithAttachAllOptions { + interface WithAllDifferentOptions extends SqlDatabase.DefinitionStages.WithElasticPoolName, + SqlDatabase.DefinitionStages.WithRestorableDroppedDatabase, + SqlDatabase.DefinitionStages.WithImportFrom, + SqlDatabase.DefinitionStages.WithRestorePointDatabase, + SqlDatabase.DefinitionStages.WithSampleDatabase, + SqlDatabase.DefinitionStages.WithSourceDatabaseId, + SqlDatabase.DefinitionStages.WithEditionDefaults, + SqlDatabase.DefinitionStages.WithAttachAllOptions { } /** @@ -345,10 +339,10 @@ interface WithElasticPoolName { */ interface WithExistingDatabaseAfterElasticPool extends SqlDatabase.DefinitionStages.WithImportFromAfterElasticPool, - SqlDatabase.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, - SqlDatabase.DefinitionStages.WithSampleDatabaseAfterElasticPool, - SqlDatabase.DefinitionStages.WithSourceDatabaseId, - SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions { + SqlDatabase.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, + SqlDatabase.DefinitionStages.WithSampleDatabaseAfterElasticPool, + SqlDatabase.DefinitionStages.WithSourceDatabaseId, + SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions { } /** @@ -373,8 +367,8 @@ interface WithImportFrom { * @param fileName the exported database file name * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAuthentication importFrom( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabase.DefinitionStages.WithAuthentication importFrom(StorageAccount storageAccount, + String containerName, String fileName); } /** @@ -407,16 +401,16 @@ interface WithAuthentication { * @param administratorPassword the SQL administrator password * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAttachAllOptions withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabase.DefinitionStages.WithAttachAllOptions + withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword); /** * @param administratorLogin the Active Directory administrator login * @param administratorPassword the Active Directory administrator password * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAttachAllOptions withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabase.DefinitionStages.WithAttachAllOptions + withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword); } /** @@ -441,8 +435,8 @@ interface WithImportFromAfterElasticPool { * @param fileName the exported database file name * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool importFrom( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool + importFrom(StorageAccount storageAccount, String containerName, String fileName); } /** @@ -455,15 +449,15 @@ interface WithStorageKeyAfterElasticPool { * @param storageAccessKey the storage access key to use * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool withStorageAccessKey( - String storageAccessKey); + SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool + withStorageAccessKey(String storageAccessKey); /** * @param sharedAccessKey the shared access key to use; it must be preceded with a "?." * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool withSharedAccessKey( - String sharedAccessKey); + SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool + withSharedAccessKey(String sharedAccessKey); } /** @@ -477,16 +471,16 @@ interface WithAuthenticationAfterElasticPool { * @param administratorPassword the SQL administrator password * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAttachFinal withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabase.DefinitionStages.WithAttachFinal + withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword); /** * @param administratorLogin the Active Directory administrator login * @param administratorPassword the Active Directory administrator password * @return next definition stage */ - SqlDatabase.DefinitionStages.WithAttachFinal withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabase.DefinitionStages.WithAttachFinal + withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword); } /** @@ -504,8 +498,8 @@ interface WithRestorableDroppedDatabase { * @param restorableDroppedDatabase the restorable dropped database * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAttachFinal fromRestorableDroppedDatabase( - SqlRestorableDroppedDatabase restorableDroppedDatabase); + SqlDatabase.DefinitionStages.WithAttachFinal + fromRestorableDroppedDatabase(SqlRestorableDroppedDatabase restorableDroppedDatabase); } /** @@ -520,8 +514,8 @@ interface WithRestorePointDatabaseAfterElasticPool { * @param restorePoint the restore point * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions fromRestorePoint( - RestorePoint restorePoint); + SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions + fromRestorePoint(RestorePoint restorePoint); /** * Creates a new database from a restore point. @@ -530,8 +524,8 @@ SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions fromRest * @param restorePointDateTime date and time to restore from * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions fromRestorePoint( - RestorePoint restorePoint, OffsetDateTime restorePointDateTime); + SqlDatabase.DefinitionStages.WithAttachAfterElasticPoolOptions + fromRestorePoint(RestorePoint restorePoint, OffsetDateTime restorePointDateTime); } /** @@ -555,8 +549,8 @@ interface WithRestorePointDatabase { * @param restorePointDateTime date and time to restore from * @return The next stage of the definition. */ - SqlDatabase.DefinitionStages.WithAttachAllOptions fromRestorePoint( - RestorePoint restorePoint, OffsetDateTime restorePointDateTime); + SqlDatabase.DefinitionStages.WithAttachAllOptions fromRestorePoint(RestorePoint restorePoint, + OffsetDateTime restorePointDateTime); } /** @@ -641,8 +635,8 @@ interface WithCreateMode { */ interface WithAttachAfterElasticPoolOptions extends SqlDatabase.DefinitionStages.WithCollationAfterElasticPoolOptions, - SqlDatabase.DefinitionStages.WithMaxSizeBytesAfterElasticPoolOptions, - SqlDatabase.DefinitionStages.WithAttachFinal { + SqlDatabase.DefinitionStages.WithMaxSizeBytesAfterElasticPoolOptions, + SqlDatabase.DefinitionStages.WithAttachFinal { } /** @@ -720,8 +714,8 @@ interface WithEditionDefaults extends WithAttachFinal { * @param maxStorageCapacity the maximum storage capacity * @return The next stage of the definition */ - SqlDatabase.DefinitionStages.WithEditionDefaults withBasicEdition( - SqlDatabaseBasicStorage maxStorageCapacity); + SqlDatabase.DefinitionStages.WithEditionDefaults + withBasicEdition(SqlDatabaseBasicStorage maxStorageCapacity); /** * Sets a "Standard" edition for the SQL Database. @@ -729,8 +723,8 @@ SqlDatabase.DefinitionStages.WithEditionDefaults withBasicEdition( * @param serviceObjective edition to be set for database * @return The next stage of the definition */ - SqlDatabase.DefinitionStages.WithEditionDefaults withStandardEdition( - SqlDatabaseStandardServiceObjective serviceObjective); + SqlDatabase.DefinitionStages.WithEditionDefaults + withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective); /** * Sets a "Standard" edition and maximum storage capacity for the SQL Database. @@ -748,8 +742,8 @@ SqlDatabase.DefinitionStages.WithEditionDefaults withStandardEdition( * @param serviceObjective edition to be set for database * @return The next stage of the definition */ - SqlDatabase.DefinitionStages.WithEditionDefaults withPremiumEdition( - SqlDatabasePremiumServiceObjective serviceObjective); + SqlDatabase.DefinitionStages.WithEditionDefaults + withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective); /** * Sets a "Premium" edition and maximum storage capacity for the SQL Database. @@ -799,12 +793,10 @@ interface WithMaxSizeBytes { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttachAllOptions - extends SqlDatabase.DefinitionStages.WithSku, - SqlDatabase.DefinitionStages.WithEditionDefaults, - SqlDatabase.DefinitionStages.WithCollation, - SqlDatabase.DefinitionStages.WithMaxSizeBytes, - SqlDatabase.DefinitionStages.WithAttachFinal { + interface WithAttachAllOptions extends SqlDatabase.DefinitionStages.WithSku, + SqlDatabase.DefinitionStages.WithEditionDefaults, + SqlDatabase.DefinitionStages.WithCollation, SqlDatabase.DefinitionStages.WithMaxSizeBytes, + SqlDatabase.DefinitionStages.WithAttachFinal { } /** @@ -820,12 +812,8 @@ interface WithAttachFinal extends Attachable.InDefinition { } /** The template for a SqlDatabase update operation, containing all the settings that can be modified. */ - interface Update - extends UpdateStages.WithEdition, - UpdateStages.WithElasticPoolName, - UpdateStages.WithMaxSizeBytes, - Resource.UpdateWithTags, - Appliable { + interface Update extends UpdateStages.WithEdition, UpdateStages.WithElasticPoolName, UpdateStages.WithMaxSizeBytes, + Resource.UpdateWithTags, Appliable { } /** Grouping of all the SqlDatabase update stages. */ @@ -880,8 +868,8 @@ interface WithEdition { * @param maxStorageCapacity edition to be set for database * @return The next stage of the definition */ - Update withStandardEdition( - SqlDatabaseStandardServiceObjective serviceObjective, SqlDatabaseStandardStorage maxStorageCapacity); + Update withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective, + SqlDatabaseStandardStorage maxStorageCapacity); /** * Sets a "Premium" edition for the SQL Database. @@ -898,8 +886,8 @@ Update withStandardEdition( * @param maxStorageCapacity edition to be set for database * @return The next stage of the definition */ - Update withPremiumEdition( - SqlDatabasePremiumServiceObjective serviceObjective, SqlDatabasePremiumStorage maxStorageCapacity); + Update withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective, + SqlDatabasePremiumStorage maxStorageCapacity); } /** The SQL Database definition to set the Max Size in Bytes for database. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseAutomaticTuning.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseAutomaticTuning.java index 0682cf7e1eda2..85b9bdcee5285 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseAutomaticTuning.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseAutomaticTuning.java @@ -13,10 +13,8 @@ /** An immutable client-side representation of an Azure SQL database automatic tuning object. */ @Fluent -public interface SqlDatabaseAutomaticTuning - extends HasInnerModel, - Refreshable, - Updatable { +public interface SqlDatabaseAutomaticTuning extends HasInnerModel, + Refreshable, Updatable { /** @return the database automatic tuning desired state */ AutomaticTuningMode desiredState(); @@ -34,10 +32,8 @@ public interface SqlDatabaseAutomaticTuning /** * The template for a SqlDatabaseAutomaticTuning update operation, containing all the settings that can be modified. */ - interface Update - extends SqlDatabaseAutomaticTuning.UpdateStages.WithAutomaticTuningMode, - SqlDatabaseAutomaticTuning.UpdateStages.WithAutomaticTuningOptions, - Appliable { + interface Update extends SqlDatabaseAutomaticTuning.UpdateStages.WithAutomaticTuningMode, + SqlDatabaseAutomaticTuning.UpdateStages.WithAutomaticTuningOptions, Appliable { } /** Grouping of all the SqlDatabaseAutomaticTuning update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseExportRequest.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseExportRequest.java index 218e32f5b0ea1..d3ed82970815c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseExportRequest.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseExportRequest.java @@ -11,15 +11,13 @@ /** An immutable client-side representation of an Azure SQL Database export operation request. */ @Fluent -public interface SqlDatabaseExportRequest - extends HasInnerModel, Executable, HasParent { +public interface SqlDatabaseExportRequest extends HasInnerModel, + Executable, HasParent { /** The entirety of database export operation definition. */ - interface SqlDatabaseExportRequestDefinition - extends SqlDatabaseExportRequest.DefinitionStages.ExportTo, - SqlDatabaseExportRequest.DefinitionStages.WithStorageTypeAndKey, - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword, - DefinitionStages.WithExecute { + interface SqlDatabaseExportRequestDefinition extends SqlDatabaseExportRequest.DefinitionStages.ExportTo, + SqlDatabaseExportRequest.DefinitionStages.WithStorageTypeAndKey, + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword, DefinitionStages.WithExecute { } /** Grouping of database export definition stages. */ @@ -38,8 +36,8 @@ interface ExportTo { * @param fileName the exported database file name * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword exportTo( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + exportTo(StorageAccount storageAccount, String containerName, String fileName); /** * @param storageAccountCreatable a storage account to be created as part of this execution flow @@ -47,8 +45,8 @@ SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword * @param fileName the exported database file name * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword exportTo( - Creatable storageAccountCreatable, String containerName, String fileName); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + exportTo(Creatable storageAccountCreatable, String containerName, String fileName); } /** Sets the storage key type and value to use. */ @@ -57,15 +55,15 @@ interface WithStorageTypeAndKey { * @param storageAccessKey the storage access key to use * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword withStorageAccessKey( - String storageAccessKey); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + withStorageAccessKey(String storageAccessKey); /** * @param sharedAccessKey the shared access key to use; it must be preceded with a "?." * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword withSharedAccessKey( - String sharedAccessKey); + SqlDatabaseExportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + withSharedAccessKey(String sharedAccessKey); } /** Sets the authentication type and SQL or Active Directory administrator login and password. */ @@ -75,16 +73,16 @@ interface WithAuthenticationTypeAndLoginPassword { * @param administratorPassword the SQL administrator password * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithExecute withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseExportRequest.DefinitionStages.WithExecute + withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword); /** * @param administratorLogin the Active Directory administrator login * @param administratorPassword the Active Directory administrator password * @return next definition stage */ - SqlDatabaseExportRequest.DefinitionStages.WithExecute withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseExportRequest.DefinitionStages.WithExecute + withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseImportRequest.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseImportRequest.java index 4613ec70a216e..822b7bc58d720 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseImportRequest.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseImportRequest.java @@ -10,15 +10,14 @@ /** An immutable client-side representation of an Azure SQL Database import operation request. */ @Fluent -public interface SqlDatabaseImportRequest - extends HasInnerModel, Executable, HasParent { +public interface SqlDatabaseImportRequest extends HasInnerModel, + Executable, HasParent { /** The entirety of database import operation definition. */ - interface SqlDatabaseImportRequestDefinition - extends SqlDatabaseImportRequest.DefinitionStages.ImportFrom, - SqlDatabaseImportRequest.DefinitionStages.WithStorageTypeAndKey, - SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword, - SqlDatabaseImportRequest.DefinitionStages.WithExecute { + interface SqlDatabaseImportRequestDefinition extends SqlDatabaseImportRequest.DefinitionStages.ImportFrom, + SqlDatabaseImportRequest.DefinitionStages.WithStorageTypeAndKey, + SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword, + SqlDatabaseImportRequest.DefinitionStages.WithExecute { } /** Grouping of database import definition stages. */ @@ -37,8 +36,8 @@ interface ImportFrom { * @param fileName the exported database file name * @return next definition stage */ - SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword importFrom( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + importFrom(StorageAccount storageAccount, String containerName, String fileName); } /** Sets the storage key type and value to use. */ @@ -47,15 +46,15 @@ interface WithStorageTypeAndKey { * @param storageAccessKey the storage access key to use * @return next definition stage */ - SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword withStorageAccessKey( - String storageAccessKey); + SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + withStorageAccessKey(String storageAccessKey); /** * @param sharedAccessKey the shared access key to use; it must be preceded with a "?." * @return next definition stage */ - SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword withSharedAccessKey( - String sharedAccessKey); + SqlDatabaseImportRequest.DefinitionStages.WithAuthenticationTypeAndLoginPassword + withSharedAccessKey(String sharedAccessKey); } /** Sets the authentication type and SQL or Active Directory administrator login and password. */ @@ -65,16 +64,16 @@ interface WithAuthenticationTypeAndLoginPassword { * @param administratorPassword the SQL administrator password * @return next definition stage */ - SqlDatabaseImportRequest.DefinitionStages.WithExecute withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseImportRequest.DefinitionStages.WithExecute + withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword); /** * @param administratorLogin the Active Directory administrator login * @param administratorPassword the Active Directory administrator password * @return next definition stage */ - SqlDatabaseImportRequest.DefinitionStages.WithExecute withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseImportRequest.DefinitionStages.WithExecute + withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseOperations.java index c28d925c22d7f..96ffbd3d10668 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseOperations.java @@ -17,19 +17,17 @@ public interface SqlDatabaseOperations /** Container interface for all the definitions that need to be implemented. */ interface SqlDatabaseOperationsDefinition - extends SqlDatabaseOperations.DefinitionStages.Blank, - SqlDatabaseOperations.DefinitionStages.WithSqlServer, - SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions, - SqlDatabaseOperations.DefinitionStages.WithElasticPoolName, - SqlDatabaseOperations.DefinitionStages.WithRestorableDroppedDatabase, - SqlDatabaseOperations.DefinitionStages.WithImportFrom, - SqlDatabaseOperations.DefinitionStages.WithStorageKey, - SqlDatabaseOperations.DefinitionStages.WithAuthentication, - SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabase, - SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, - SqlDatabaseOperations.DefinitionStages.WithCreateMode, - SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions, - SqlDatabaseOperations.DefinitionStages.WithCreateFinal { + extends SqlDatabaseOperations.DefinitionStages.Blank, SqlDatabaseOperations.DefinitionStages.WithSqlServer, + SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions, + SqlDatabaseOperations.DefinitionStages.WithElasticPoolName, + SqlDatabaseOperations.DefinitionStages.WithRestorableDroppedDatabase, + SqlDatabaseOperations.DefinitionStages.WithImportFrom, SqlDatabaseOperations.DefinitionStages.WithStorageKey, + SqlDatabaseOperations.DefinitionStages.WithAuthentication, + SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabase, + SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, + SqlDatabaseOperations.DefinitionStages.WithCreateMode, + SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions, + SqlDatabaseOperations.DefinitionStages.WithCreateFinal { } /** Grouping of all the SQL database definition stages. */ @@ -51,8 +49,8 @@ interface WithSqlServer { * @param location the parent SQL server location * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions withExistingSqlServer( - String resourceGroupName, String sqlServerName, String location); + SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions + withExistingSqlServer(String resourceGroupName, String sqlServerName, String location); /** * Sets the parent SQL server for the new SQL Database. @@ -64,14 +62,13 @@ SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions withExistingSqlSe } /** The SQL database interface with all starting options for definition. */ - interface WithAllDifferentOptions - extends SqlDatabaseOperations.DefinitionStages.WithElasticPoolName, - SqlDatabaseOperations.DefinitionStages.WithRestorableDroppedDatabase, - SqlDatabaseOperations.DefinitionStages.WithImportFrom, - SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabase, - SqlDatabaseOperations.DefinitionStages.WithSampleDatabase, - SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, - SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions { + interface WithAllDifferentOptions extends SqlDatabaseOperations.DefinitionStages.WithElasticPoolName, + SqlDatabaseOperations.DefinitionStages.WithRestorableDroppedDatabase, + SqlDatabaseOperations.DefinitionStages.WithImportFrom, + SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabase, + SqlDatabaseOperations.DefinitionStages.WithSampleDatabase, + SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, + SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions { } /** The SQL Database definition to set the elastic pool for database. */ @@ -115,17 +112,17 @@ interface WithElasticPoolName { * @param elasticPoolName the name of the new SQL Elastic Pool * @return the first stage of the new SQL Elastic Pool definition */ - SqlElasticPool.DefinitionStages.Blank defineElasticPool( - String elasticPoolName); + SqlElasticPool.DefinitionStages.Blank + defineElasticPool(String elasticPoolName); } /** The stage to decide whether using existing database or not. */ interface WithExistingDatabaseAfterElasticPool extends SqlDatabaseOperations.DefinitionStages.WithImportFromAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithSampleDatabaseAfterElasticPool, - SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, - SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions { + SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabaseAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithSampleDatabaseAfterElasticPool, + SqlDatabaseOperations.DefinitionStages.WithSourceDatabaseId, + SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions { } /** The SQL Database definition to import a BACPAC file as the source database. */ @@ -146,8 +143,8 @@ interface WithImportFrom { * @param fileName the exported database file name * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithAuthentication importFrom( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseOperations.DefinitionStages.WithAuthentication importFrom(StorageAccount storageAccount, + String containerName, String fileName); } /** Sets the storage key type and value to use. */ @@ -172,16 +169,16 @@ interface WithAuthentication { * @param administratorPassword the SQL administrator password * @return next definition stage */ - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withSqlAdministratorLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults + withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword); /** * @param administratorLogin the Active Directory administrator login * @param administratorPassword the Active Directory administrator password * @return next definition stage */ - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withActiveDirectoryLoginAndPassword( - String administratorLogin, String administratorPassword); + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults + withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword); } /** The SQL Database definition to import a BACPAC file as the source database. */ @@ -202,8 +199,8 @@ interface WithImportFromAfterElasticPool { * @param fileName the exported database file name * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool importFrom( - StorageAccount storageAccount, String containerName, String fileName); + SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool + importFrom(StorageAccount storageAccount, String containerName, String fileName); } /** Sets the storage key type and value to use. */ @@ -212,15 +209,15 @@ interface WithStorageKeyAfterElasticPool { * @param storageAccessKey the storage access key to use * @return next definition stage */ - SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool withStorageAccessKey( - String storageAccessKey); + SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool + withStorageAccessKey(String storageAccessKey); /** * @param sharedAccessKey the shared access key to use; it must be preceded with a "?." * @return next definition stage */ - SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool withSharedAccessKey( - String sharedAccessKey); + SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool + withSharedAccessKey(String sharedAccessKey); } /** Sets the authentication type and SQL or Active Directory administrator login and password. */ @@ -253,8 +250,8 @@ interface WithRestorableDroppedDatabase { * @param restorableDroppedDatabase the restorable dropped database * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithCreateFinal fromRestorableDroppedDatabase( - SqlRestorableDroppedDatabase restorableDroppedDatabase); + SqlDatabaseOperations.DefinitionStages.WithCreateFinal + fromRestorableDroppedDatabase(SqlRestorableDroppedDatabase restorableDroppedDatabase); } /** The SQL Database definition to set a restore point as the source database. */ @@ -274,8 +271,8 @@ interface WithRestorePointDatabase { * @param restorePointDateTime date and time to restore from * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions fromRestorePoint( - RestorePoint restorePoint, OffsetDateTime restorePointDateTime); + SqlDatabaseOperations.DefinitionStages.WithCreateAllOptions fromRestorePoint(RestorePoint restorePoint, + OffsetDateTime restorePointDateTime); } /** The SQL Database definition to set a restore point as the source database within an elastic pool. */ @@ -286,8 +283,8 @@ interface WithRestorePointDatabaseAfterElasticPool { * @param restorePoint the restore point * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions fromRestorePoint( - RestorePoint restorePoint); + SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions + fromRestorePoint(RestorePoint restorePoint); /** * Creates a new database from a restore point. @@ -296,8 +293,8 @@ SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions fromRes * @param restorePointDateTime date and time to restore from * @return The next stage of the definition. */ - SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions fromRestorePoint( - RestorePoint restorePoint, OffsetDateTime restorePointDateTime); + SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions + fromRestorePoint(RestorePoint restorePoint, OffsetDateTime restorePointDateTime); } /** The SQL Database definition to set a sample database as the source database within an elastic pool. */ @@ -362,8 +359,8 @@ interface WithCreateMode { /** The final stage of the SQL Database definition after the SQL Elastic Pool definition. */ interface WithCreateAfterElasticPoolOptions extends SqlDatabaseOperations.DefinitionStages.WithCollationAfterElasticPoolOptions, - SqlDatabaseOperations.DefinitionStages.WithMaxSizeBytesAfterElasticPoolOptions, - SqlDatabaseOperations.DefinitionStages.WithCreateFinal { + SqlDatabaseOperations.DefinitionStages.WithMaxSizeBytesAfterElasticPoolOptions, + SqlDatabaseOperations.DefinitionStages.WithCreateFinal { } /** The SQL Database definition to set the collation for database. */ @@ -425,8 +422,8 @@ interface WithEditionDefaults extends SqlDatabaseOperations.DefinitionStages.Wit * @param maxStorageCapacity the maximum storage capacity * @return The next stage of the definition */ - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withBasicEdition( - SqlDatabaseBasicStorage maxStorageCapacity); + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults + withBasicEdition(SqlDatabaseBasicStorage maxStorageCapacity); /** * Sets a "Standard" edition for the SQL Database. @@ -434,8 +431,8 @@ SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withBasicEdition( * @param serviceObjective edition to be set for database * @return The next stage of the definition */ - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withStandardEdition( - SqlDatabaseStandardServiceObjective serviceObjective); + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults + withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective); /** * Sets a "Standard" edition and maximum storage capacity for the SQL Database. @@ -453,8 +450,8 @@ SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withStandardEdition( * @param serviceObjective edition to be set for database * @return The next stage of the definition */ - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults withPremiumEdition( - SqlDatabasePremiumServiceObjective serviceObjective); + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults + withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective); /** * Sets a "Premium" edition and maximum storage capacity for the SQL Database. @@ -506,12 +503,11 @@ interface WithMaxSizeBytes { * A SQL Database definition with sufficient inputs to create a new SQL database in the cloud, but exposing * additional optional settings to specify. */ - interface WithCreateAllOptions - extends SqlDatabaseOperations.DefinitionStages.WithEdition, - SqlDatabaseOperations.DefinitionStages.WithEditionDefaults, - SqlDatabaseOperations.DefinitionStages.WithCollation, - SqlDatabaseOperations.DefinitionStages.WithMaxSizeBytes, - SqlDatabaseOperations.DefinitionStages.WithCreateFinal { + interface WithCreateAllOptions extends SqlDatabaseOperations.DefinitionStages.WithEdition, + SqlDatabaseOperations.DefinitionStages.WithEditionDefaults, + SqlDatabaseOperations.DefinitionStages.WithCollation, + SqlDatabaseOperations.DefinitionStages.WithMaxSizeBytes, + SqlDatabaseOperations.DefinitionStages.WithCreateFinal { } /** @@ -520,7 +516,7 @@ interface WithCreateAllOptions */ interface WithCreateFinal extends Resource.DefinitionWithTags, - Creatable { + Creatable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseThreatDetectionPolicy.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseThreatDetectionPolicy.java index 96434af6ffbcf..6300ecc4c4fc7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseThreatDetectionPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlDatabaseThreatDetectionPolicy.java @@ -20,12 +20,9 @@ /** A representation of the Azure SQL Database threat detection policy. */ @Fluent public interface SqlDatabaseThreatDetectionPolicy - extends ExternalChildResource, - HasParent, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { + extends ExternalChildResource, HasParent, + HasInnerModel, HasResourceGroup, Refreshable, + Updatable { /** @return the geo-location where the resource lives */ Region region(); @@ -93,14 +90,14 @@ interface SqlDatabaseThreatDetectionPolicyOperations /** Container interface for all the definitions that need to be implemented. */ interface SqlDatabaseThreatDetectionPolicyDefinition extends SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithSecurityAlertPolicyState, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageEndpoint, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithAlertsFilter, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailAddresses, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithRetentionDays, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailToAccountAdmins, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithCreate { + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithSecurityAlertPolicyState, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageEndpoint, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithAlertsFilter, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailAddresses, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithRetentionDays, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailToAccountAdmins, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithCreate { } /** Grouping of all the SQL database threat detection policy definition stages. */ @@ -142,8 +139,8 @@ interface WithStorageEndpoint { * blob storage will hold all Threat Detection audit logs. * @return the next stage of the definition */ - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey withStorageEndpoint( - String storageEndpoint); + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey + withStorageEndpoint(String storageEndpoint); } /** The SQL database threat detection policy definition to set the storage access key. */ @@ -154,8 +151,8 @@ interface WithStorageAccountAccessKey { * @param storageAccountAccessKey the storage access key * @return the next stage of the definition */ - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithCreate withStorageAccountAccessKey( - String storageAccountAccessKey); + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithCreate + withStorageAccountAccessKey(String storageAccountAccessKey); } /** @@ -243,14 +240,13 @@ interface WithEmailToAccountAdmins { } /** The final stage of the SQL database threat detection policy definition. */ - interface WithCreate - extends SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageEndpoint, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithAlertsFilter, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailAddresses, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithRetentionDays, - SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailToAccountAdmins, - Creatable { + interface WithCreate extends SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageEndpoint, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithStorageAccountAccessKey, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithAlertsFilter, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailAddresses, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithRetentionDays, + SqlDatabaseThreatDetectionPolicy.DefinitionStages.WithEmailToAccountAdmins, + Creatable { } } @@ -258,15 +254,10 @@ interface WithCreate * The template for a SQL database threat detection policy update operation, containing all the settings that can be * modified. */ - interface Update - extends UpdateStages.WithSecurityAlertPolicyState, - UpdateStages.WithStorageEndpoint, - UpdateStages.WithStorageAccountAccessKey, - UpdateStages.WithAlertsFilter, - UpdateStages.WithEmailAddresses, - UpdateStages.WithRetentionDays, - UpdateStages.WithEmailToAccountAdmins, - Appliable { + interface Update extends UpdateStages.WithSecurityAlertPolicyState, UpdateStages.WithStorageEndpoint, + UpdateStages.WithStorageAccountAccessKey, UpdateStages.WithAlertsFilter, UpdateStages.WithEmailAddresses, + UpdateStages.WithRetentionDays, UpdateStages.WithEmailToAccountAdmins, + Appliable { } /** Grouping of all the SQL database threat detection policy update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPool.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPool.java index 343ecac5e0185..80f506a60c177 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPool.java @@ -22,12 +22,8 @@ /** An immutable client-side representation of an Azure SQL Elastic Pool. */ @Fluent -public interface SqlElasticPool - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { +public interface SqlElasticPool extends ExternalChildResource, + HasInnerModel, HasResourceGroup, Refreshable, Updatable { /** @return name of the SQL Server to which this elastic pool belongs */ String sqlServerName(); @@ -144,12 +140,9 @@ public interface SqlElasticPool * @param the stage of the parent definition to return to after attaching this definition */ interface SqlElasticPoolDefinition - extends DefinitionStages.Blank, - DefinitionStages.WithEdition, - DefinitionStages.WithBasicEdition, - DefinitionStages.WithStandardEdition, - DefinitionStages.WithPremiumEdition, - DefinitionStages.WithAttach { + extends DefinitionStages.Blank, DefinitionStages.WithEdition, + DefinitionStages.WithBasicEdition, DefinitionStages.WithStandardEdition, + DefinitionStages.WithPremiumEdition, DefinitionStages.WithAttach { } /** Grouping of all the storage account definition stages. */ @@ -227,8 +220,8 @@ interface WithBasicEdition extends SqlElasticPool.DefinitionStages.With * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithBasicEdition withDatabaseDtuMax( - SqlElasticPoolBasicMaxEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithBasicEdition + withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -236,8 +229,8 @@ SqlElasticPool.DefinitionStages.WithBasicEdition withDatabaseDtuMax( * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithBasicEdition withDatabaseDtuMin( - SqlElasticPoolBasicMinEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithBasicEdition + withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs eDTU); } /** @@ -252,8 +245,8 @@ interface WithStandardEdition extends SqlElasticPool.DefinitionStages.W * @param eDTU total shared eDTU for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithStandardEdition withReservedDtu( - SqlElasticPoolStandardEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithStandardEdition + withReservedDtu(SqlElasticPoolStandardEDTUs eDTU); /** * Sets the maximum number of eDTU a database in the pool can consume. @@ -261,8 +254,8 @@ SqlElasticPool.DefinitionStages.WithStandardEdition withReservedDtu( * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithStandardEdition withDatabaseDtuMax( - SqlElasticPoolStandardMaxEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithStandardEdition + withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -270,8 +263,8 @@ SqlElasticPool.DefinitionStages.WithStandardEdition withDatabaseDtuMax( * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithStandardEdition withDatabaseDtuMin( - SqlElasticPoolStandardMinEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithStandardEdition + withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs eDTU); /** * Sets the storage capacity for the SQL Azure Database Elastic Pool. @@ -279,8 +272,8 @@ SqlElasticPool.DefinitionStages.WithStandardEdition withDatabaseDtuMin( * @param storageCapacity storage capacity for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithStandardEdition withStorageCapacity( - SqlElasticPoolStandardStorage storageCapacity); + SqlElasticPool.DefinitionStages.WithStandardEdition + withStorageCapacity(SqlElasticPoolStandardStorage storageCapacity); } /** @@ -295,8 +288,8 @@ interface WithPremiumEdition extends SqlElasticPool.DefinitionStages.Wi * @param eDTU total shared eDTU for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithPremiumEdition withReservedDtu( - SqlElasticPoolPremiumEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithPremiumEdition + withReservedDtu(SqlElasticPoolPremiumEDTUs eDTU); /** * Sets the maximum number of eDTU a database in the pool can consume. @@ -304,8 +297,8 @@ SqlElasticPool.DefinitionStages.WithPremiumEdition withReservedDtu( * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithPremiumEdition withDatabaseDtuMax( - SqlElasticPoolPremiumMaxEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithPremiumEdition + withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -313,8 +306,8 @@ SqlElasticPool.DefinitionStages.WithPremiumEdition withDatabaseDtuMax( * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithPremiumEdition withDatabaseDtuMin( - SqlElasticPoolPremiumMinEDTUs eDTU); + SqlElasticPool.DefinitionStages.WithPremiumEdition + withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs eDTU); /** * Sets the storage capacity for the SQL Azure Database Elastic Pool. @@ -322,8 +315,8 @@ SqlElasticPool.DefinitionStages.WithPremiumEdition withDatabaseDtuMin( * @param storageCapacity storage capacity for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPool.DefinitionStages.WithPremiumEdition withStorageCapacity( - SqlElasticPoolPremiumSorage storageCapacity); + SqlElasticPool.DefinitionStages.WithPremiumEdition + withStorageCapacity(SqlElasticPoolPremiumSorage storageCapacity); } /** @@ -379,23 +372,15 @@ interface WithStorageCapacity { * * @param the stage of the parent definition to return to after attaching this definition */ - interface WithAttach - extends WithDatabaseMinCapacity, - WithDatabaseMaxCapacity, - WithStorageCapacity, - Attachable.InDefinition { + interface WithAttach extends WithDatabaseMinCapacity, WithDatabaseMaxCapacity, + WithStorageCapacity, Attachable.InDefinition { } } /** The template for a SQL Elastic Pool update operation, containing all the settings that can be modified. */ - interface Update - extends UpdateStages.WithReservedDTUAndStorageCapacity, - UpdateStages.WithDatabaseMinCapacity, - UpdateStages.WithDatabaseMaxCapacity, - UpdateStages.WithStorageCapacity, - UpdateStages.WithDatabase, - Resource.UpdateWithTags, - Appliable { + interface Update extends UpdateStages.WithReservedDTUAndStorageCapacity, UpdateStages.WithDatabaseMinCapacity, + UpdateStages.WithDatabaseMaxCapacity, UpdateStages.WithStorageCapacity, UpdateStages.WithDatabase, + Resource.UpdateWithTags, Appliable { } /** Grouping of all the SQL Elastic Pool update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPoolOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPoolOperations.java index 38f1089969f56..be5f8c0c968fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPoolOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlElasticPoolOperations.java @@ -10,17 +10,15 @@ /** A representation of the Azure SQL Elastic Pool operations. */ @Fluent -public interface SqlElasticPoolOperations - extends SupportsCreating, - SqlChildrenOperations { +public interface SqlElasticPoolOperations extends + SupportsCreating, SqlChildrenOperations { /** Container interface for all the definitions that need to be implemented. */ - interface SqlElasticPoolOperationsDefinition - extends SqlElasticPoolOperations.DefinitionStages.WithSqlServer, - SqlElasticPoolOperations.DefinitionStages.WithEdition, - SqlElasticPoolOperations.DefinitionStages.WithBasicEdition, - SqlElasticPoolOperations.DefinitionStages.WithStandardEdition, - SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition { + interface SqlElasticPoolOperationsDefinition extends SqlElasticPoolOperations.DefinitionStages.WithSqlServer, + SqlElasticPoolOperations.DefinitionStages.WithEdition, + SqlElasticPoolOperations.DefinitionStages.WithBasicEdition, + SqlElasticPoolOperations.DefinitionStages.WithStandardEdition, + SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition { } /** Grouping of all the SQL Elastic Pool definition stages. */ @@ -35,8 +33,8 @@ interface WithSqlServer { * @param location the parent SQL server location * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithEdition withExistingSqlServer( - String resourceGroupName, String sqlServerName, String location); + SqlElasticPoolOperations.DefinitionStages.WithEdition withExistingSqlServer(String resourceGroupName, + String sqlServerName, String location); /** * Sets the parent SQL server for the new Elastic Pool. @@ -104,8 +102,8 @@ interface WithBasicEdition extends SqlElasticPoolOperations.DefinitionStages.Wit * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithBasicEdition withDatabaseDtuMax( - SqlElasticPoolBasicMaxEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithBasicEdition + withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -113,8 +111,8 @@ SqlElasticPoolOperations.DefinitionStages.WithBasicEdition withDatabaseDtuMax( * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithBasicEdition withDatabaseDtuMin( - SqlElasticPoolBasicMinEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithBasicEdition + withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs eDTU); } /** The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a standard pool. */ @@ -125,8 +123,8 @@ interface WithStandardEdition extends SqlElasticPoolOperations.DefinitionStages. * @param eDTU total shared eDTU for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withReservedDtu( - SqlElasticPoolStandardEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithStandardEdition + withReservedDtu(SqlElasticPoolStandardEDTUs eDTU); /** * Sets the maximum number of eDTU a database in the pool can consume. @@ -134,8 +132,8 @@ SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withReservedDtu( * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withDatabaseDtuMax( - SqlElasticPoolStandardMaxEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithStandardEdition + withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -143,8 +141,8 @@ SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withDatabaseDtuMax * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withDatabaseDtuMin( - SqlElasticPoolStandardMinEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithStandardEdition + withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs eDTU); /** * Sets the storage capacity for the SQL Azure Database Elastic Pool. @@ -152,8 +150,8 @@ SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withDatabaseDtuMin * @param storageCapacity storage capacity for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithStandardEdition withStorageCapacity( - SqlElasticPoolStandardStorage storageCapacity); + SqlElasticPoolOperations.DefinitionStages.WithStandardEdition + withStorageCapacity(SqlElasticPoolStandardStorage storageCapacity); } /** The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a premium pool. */ @@ -164,8 +162,8 @@ interface WithPremiumEdition extends SqlElasticPoolOperations.DefinitionStages.W * @param eDTU total shared eDTU for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withReservedDtu( - SqlElasticPoolPremiumEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition + withReservedDtu(SqlElasticPoolPremiumEDTUs eDTU); /** * Sets the maximum number of eDTU a database in the pool can consume. @@ -173,8 +171,8 @@ SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withReservedDtu( * @param eDTU maximum eDTU a database in the pool can consume * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withDatabaseDtuMax( - SqlElasticPoolPremiumMaxEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition + withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs eDTU); /** * Sets the minimum number of eDTU for each database in the pool are regardless of its activity. @@ -182,8 +180,8 @@ SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withDatabaseDtuMax( * @param eDTU minimum eDTU for all SQL Azure databases * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withDatabaseDtuMin( - SqlElasticPoolPremiumMinEDTUs eDTU); + SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition + withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs eDTU); /** * Sets the storage capacity for the SQL Azure Database Elastic Pool. @@ -191,8 +189,8 @@ SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withDatabaseDtuMin( * @param storageCapacity storage capacity for the SQL Azure Database Elastic Pool * @return The next stage of the definition. */ - SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition withStorageCapacity( - SqlElasticPoolPremiumSorage storageCapacity); + SqlElasticPoolOperations.DefinitionStages.WithPremiumEdition + withStorageCapacity(SqlElasticPoolPremiumSorage storageCapacity); } /** The SQL Elastic Pool definition to set the minimum capacity for database. */ @@ -262,21 +260,20 @@ interface WithDatabase { * @param databaseName the name of the new SQL Database * @return the first stage of the new SQL Database definition */ - SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool defineDatabase( - String databaseName); + SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool + defineDatabase(String databaseName); } /** * A SQL Server definition with sufficient inputs to create a new SQL Elastic Pool in the cloud, but exposing * additional optional inputs to specify. */ - interface WithCreate - extends SqlElasticPoolOperations.DefinitionStages.WithDatabaseMinCapacity, - SqlElasticPoolOperations.DefinitionStages.WithDatabaseMaxCapacity, - SqlElasticPoolOperations.DefinitionStages.WithStorageCapacity, - SqlElasticPoolOperations.DefinitionStages.WithDatabase, - Resource.DefinitionWithTags, - Creatable { + interface WithCreate extends SqlElasticPoolOperations.DefinitionStages.WithDatabaseMinCapacity, + SqlElasticPoolOperations.DefinitionStages.WithDatabaseMaxCapacity, + SqlElasticPoolOperations.DefinitionStages.WithStorageCapacity, + SqlElasticPoolOperations.DefinitionStages.WithDatabase, + Resource.DefinitionWithTags, + Creatable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlEncryptionProtector.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlEncryptionProtector.java index 2d3fccf9d4151..6533d9a54f8fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlEncryptionProtector.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlEncryptionProtector.java @@ -15,13 +15,8 @@ /** An immutable client-side representation of an Azure SQL Encryption Protector. */ @Fluent -public interface SqlEncryptionProtector - extends HasId, - HasInnerModel, - HasResourceGroup, - Indexable, - Refreshable, - Updatable { +public interface SqlEncryptionProtector extends HasId, HasInnerModel, HasResourceGroup, + Indexable, Refreshable, Updatable { /** @return name of the SQL Server to which this DNS alias belongs */ String sqlServerName(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroup.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroup.java index a7b90ff608968..d418c8772e9c7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroup.java @@ -15,12 +15,8 @@ /** An immutable client-side representation of an Azure SQL Failover Group. */ @Fluent -public interface SqlFailoverGroup - extends Resource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { +public interface SqlFailoverGroup extends Resource, HasInnerModel, HasResourceGroup, + Refreshable, Updatable { /** @return name of the SQL Server to which this Failover Group belongs */ String sqlServerName(); @@ -60,12 +56,9 @@ public interface SqlFailoverGroup Mono deleteAsync(); /** The template for a SQL Failover Group update operation, containing all the settings that can be modified. */ - interface Update - extends SqlFailoverGroup.UpdateStages.WithReadWriteEndpointPolicy, - SqlFailoverGroup.UpdateStages.WithReadOnlyEndpointPolicy, - SqlFailoverGroup.UpdateStages.WithDatabase, - Resource.UpdateWithTags, - Appliable { + interface Update extends SqlFailoverGroup.UpdateStages.WithReadWriteEndpointPolicy, + SqlFailoverGroup.UpdateStages.WithReadOnlyEndpointPolicy, SqlFailoverGroup.UpdateStages.WithDatabase, + Resource.UpdateWithTags, Appliable { } /** Grouping of all the SQL Virtual Network Rule update stages. */ @@ -79,8 +72,8 @@ interface WithReadWriteEndpointPolicy { * read-write endpoint * @return the next stage of the definition */ - SqlFailoverGroup.Update withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod( - int gracePeriodInMinutes); + SqlFailoverGroup.Update + withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(int gracePeriodInMinutes); /** * Sets the SQL Failover Group read-write endpoint failover policy as "Manual". diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroupOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroupOperations.java index 14824baae244c..9903bfeea77fd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroupOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFailoverGroupOperations.java @@ -12,7 +12,7 @@ @Fluent public interface SqlFailoverGroupOperations extends SupportsCreating, - SqlChildrenOperations { + SqlChildrenOperations { /** * Fails over from the current primary server to this server. @@ -52,17 +52,16 @@ public interface SqlFailoverGroupOperations * @param failoverGroupName the name of the failover group * @return a representation of the deferred computation of this call returning the SqlFailoverGroup object */ - Mono forceFailoverAllowDataLossAsync( - String resourceGroupName, String serverName, String failoverGroupName); + Mono forceFailoverAllowDataLossAsync(String resourceGroupName, String serverName, + String failoverGroupName); /** Container interface for all the definitions that need to be implemented. */ - interface SqlFailoverGroupOperationsDefinition - extends SqlFailoverGroupOperations.DefinitionStages.WithSqlServer, - SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy, - SqlFailoverGroupOperations.DefinitionStages.WithReadOnlyEndpointPolicy, - SqlFailoverGroupOperations.DefinitionStages.WithPartnerServer, - SqlFailoverGroupOperations.DefinitionStages.WithDatabase, - SqlFailoverGroupOperations.DefinitionStages.WithCreate { + interface SqlFailoverGroupOperationsDefinition extends SqlFailoverGroupOperations.DefinitionStages.WithSqlServer, + SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy, + SqlFailoverGroupOperations.DefinitionStages.WithReadOnlyEndpointPolicy, + SqlFailoverGroupOperations.DefinitionStages.WithPartnerServer, + SqlFailoverGroupOperations.DefinitionStages.WithDatabase, + SqlFailoverGroupOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Failover Group definition stages. */ @@ -77,8 +76,8 @@ interface WithSqlServer { * @param location the parent SQL server location * @return the next stage of the definition */ - SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy withExistingSqlServer( - String resourceGroupName, String sqlServerName, String location); + SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy + withExistingSqlServer(String resourceGroupName, String sqlServerName, String location); /** * Sets the parent SQL server for the new Failover Group. @@ -86,8 +85,8 @@ SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy withExis * @param sqlServer the parent SQL server * @return the next stage of the definition */ - SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy withExistingSqlServer( - SqlServer sqlServer); + SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy + withExistingSqlServer(SqlServer sqlServer); } /** The SQL Failover Group definition to set the read-write endpoint failover policy. */ @@ -158,11 +157,10 @@ interface WithDatabase { } /** The final stage of the SQL Failover Group definition. */ - interface WithCreate - extends SqlFailoverGroupOperations.DefinitionStages.WithReadOnlyEndpointPolicy, - SqlFailoverGroupOperations.DefinitionStages.WithDatabase, - Resource.DefinitionWithTags, - Creatable { + interface WithCreate extends SqlFailoverGroupOperations.DefinitionStages.WithReadOnlyEndpointPolicy, + SqlFailoverGroupOperations.DefinitionStages.WithDatabase, + Resource.DefinitionWithTags, + Creatable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRule.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRule.java index 15d3cc5fa76e7..62b5a0cd3024d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRule.java @@ -17,11 +17,8 @@ /** An immutable client-side representation of an Azure SQL Server Firewall Rule. */ @Fluent public interface SqlFirewallRule - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { + extends ExternalChildResource, HasInnerModel, HasResourceGroup, + Refreshable, Updatable { /** @return name of the SQL Server to which this Firewall Rule belongs */ String sqlServerName(); @@ -60,11 +57,10 @@ public interface SqlFirewallRule * * @param the stage of the parent definition to return to after attaching this definition */ - interface SqlFirewallRuleDefinition - extends SqlFirewallRule.DefinitionStages.Blank, - SqlFirewallRule.DefinitionStages.WithIpAddress, - SqlFirewallRule.DefinitionStages.WithIpAddressRange, - SqlFirewallRule.DefinitionStages.WithAttach { + interface SqlFirewallRuleDefinition extends SqlFirewallRule.DefinitionStages.Blank, + SqlFirewallRule.DefinitionStages.WithIpAddress, + SqlFirewallRule.DefinitionStages.WithIpAddressRange, + SqlFirewallRule.DefinitionStages.WithAttach { } /** Grouping of all the SQL Firewall Rule definition stages. */ @@ -74,9 +70,8 @@ interface DefinitionStages { * * @param the stage of the parent definition to return to after attaching this definition */ - interface Blank - extends SqlFirewallRule.DefinitionStages.WithIpAddressRange, - SqlFirewallRule.DefinitionStages.WithIpAddress { + interface Blank extends SqlFirewallRule.DefinitionStages.WithIpAddressRange, + SqlFirewallRule.DefinitionStages.WithIpAddress { } /** The SQL Firewall Rule definition to set the Ip address range for the parent SQL Server. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRuleOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRuleOperations.java index 50792711c7ce0..1265fd2b295a4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRuleOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlFirewallRuleOperations.java @@ -8,15 +8,13 @@ /** A representation of the Azure SQL Firewall rule operations. */ @Fluent -public interface SqlFirewallRuleOperations - extends SupportsCreating, - SqlChildrenOperations { +public interface SqlFirewallRuleOperations extends + SupportsCreating, SqlChildrenOperations { /** Container interface for all the definitions that need to be implemented. */ - interface SqlFirewallRuleOperationsDefinition - extends SqlFirewallRuleOperations.DefinitionStages.WithSqlServer, - SqlFirewallRuleOperations.DefinitionStages.WithIpAddressRange, - SqlFirewallRuleOperations.DefinitionStages.WithCreate { + interface SqlFirewallRuleOperationsDefinition extends SqlFirewallRuleOperations.DefinitionStages.WithSqlServer, + SqlFirewallRuleOperations.DefinitionStages.WithIpAddressRange, + SqlFirewallRuleOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Firewall rule definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlRestorableDroppedDatabase.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlRestorableDroppedDatabase.java index ec20026f1b3c8..13c7bddf49d64 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlRestorableDroppedDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlRestorableDroppedDatabase.java @@ -15,12 +15,8 @@ /** Response containing Azure SQL restorable dropped database. */ @Fluent -public interface SqlRestorableDroppedDatabase - extends Refreshable, - HasInnerModel, - HasResourceGroup, - HasName, - HasId { +public interface SqlRestorableDroppedDatabase extends Refreshable, + HasInnerModel, HasResourceGroup, HasName, HasId { /** @return the geo-location where the resource lives */ Region region(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServer.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServer.java index 351941055b810..c68372c76f355 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServer.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServer.java @@ -153,15 +153,9 @@ public interface SqlServer /** Container interface for all the definitions that need to be implemented. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithAdministratorLogin, - DefinitionStages.WithAdministratorPassword, - DefinitionStages.WithElasticPool, - DefinitionStages.WithDatabase, - DefinitionStages.WithFirewallRule, - DefinitionStages.WithPublicNetworkAccess, - DefinitionStages.WithCreate { + extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithAdministratorLogin, + DefinitionStages.WithAdministratorPassword, DefinitionStages.WithElasticPool, DefinitionStages.WithDatabase, + DefinitionStages.WithFirewallRule, DefinitionStages.WithPublicNetworkAccess, DefinitionStages.WithCreate { } /** Grouping of all the storage account definition stages. */ @@ -272,11 +266,10 @@ interface WithVirtualNetworkRule { * @param virtualNetworkRuleName the name of the new SQL Virtual Network Rule * @return the first stage of the new SQL Virtual Network Rule definition */ - SqlVirtualNetworkRule.DefinitionStages.Blank defineVirtualNetworkRule( - String virtualNetworkRuleName); + SqlVirtualNetworkRule.DefinitionStages.Blank + defineVirtualNetworkRule(String virtualNetworkRuleName); } - /** The stage of SQL Server definition allowing to configure network access settings. */ interface WithPublicNetworkAccess { /** @@ -291,29 +284,16 @@ interface WithPublicNetworkAccess { * A SQL Server definition with sufficient inputs to create a new SQL Server in the cloud, but exposing * additional optional inputs to specify. */ - interface WithCreate - extends Creatable, - WithActiveDirectoryAdministrator, - WithSystemAssignedManagedServiceIdentity, - WithElasticPool, - WithDatabase, - WithFirewallRule, - WithVirtualNetworkRule, - WithPublicNetworkAccess, - DefinitionWithTags { + interface WithCreate extends Creatable, WithActiveDirectoryAdministrator, + WithSystemAssignedManagedServiceIdentity, WithElasticPool, WithDatabase, WithFirewallRule, + WithVirtualNetworkRule, WithPublicNetworkAccess, DefinitionWithTags { } } /** The template for a SQLServer update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithAdministratorPassword, - UpdateStages.WithElasticPool, - UpdateStages.WithDatabase, - UpdateStages.WithFirewallRule, - UpdateStages.WithSystemAssignedManagedServiceIdentity, - UpdateStages.WithPublicNetworkAccess, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithAdministratorPassword, UpdateStages.WithElasticPool, + UpdateStages.WithDatabase, UpdateStages.WithFirewallRule, UpdateStages.WithSystemAssignedManagedServiceIdentity, + UpdateStages.WithPublicNetworkAccess, Resource.UpdateWithTags { } /** Grouping of all the SQLServer update stages. */ @@ -347,8 +327,7 @@ interface WithElasticPool { * @param elasticPoolName the name of the new SQL Elastic Pool * @return the first stage of the new SQL Elastic Pool definition */ - SqlElasticPool.DefinitionStages.Blank defineElasticPool( - String elasticPoolName); + SqlElasticPool.DefinitionStages.Blank defineElasticPool(String elasticPoolName); /** * Removes elastic pool from the SQL Server. @@ -386,8 +365,7 @@ interface WithFirewallRule { * @param firewallRuleName the name of the new SQL Firewall rule * @return the first stage of the new SQL Firewall rule definition */ - SqlFirewallRule.DefinitionStages.Blank defineFirewallRule( - String firewallRuleName); + SqlFirewallRule.DefinitionStages.Blank defineFirewallRule(String firewallRuleName); /** * Removes firewall rule from the SQL Server. @@ -406,6 +384,7 @@ interface WithPublicNetworkAccess { * @return the next stage of the update */ Update enablePublicNetworkAccess(); + /** * Disables public network access for the SQL Server. * diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerAutomaticTuning.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerAutomaticTuning.java index e36452105adab..a73e319e9b5d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerAutomaticTuning.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerAutomaticTuning.java @@ -13,10 +13,8 @@ /** An immutable client-side representation of an Azure SQL Server automatic tuning object. */ @Fluent -public interface SqlServerAutomaticTuning - extends HasInnerModel, - Refreshable, - Updatable { +public interface SqlServerAutomaticTuning extends HasInnerModel, + Refreshable, Updatable { /** @return the server automatic tuning desired state */ AutomaticTuningServerMode desiredState(); @@ -34,10 +32,8 @@ public interface SqlServerAutomaticTuning /** * The template for a SqlServerAutomaticTuning update operation, containing all the settings that can be modified. */ - interface Update - extends SqlServerAutomaticTuning.UpdateStages.WithAutomaticTuningMode, - SqlServerAutomaticTuning.UpdateStages.WithAutomaticTuningOptions, - Appliable { + interface Update extends SqlServerAutomaticTuning.UpdateStages.WithAutomaticTuningMode, + SqlServerAutomaticTuning.UpdateStages.WithAutomaticTuningOptions, Appliable { } /** Grouping of all the SqlServerAutomaticTuning update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAlias.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAlias.java index 00363d9b78b04..da49a81e1efca 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAlias.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAlias.java @@ -14,13 +14,8 @@ /** An immutable client-side representation of an Azure SQL Server DNS alias. */ @Fluent -public interface SqlServerDnsAlias - extends HasId, - HasInnerModel, - HasName, - HasResourceGroup, - Indexable, - Refreshable { +public interface SqlServerDnsAlias extends HasId, HasInnerModel, HasName, HasResourceGroup, + Indexable, Refreshable { /** @return name of the SQL Server to which this DNS alias belongs */ String sqlServerName(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAliasOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAliasOperations.java index 603b9a22abe96..0756fb727102f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAliasOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerDnsAliasOperations.java @@ -11,7 +11,7 @@ @Fluent public interface SqlServerDnsAliasOperations extends SupportsCreating, - SqlChildrenOperations { + SqlChildrenOperations { /** * Acquires server DNS alias from another server. @@ -54,9 +54,8 @@ public interface SqlServerDnsAliasOperations Mono acquireAsync(String dnsAliasName, String oldSqlServerId, String newSqlServerId); /** Container interface for all the definitions that need to be implemented. */ - interface SqlServerDnsAliasOperationsDefinition - extends SqlServerDnsAliasOperations.DefinitionStages.WithSqlServer, - SqlServerDnsAliasOperations.DefinitionStages.WithCreate { + interface SqlServerDnsAliasOperationsDefinition extends SqlServerDnsAliasOperations.DefinitionStages.WithSqlServer, + SqlServerDnsAliasOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Server DNS alias definition stages. */ @@ -70,8 +69,8 @@ interface WithSqlServer { * @param sqlServerName the parent SQL server name * @return The next stage of the definition. */ - SqlServerDnsAliasOperations.DefinitionStages.WithCreate withExistingSqlServer( - String resourceGroupName, String sqlServerName); + SqlServerDnsAliasOperations.DefinitionStages.WithCreate withExistingSqlServer(String resourceGroupName, + String sqlServerName); /** * Sets the parent SQL server for the new Server DNS alias. diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKey.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKey.java index e4b7e88a0fed4..02f5fb10e85c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKey.java @@ -18,12 +18,7 @@ /** An immutable client-side representation of an Azure SQL Server Key. */ @Fluent public interface SqlServerKey - extends HasId, - HasInnerModel, - HasName, - HasResourceGroup, - Indexable, - Refreshable { + extends HasId, HasInnerModel, HasName, HasResourceGroup, Indexable, Refreshable { /** @return name of the SQL Server to which this DNS alias belongs */ String sqlServerName(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKeyOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKeyOperations.java index 626dcca291533..ce52782a11ab6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKeyOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerKeyOperations.java @@ -17,10 +17,8 @@ public interface SqlServerKeyOperations extends SqlChildrenOperations { + interface WithCreate extends Creatable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicy.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicy.java index 16d3c8ec740f1..fa7b864d40d1e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicy.java @@ -17,13 +17,8 @@ /** An immutable client-side representation of an Azure SQL Server Security Alert Policy. */ @Fluent public interface SqlServerSecurityAlertPolicy - extends HasId, - HasInnerModel, - HasName, - HasResourceGroup, - Indexable, - Refreshable, - Updatable { + extends HasId, HasInnerModel, HasName, HasResourceGroup, Indexable, + Refreshable, Updatable { /** @return name of the SQL Server to which this DNS alias belongs */ String sqlServerName(); @@ -59,14 +54,12 @@ public interface SqlServerSecurityAlertPolicy * The template for a SQL Server Security Alert Policy update operation, containing all the settings that can be * modified. */ - interface Update - extends SqlServerSecurityAlertPolicy.UpdateStages.WithState, - SqlServerSecurityAlertPolicy.UpdateStages.WithEmailAccountAdmins, - SqlServerSecurityAlertPolicy.UpdateStages.WithStorageAccount, - SqlServerSecurityAlertPolicy.UpdateStages.WithEmailAddresses, - SqlServerSecurityAlertPolicy.UpdateStages.WithDisabledAlerts, - SqlServerSecurityAlertPolicy.UpdateStages.WithRetentionDays, - Appliable { + interface Update extends SqlServerSecurityAlertPolicy.UpdateStages.WithState, + SqlServerSecurityAlertPolicy.UpdateStages.WithEmailAccountAdmins, + SqlServerSecurityAlertPolicy.UpdateStages.WithStorageAccount, + SqlServerSecurityAlertPolicy.UpdateStages.WithEmailAddresses, + SqlServerSecurityAlertPolicy.UpdateStages.WithDisabledAlerts, + SqlServerSecurityAlertPolicy.UpdateStages.WithRetentionDays, Appliable { } /** Grouping of all the SQL Server Security Alert Policy update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicyOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicyOperations.java index d32695a28242f..d3eb007959797 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicyOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServerSecurityAlertPolicyOperations.java @@ -75,13 +75,13 @@ public interface SqlServerSecurityAlertPolicyOperations { /** Container interface for all the definitions that need to be implemented. */ interface SqlServerSecurityAlertPolicyOperationsDefinition extends SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithSqlServer, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAccountAdmins, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithStorageAccount, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAddresses, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithDisabledAlerts, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithRetentionDays, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate { + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAccountAdmins, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithStorageAccount, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAddresses, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithDisabledAlerts, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithRetentionDays, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Server Security Alert Policy definition stages. */ @@ -95,8 +95,8 @@ interface WithSqlServer { * @param sqlServerName the parent SQL server name * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState withExistingSqlServer( - String resourceGroupName, String sqlServerName); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState + withExistingSqlServer(String resourceGroupName, String sqlServerName); /** * Sets the parent SQL server for the new Server Security Alert Policy. @@ -104,8 +104,8 @@ SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState withExistingSq * @param sqlServerId the parent SQL server ID * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState withExistingSqlServerId( - String sqlServerId); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState + withExistingSqlServerId(String sqlServerId); /** * Sets the parent SQL server for the new Server Security Alert Policy. @@ -113,8 +113,8 @@ SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState withExistingSq * @param sqlServer the parent SQL server * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState withExistingSqlServer( - SqlServer sqlServer); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithState + withExistingSqlServer(SqlServer sqlServer); } /** The SQL Server Security Alert Policy definition to set the state. */ @@ -125,8 +125,8 @@ interface WithState { * @param state the state of the policy, whether it is enabled or disabled * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAccountAdmins withState( - SecurityAlertPolicyState state); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAccountAdmins + withState(SecurityAlertPolicyState state); } /** @@ -161,8 +161,8 @@ interface WithStorageAccount { * @param storageAccessKey the identifier key of the Threat Detection audit storage account * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate withStorageEndpoint( - String storageEndpointUri, String storageAccessKey); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate + withStorageEndpoint(String storageEndpointUri, String storageAccessKey); } /** @@ -176,8 +176,8 @@ interface WithEmailAddresses { * @param emailAddresses an array of e-mail addresses to which the alert is sent to * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate withEmailAddresses( - String... emailAddresses); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate + withEmailAddresses(String... emailAddresses); } /** The SQL Server Security Alert Policy definition to set an array of alerts that are disabled. */ @@ -188,8 +188,8 @@ interface WithDisabledAlerts { * @param disabledAlerts an array of alerts that are disabled * @return The next stage of the definition. */ - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate withDisabledAlerts( - String... disabledAlerts); + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithCreate + withDisabledAlerts(String... disabledAlerts); } /** @@ -207,11 +207,10 @@ interface WithRetentionDays { } /** The final stage of the SQL Server Security Alert Policy definition. */ - interface WithCreate - extends SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAddresses, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithDisabledAlerts, - SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithRetentionDays, - Creatable { + interface WithCreate extends SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithEmailAddresses, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithDisabledAlerts, + SqlServerSecurityAlertPolicyOperations.DefinitionStages.WithRetentionDays, + Creatable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServers.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServers.java index be538bafff6aa..3379fdd0a92ae 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServers.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlServers.java @@ -23,17 +23,10 @@ /** Entry point to SQL Server management API. */ @Fluent -public interface SqlServers - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface SqlServers extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** @return the SQL Server Firewall Rules API entry point */ SqlFirewallRuleOperations firewallRules(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroup.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroup.java index 8e837ec47f76f..d6d6c99ed3581 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroup.java @@ -17,12 +17,8 @@ /** An immutable client-side representation of an Azure SQL Server Sync Group. */ @Fluent -public interface SqlSyncGroup - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { +public interface SqlSyncGroup extends ExternalChildResource, HasInnerModel, + HasResourceGroup, Refreshable, Updatable { /** @return name of the SQL Server to which this Sync Group belongs */ String sqlServerName(); @@ -137,13 +133,9 @@ public interface SqlSyncGroup /** The template for a SQL Sync Group update operation, containing all the settings that can be modified. */ interface Update - extends SqlSyncGroup.UpdateStages.WithSyncDatabaseId, - SqlSyncGroup.UpdateStages.WithDatabaseUserName, - SqlSyncGroup.UpdateStages.WithDatabasePassword, - SqlSyncGroup.UpdateStages.WithConflictResolutionPolicy, - SqlSyncGroup.UpdateStages.WithInterval, - SqlSyncGroup.UpdateStages.WithSchema, - Appliable { + extends SqlSyncGroup.UpdateStages.WithSyncDatabaseId, SqlSyncGroup.UpdateStages.WithDatabaseUserName, + SqlSyncGroup.UpdateStages.WithDatabasePassword, SqlSyncGroup.UpdateStages.WithConflictResolutionPolicy, + SqlSyncGroup.UpdateStages.WithInterval, SqlSyncGroup.UpdateStages.WithSchema, Appliable { } /** Grouping of all the SQL Sync Group update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroupOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroupOperations.java index 8f1ff0123e23a..da355bbfaec23 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroupOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncGroupOperations.java @@ -37,8 +37,8 @@ public interface SqlSyncGroupOperations * @param name the name of the child resource * @return a representation of the deferred computation of this call returning the found resource */ - Mono getBySqlServerAsync( - String resourceGroupName, String sqlServerName, String databaseName, String name); + Mono getBySqlServerAsync(String resourceGroupName, String sqlServerName, String databaseName, + String name); /** * Gets a collection of sync database ids. @@ -73,16 +73,14 @@ Mono getBySqlServerAsync( PagedFlux listSyncDatabaseIdsAsync(Region region); /** Container interface for all the definitions that need to be implemented. */ - interface SqlSyncGroupOperationsDefinition - extends SqlSyncGroupOperations.DefinitionStages.WithSqlServer, - SqlSyncGroupOperations.DefinitionStages.WithSyncGroupDatabase, - SqlSyncGroupOperations.DefinitionStages.WithSyncDatabaseId, - SqlSyncGroupOperations.DefinitionStages.WithDatabaseUserName, - SqlSyncGroupOperations.DefinitionStages.WithDatabasePassword, - SqlSyncGroupOperations.DefinitionStages.WithConflictResolutionPolicy, - SqlSyncGroupOperations.DefinitionStages.WithInterval, - SqlSyncGroupOperations.DefinitionStages.WithSchema, - SqlSyncGroupOperations.DefinitionStages.WithCreate { + interface SqlSyncGroupOperationsDefinition extends SqlSyncGroupOperations.DefinitionStages.WithSqlServer, + SqlSyncGroupOperations.DefinitionStages.WithSyncGroupDatabase, + SqlSyncGroupOperations.DefinitionStages.WithSyncDatabaseId, + SqlSyncGroupOperations.DefinitionStages.WithDatabaseUserName, + SqlSyncGroupOperations.DefinitionStages.WithDatabasePassword, + SqlSyncGroupOperations.DefinitionStages.WithConflictResolutionPolicy, + SqlSyncGroupOperations.DefinitionStages.WithInterval, SqlSyncGroupOperations.DefinitionStages.WithSchema, + SqlSyncGroupOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Sync Group definition stages. */ @@ -96,8 +94,8 @@ interface WithSqlServer { * @param sqlServerName the parent SQL server name * @return The next stage of the definition. */ - SqlSyncGroupOperations.DefinitionStages.WithSyncGroupDatabase withExistingSqlServer( - String resourceGroupName, String sqlServerName); + SqlSyncGroupOperations.DefinitionStages.WithSyncGroupDatabase + withExistingSqlServer(String resourceGroupName, String sqlServerName); /** * Sets the parent SQL server for the new Sync Group. diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMember.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMember.java index dad762d76f2f7..db483020eddc3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMember.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMember.java @@ -16,12 +16,8 @@ /** An immutable client-side representation of an Azure SQL Server Sync Member. */ @Fluent -public interface SqlSyncMember - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { +public interface SqlSyncMember extends ExternalChildResource, + HasInnerModel, HasResourceGroup, Refreshable, Updatable { /** @return name of the SQL Server to which this Sync Member belongs */ String sqlServerName(); @@ -97,12 +93,9 @@ public interface SqlSyncMember **************************************************************/ /** The template for a SQL Sync Group update operation, containing all the settings that can be modified. */ - interface Update - extends SqlSyncMember.UpdateStages.WithMemberUserName, - SqlSyncMember.UpdateStages.WithMemberPassword, - SqlSyncMember.UpdateStages.WithMemberDatabaseType, - SqlSyncMember.UpdateStages.WithSyncDirection, - Appliable { + interface Update extends SqlSyncMember.UpdateStages.WithMemberUserName, + SqlSyncMember.UpdateStages.WithMemberPassword, SqlSyncMember.UpdateStages.WithMemberDatabaseType, + SqlSyncMember.UpdateStages.WithSyncDirection, Appliable { } /** Grouping of all the SQL Sync Group update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMemberOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMemberOperations.java index a46417b0f7243..5147fda207c41 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMemberOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlSyncMemberOperations.java @@ -23,8 +23,8 @@ public interface SqlSyncMemberOperations * @param name the name of the child resource * @return an immutable representation of the resource */ - SqlSyncMember getBySqlServer( - String resourceGroupName, String sqlServerName, String databaseName, String syncGroupName, String name); + SqlSyncMember getBySqlServer(String resourceGroupName, String sqlServerName, String databaseName, + String syncGroupName, String name); /** * Asynchronously gets the information about a child resource from Azure SQL server, identifying it by its name and @@ -37,21 +37,20 @@ SqlSyncMember getBySqlServer( * @param name the name of the child resource * @return a representation of the deferred computation of this call returning the found resource */ - Mono getBySqlServerAsync( - String resourceGroupName, String sqlServerName, String databaseName, String syncGroupName, String name); + Mono getBySqlServerAsync(String resourceGroupName, String sqlServerName, String databaseName, + String syncGroupName, String name); /** Container interface for all the definitions that need to be implemented. */ - interface SqlSyncMemberOperationsDefinition - extends SqlSyncMemberOperations.DefinitionStages.WithSqlServer, - SqlSyncMemberOperations.DefinitionStages.WithSyncMemberDatabase, - SqlSyncMemberOperations.DefinitionStages.WithSyncGroupName, - SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer, - SqlSyncMemberOperations.DefinitionStages.WithMemberSqlDatabase, - SqlSyncMemberOperations.DefinitionStages.WithMemberUserName, - SqlSyncMemberOperations.DefinitionStages.WithMemberPassword, - SqlSyncMemberOperations.DefinitionStages.WithMemberDatabaseType, - SqlSyncMemberOperations.DefinitionStages.WithSyncDirection, - SqlSyncMemberOperations.DefinitionStages.WithCreate { + interface SqlSyncMemberOperationsDefinition extends SqlSyncMemberOperations.DefinitionStages.WithSqlServer, + SqlSyncMemberOperations.DefinitionStages.WithSyncMemberDatabase, + SqlSyncMemberOperations.DefinitionStages.WithSyncGroupName, + SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer, + SqlSyncMemberOperations.DefinitionStages.WithMemberSqlDatabase, + SqlSyncMemberOperations.DefinitionStages.WithMemberUserName, + SqlSyncMemberOperations.DefinitionStages.WithMemberPassword, + SqlSyncMemberOperations.DefinitionStages.WithMemberDatabaseType, + SqlSyncMemberOperations.DefinitionStages.WithSyncDirection, + SqlSyncMemberOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Sync Member definition stages. */ @@ -65,8 +64,8 @@ interface WithSqlServer { * @param sqlServerName the parent SQL server name * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithSyncMemberDatabase withExistingSqlServer( - String resourceGroupName, String sqlServerName); + SqlSyncMemberOperations.DefinitionStages.WithSyncMemberDatabase + withExistingSqlServer(String resourceGroupName, String sqlServerName); /** * Sets the parent SQL server for the new Sync Member. @@ -74,8 +73,8 @@ SqlSyncMemberOperations.DefinitionStages.WithSyncMemberDatabase withExistingSqlS * @param sqlSyncGroup the parent SQL Sync Group * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer withExistingSyncGroup( - SqlSyncGroup sqlSyncGroup); + SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer + withExistingSyncGroup(SqlSyncGroup sqlSyncGroup); } /** The SQL Sync Member definition to set the parent database name. */ @@ -97,8 +96,8 @@ interface WithSyncGroupName { * @param syncGroupName the name of the sync group on which the Sync Member is hosted * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer withExistingSyncGroupName( - String syncGroupName); + SqlSyncMemberOperations.DefinitionStages.WithMemberSqlServer + withExistingSyncGroupName(String syncGroupName); } /** The SQL Sync Member definition to set the member server and database. */ @@ -109,8 +108,8 @@ interface WithMemberSqlServer { * @param sqlServerName the member SQL server name value to set * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithMemberSqlDatabase withMemberSqlServerName( - String sqlServerName); + SqlSyncMemberOperations.DefinitionStages.WithMemberSqlDatabase + withMemberSqlServerName(String sqlServerName); /** * Sets the member SQL Database. @@ -129,8 +128,8 @@ interface WithMemberSqlDatabase { * @param sqlDatabaseName the member SQL Database name value to set * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithMemberUserName withMemberSqlDatabaseName( - String sqlDatabaseName); + SqlSyncMemberOperations.DefinitionStages.WithMemberUserName + withMemberSqlDatabaseName(String sqlDatabaseName); } /** The SQL Sync Member definition to set the member database user name. */ @@ -163,8 +162,8 @@ interface WithMemberDatabaseType { * @param databaseType the database type value to set * @return The next stage of the definition. */ - SqlSyncMemberOperations.DefinitionStages.WithSyncDirection withMemberDatabaseType( - SyncMemberDbType databaseType); + SqlSyncMemberOperations.DefinitionStages.WithSyncDirection + withMemberDatabaseType(SyncMemberDbType databaseType); } /** The SQL Sync Member definition to set the sync direction. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRule.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRule.java index a8228896362fc..18acf0004d33e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRule.java @@ -16,11 +16,8 @@ /** An immutable client-side representation of an Azure SQL Server Virtual Network Rule. */ @Fluent public interface SqlVirtualNetworkRule - extends ExternalChildResource, - HasInnerModel, - HasResourceGroup, - Refreshable, - Updatable { + extends ExternalChildResource, HasInnerModel, + HasResourceGroup, Refreshable, Updatable { /** @return name of the SQL Server to which this Virtual Network Rule belongs */ String sqlServerName(); @@ -56,11 +53,10 @@ public interface SqlVirtualNetworkRule * * @param the stage of the parent definition to return to after attaching this definition */ - interface SqlVirtualNetworkRuleDefinition - extends SqlVirtualNetworkRule.DefinitionStages.Blank, - SqlVirtualNetworkRule.DefinitionStages.WithSubnet, - SqlVirtualNetworkRule.DefinitionStages.WithServiceEndpoint, - SqlVirtualNetworkRule.DefinitionStages.WithAttach { + interface SqlVirtualNetworkRuleDefinition extends SqlVirtualNetworkRule.DefinitionStages.Blank, + SqlVirtualNetworkRule.DefinitionStages.WithSubnet, + SqlVirtualNetworkRule.DefinitionStages.WithServiceEndpoint, + SqlVirtualNetworkRule.DefinitionStages.WithAttach { } /** Grouping of all the SQL Virtual Network Rule definition stages. */ @@ -82,8 +78,8 @@ interface WithSubnet { * @param subnetName the name of the subnet within the virtual network to be used * @return The next stage of the definition. */ - SqlVirtualNetworkRule.DefinitionStages.WithServiceEndpoint withSubnet( - String networkId, String subnetName); + SqlVirtualNetworkRule.DefinitionStages.WithServiceEndpoint withSubnet(String networkId, + String subnetName); } /** @@ -117,10 +113,8 @@ interface WithAttach extends Attachable.InDefinition { /** * The template for a SQL Virtual Network Rule update operation, containing all the settings that can be modified. */ - interface Update - extends SqlVirtualNetworkRule.UpdateStages.WithSubnet, - SqlVirtualNetworkRule.UpdateStages.WithServiceEndpoint, - Appliable { + interface Update extends SqlVirtualNetworkRule.UpdateStages.WithSubnet, + SqlVirtualNetworkRule.UpdateStages.WithServiceEndpoint, Appliable { } /** Grouping of all the SQL Virtual Network Rule update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRuleOperations.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRuleOperations.java index a6d282e21721b..1362223792043 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRuleOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SqlVirtualNetworkRuleOperations.java @@ -10,14 +10,14 @@ @Fluent public interface SqlVirtualNetworkRuleOperations extends SupportsCreating, - SqlChildrenOperations { + SqlChildrenOperations { /** Container interface for all the definitions that need to be implemented. */ interface SqlVirtualNetworkRuleOperationsDefinition extends SqlVirtualNetworkRuleOperations.DefinitionStages.WithSqlServer, - SqlVirtualNetworkRuleOperations.DefinitionStages.WithSubnet, - SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint, - SqlVirtualNetworkRuleOperations.DefinitionStages.WithCreate { + SqlVirtualNetworkRuleOperations.DefinitionStages.WithSubnet, + SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint, + SqlVirtualNetworkRuleOperations.DefinitionStages.WithCreate { } /** Grouping of all the SQL Virtual Network Rule definition stages. */ @@ -31,8 +31,8 @@ interface WithSqlServer { * @param sqlServerName the parent SQL server name * @return The next stage of the definition. */ - SqlVirtualNetworkRuleOperations.DefinitionStages.WithSubnet withExistingSqlServer( - String resourceGroupName, String sqlServerName); + SqlVirtualNetworkRuleOperations.DefinitionStages.WithSubnet withExistingSqlServer(String resourceGroupName, + String sqlServerName); /** * Sets the parent SQL server for the new Virtual Network Rule. @@ -60,8 +60,8 @@ interface WithSubnet { * @param subnetName the name of the subnet within the virtual network to be used * @return The next stage of the definition. */ - SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint withSubnet( - String networkId, String subnetName); + SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint withSubnet(String networkId, + String subnetName); } /** @@ -79,6 +79,7 @@ interface WithServiceEndpoint extends SqlVirtualNetworkRuleOperations.Definition */ SqlVirtualNetworkRuleOperations.DefinitionStages.WithCreate ignoreMissingSqlServiceEndpoint(); } + /** The final stage of the SQL Virtual Network Rule definition. */ interface WithCreate extends Creatable { } diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/TransparentDataEncryption.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/TransparentDataEncryption.java index 0cc0f5581e5a0..161da2be2f2c8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/TransparentDataEncryption.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/TransparentDataEncryption.java @@ -14,12 +14,8 @@ /** An immutable client-side representation of an Azure SQL database's TransparentDataEncryption. */ @Fluent -public interface TransparentDataEncryption - extends Refreshable, - HasInnerModel, - HasResourceGroup, - HasName, - HasId { +public interface TransparentDataEncryption extends Refreshable, + HasInnerModel, HasResourceGroup, HasName, HasId { /** @return name of the SQL Server to which this replication belongs */ String sqlServerName(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerOperationsTests.java index 9973b50089bfb..e962324290bf8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerOperationsTests.java @@ -100,56 +100,49 @@ public void canCRUDSqlSyncMember() throws Exception { final String administratorPassword = password(); // Create - SqlServer sqlPrimaryServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_WEST3) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineDatabase(dbName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .defineDatabase(dbSyncName) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .defineDatabase(dbMemberName) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .create(); + SqlServer sqlPrimaryServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_WEST3) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .defineDatabase(dbSyncName) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .defineDatabase(dbMemberName) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); SqlDatabase dbMember = sqlPrimaryServer.databases().get(dbMemberName); - SqlSyncGroup sqlSyncGroup = - dbSync - .syncGroups() - .define(syncGroupName) - .withSyncDatabaseId(dbSource.id()) - .withDatabaseUserName(administratorLogin) - .withDatabasePassword(administratorPassword) - .withConflictResolutionPolicyHubWins() - .withInterval(-1) - .create(); + SqlSyncGroup sqlSyncGroup = dbSync.syncGroups() + .define(syncGroupName) + .withSyncDatabaseId(dbSource.id()) + .withDatabaseUserName(administratorLogin) + .withDatabasePassword(administratorPassword) + .withConflictResolutionPolicyHubWins() + .withInterval(-1) + .create(); Assertions.assertNotNull(sqlSyncGroup); - SqlSyncMember sqlSyncMember = - sqlSyncGroup - .syncMembers() - .define(syncMemberName) - .withMemberSqlDatabase(dbMember) - .withMemberUserName(administratorLogin) - .withMemberPassword(administratorPassword) - .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) - .withDatabaseType(SyncDirection.ONE_WAY_MEMBER_TO_HUB) - .create(); + SqlSyncMember sqlSyncMember = sqlSyncGroup.syncMembers() + .define(syncMemberName) + .withMemberSqlDatabase(dbMember) + .withMemberUserName(administratorLogin) + .withMemberPassword(administratorPassword) + .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) + .withDatabaseType(SyncDirection.ONE_WAY_MEMBER_TO_HUB) + .create(); Assertions.assertNotNull(sqlSyncMember); - sqlSyncMember - .update() + sqlSyncMember.update() .withDatabaseType(SyncDirection.BIDIRECTIONAL) .withMemberUserName(administratorLogin) .withMemberPassword(administratorPassword) @@ -158,11 +151,9 @@ public void canCRUDSqlSyncMember() throws Exception { Assertions.assertFalse(sqlSyncGroup.syncMembers().list().isEmpty()); - sqlSyncMember = - sqlServerManager - .sqlServers() - .syncMembers() - .getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName, syncMemberName); + sqlSyncMember = sqlServerManager.sqlServers() + .syncMembers() + .getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName, syncMemberName); Assertions.assertNotNull(sqlSyncMember); sqlSyncMember.delete(); @@ -179,55 +170,49 @@ public void canCRUDSqlSyncGroup() throws Exception { final String administratorPassword = password(); // Create - SqlServer sqlPrimaryServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineDatabase(dbName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .defineDatabase(dbSyncName) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .create(); + SqlServer sqlPrimaryServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .defineDatabase(dbSyncName) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); - SqlSyncGroup sqlSyncGroup = - dbSync - .syncGroups() - .define(syncGroupName) - .withSyncDatabaseId(dbSource.id()) - .withDatabaseUserName(administratorLogin) - .withDatabasePassword(administratorPassword) - .withConflictResolutionPolicyHubWins() - .withInterval(-1) - .create(); + SqlSyncGroup sqlSyncGroup = dbSync.syncGroups() + .define(syncGroupName) + .withSyncDatabaseId(dbSource.id()) + .withDatabaseUserName(administratorLogin) + .withDatabasePassword(administratorPassword) + .withConflictResolutionPolicyHubWins() + .withInterval(-1) + .create(); Assertions.assertNotNull(sqlSyncGroup); // service no longer supports updating ConflictResolutionPolicy // sqlSyncGroup.update().withInterval(600).withConflictResolutionPolicyMemberWins().apply(); - Assertions - .assertTrue( - sqlServerManager - .sqlServers() - .syncGroups() - .listSyncDatabaseIds(Region.US_EAST) - .stream() - .findAny() - .isPresent()); + Assertions.assertTrue(sqlServerManager.sqlServers() + .syncGroups() + .listSyncDatabaseIds(Region.US_EAST) + .stream() + .findAny() + .isPresent()); Assertions.assertFalse(dbSync.syncGroups().list().isEmpty()); - sqlSyncGroup = - sqlServerManager.sqlServers().syncGroups().getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName); + sqlSyncGroup = sqlServerManager.sqlServers() + .syncGroups() + .getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName); Assertions.assertNotNull(sqlSyncGroup); sqlSyncGroup.delete(); @@ -243,43 +228,37 @@ public void canCopySqlDatabase() throws Exception { final String administratorPassword = password(); // Create - SqlServer sqlPrimaryServer = - sqlServerManager - .sqlServers() - .define(sqlPrimaryServerName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineElasticPool(epName) - .withPremiumPool() - .attach() - .defineDatabase(dbName) - .withExistingElasticPool(epName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .attach() - .create(); - - SqlServer sqlSecondaryServer = - sqlServerManager - .sqlServers() - .define(sqlSecondaryServerName) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); + SqlServer sqlPrimaryServer = sqlServerManager.sqlServers() + .define(sqlPrimaryServerName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineElasticPool(epName) + .withPremiumPool() + .attach() + .defineDatabase(dbName) + .withExistingElasticPool(epName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .attach() + .create(); + + SqlServer sqlSecondaryServer = sqlServerManager.sqlServers() + .define(sqlSecondaryServerName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); SqlDatabase dbSample = sqlPrimaryServer.databases().get(dbName); - SqlDatabase dbCopy = - sqlSecondaryServer - .databases() - .define("dbCopy") - .withSourceDatabase(dbSample) - .withMode(CreateMode.COPY) - .withPremiumEdition(SqlDatabasePremiumServiceObjective.P1) - .create(); + SqlDatabase dbCopy = sqlSecondaryServer.databases() + .define("dbCopy") + .withSourceDatabase(dbSample) + .withMode(CreateMode.COPY) + .withPremiumEdition(SqlDatabasePremiumServiceObjective.P1) + .create(); Assertions.assertNotNull(dbCopy); } @@ -296,48 +275,40 @@ public void canCRUDSqlFailoverGroup() throws Exception { final String administratorPassword = password(); // Create - SqlServer sqlPrimaryServer = - sqlServerManager - .sqlServers() - .define(sqlPrimaryServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .defineDatabase(dbName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .attach() - .create(); - - SqlServer sqlSecondaryServer = - sqlServerManager - .sqlServers() - .define(sqlSecondaryServerName) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); - - SqlServer sqlOtherServer = - sqlServerManager - .sqlServers() - .define(sqlOtherServerName) - .withRegion(Region.US_SOUTH_CENTRAL) - .withExistingResourceGroup(rgName) - .withAdministratorLogin(administratorLogin) - .withAdministratorPassword(administratorPassword) - .create(); - - SqlFailoverGroup failoverGroup = - sqlPrimaryServer - .failoverGroups() - .define(failoverGroupName) - .withManualReadWriteEndpointPolicy() - .withPartnerServerId(sqlSecondaryServer.id()) - .withReadOnlyEndpointPolicyDisabled() - .create(); + SqlServer sqlPrimaryServer = sqlServerManager.sqlServers() + .define(sqlPrimaryServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); + + SqlServer sqlSecondaryServer = sqlServerManager.sqlServers() + .define(sqlSecondaryServerName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + + SqlServer sqlOtherServer = sqlServerManager.sqlServers() + .define(sqlOtherServerName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + + SqlFailoverGroup failoverGroup = sqlPrimaryServer.failoverGroups() + .define(failoverGroupName) + .withManualReadWriteEndpointPolicy() + .withPartnerServerId(sqlSecondaryServer.id()) + .withReadOnlyEndpointPolicyDisabled() + .create(); Assertions.assertNotNull(failoverGroup); Assertions.assertEquals(failoverGroupName, failoverGroup.name()); Assertions.assertEquals(rgName, failoverGroup.resourceGroupName()); @@ -345,9 +316,8 @@ public void canCRUDSqlFailoverGroup() throws Exception { Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup.replicationRole()); Assertions.assertEquals(1, failoverGroup.partnerServers().size()); Assertions.assertEquals(sqlSecondaryServer.id(), failoverGroup.partnerServers().get(0).id()); - Assertions - .assertEquals( - FailoverGroupReplicationRole.SECONDARY, failoverGroup.partnerServers().get(0).replicationRole()); + Assertions.assertEquals(FailoverGroupReplicationRole.SECONDARY, + failoverGroup.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup.databases().size()); Assertions.assertEquals(0, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroup.readWriteEndpointPolicy()); @@ -360,24 +330,21 @@ public void canCRUDSqlFailoverGroup() throws Exception { Assertions.assertEquals(FailoverGroupReplicationRole.SECONDARY, failoverGroupOnPartner.replicationRole()); Assertions.assertEquals(1, failoverGroupOnPartner.partnerServers().size()); Assertions.assertEquals(sqlPrimaryServer.id(), failoverGroupOnPartner.partnerServers().get(0).id()); - Assertions - .assertEquals( - FailoverGroupReplicationRole.PRIMARY, failoverGroupOnPartner.partnerServers().get(0).replicationRole()); + Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, + failoverGroupOnPartner.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroupOnPartner.databases().size()); Assertions.assertEquals(0, failoverGroupOnPartner.readWriteEndpointDataLossGracePeriodMinutes()); - Assertions - .assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroupOnPartner.readWriteEndpointPolicy()); - Assertions - .assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroupOnPartner.readOnlyEndpointPolicy()); - - SqlFailoverGroup failoverGroup2 = - sqlPrimaryServer - .failoverGroups() - .define(failoverGroupName2) - .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) - .withPartnerServerId(sqlOtherServer.id()) - .withReadOnlyEndpointPolicyEnabled() - .create(); + Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, + failoverGroupOnPartner.readWriteEndpointPolicy()); + Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, + failoverGroupOnPartner.readOnlyEndpointPolicy()); + + SqlFailoverGroup failoverGroup2 = sqlPrimaryServer.failoverGroups() + .define(failoverGroupName2) + .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) + .withPartnerServerId(sqlOtherServer.id()) + .withReadOnlyEndpointPolicyEnabled() + .create(); Assertions.assertNotNull(failoverGroup2); Assertions.assertEquals(failoverGroupName2, failoverGroup2.name()); Assertions.assertEquals(rgName, failoverGroup2.resourceGroupName()); @@ -385,16 +352,14 @@ public void canCRUDSqlFailoverGroup() throws Exception { Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup2.replicationRole()); Assertions.assertEquals(1, failoverGroup2.partnerServers().size()); Assertions.assertEquals(sqlOtherServer.id(), failoverGroup2.partnerServers().get(0).id()); - Assertions - .assertEquals( - FailoverGroupReplicationRole.SECONDARY, failoverGroup2.partnerServers().get(0).replicationRole()); + Assertions.assertEquals(FailoverGroupReplicationRole.SECONDARY, + failoverGroup2.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup2.databases().size()); Assertions.assertEquals(120, failoverGroup2.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.AUTOMATIC, failoverGroup2.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup2.readOnlyEndpointPolicy()); - failoverGroup - .update() + failoverGroup.update() .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) .withReadOnlyEndpointPolicyEnabled() .withTag("tag1", "value1") @@ -404,8 +369,7 @@ public void canCRUDSqlFailoverGroup() throws Exception { Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup.readOnlyEndpointPolicy()); SqlDatabase db = sqlPrimaryServer.databases().get(dbName); - failoverGroup - .update() + failoverGroup.update() .withManualReadWriteEndpointPolicy() .withReadOnlyEndpointPolicyDisabled() .withNewDatabaseId(db.id()) @@ -434,19 +398,17 @@ public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { String storageName = generateRandomResourceName(sqlServerName, 22); // Create - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(sqlServerAdminPassword) - .defineDatabase(databaseName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withBasicEdition() - .attach() - .create(); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(sqlServerAdminPassword) + .defineDatabase(databaseName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withBasicEdition() + .attach() + .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); @@ -456,8 +418,7 @@ public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); Assertions.assertEquals(4, serverAutomaticTuning.tuningOptions().size()); - serverAutomaticTuning - .update() + serverAutomaticTuning.update() .withAutomaticTuningMode(AutomaticTuningServerMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) @@ -465,33 +426,22 @@ public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { .apply(); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.OFF, - serverAutomaticTuning.tuningOptions().get("createIndex").desiredState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeActual.OFF, - serverAutomaticTuning.tuningOptions().get("createIndex").actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.ON, - serverAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeActual.ON, - serverAutomaticTuning.tuningOptions().get("dropIndex").actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.DEFAULT, - serverAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.OFF, + serverAutomaticTuning.tuningOptions().get("createIndex").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeActual.OFF, + serverAutomaticTuning.tuningOptions().get("createIndex").actualState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.ON, + serverAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeActual.ON, + serverAutomaticTuning.tuningOptions().get("dropIndex").actualState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.DEFAULT, + serverAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); SqlDatabaseAutomaticTuning databaseAutomaticTuning = dbFromSample.getDatabaseAutomaticTuning(); Assertions.assertEquals(4, databaseAutomaticTuning.tuningOptions().size()); // The following results in "InternalServerError" at the moment - databaseAutomaticTuning - .update() + databaseAutomaticTuning.update() .withAutomaticTuningMode(AutomaticTuningMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) @@ -499,26 +449,16 @@ public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { .apply(); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.OFF, - databaseAutomaticTuning.tuningOptions().get("createIndex").desiredState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeActual.OFF, - databaseAutomaticTuning.tuningOptions().get("createIndex").actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.ON, - databaseAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeActual.ON, - databaseAutomaticTuning.tuningOptions().get("dropIndex").actualState()); - Assertions - .assertEquals( - AutomaticTuningOptionModeDesired.DEFAULT, - databaseAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.OFF, + databaseAutomaticTuning.tuningOptions().get("createIndex").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeActual.OFF, + databaseAutomaticTuning.tuningOptions().get("createIndex").actualState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.ON, + databaseAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); + Assertions.assertEquals(AutomaticTuningOptionModeActual.ON, + databaseAutomaticTuning.tuningOptions().get("dropIndex").actualState()); + Assertions.assertEquals(AutomaticTuningOptionModeDesired.DEFAULT, + databaseAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); // cleanup dbFromSample.delete(); @@ -533,15 +473,13 @@ public void canCreateAndAquireServerDnsAlias() throws Exception { String sqlServerAdminPassword = password(); // Create - SqlServer sqlServer1 = - sqlServerManager - .sqlServers() - .define(sqlServerName1) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(sqlServerAdminPassword) - .create(); + SqlServer sqlServer1 = sqlServerManager.sqlServers() + .define(sqlServerName1) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(sqlServerAdminPassword) + .create(); Assertions.assertNotNull(sqlServer1); SqlServerDnsAlias dnsAlias = sqlServer1.dnsAliases().define(sqlServerName).create(); @@ -557,15 +495,13 @@ public void canCreateAndAquireServerDnsAlias() throws Exception { Assertions.assertEquals(1, sqlServer1.databases().list().size()); - SqlServer sqlServer2 = - sqlServerManager - .sqlServers() - .define(sqlServerName2) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(sqlServerAdminPassword) - .create(); + SqlServer sqlServer2 = sqlServerManager.sqlServers() + .define(sqlServerName2) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(sqlServerAdminPassword) + .create(); Assertions.assertNotNull(sqlServer2); sqlServer2.dnsAliases().acquire(sqlServerName, sqlServer1.id()); @@ -594,47 +530,41 @@ public void canGetSqlServerCapabilitiesAndCreateIdentity() throws Exception { RegionCapabilities regionCapabilities = sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST); Assertions.assertNotNull(regionCapabilities); Assertions.assertNotNull(regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0")); - Assertions - .assertTrue( - regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0").supportedEditions().size() > 0); - Assertions - .assertTrue( - regionCapabilities - .supportedCapabilitiesByServerVersion() - .get("12.0") - .supportedElasticPoolEditions() - .size() - > 0); + Assertions.assertTrue( + regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0").supportedEditions().size() > 0); + Assertions.assertTrue( + regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0").supportedElasticPoolEditions().size() + > 0); // Create - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(sqlServerAdminPassword) - .withSystemAssignedManagedServiceIdentity() - .defineDatabase(databaseName) - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withBasicEdition() - .attach() - .create(); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(sqlServerAdminPassword) + .withSystemAssignedManagedServiceIdentity() + .defineDatabase(databaseName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withBasicEdition() + .attach() + .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); if (!isPlaybackMode()) { - Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); + Assertions.assertEquals(sqlServerManager.tenantId(), + sqlServer.systemAssignedManagedServiceIdentityTenantId()); } Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); sqlServer.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); if (!isPlaybackMode()) { - Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); + Assertions.assertEquals(sqlServerManager.tenantId(), + sqlServer.systemAssignedManagedServiceIdentityTenantId()); } Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); @@ -654,70 +584,58 @@ public void canCRUDSqlServerWithImportDatabase() throws Exception { String id = generateRandomUuid(); String storageName = generateRandomResourceName(sqlServerName, 22); - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(sqlServerAdminPassword) - .withActiveDirectoryAdministrator("DSEng", id) - .create(); - - SqlDatabase dbFromSample = - sqlServer - .databases() - .define("db-from-sample") - .fromSample(SampleName.ADVENTURE_WORKS_LT) - .withBasicEdition() - .withTag("tag1", "value1") - .create(); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(sqlServerAdminPassword) + .withActiveDirectoryAdministrator("DSEng", id) + .create(); + + SqlDatabase dbFromSample = sqlServer.databases() + .define("db-from-sample") + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withBasicEdition() + .withTag("tag1", "value1") + .create(); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); SqlDatabaseImportExportResponse exportedDB; StorageAccount storageAccount = null; try { - storageAccount = - storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); + storageAccount + = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } catch (ManagementException e) { Assertions.assertEquals(404, e.getResponse().getStatusCode()); } if (storageAccount == null) { - Creatable storageAccountCreatable = - storageManager - .storageAccounts() - .define(storageName) - .withRegion(sqlServer.regionName()) - .withExistingResourceGroup(sqlServer.resourceGroupName()); - - exportedDB = - dbFromSample - .exportTo(storageAccountCreatable, "from-sample", "dbfromsample.bacpac") - .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) - .execute(); - storageAccount = - storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); + Creatable storageAccountCreatable = storageManager.storageAccounts() + .define(storageName) + .withRegion(sqlServer.regionName()) + .withExistingResourceGroup(sqlServer.resourceGroupName()); + + exportedDB = dbFromSample.exportTo(storageAccountCreatable, "from-sample", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) + .execute(); + storageAccount + = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } else { - exportedDB = - dbFromSample - .exportTo(storageAccount, "from-sample", "dbfromsample.bacpac") - .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) - .execute(); + exportedDB = dbFromSample.exportTo(storageAccount, "from-sample", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) + .execute(); } - SqlDatabase dbFromImport = - sqlServer - .databases() - .define("db-from-import") - .defineElasticPool("ep1") - .withBasicPool() - .attach() - .importFrom(storageAccount, "from-sample", "dbfromsample.bacpac") - .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) - .withTag("tag2", "value2") - .create(); + SqlDatabase dbFromImport = sqlServer.databases() + .define("db-from-import") + .defineElasticPool("ep1") + .withBasicPool() + .attach() + .importFrom(storageAccount, "from-sample", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) + .withTag("tag2", "value2") + .create(); Assertions.assertNotNull(dbFromImport); Assertions.assertEquals("ep1", dbFromImport.elasticPoolName()); @@ -733,21 +651,19 @@ public void canCRUDSqlServerWithFirewallRule() throws Exception { String sqlServerAdminName = "sqladmin"; String id = azureCliSignedInUser().id(); - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin(sqlServerAdminName) - .withAdministratorPassword(password()) - .withActiveDirectoryAdministrator("DSEng", id) - .withoutAccessFromAzureServices() - .defineFirewallRule("somefirewallrule1") - .withIpAddress("0.0.0.1") - .attach() - .withTag("tag1", "value1") - .create(); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(sqlServerAdminName) + .withAdministratorPassword(password()) + .withActiveDirectoryAdministrator("DSEng", id) + .withoutAccessFromAzureServices() + .defineFirewallRule("somefirewallrule1") + .withIpAddress("0.0.0.1") + .attach() + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(sqlServerAdminName, sqlServer.administratorLogin()); Assertions.assertEquals("v12.0", sqlServer.kind()); Assertions.assertEquals("12.0", sqlServer.version()); @@ -773,44 +689,34 @@ public void canCRUDSqlServerWithFirewallRule() throws Exception { final SqlServer finalSqlServer = sqlServer; validateResourceNotFound(() -> finalSqlServer.getActiveDirectoryAdministrator()); - SqlFirewallRule firewallRule = - sqlServerManager.sqlServers().firewallRules().getBySqlServer(rgName, sqlServerName, "somefirewallrule1"); + SqlFirewallRule firewallRule + = sqlServerManager.sqlServers().firewallRules().getBySqlServer(rgName, sqlServerName, "somefirewallrule1"); Assertions.assertEquals("0.0.0.1", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.1", firewallRule.endIpAddress()); - validateResourceNotFound( - () -> - sqlServerManager - .sqlServers() - .firewallRules() - .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps")); + validateResourceNotFound(() -> sqlServerManager.sqlServers() + .firewallRules() + .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps")); sqlServer.enableAccessFromAzureServices(); - firewallRule = - sqlServerManager - .sqlServers() - .firewallRules() - .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps"); + firewallRule = sqlServerManager.sqlServers() + .firewallRules() + .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps"); Assertions.assertEquals("0.0.0.0", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.0", firewallRule.endIpAddress()); - sqlServer.update().defineFirewallRule("newFirewallRule1") - .withIpAddress("0.0.0.2") - .attach() - .apply(); + sqlServer.update().defineFirewallRule("newFirewallRule1").withIpAddress("0.0.0.2").attach().apply(); sqlServer.firewallRules().delete("newFirewallRule2"); final SqlServer finalSqlServer1 = sqlServer; validateResourceNotFound(() -> finalSqlServer1.firewallRules().get("newFirewallRule2")); - firewallRule = - sqlServerManager - .sqlServers() - .firewallRules() - .define("newFirewallRule2") - .withExistingSqlServer(rgName, sqlServerName) - .withIpAddress("0.0.0.3") - .create(); + firewallRule = sqlServerManager.sqlServers() + .firewallRules() + .define("newFirewallRule2") + .withExistingSqlServer(rgName, sqlServerName) + .withIpAddress("0.0.0.3") + .create(); Assertions.assertEquals("0.0.0.3", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); @@ -821,19 +727,16 @@ public void canCRUDSqlServerWithFirewallRule() throws Exception { Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); sqlServer.firewallRules().delete("somefirewallrule1"); - validateResourceNotFound( - () -> - sqlServerManager - .sqlServers() - .firewallRules() - .getBySqlServer(rgName, sqlServerName, "somefirewallrule1")); + validateResourceNotFound(() -> sqlServerManager.sqlServers() + .firewallRules() + .getBySqlServer(rgName, sqlServerName, "somefirewallrule1")); firewallRule = sqlServer.firewallRules().define("somefirewallrule2").withIpAddress("0.0.0.4").create(); Assertions.assertEquals("0.0.0.4", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.4", firewallRule.endIpAddress()); -// sqlServer.enableAccessFromAzureServices(); + // sqlServer.enableAccessFromAzureServices(); firewallRule.delete(); } @@ -842,8 +745,8 @@ public void canCRUDSqlServerWithFirewallRule() throws Exception { public void canCRUDSqlServer() throws Exception { // Check if the name is available - CheckNameAvailabilityResult checkNameResult = - sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); + CheckNameAvailabilityResult checkNameResult + = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertTrue(checkNameResult.isAvailable()); // Create @@ -854,9 +757,8 @@ public void canCRUDSqlServer() throws Exception { // Confirm the server name is unavailable checkNameResult = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertFalse(checkNameResult.isAvailable()); - Assertions - .assertEquals( - CheckNameAvailabilityReason.ALREADY_EXISTS.toString(), checkNameResult.unavailabilityReason()); + Assertions.assertEquals(CheckNameAvailabilityReason.ALREADY_EXISTS.toString(), + checkNameResult.unavailabilityReason()); sqlServer.update().withAdministratorPassword("P@ssword~2").apply(); @@ -887,36 +789,45 @@ public void canUseCoolShortcutsForResourceCreation() throws Exception { String elasticPool1Name = SQL_ELASTIC_POOL_NAME; // Create - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin("userName") - .withAdministratorPassword("Password~1") - .withoutAccessFromAzureServices() - .defineDatabase(SQL_DATABASE_NAME).attach() - .defineDatabase(database2Name).attach() - .defineElasticPool(elasticPool1Name).withStandardPool().attach() - .defineElasticPool(elasticPool2Name).withPremiumPool().attach() - .defineElasticPool(elasticPool3Name).withStandardPool().attach() - .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() - .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() - .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() - .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() - .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() - .create(); - - validateMultiCreation( - database2Name, - database1InEPName, - database2InEPName, - elasticPool1Name, - elasticPool2Name, - elasticPool3Name, - sqlServer, - false); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin("userName") + .withAdministratorPassword("Password~1") + .withoutAccessFromAzureServices() + .defineDatabase(SQL_DATABASE_NAME) + .attach() + .defineDatabase(database2Name) + .attach() + .defineElasticPool(elasticPool1Name) + .withStandardPool() + .attach() + .defineElasticPool(elasticPool2Name) + .withPremiumPool() + .attach() + .defineElasticPool(elasticPool3Name) + .withStandardPool() + .attach() + .defineDatabase(database1InEPName) + .withExistingElasticPool(elasticPool2Name) + .attach() + .defineDatabase(database2InEPName) + .withExistingElasticPool(elasticPool2Name) + .attach() + .defineFirewallRule(SQL_FIREWALLRULE_NAME) + .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) + .attach() + .defineFirewallRule(generateRandomResourceName("firewall_", 15)) + .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) + .attach() + .defineFirewallRule(generateRandomResourceName("firewall_", 15)) + .withIpAddress(START_IPADDRESS) + .attach() + .create(); + + validateMultiCreation(database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, + elasticPool3Name, sqlServer, false); elasticPool1Name = SQL_ELASTIC_POOL_NAME + " U"; database2Name = "database2U"; database1InEPName = "database1InEPU"; @@ -925,31 +836,40 @@ public void canUseCoolShortcutsForResourceCreation() throws Exception { elasticPool3Name = "elasticPool3U"; // Update - sqlServer = - sqlServer - .update() - .defineDatabase(SQL_DATABASE_NAME).attach() - .defineDatabase(database2Name).attach() - .defineElasticPool(elasticPool1Name).withStandardPool().attach() - .defineElasticPool(elasticPool2Name).withPremiumPool().attach() - .defineElasticPool(elasticPool3Name).withStandardPool().attach() - .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() - .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() - .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() - .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() - .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() - .withTag("tag2", "value2") - .apply(); + sqlServer = sqlServer.update() + .defineDatabase(SQL_DATABASE_NAME) + .attach() + .defineDatabase(database2Name) + .attach() + .defineElasticPool(elasticPool1Name) + .withStandardPool() + .attach() + .defineElasticPool(elasticPool2Name) + .withPremiumPool() + .attach() + .defineElasticPool(elasticPool3Name) + .withStandardPool() + .attach() + .defineDatabase(database1InEPName) + .withExistingElasticPool(elasticPool2Name) + .attach() + .defineDatabase(database2InEPName) + .withExistingElasticPool(elasticPool2Name) + .attach() + .defineFirewallRule(SQL_FIREWALLRULE_NAME) + .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) + .attach() + .defineFirewallRule(generateRandomResourceName("firewall_", 15)) + .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) + .attach() + .defineFirewallRule(generateRandomResourceName("firewall_", 15)) + .withIpAddress(START_IPADDRESS) + .attach() + .withTag("tag2", "value2") + .apply(); - validateMultiCreation( - database2Name, - database1InEPName, - database2InEPName, - elasticPool1Name, - elasticPool2Name, - elasticPool3Name, - sqlServer, - true); + validateMultiCreation(database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, + elasticPool3Name, sqlServer, true); sqlServer.refresh(); Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); @@ -976,8 +896,10 @@ public void canUseCoolShortcutsForResourceCreation() throws Exception { public void canCRUDSqlDatabase() throws Exception { // Create SqlServer sqlServer = createSqlServer(); - Mono resourceStream = - sqlServer.databases().define(SQL_DATABASE_NAME).withStandardEdition(SqlDatabaseStandardServiceObjective.S0).createAsync(); + Mono resourceStream = sqlServer.databases() + .define(SQL_DATABASE_NAME) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); @@ -987,7 +909,8 @@ public void canCRUDSqlDatabase() throws Exception { // Test security alert policy settings. final String storageAccountName = generateRandomResourceName("sqlsa", 20); - StorageAccount storageAccount = storageManager.storageAccounts().define(storageAccountName) + StorageAccount storageAccount = storageManager.storageAccounts() + .define(storageAccountName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); @@ -1022,8 +945,8 @@ public void canCRUDSqlDatabase() throws Exception { Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.ENABLED, transparentDataEncryption.status()); - transparentDataEncryption = - sqlDatabase.getTransparentDataEncryption().updateStatus(TransparentDataEncryptionState.DISABLED); + transparentDataEncryption + = sqlDatabase.getTransparentDataEncryption().updateStatus(TransparentDataEncryptionState.DISABLED); Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.DISABLED, transparentDataEncryption.status()); @@ -1039,17 +962,15 @@ public void canCRUDSqlDatabase() throws Exception { validateSqlServer(sqlServer); // Create another database with above created database as source database. - Creatable sqlElasticPoolCreatable = - sqlServer.elasticPools().define(SQL_ELASTIC_POOL_NAME).withStandardPool(); + Creatable sqlElasticPoolCreatable + = sqlServer.elasticPools().define(SQL_ELASTIC_POOL_NAME).withStandardPool(); String anotherDatabaseName = "anotherDatabase"; - SqlDatabase anotherDatabase = - sqlServer - .databases() - .define(anotherDatabaseName) - .withNewElasticPool(sqlElasticPoolCreatable) - .withSourceDatabase(sqlDatabase.id()) - .withMode(CreateMode.COPY) - .create(); + SqlDatabase anotherDatabase = sqlServer.databases() + .define(anotherDatabaseName) + .withNewElasticPool(sqlElasticPoolCreatable) + .withSourceDatabase(sqlDatabase.id()) + .withMode(CreateMode.COPY) + .create(); validateSqlDatabaseWithElasticPool(anotherDatabase, anotherDatabaseName); sqlServer.databases().delete(anotherDatabase.name()); @@ -1065,13 +986,11 @@ public void canCRUDSqlDatabase() throws Exception { validateSqlDatabaseNotFound(SQL_DATABASE_NAME); // Add another database to the server - resourceStream = - sqlServer - .databases() - .define("newDatabase") - .withCollation(COLLATION) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .createAsync(); + resourceStream = sqlServer.databases() + .define("newDatabase") + .withCollation(COLLATION) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .createAsync(); sqlDatabase = resourceStream.block(); @@ -1092,34 +1011,30 @@ public void canManageReplicationLinks() throws Exception { SqlServer sqlServer1 = createSqlServer(); SqlServer sqlServer2 = createSqlServer(anotherSqlServerName); - Mono resourceStream = - sqlServer1 - .databases() - .define(SQL_DATABASE_NAME) - .withCollation(COLLATION) - .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) - .createAsync(); + Mono resourceStream = sqlServer1.databases() + .define(SQL_DATABASE_NAME) + .withCollation(COLLATION) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .createAsync(); SqlDatabase databaseInServer1 = resourceStream.block(); validateSqlDatabase(databaseInServer1, SQL_DATABASE_NAME); - SqlDatabase databaseInServer2 = - sqlServer2 - .databases() - .define(SQL_DATABASE_NAME) - .withSourceDatabase(databaseInServer1.id()) - .withMode(CreateMode.ONLINE_SECONDARY) - .create(); + SqlDatabase databaseInServer2 = sqlServer2.databases() + .define(SQL_DATABASE_NAME) + .withSourceDatabase(databaseInServer1.id()) + .withMode(CreateMode.ONLINE_SECONDARY) + .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(2)); - List replicationLinksInDb1 = - new ArrayList<>(databaseInServer1.listReplicationLinks().values()); + List replicationLinksInDb1 + = new ArrayList<>(databaseInServer1.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb1.size(), 1); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerDatabase(), databaseInServer2.name()); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerServer(), databaseInServer2.sqlServerName()); - List replicationLinksInDb2 = - new ArrayList<>(databaseInServer2.listReplicationLinks().values()); + List replicationLinksInDb2 + = new ArrayList<>(databaseInServer2.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb2.size(), 1); Assertions.assertEquals(replicationLinksInDb2.get(0).partnerDatabase(), databaseInServer1.name()); @@ -1157,15 +1072,13 @@ public void canDoOperationsOnDataWarehouse() throws Exception { validateSqlServer(sqlServer); // List usages for the server.TODO (xiaofeicao) server backend not deployed -// Assertions.assertNotNull(sqlServer.listUsageMetrics()); + // Assertions.assertNotNull(sqlServer.listUsageMetrics()); - Mono resourceStream = - sqlServer - .databases() - .define(SQL_DATABASE_NAME) - .withCollation(COLLATION) - .withSku(DatabaseSku.DATAWAREHOUSE_DW1000C) - .createAsync(); + Mono resourceStream = sqlServer.databases() + .define(SQL_DATABASE_NAME) + .withCollation(COLLATION) + .withSku(DatabaseSku.DATAWAREHOUSE_DW1000C) + .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); Assertions.assertNotNull(sqlDatabase); @@ -1184,7 +1097,7 @@ public void canDoOperationsOnDataWarehouse() throws Exception { // List Restore points. Assertions.assertNotNull(dataWarehouse.listRestorePoints()); // Get usages. TODO (xiaofeicao) server backend not deployed -// Assertions.assertNotNull(dataWarehouse.listUsageMetrics()); + // Assertions.assertNotNull(dataWarehouse.listUsageMetrics()); // Pause warehouse dataWarehouse.pauseDataWarehouse(); @@ -1203,20 +1116,14 @@ public void canCRUDSqlDatabaseWithElasticPool() throws Exception { // Create SqlServer sqlServer = createSqlServer(); - Creatable sqlElasticPoolCreatable = - sqlServer - .elasticPools() - .define(SQL_ELASTIC_POOL_NAME) - .withStandardPool() - .withTag("tag1", "value1"); - - Mono resourceStream = - sqlServer - .databases() - .define(SQL_DATABASE_NAME) - .withNewElasticPool(sqlElasticPoolCreatable) - .withCollation(COLLATION) - .createAsync(); + Creatable sqlElasticPoolCreatable + = sqlServer.elasticPools().define(SQL_ELASTIC_POOL_NAME).withStandardPool().withTag("tag1", "value1"); + + Mono resourceStream = sqlServer.databases() + .define(SQL_DATABASE_NAME) + .withNewElasticPool(sqlElasticPoolCreatable) + .withCollation(COLLATION) + .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); @@ -1236,11 +1143,7 @@ public void canCRUDSqlDatabaseWithElasticPool() throws Exception { validateListSqlDatabase(sqlServer.databases().list()); // Remove database from elastic pools. - sqlDatabase - .update() - .withoutElasticPool() - .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) - .apply(); + sqlDatabase.update().withoutElasticPool().withStandardEdition(SqlDatabaseStandardServiceObjective.S3).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertNull(sqlDatabase.elasticPoolName()); @@ -1293,13 +1196,11 @@ public void canCRUDSqlDatabaseWithElasticPool() throws Exception { SqlElasticPool sqlElasticPool = sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME); // Add another database to the server and pool. - resourceStream = - sqlServer - .databases() - .define("newDatabase") - .withExistingElasticPool(sqlElasticPool) - .withCollation(COLLATION) - .createAsync(); + resourceStream = sqlServer.databases() + .define("newDatabase") + .withExistingElasticPool(sqlElasticPool) + .withCollation(COLLATION) + .createAsync(); sqlDatabase = resourceStream.block(); sqlServer.databases().delete(sqlDatabase.name()); @@ -1318,27 +1219,23 @@ public void canCRUDSqlElasticPool() throws Exception { sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); - Mono resourceStream = - sqlServer - .elasticPools() - .define(SQL_ELASTIC_POOL_NAME) - .withStandardPool() - .withTag("tag1", "value1") - .createAsync(); + Mono resourceStream = sqlServer.elasticPools() + .define(SQL_ELASTIC_POOL_NAME) + .withStandardPool() + .withTag("tag1", "value1") + .createAsync(); SqlElasticPool sqlElasticPool = resourceStream.block(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 0); - sqlElasticPool = - sqlElasticPool - .update() - .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_100) - .withDatabaseMaxCapacity(20) - .withDatabaseMinCapacity(10) - .withStorageCapacity(102400 * 1024 * 1024L) - .withNewDatabase(SQL_DATABASE_NAME) - .withTag("tag2", "value2") - .apply(); + sqlElasticPool = sqlElasticPool.update() + .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_100) + .withDatabaseMaxCapacity(20) + .withDatabaseMinCapacity(10) + .withStorageCapacity(102400 * 1024 * 1024L) + .withNewDatabase(SQL_DATABASE_NAME) + .withTag("tag2", "value2") + .apply(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 1); @@ -1356,8 +1253,7 @@ public void canCRUDSqlElasticPool() throws Exception { validateSqlElasticPoolNotFound(sqlServer, SQL_ELASTIC_POOL_NAME); // Add another database to the server - resourceStream = - sqlServer.elasticPools().define("newElasticPool").withStandardPool().createAsync(); + resourceStream = sqlServer.elasticPools().define("newElasticPool").withStandardPool().createAsync(); sqlElasticPool = resourceStream.block(); @@ -1376,12 +1272,10 @@ public void canCRUDSqlFirewallRule() throws Exception { sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); - Mono resourceStream = - sqlServer - .firewallRules() - .define(SQL_FIREWALLRULE_NAME) - .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) - .createAsync(); + Mono resourceStream = sqlServer.firewallRules() + .define(SQL_FIREWALLRULE_NAME) + .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) + .createAsync(); SqlFirewallRule sqlFirewallRule = resourceStream.block(); @@ -1389,8 +1283,8 @@ public void canCRUDSqlFirewallRule() throws Exception { validateSqlFirewallRule(sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME), SQL_FIREWALLRULE_NAME); String secondFirewallRuleName = "secondFireWallRule"; - SqlFirewallRule secondFirewallRule = - sqlServer.firewallRules().define(secondFirewallRuleName).withIpAddress(START_IPADDRESS).create(); + SqlFirewallRule secondFirewallRule + = sqlServer.firewallRules().define(secondFirewallRuleName).withIpAddress(START_IPADDRESS).create(); Assertions.assertNotNull(secondFirewallRule); secondFirewallRule = sqlServer.firewallRules().get(secondFirewallRuleName); @@ -1427,14 +1321,8 @@ public void canCRUDSqlFirewallRule() throws Exception { validateSqlServerNotFound(sqlServer); } - private void validateMultiCreation( - String database2Name, - String database1InEPName, - String database2InEPName, - String elasticPool1Name, - String elasticPool2Name, - String elasticPool3Name, - SqlServer sqlServer, + private void validateMultiCreation(String database2Name, String database1InEPName, String database2InEPName, + String elasticPool1Name, String elasticPool2Name, String elasticPool3Name, SqlServer sqlServer, boolean deleteUsingUpdate) { validateSqlServer(sqlServer); validateSqlServer(sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName)); @@ -1500,8 +1388,7 @@ private void validateMultiCreation( firewallRule.delete(); } } else { - sqlServer - .update() + sqlServer.update() .withoutDatabase(database2Name) .withoutElasticPool(elasticPool1Name) .withoutElasticPool(elasticPool2Name) @@ -1527,13 +1414,10 @@ private void validateMultiCreation( } private void validateSqlFirewallRuleNotFound() { - validateResourceNotFound( - () -> - sqlServerManager - .sqlServers() - .getByResourceGroup(rgName, sqlServerName) - .firewallRules() - .get(SQL_FIREWALLRULE_NAME)); + validateResourceNotFound(() -> sqlServerManager.sqlServers() + .getByResourceGroup(rgName, sqlServerName) + .firewallRules() + .get(SQL_FIREWALLRULE_NAME)); } private void validateSqlElasticPoolNotFound(SqlServer sqlServer, String elasticPoolName) { @@ -1563,8 +1447,7 @@ private SqlServer createSqlServer() { } private SqlServer createSqlServer(String sqlServerName) { - return sqlServerManager - .sqlServers() + return sqlServerManager.sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) @@ -1655,31 +1538,41 @@ private void validateSqlDatabaseWithElasticPool(SqlDatabase sqlDatabase, String public void testRandomSku() { // LiveOnly because "test timing out after latest test proxy update" // "M" series is not supported in this region - List capabilityStatusList = Arrays.asList(CapabilityStatus.AVAILABLE, CapabilityStatus.DEFAULT); - List databaseSkus = DatabaseSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); + List capabilityStatusList + = Arrays.asList(CapabilityStatus.AVAILABLE, CapabilityStatus.DEFAULT); + List databaseSkus = DatabaseSku.getAll() + .stream() + .filter(sku -> !"M".equals(sku.toSku().family())) + .collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(databaseSkus); - List elasticPoolSkus = ElasticPoolSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); + List elasticPoolSkus = ElasticPoolSku.getAll() + .stream() + .filter(sku -> !"M".equals(sku.toSku().family())) + .collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(elasticPoolSkus); - sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() + sqlServerManager.sqlServers() + .getCapabilitiesByRegion(Region.US_EAST) + .supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { edition.supportedServiceLevelObjectives() - .stream().filter(serviceObjective -> - !capabilityStatusList.contains(serviceObjective.status()) - || "M".equals(serviceObjective.sku().family())) + .stream() + .filter(serviceObjective -> !capabilityStatusList.contains(serviceObjective.status()) + || "M".equals(serviceObjective.sku().family())) .forEach(serviceObjective -> databaseSkus.remove(DatabaseSku.fromSku(serviceObjective.sku()))); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { edition.supportedElasticPoolPerformanceLevels() - .stream().filter(performance -> - !capabilityStatusList.contains(performance.status()) - || "M".equals(performance.sku().family())) + .stream() + .filter(performance -> !capabilityStatusList.contains(performance.status()) + || "M".equals(performance.sku().family())) .forEach(performance -> elasticPoolSkus.remove(ElasticPoolSku.fromSku(performance.sku()))); }); }); - SqlServer sqlServer = sqlServerManager.sqlServers().define(sqlServerName) + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") @@ -1690,10 +1583,17 @@ public void testRandomSku() { // https://learn.microsoft.com/en-us/azure/azure-sql/database/resource-limits-logical-server?view=azuresql#logical-server-limits Flux.merge( Flux.range(0, 3) - .flatMap(i -> sqlServer.databases().define("database" + i).withSku(databaseSkus.get(i)).createAsync().cast(Indexable.class)), + .flatMap(i -> sqlServer.databases() + .define("database" + i) + .withSku(databaseSkus.get(i)) + .createAsync() + .cast(Indexable.class)), Flux.range(0, 3) - .flatMap(i -> sqlServer.elasticPools().define("elasticPool" + i).withSku(elasticPoolSkus.get(i)).createAsync().cast(Indexable.class)) - ) + .flatMap(i -> sqlServer.elasticPools() + .define("elasticPool" + i) + .withSku(elasticPoolSkus.get(i)) + .createAsync() + .cast(Indexable.class))) .blockLast(); } @@ -1702,14 +1602,17 @@ public void testRandomSku() { public void generateSku() throws IOException { StringBuilder databaseSkuBuilder = new StringBuilder(); StringBuilder elasticPoolSkuBuilder = new StringBuilder(); - sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() + sqlServerManager.sqlServers() + .getCapabilitiesByRegion(Region.US_EAST) + .supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { if (edition.name().equalsIgnoreCase("System")) { return; } edition.supportedServiceLevelObjectives().forEach(serviceObjective -> { - addStaticSkuDefinition(databaseSkuBuilder, edition.name(), serviceObjective.name(), serviceObjective.sku(), "DatabaseSku"); + addStaticSkuDefinition(databaseSkuBuilder, edition.name(), serviceObjective.name(), + serviceObjective.sku(), "DatabaseSku"); }); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { @@ -1717,19 +1620,25 @@ public void generateSku() throws IOException { return; } edition.supportedElasticPoolPerformanceLevels().forEach(performance -> { - String detailName = String.format("%s_%d", performance.sku().name(), performance.sku().capacity()); - addStaticSkuDefinition(elasticPoolSkuBuilder, edition.name(), detailName, performance.sku(), "ElasticPoolSku"); + String detailName + = String.format("%s_%d", performance.sku().name(), performance.sku().capacity()); + addStaticSkuDefinition(elasticPoolSkuBuilder, edition.name(), detailName, performance.sku(), + "ElasticPoolSku"); }); }); }); - String databaseSku = new String(readAllBytes(getClass().getResourceAsStream("/DatabaseSku.java")), StandardCharsets.UTF_8); + String databaseSku + = new String(readAllBytes(getClass().getResourceAsStream("/DatabaseSku.java")), StandardCharsets.UTF_8); databaseSku = databaseSku.replace("", databaseSkuBuilder.toString()); - Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java").toPath(), databaseSku.getBytes(StandardCharsets.UTF_8)); + Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java").toPath(), + databaseSku.getBytes(StandardCharsets.UTF_8)); - String elasticPoolSku = new String(readAllBytes(getClass().getResourceAsStream("/ElasticPoolSku.java")), StandardCharsets.UTF_8); + String elasticPoolSku + = new String(readAllBytes(getClass().getResourceAsStream("/ElasticPoolSku.java")), StandardCharsets.UTF_8); elasticPoolSku = elasticPoolSku.replace("", elasticPoolSkuBuilder.toString()); - Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java").toPath(), elasticPoolSku.getBytes(StandardCharsets.UTF_8)); + Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java").toPath(), + elasticPoolSku.getBytes(StandardCharsets.UTF_8)); sqlServerManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); // for deletion } @@ -1748,37 +1657,47 @@ private byte[] readAllBytes(InputStream inputStream) throws IOException { } } - private void addStaticSkuDefinition(StringBuilder builder, String edition, String detailName, Sku sku, String className) { - builder - .append("\n ").append("/** ").append(edition).append(" Edition with ").append(detailName).append(" sku. */") - .append("\n ").append("public static final ").append(className).append(" ").append(String.format("%s_%s", edition.toUpperCase(Locale.ROOT), detailName.toUpperCase(Locale.ROOT))).append(" =") - .append("\n new ").append(className).append("(") - .append(sku.name() == null ? null : "\"" + sku.name() + "\"") - .append(", ") - .append(sku.tier() == null ? null : "\"" + sku.tier() + "\"") - .append(", ") - .append(sku.family() == null ? null : "\"" + sku.family() + "\"") - .append(", ") - .append(sku.capacity()) - .append(", ") - .append(sku.size() == null ? null : "\"" + sku.size() + "\"") - .append(");"); + private void addStaticSkuDefinition(StringBuilder builder, String edition, String detailName, Sku sku, + String className) { + builder.append("\n ") + .append("/** ") + .append(edition) + .append(" Edition with ") + .append(detailName) + .append(" sku. */") + .append("\n ") + .append("public static final ") + .append(className) + .append(" ") + .append(String.format("%s_%s", edition.toUpperCase(Locale.ROOT), detailName.toUpperCase(Locale.ROOT))) + .append(" =") + .append("\n new ") + .append(className) + .append("(") + .append(sku.name() == null ? null : "\"" + sku.name() + "\"") + .append(", ") + .append(sku.tier() == null ? null : "\"" + sku.tier() + "\"") + .append(", ") + .append(sku.family() == null ? null : "\"" + sku.family() + "\"") + .append(", ") + .append(sku.capacity()) + .append(", ") + .append(sku.size() == null ? null : "\"" + sku.size() + "\"") + .append(");"); } @Test public void canCreateAndUpdatePublicNetworkAccess() { // Create - SqlServer sqlServer = - sqlServerManager - .sqlServers() - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAdministratorLogin("userName") - .withAdministratorPassword("P@ssword~1") - .withoutAccessFromAzureServices() - .disablePublicNetworkAccess() - .create(); + SqlServer sqlServer = sqlServerManager.sqlServers() + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin("userName") + .withAdministratorPassword("P@ssword~1") + .withoutAccessFromAzureServices() + .disablePublicNetworkAccess() + .create(); sqlServer.refresh(); Assertions.assertEquals(ServerNetworkAccessFlag.DISABLED, sqlServer.publicNetworkAccess()); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerTest.java b/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerTest.java index 58e1cfdf9a43d..d0e69fa5a50b2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-sql/src/test/java/com/azure/resourcemanager/sql/SqlServerTest.java @@ -30,21 +30,10 @@ public abstract class SqlServerTest extends ResourceManagerTestProxyTestBase { protected String sqlServerName = ""; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml index e536840307f59..d44ee9dcd8c80 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml @@ -50,6 +50,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/StorageManager.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/StorageManager.java index ac559a10039a8..3be8725ddde5a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/StorageManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/StorageManager.java @@ -99,11 +99,8 @@ public StorageManager authenticate(TokenCredential credential, AzureProfile prof } private StorageManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new StorageManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new StorageManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainerImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainerImpl.java index 9d26bb8f4c9a8..5b2e5a844c5a2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainerImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainerImpl.java @@ -78,7 +78,10 @@ public Mono updateResourceAsync() { @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getBlobContainers().getAsync(resourceGroupName, accountName, containerName); + return this.manager() + .serviceClient() + .getBlobContainers() + .getAsync(resourceGroupName, accountName, containerName); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainersImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainersImpl.java index 88bec79a1f2dc..8a69bb2c148c1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainersImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobContainersImpl.java @@ -71,9 +71,7 @@ public PagedFlux listAsync(String resourceGroupName, Str @Override public Mono getAsync(String resourceGroupName, String accountName, String containerName) { BlobContainersClient client = this.innerModel(); - return client - .getAsync(resourceGroupName, accountName, containerName) - .map(this::wrapBlobContainerModel); + return client.getAsync(resourceGroupName, accountName, containerName).map(this::wrapBlobContainerModel); } @Override @@ -83,8 +81,8 @@ public Mono deleteAsync(String resourceGroupName, String accountName, Stri } @Override - public Mono setLegalHoldAsync( - String resourceGroupName, String accountName, String containerName, List tags) { + public Mono setLegalHoldAsync(String resourceGroupName, String accountName, String containerName, + List tags) { BlobContainersClient client = this.innerModel(); return client .setLegalHoldAsync(resourceGroupName, accountName, containerName, new LegalHoldInner().withTags(tags)) @@ -92,8 +90,8 @@ public Mono setLegalHoldAsync( } @Override - public Mono clearLegalHoldAsync( - String resourceGroupName, String accountName, String containerName, List tags) { + public Mono clearLegalHoldAsync(String resourceGroupName, String accountName, String containerName, + List tags) { BlobContainersClient client = this.innerModel(); return client .clearLegalHoldAsync(resourceGroupName, accountName, containerName, new LegalHoldInner().withTags(tags)) @@ -101,80 +99,61 @@ public Mono clearLegalHoldAsync( } @Override - public Mono getImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName) { + public Mono getImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName) { return getImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, null); } @Override - public Mono getImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue) { + public Mono getImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, String eTagValue) { BlobContainersClient client = this.innerModel(); - return client - .getImmutabilityPolicyWithResponseAsync(resourceGroupName, accountName, containerName, eTagValue) + return client.getImmutabilityPolicyWithResponseAsync(resourceGroupName, accountName, containerName, eTagValue) .flatMap(r -> Mono.justOrEmpty(r.getValue())) .map(this::wrapImmutabilityPolicyModel); } @Override - public Mono deleteImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName) { + public Mono deleteImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName) { return deleteImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, null); } @Override - public Mono deleteImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue) { + public Mono deleteImmutabilityPolicyAsync(String resourceGroupName, String accountName, String containerName, + String eTagValue) { return innerModel().deleteImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, eTagValue) .then(); } @Override - public Mono lockImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName) { + public Mono lockImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName) { return lockImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, null); } @Override - public Mono lockImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue) { + public Mono lockImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, String eTagValue) { BlobContainersClient client = this.innerModel(); - return client - .lockImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, eTagValue) + return client.lockImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, eTagValue) .map(inner -> new ImmutabilityPolicyImpl(inner, manager())); } @Override - public Mono extendImmutabilityPolicyAsync( - String resourceGroupName, - String accountName, - String containerName, - int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites) { - return extendImmutabilityPolicyAsync( - resourceGroupName, - accountName, - containerName, - immutabilityPeriodSinceCreationInDays, - allowProtectedAppendWrites, - null); + public Mono extendImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites) { + return extendImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, + immutabilityPeriodSinceCreationInDays, allowProtectedAppendWrites, null); } @Override - public Mono extendImmutabilityPolicyAsync( - String resourceGroupName, - String accountName, - String containerName, - int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites, + public Mono extendImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites, String eTagValue) { BlobContainersClient client = this.innerModel(); return client - .extendImmutabilityPolicyWithResponseAsync( - resourceGroupName, - accountName, - containerName, - eTagValue, + .extendImmutabilityPolicyWithResponseAsync(resourceGroupName, accountName, containerName, eTagValue, new ImmutabilityPolicyInner() .withImmutabilityPeriodSinceCreationInDays(immutabilityPeriodSinceCreationInDays) .withAllowProtectedAppendWrites(allowProtectedAppendWrites)) @@ -199,59 +178,61 @@ public void delete(String resourceGroupName, String accountName, String containe @Override public LegalHold setLegalHold(String resourceGroupName, String accountName, String containerName, - List tags) { + List tags) { return this.setLegalHoldAsync(resourceGroupName, accountName, containerName, tags).block(); } @Override public LegalHold clearLegalHold(String resourceGroupName, String accountName, String containerName, - List tags) { + List tags) { return this.clearLegalHoldAsync(resourceGroupName, accountName, containerName, tags).block(); } @Override public ImmutabilityPolicy getImmutabilityPolicy(String resourceGroupName, String accountName, - String containerName) { + String containerName) { return this.getImmutabilityPolicyAsync(resourceGroupName, accountName, containerName).block(); } @Override - public void deleteImmutabilityPolicy(String resourceGroupName, String accountName, - String containerName) { + public void deleteImmutabilityPolicy(String resourceGroupName, String accountName, String containerName) { this.deleteImmutabilityPolicyAsync(resourceGroupName, accountName, containerName).block(); } @Override public ImmutabilityPolicy lockImmutabilityPolicy(String resourceGroupName, String accountName, - String containerName) { + String containerName) { return this.lockImmutabilityPolicyAsync(resourceGroupName, accountName, containerName).block(); } @Override public ImmutabilityPolicy extendImmutabilityPolicy(String resourceGroupName, String accountName, - String containerName, int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites) { - return this.extendImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, - immutabilityPeriodSinceCreationInDays, allowProtectedAppendWrites).block(); + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites) { + return this + .extendImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, + immutabilityPeriodSinceCreationInDays, allowProtectedAppendWrites) + .block(); } @Override public void deleteImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, - String eTagValue) { + String eTagValue) { this.deleteImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, eTagValue).block(); } @Override public ImmutabilityPolicy lockImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, - String eTagValue) { + String eTagValue) { return this.lockImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, eTagValue).block(); } @Override public ImmutabilityPolicy extendImmutabilityPolicy(String resourceGroupName, String accountName, - String containerName, int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites, String eTagValue) { - return this.extendImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, - immutabilityPeriodSinceCreationInDays, allowProtectedAppendWrites, eTagValue).block(); + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites, + String eTagValue) { + return this + .extendImmutabilityPolicyAsync(resourceGroupName, accountName, containerName, + immutabilityPeriodSinceCreationInDays, allowProtectedAppendWrites, eTagValue) + .block(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicePropertiesImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicePropertiesImpl.java index 685c60547ad54..0a6dbc9c34e82 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicePropertiesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicePropertiesImpl.java @@ -52,16 +52,14 @@ public StorageManager manager() { @Override public Mono createResourceAsync() { BlobServicesClient client = this.manager().serviceClient().getBlobServices(); - return client - .setServicePropertiesAsync(this.resourceGroupName, this.accountName, this.innerModel()) + return client.setServicePropertiesAsync(this.resourceGroupName, this.accountName, this.innerModel()) .map(innerToFluentMap(this)); } @Override public Mono updateResourceAsync() { BlobServicesClient client = this.manager().serviceClient().getBlobServices(); - return client - .setServicePropertiesAsync(this.resourceGroupName, this.accountName, this.innerModel()) + return client.setServicePropertiesAsync(this.resourceGroupName, this.accountName, this.innerModel()) .map(innerToFluentMap(this)); } @@ -169,7 +167,8 @@ public BlobServicePropertiesImpl withDeleteRetentionPolicy(DeleteRetentionPolicy @Override public BlobServicePropertiesImpl withDeleteRetentionPolicyEnabled(int numDaysEnabled) { - this.innerModel().withDeleteRetentionPolicy(new DeleteRetentionPolicy().withEnabled(true).withDays(numDaysEnabled)); + this.innerModel() + .withDeleteRetentionPolicy(new DeleteRetentionPolicy().withEnabled(true).withDays(numDaysEnabled)); return this; } @@ -199,7 +198,8 @@ public BlobServicePropertiesImpl withContainerDeleteRetentionPolicy(DeleteRetent @Override public BlobServicePropertiesImpl withContainerDeleteRetentionPolicyEnabled(int numDaysEnabled) { - this.innerModel().withContainerDeleteRetentionPolicy(new DeleteRetentionPolicy().withEnabled(true).withDays(numDaysEnabled)); + this.innerModel() + .withContainerDeleteRetentionPolicy(new DeleteRetentionPolicy().withEnabled(true).withDays(numDaysEnabled)); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ImmutabilityPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ImmutabilityPolicyImpl.java index 44427671a58f3..e91d174e41ab4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ImmutabilityPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ImmutabilityPolicyImpl.java @@ -50,11 +50,8 @@ public StorageManager manager() { public Mono createResourceAsync() { BlobContainersClient client = this.manager().serviceClient().getBlobContainers(); return client - .createOrUpdateImmutabilityPolicyWithResponseAsync( - this.resourceGroupName, - this.accountName, - this.containerName, - null, + .createOrUpdateImmutabilityPolicyWithResponseAsync(this.resourceGroupName, this.accountName, + this.containerName, null, new ImmutabilityPolicyInner() .withImmutabilityPeriodSinceCreationInDays(this.cImmutabilityPeriodSinceCreationInDays)) .flatMap(r -> Mono.justOrEmpty(r.getValue())) @@ -65,27 +62,23 @@ public Mono createResourceAsync() { public Mono updateResourceAsync() { BlobContainersClient client = this.manager().serviceClient().getBlobContainers(); return client - .createOrUpdateImmutabilityPolicyWithResponseAsync( - this.resourceGroupName, - this.accountName, - this.containerName, - this.eTagState.ifMatchValueOnUpdate(this.innerModel().etag()), + .createOrUpdateImmutabilityPolicyWithResponseAsync(this.resourceGroupName, this.accountName, + this.containerName, this.eTagState.ifMatchValueOnUpdate(this.innerModel().etag()), new ImmutabilityPolicyInner() .withImmutabilityPeriodSinceCreationInDays(this.uImmutabilityPeriodSinceCreationInDays)) .flatMap(r -> Mono.justOrEmpty(r.getValue())) .map(innerToFluentMap(this)) - .map( - self -> { - eTagState.clear(); - return self; - }); + .map(self -> { + eTagState.clear(); + return self; + }); } @Override protected Mono getInnerAsync() { BlobContainersClient client = this.manager().serviceClient().getBlobContainers(); - return client.getImmutabilityPolicyWithResponseAsync( - this.resourceGroupName, this.accountName, this.containerName, null) + return client + .getImmutabilityPolicyWithResponseAsync(this.resourceGroupName, this.accountName, this.containerName, null) .flatMap(r -> Mono.justOrEmpty(r.getValue())); } @@ -131,8 +124,8 @@ public void lock() { @Override public Mono lockAsync() { - return manager().blobContainers().lockImmutabilityPolicyAsync(this.resourceGroupName, this.accountName, - this.containerName, this.etag()) + return manager().blobContainers() + .lockImmutabilityPolicyAsync(this.resourceGroupName, this.accountName, this.containerName, this.etag()) .map(p -> { this.setInner(p.innerModel()); return p; @@ -147,9 +140,9 @@ public void extend(int immutabilityPeriodSinceCreationInDays) { @Override public Mono extendAsync(int immutabilityPeriodSinceCreationInDays) { - return manager().blobContainers().extendImmutabilityPolicyAsync(this.resourceGroupName, this.accountName, - this.containerName, immutabilityPeriodSinceCreationInDays, this.innerModel().allowProtectedAppendWrites(), - this.etag()) + return manager().blobContainers() + .extendImmutabilityPolicyAsync(this.resourceGroupName, this.accountName, this.containerName, + immutabilityPeriodSinceCreationInDays, this.innerModel().allowProtectedAppendWrites(), this.etag()) .map(p -> { this.setInner(p.innerModel()); return p; @@ -158,8 +151,8 @@ public Mono extendAsync(int immutabilityPeriodSinceCreationInDays) { } @Override - public ImmutabilityPolicyImpl withExistingContainer( - String resourceGroupName, String accountName, String containerName) { + public ImmutabilityPolicyImpl withExistingContainer(String resourceGroupName, String accountName, + String containerName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; this.containerName = containerName; diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPoliciesImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPoliciesImpl.java index 13d9a7a9c22aa..f0224fc7c9978 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPoliciesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPoliciesImpl.java @@ -39,7 +39,8 @@ private ManagementPolicyImpl wrapModel(String name) { @Override public Mono getAsync(String resourceGroupName, String accountName) { - return this.innerModel().getAsync(resourceGroupName, accountName, ManagementPolicyName.DEFAULT) + return this.innerModel() + .getAsync(resourceGroupName, accountName, ManagementPolicyName.DEFAULT) .map(inner -> wrapModel(inner)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPolicyImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPolicyImpl.java index 0c57928d95b03..03b93621d82ac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPolicyImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/ManagementPolicyImpl.java @@ -64,11 +64,10 @@ public Mono createResourceAsync() { return client .createOrUpdateAsync(this.resourceGroupName, this.accountName, ManagementPolicyName.DEFAULT, new ManagementPolicyInner().withPolicy(cpolicy)) - .map( - resource -> { - resetCreateUpdateParameters(); - return resource; - }) + .map(resource -> { + resetCreateUpdateParameters(); + return resource; + }) .map(innerToFluentMap(this)); } @@ -78,11 +77,10 @@ public Mono updateResourceAsync() { return client .createOrUpdateAsync(this.resourceGroupName, this.accountName, ManagementPolicyName.DEFAULT, new ManagementPolicyInner().withPolicy(upolicy)) - .map( - resource -> { - resetCreateUpdateParameters(); - return resource; - }) + .map(resource -> { + resetCreateUpdateParameters(); + return resource; + }) .map(innerToFluentMap(this)); } @@ -132,9 +130,7 @@ public List rules() { List originalRules = this.policy().rules(); return originalRules == null ? Collections.emptyList() - : originalRules.stream() - .map(rule -> new PolicyRuleImpl(rule, this)) - .collect(Collectors.toList()); + : originalRules.stream().map(rule -> new PolicyRuleImpl(rule, this)).collect(Collectors.toList()); } @Override @@ -186,10 +182,9 @@ public PolicyRule.Update updateRule(String name) { } } if (ruleToUpdate == null) { - throw logger.logExceptionAsError(new UnsupportedOperationException( - "There is no rule that exists with the name " - + name - + ". Please define a rule with this name before updating.")); + throw logger + .logExceptionAsError(new UnsupportedOperationException("There is no rule that exists with the name " + + name + ". Please define a rule with this name before updating.")); } return new PolicyRuleImpl(ruleToUpdate, this); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/PolicyRuleImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/PolicyRuleImpl.java index 33f6d0688acaa..7120cb7372f54 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/PolicyRuleImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/PolicyRuleImpl.java @@ -21,7 +21,8 @@ import java.util.Collections; import java.util.List; -class PolicyRuleImpl implements PolicyRule, PolicyRule.Definition, PolicyRule.Update, HasInnerModel { +class PolicyRuleImpl + implements PolicyRule, PolicyRule.Definition, PolicyRule.Update, HasInnerModel { private ManagementPolicyRule inner; private ManagementPolicyImpl managementPolicyImpl; @@ -225,10 +226,8 @@ public PolicyRuleImpl withTierToCoolActionOnBaseBlob(float daysAfterBaseBlobModi if (currentBaseBlob == null) { currentBaseBlob = new ManagementPolicyBaseBlob(); } - currentBaseBlob - .withTierToCool( - new DateAfterModification() - .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilCooling)); + currentBaseBlob.withTierToCool(new DateAfterModification() + .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilCooling)); this.inner.definition().actions().withBaseBlob(currentBaseBlob); return this; } @@ -239,10 +238,8 @@ public PolicyRuleImpl withTierToArchiveActionOnBaseBlob(float daysAfterBaseBlobM if (currentBaseBlob == null) { currentBaseBlob = new ManagementPolicyBaseBlob(); } - currentBaseBlob - .withTierToArchive( - new DateAfterModification() - .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilArchiving)); + currentBaseBlob.withTierToArchive(new DateAfterModification() + .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilArchiving)); this.inner.definition().actions().withBaseBlob(currentBaseBlob); return this; } @@ -253,10 +250,8 @@ public PolicyRuleImpl withDeleteActionOnBaseBlob(float daysAfterBaseBlobModifica if (currentBaseBlob == null) { currentBaseBlob = new ManagementPolicyBaseBlob(); } - currentBaseBlob - .withDelete( - new DateAfterModification() - .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilDeleting)); + currentBaseBlob.withDelete(new DateAfterModification() + .withDaysAfterModificationGreaterThan(daysAfterBaseBlobModificationUntilDeleting)); this.inner.definition().actions().withBaseBlob(currentBaseBlob); return this; } @@ -264,9 +259,8 @@ public PolicyRuleImpl withDeleteActionOnBaseBlob(float daysAfterBaseBlobModifica @Override public PolicyRuleImpl withDeleteActionOnSnapShot(float daysAfterSnapShotCreationUntilDeleting) { ManagementPolicySnapShot currentSnapShot = new ManagementPolicySnapShot(); - currentSnapShot - .withDelete( - new DateAfterCreation().withDaysAfterCreationGreaterThan(daysAfterSnapShotCreationUntilDeleting)); + currentSnapShot.withDelete( + new DateAfterCreation().withDaysAfterCreationGreaterThan(daysAfterSnapShotCreationUntilDeleting)); this.inner.definition().actions().withSnapshot(currentSnapShot); return this; } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountImpl.java index b0420002c3a1f..a3c25abf18fe3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountImpl.java @@ -72,7 +72,8 @@ class StorageAccountImpl private StorageEncryptionHelper encryptionHelper; private StorageAccountMsiHandler storageAccountMsiHandler; - StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager, final AuthorizationManager authorizationManager) { + StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager, + final AuthorizationManager authorizationManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); @@ -83,7 +84,8 @@ class StorageAccountImpl @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { - accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); + accountStatuses + = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @@ -124,7 +126,8 @@ public ProvisioningState provisioningState() { @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { - publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); + publicEndpoints + = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @@ -169,8 +172,7 @@ public String systemAssignedManagedServiceIdentityPrincipalId() { @Override public Set userAssignedManagedServiceIdentityIds() { - if (innerModel().identity() != null - && innerModel().identity().userAssignedIdentities() != null) { + if (innerModel().identity() != null && innerModel().identity().userAssignedIdentities() != null) { return Collections .unmodifiableSet(new HashSet(this.innerModel().identity().userAssignedIdentities().keySet())); } @@ -293,8 +295,7 @@ public List getKeys() { @Override public Mono> getKeysAsync() { - return this - .manager() + return this.manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) @@ -308,8 +309,7 @@ public List regenerateKey(String keyName) { @Override public Mono> regenerateKeyAsync(String keyName) { - return this - .manager() + return this.manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), @@ -324,11 +324,12 @@ public PagedIterable listPrivateLinkResources() { @Override public PagedFlux listPrivateLinkResourcesAsync() { - Mono>> retList = this.manager().serviceClient().getPrivateLinkResources() + Mono>> retList = this.manager() + .serviceClient() + .getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) - .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() - .map(PrivateLinkResourceImpl::new) - .collect(Collectors.toList()))); + .map(response -> new SimpleResponse<>(response, + response.getValue().value().stream().map(PrivateLinkResourceImpl::new).collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @@ -340,7 +341,9 @@ public PagedIterable listPrivateEndpointConnections() @Override public PagedFlux listPrivateEndpointConnectionsAsync() { - return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() + return PagedConverter.mapPage(this.manager() + .serviceClient() + .getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @@ -351,12 +354,13 @@ public void approvePrivateEndpointConnection(String privateEndpointConnectionNam @Override public Mono approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState() - .withStatus( - PrivateEndpointServiceConnectionStatus.APPROVED))) + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED))) .then(); } @@ -367,30 +371,31 @@ public void rejectPrivateEndpointConnection(String privateEndpointConnectionName @Override public Mono rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { - return this.manager().serviceClient().getPrivateEndpointConnections() + return this.manager() + .serviceClient() + .getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionState() - .withStatus( - PrivateEndpointServiceConnectionStatus.REJECTED))) + new PrivateEndpointConnectionInner() + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED))) .then(); } @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - storageAccount -> { - StorageAccountImpl impl = (StorageAccountImpl) storageAccount; - impl.clearWrapperProperties(); - return impl; - }); + return super.refreshAsync().map(storageAccount -> { + StorageAccountImpl impl = (StorageAccountImpl) storageAccount; + impl.clearWrapperProperties(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); + return this.manager() + .serviceClient() + .getStorageAccounts() + .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override @@ -458,7 +463,8 @@ public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, Stri } @Override - public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, Identity userAssignedIdentity) { + public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + Identity userAssignedIdentity) { if (userAssignedIdentity == null) { throw new IllegalArgumentException("User-assigned identity is null."); } @@ -466,7 +472,8 @@ public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, Stri } @Override - public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, String userAssignedIdentityId) { + public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + String userAssignedIdentityId) { if (CoreUtils.isNullOrEmpty(userAssignedIdentityId)) { throw new IllegalArgumentException("User-assigned identity ID is null."); } @@ -793,17 +800,13 @@ public Mono createResourceAsync() { this.storageAccountMsiHandler.handleExternalIdentities(); this.storageAccountMsiHandler.clear(); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); - return this - .manager() + return this.manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) - .flatMap( - storageAccountInner -> - client - .getByResourceGroupAsync(resourceGroupName(), this.name()) - .map(innerToFluentMap(this)) - .doOnNext(storageAccount -> clearWrapperProperties())); + .flatMap(storageAccountInner -> client.getByResourceGroupAsync(resourceGroupName(), this.name()) + .map(innerToFluentMap(this)) + .doOnNext(storageAccount -> clearWrapperProperties())); } @Override @@ -813,8 +816,7 @@ public Mono updateResourceAsync() { this.storageAccountMsiHandler.processCreatedExternalIdentities(); this.storageAccountMsiHandler.handleExternalIdentities(); this.storageAccountMsiHandler.clear(); - return this - .manager() + return this.manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) @@ -826,27 +828,20 @@ public Mono updateResourceAsync() { public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { - this - .createParameters - .withAzureFilesIdentityBasedAuthentication( - new AzureFilesIdentityBasedAuthentication() - .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); + this.createParameters + .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication() + .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { - this - .createParameters + this.createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { - this - .updateParameters - .azureFilesIdentityBasedAuthentication() + this.updateParameters.azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { - this - .updateParameters - .azureFilesIdentityBasedAuthentication() + this.updateParameters.azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } @@ -872,13 +867,15 @@ public StorageAccountImpl withHnsEnabled(boolean enabled) { } @Override - public StorageAccountImpl withNewUserAssignedManagedServiceIdentity(Creatable creatableIdentity) { + public StorageAccountImpl withNewUserAssignedManagedServiceIdentity( + Creatable creatableIdentity) { this.storageAccountMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity); return this; } @Override - public StorageAccountImpl withExistingUserAssignedManagedServiceIdentity(com.azure.resourcemanager.msi.models.Identity identity) { + public StorageAccountImpl + withExistingUserAssignedManagedServiceIdentity(com.azure.resourcemanager.msi.models.Identity identity) { this.storageAccountMsiHandler.withExistingExternalManagedServiceIdentity(identity); return this; } @@ -944,25 +941,23 @@ private static final class PrivateEndpointConnectionImpl implements PrivateEndpo private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; - private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState - privateLinkServiceConnectionState; + private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; - this.privateEndpoint = innerModel.privateEndpoint() == null - ? null - : new PrivateEndpoint(innerModel.privateEndpoint().id()); + this.privateEndpoint + = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( - innerModel.privateLinkServiceConnectionState().status() == null - ? null - : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus - .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), - innerModel.privateLinkServiceConnectionState().description(), - innerModel.privateLinkServiceConnectionState().actionRequired()); + innerModel.privateLinkServiceConnectionState().status() == null + ? null + : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus + .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), + innerModel.privateLinkServiceConnectionState().description(), + innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountMsiHandler.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountMsiHandler.java index 311a1e58d3d89..750b8d26f3a4d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountMsiHandler.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountMsiHandler.java @@ -79,7 +79,8 @@ StorageAccountMsiHandler withoutLocalManagedServiceIdentity() { * @param creatableIdentity yet-to-be-created identity to be associated with the storage account * @return StorageAccountMsiHandler */ - StorageAccountMsiHandler withNewExternalManagedServiceIdentity(Creatable creatableIdentity) { + StorageAccountMsiHandler withNewExternalManagedServiceIdentity( + Creatable creatableIdentity) { this.initStorageAccountIdentity(IdentityType.USER_ASSIGNED, false); TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatableIdentity; @@ -98,7 +99,8 @@ StorageAccountMsiHandler withNewExternalManagedServiceIdentity(Creatable removeIds = new HashSet<>(); - for (Map.Entry entrySet - : this.userAssignedIdentities.entrySet()) { + for (Map.Entry entrySet : this.userAssignedIdentities.entrySet()) { if (entrySet.getValue() == null) { removeIds.add(entrySet.getKey().toLowerCase(Locale.ROOT)); } } // If so check user want to remove all the identities - boolean removeAllCurrentIds = - currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); + boolean removeAllCurrentIds + = currentIds.size() == removeIds.size() && currentIds.containsAll(removeIds); if (removeAllCurrentIds) { // If so adjust the identity type [Setting type to SYSTEM_ASSIGNED orNONE will remove all the // identities] @@ -239,8 +242,8 @@ private boolean handleRemoveAllExternalIdentitiesCase() { if (currentIds.isEmpty() && !removeIds.isEmpty() && currentIdentity == null) { // If so we are in a invalid state but we want to send user input to service and let service // handle it (ignore or error). - this.storageAccount.updateParameters.withIdentity( - new Identity().withType(IdentityType.NONE).withUserAssignedIdentities(null)); + this.storageAccount.updateParameters + .withIdentity(new Identity().withType(IdentityType.NONE).withUserAssignedIdentities(null)); return true; } } @@ -255,8 +258,7 @@ private boolean handleRemoveAllExternalIdentitiesCase() { * @param identityType the identity type to set */ private void initStorageAccountIdentity(IdentityType identityType, Boolean isWithout) { - if (!identityType.equals(IdentityType.USER_ASSIGNED) - && !identityType.equals(IdentityType.SYSTEM_ASSIGNED)) { + if (!identityType.equals(IdentityType.USER_ASSIGNED) && !identityType.equals(IdentityType.SYSTEM_ASSIGNED)) { throw logger.logExceptionAsError(new IllegalArgumentException("Invalid argument: " + identityType)); } if (this.storageAccount.isInCreateMode()) { @@ -291,7 +293,8 @@ private void initStorageAccountIdentity(IdentityType identityType, Boolean isWit || this.storageAccount.updateParameters.identity().type().equals(identityType)) { this.storageAccount.updateParameters.identity().withType(identityType); } else { - this.storageAccount.updateParameters.identity().withType(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED); + this.storageAccount.updateParameters.identity() + .withType(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountsImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountsImpl.java index ce4bf1b979a0c..8b342b6487e4d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageAccountsImpl.java @@ -19,9 +19,8 @@ import reactor.core.publisher.Mono; /** The implementation of StorageAccounts and its parent interfaces. */ -public class StorageAccountsImpl - extends TopLevelModifiableResourcesImpl< - StorageAccount, StorageAccountImpl, StorageAccountInner, StorageAccountsClient, StorageManager> +public class StorageAccountsImpl extends + TopLevelModifiableResourcesImpl implements StorageAccounts { private final AuthorizationManager authorizationManager; @@ -37,16 +36,14 @@ public CheckNameAvailabilityResult checkNameAvailability(String name) { @Override public Mono checkNameAvailabilityAsync(String name) { - return this - .inner() + return this.inner() .checkNameAvailabilityAsync(new StorageAccountCheckNameAvailabilityParameters().withName(name)) .map(CheckNameAvailabilityResult::new); } @Override public StorageAccountImpl define(String name) { - return wrapModel(name) - .withSku(StorageAccountSkuType.STANDARD_RAGRS) + return wrapModel(name).withSku(StorageAccountSkuType.STANDARD_RAGRS) .withGeneralPurposeAccountKindV2() .withOnlyHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_2) @@ -64,7 +61,8 @@ protected StorageAccountImpl wrapModel(StorageAccountInner storageAccountInner) if (storageAccountInner == null) { return null; } - return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager(), this.authorizationManager); + return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager(), + this.authorizationManager); } @Override @@ -73,10 +71,9 @@ public String createSasToken(String resourceGroupName, String accountName, Servi } @Override - public Mono createSasTokenAsync( - String resourceGroupName, String accountName, ServiceSasParameters parameters) { - return this - .inner() + public Mono createSasTokenAsync(String resourceGroupName, String accountName, + ServiceSasParameters parameters) { + return this.inner() .listServiceSasAsync(resourceGroupName, accountName, parameters) .map(ListServiceSasResponseInner::serviceSasToken); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageEncryptionHelper.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageEncryptionHelper.java index c2a11c46dbb48..1a5632fe0c902 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageEncryptionHelper.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageEncryptionHelper.java @@ -85,7 +85,8 @@ static Map encryptionStatuses(St } static boolean infrastructureEncryptionEnabled(StorageAccountInner inner) { - return inner != null && inner.encryption() != null + return inner != null + && inner.encryption() != null && ResourceManagerUtils.toPrimitiveBoolean(inner.encryption().requireInfrastructureEncryption()); } @@ -93,15 +94,19 @@ public IdentityType identityTypeForKeyVault(StorageAccountInner inner) { if (!StorageAccountEncryptionKeySource.MICROSOFT_KEYVAULT.equals(encryptionKeySource(inner))) { return null; } - return inner.encryption().encryptionIdentity() == null || inner.encryption().encryptionIdentity().encryptionUserAssignedIdentity() == null - ? IdentityType.SYSTEM_ASSIGNED : IdentityType.USER_ASSIGNED; + return inner.encryption().encryptionIdentity() == null + || inner.encryption().encryptionIdentity().encryptionUserAssignedIdentity() == null + ? IdentityType.SYSTEM_ASSIGNED + : IdentityType.USER_ASSIGNED; } public String userAssignedIdentityIdForKeyVault(StorageAccountInner inner) { if (!IdentityType.USER_ASSIGNED.equals(identityTypeForKeyVault(inner))) { return null; } - return inner.encryption().encryptionIdentity() == null ? null : inner.encryption().encryptionIdentity().encryptionUserAssignedIdentity(); + return inner.encryption().encryptionIdentity() == null + ? null + : inner.encryption().encryptionIdentity().encryptionUserAssignedIdentity(); } /** @@ -195,11 +200,11 @@ StorageEncryptionHelper withEncryptionKeyFromKeyVault(String keyVaultUri, String return withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion, null); } - public StorageEncryptionHelper withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, String identityId) { + public StorageEncryptionHelper withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + String identityId) { Encryption encryption = getEncryptionConfig(true); encryption.withKeySource(KeySource.MICROSOFT_KEYVAULT); - encryption - .withEncryptionIdentity(new EncryptionIdentity().withEncryptionUserAssignedIdentity(identityId)) + encryption.withEncryptionIdentity(new EncryptionIdentity().withEncryptionUserAssignedIdentity(identityId)) .withKeyVaultProperties( new KeyVaultProperties().withKeyVaultUri(keyVaultUri).withKeyName(keyName).withKeyVersion(keyVersion)); return this; @@ -290,8 +295,7 @@ private Encryption getEncryptionConfig(boolean createIfNotExists) { } if (this.inner.encryption().keyVaultProperties() != null) { clonedEncryption.withKeyVaultProperties(new KeyVaultProperties()); - clonedEncryption - .keyVaultProperties() + clonedEncryption.keyVaultProperties() .withKeyName(this.inner.encryption().keyVaultProperties().keyName()) .withKeyVaultUri(this.inner.encryption().keyVaultProperties().keyVaultUri()) .withKeyVersion(this.inner.encryption().keyVaultProperties().keyVersion()); @@ -300,32 +304,28 @@ private Encryption getEncryptionConfig(boolean createIfNotExists) { clonedEncryption.withServices(new EncryptionServices()); if (this.inner.encryption().services().blob() != null) { clonedEncryption.services().withBlob(new EncryptionService()); - clonedEncryption - .services() + clonedEncryption.services() .blob() .withEnabled(this.inner.encryption().services().blob().enabled()) .withKeyType(this.inner.encryption().services().blob().keyType()); } if (this.inner.encryption().services().file() != null) { clonedEncryption.services().withFile(new EncryptionService()); - clonedEncryption - .services() + clonedEncryption.services() .file() .withEnabled(this.inner.encryption().services().file().enabled()) .withKeyType(this.inner.encryption().services().file().keyType()); } if (this.inner.encryption().services().table() != null) { clonedEncryption.services().withTable(new EncryptionService()); - clonedEncryption - .services() + clonedEncryption.services() .table() .withEnabled(this.inner.encryption().services().table().enabled()) .withKeyType(this.inner.encryption().services().table().keyType()); } if (this.inner.encryption().services().queue() != null) { clonedEncryption.services().withQueue(new EncryptionService()); - clonedEncryption - .services() + clonedEncryption.services() .queue() .withEnabled(this.inner.encryption().services().queue().enabled()) .withKeyType(this.inner.encryption().services().queue().keyType()); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageNetworkRulesHelper.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageNetworkRulesHelper.java index 0e59e30d30553..311280751ac32 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageNetworkRulesHelper.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageNetworkRulesHelper.java @@ -208,8 +208,7 @@ StorageNetworkRulesHelper withAccessFromNetworkSubnet(String subnetId) { } } if (!found) { - networkRuleSet - .virtualNetworkRules() + networkRuleSet.virtualNetworkRules() .add(new VirtualNetworkRule().withVirtualNetworkResourceId(subnetId).withAction(Action.ALLOW)); } return this; @@ -449,8 +448,8 @@ void setDefaultActionIfRequired() { && updateParameters.networkRuleSet().ipRules().size() > 0) { anyRulesAddedFirstTime = true; } - final boolean anyExceptionAddedFirstTime = - !hasNoExistingException && updateParameters.networkRuleSet().bypass() != null; + final boolean anyExceptionAddedFirstTime + = !hasNoExistingException && updateParameters.networkRuleSet().bypass() != null; if ((anyRulesAddedFirstTime || anyExceptionAddedFirstTime) && updateParameters.networkRuleSet().defaultAction() == null) { // If there was no existing rules & exceptions and if user specified at least one @@ -556,18 +555,16 @@ private NetworkRuleSet getNetworkRuleSetConfig(boolean createIfNotExists) { if (this.inner.networkRuleSet().virtualNetworkRules() != null) { clonedNetworkRuleSet.withVirtualNetworkRules(new ArrayList()); for (VirtualNetworkRule rule : this.inner.networkRuleSet().virtualNetworkRules()) { - VirtualNetworkRule clonedRule = - new VirtualNetworkRule() - .withAction(rule.action()) - .withVirtualNetworkResourceId(rule.virtualNetworkResourceId()); + VirtualNetworkRule clonedRule = new VirtualNetworkRule().withAction(rule.action()) + .withVirtualNetworkResourceId(rule.virtualNetworkResourceId()); clonedNetworkRuleSet.virtualNetworkRules().add(clonedRule); } } if (this.inner.networkRuleSet().ipRules() != null) { clonedNetworkRuleSet.withIpRules(new ArrayList()); for (IpRule rule : this.inner.networkRuleSet().ipRules()) { - IpRule clonedRule = - new IpRule().withAction(rule.action()).withIpAddressOrRange(rule.ipAddressOrRange()); + IpRule clonedRule + = new IpRule().withAction(rule.action()).withIpAddressOrRange(rule.ipAddressOrRange()); clonedNetworkRuleSet.ipRules().add(clonedRule); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainer.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainer.java index 7c203d1ff7683..0f98e3ff63449 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainer.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainer.java @@ -62,12 +62,8 @@ public interface BlobContainer String type(); /** The entirety of the BlobContainer definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithBlobService, - DefinitionStages.WithPublicAccess, - DefinitionStages.WithMetadata, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithBlobService, + DefinitionStages.WithPublicAccess, DefinitionStages.WithMetadata, DefinitionStages.WithCreate { } /** Grouping of BlobContainer definition stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainers.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainers.java index c5ca1530c12aa..4cd0e9de1abed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainers.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobContainers.java @@ -97,8 +97,8 @@ public interface BlobContainers { * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono setLegalHoldAsync( - String resourceGroupName, String accountName, String containerName, List tags); + Mono setLegalHoldAsync(String resourceGroupName, String accountName, String containerName, + List tags); /** * Clears legal hold tags. Clearing the same or non-existent tag results in an idempotent operation. ClearLegalHold @@ -115,8 +115,8 @@ Mono setLegalHoldAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono clearLegalHoldAsync( - String resourceGroupName, String accountName, String containerName, List tags); + Mono clearLegalHoldAsync(String resourceGroupName, String accountName, String containerName, + List tags); /** * Gets the existing immutability policy along with the corresponding ETag in response headers and body. @@ -131,8 +131,8 @@ Mono clearLegalHoldAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono getImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName); + Mono getImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName); /** * Gets the existing immutability policy along with the corresponding ETag in response headers and body. @@ -150,8 +150,8 @@ Mono getImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono getImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue); + Mono getImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, String eTagValue); /** * Aborts an unlocked immutability policy. The response of delete has immutabilityPeriodSinceCreationInDays set to @@ -168,8 +168,7 @@ Mono getImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono deleteImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName); + Mono deleteImmutabilityPolicyAsync(String resourceGroupName, String accountName, String containerName); /** * Aborts an unlocked immutability policy. The response of delete has immutabilityPeriodSinceCreationInDays set to @@ -189,8 +188,8 @@ Mono deleteImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono deleteImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue); + Mono deleteImmutabilityPolicyAsync(String resourceGroupName, String accountName, String containerName, + String eTagValue); /** * Sets the ImmutabilityPolicy to Locked state. The only action allowed on a Locked policy is @@ -206,8 +205,8 @@ Mono deleteImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono lockImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName); + Mono lockImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName); /** * Sets the ImmutabilityPolicy to Locked state. The only action allowed on a Locked policy is @@ -226,8 +225,8 @@ Mono lockImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono lockImmutabilityPolicyAsync( - String resourceGroupName, String accountName, String containerName, String eTagValue); + Mono lockImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, String eTagValue); /** * Extends the immutabilityPeriodSinceCreationInDays of a locked immutabilityPolicy. The only action allowed on a @@ -249,12 +248,8 @@ Mono lockImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono extendImmutabilityPolicyAsync( - String resourceGroupName, - String accountName, - String containerName, - int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites); + Mono extendImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites); /** * Extends the immutabilityPeriodSinceCreationInDays of a locked immutabilityPolicy. The only action allowed on a @@ -279,12 +274,8 @@ Mono extendImmutabilityPolicyAsync( * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ - Mono extendImmutabilityPolicyAsync( - String resourceGroupName, - String accountName, - String containerName, - int immutabilityPeriodSinceCreationInDays, - Boolean allowProtectedAppendWrites, + Mono extendImmutabilityPolicyAsync(String resourceGroupName, String accountName, + String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites, String eTagValue); /** @@ -352,8 +343,7 @@ Mono extendImmutabilityPolicyAsync( * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the LegalHold property of a blob container. */ - LegalHold setLegalHold( - String resourceGroupName, String accountName, String containerName, List tags); + LegalHold setLegalHold(String resourceGroupName, String accountName, String containerName, List tags); /** * Clears legal hold tags. Clearing the same or non-existent tag results in an idempotent operation. ClearLegalHold @@ -372,8 +362,7 @@ LegalHold setLegalHold( * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the LegalHold property of a blob container. */ - LegalHold clearLegalHold( - String resourceGroupName, String accountName, String containerName, List tags); + LegalHold clearLegalHold(String resourceGroupName, String accountName, String containerName, List tags); /** * Gets the existing immutability policy along with the corresponding ETag in response headers and body. @@ -433,8 +422,7 @@ LegalHold clearLegalHold( * @return the ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. */ @Deprecated - ImmutabilityPolicy lockImmutabilityPolicy( - String resourceGroupName, String accountName, String containerName); + ImmutabilityPolicy lockImmutabilityPolicy(String resourceGroupName, String accountName, String containerName); /** * Extends the immutabilityPeriodSinceCreationInDays of a locked immutabilityPolicy. The only action allowed on a @@ -462,8 +450,7 @@ ImmutabilityPolicy lockImmutabilityPolicy( * @return the ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. */ @Deprecated - ImmutabilityPolicy extendImmutabilityPolicy( - String resourceGroupName, String accountName, String containerName, + ImmutabilityPolicy extendImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites); /** @@ -485,8 +472,7 @@ ImmutabilityPolicy extendImmutabilityPolicy( * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ - void deleteImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, - String eTagValue); + void deleteImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, String eTagValue); /** * Sets the ImmutabilityPolicy to Locked state. The only action allowed on a Locked policy is @@ -507,8 +493,8 @@ void deleteImmutabilityPolicy(String resourceGroupName, String accountName, Stri * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. */ - ImmutabilityPolicy lockImmutabilityPolicy( - String resourceGroupName, String accountName, String containerName, String eTagValue); + ImmutabilityPolicy lockImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, + String eTagValue); /** * Extends the immutabilityPeriodSinceCreationInDays of a locked immutabilityPolicy. The only action allowed on a @@ -535,8 +521,6 @@ ImmutabilityPolicy lockImmutabilityPolicy( * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. */ - ImmutabilityPolicy extendImmutabilityPolicy( - String resourceGroupName, String accountName, String containerName, - int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites, - String eTagValue); + ImmutabilityPolicy extendImmutabilityPolicy(String resourceGroupName, String accountName, String containerName, + int immutabilityPeriodSinceCreationInDays, Boolean allowProtectedAppendWrites, String eTagValue); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServiceProperties.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServiceProperties.java index dd3bcbdf38238..71461f1f7fcb1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServiceProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServiceProperties.java @@ -17,12 +17,8 @@ /** Type representing BlobServiceProperties. */ @Fluent -public interface BlobServiceProperties - extends HasInnerModel, - Indexable, - Refreshable, - Updatable, - HasManager { +public interface BlobServiceProperties extends HasInnerModel, Indexable, + Refreshable, Updatable, HasManager { /** @return the cors value. */ CorsRules cors(); @@ -231,25 +227,17 @@ interface WithLastAccessTimeTrackingPolicy { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithCors, - DefinitionStages.WithDefaultServiceVersion, - DefinitionStages.WithDeleteRetentionPolicy, - DefinitionStages.WithBlobVersioning, - DefinitionStages.WithContainerDeleteRetentionPolicy, - DefinitionStages.WithLastAccessTimeTrackingPolicy { + interface WithCreate extends Creatable, DefinitionStages.WithCors, + DefinitionStages.WithDefaultServiceVersion, DefinitionStages.WithDeleteRetentionPolicy, + DefinitionStages.WithBlobVersioning, DefinitionStages.WithContainerDeleteRetentionPolicy, + DefinitionStages.WithLastAccessTimeTrackingPolicy { } } + /** The template for a BlobServiceProperties update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithCors, - UpdateStages.WithDefaultServiceVersion, - UpdateStages.WithDeleteRetentionPolicy, - UpdateStages.WithBlobVersioning, - UpdateStages.WithContainerDeleteRetentionPolicy, - UpdateStages.WithLastAccessTimeTrackingPolicy { + interface Update extends Appliable, UpdateStages.WithCors, + UpdateStages.WithDefaultServiceVersion, UpdateStages.WithDeleteRetentionPolicy, UpdateStages.WithBlobVersioning, + UpdateStages.WithContainerDeleteRetentionPolicy, UpdateStages.WithLastAccessTimeTrackingPolicy { } /** Grouping of BlobServiceProperties update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServices.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServices.java index 6aea612dc91ac..2e315599d3350 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServices.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BlobServices.java @@ -9,8 +9,7 @@ /** Type representing BlobServices. */ @Fluent -public interface BlobServices - extends SupportsCreating { +public interface BlobServices extends SupportsCreating { /** * Gets the properties of a storage account’s Blob service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ImmutabilityPolicy.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ImmutabilityPolicy.java index 373dedcea4f00..d328819cc9f02 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ImmutabilityPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ImmutabilityPolicy.java @@ -17,12 +17,8 @@ /** Type representing ImmutabilityPolicy. */ @Fluent -public interface ImmutabilityPolicy - extends HasInnerModel, - Indexable, - Refreshable, - Updatable, - HasManager { +public interface ImmutabilityPolicy extends HasInnerModel, Indexable, + Refreshable, Updatable, HasManager { /** @return the etag value. */ String etag(); @@ -55,7 +51,7 @@ public interface ImmutabilityPolicy /** * Extends the immutability policy. - + * @param immutabilityPeriodSinceCreationInDays The immutability period for the blobs in the container since the * policy creation, in days. */ @@ -63,7 +59,7 @@ public interface ImmutabilityPolicy /** * Extends the immutability policy. - + * @param immutabilityPeriodSinceCreationInDays The immutability period for the blobs in the container since the * policy creation, in days. * @return the completion @@ -71,11 +67,8 @@ public interface ImmutabilityPolicy Mono extendAsync(int immutabilityPeriodSinceCreationInDays); /** The entirety of the ImmutabilityPolicy definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithContainer, - DefinitionStages.WithImmutabilityPeriodSinceCreationInDays, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithContainer, + DefinitionStages.WithImmutabilityPeriodSinceCreationInDays, DefinitionStages.WithCreate { } /** Grouping of ImmutabilityPolicy definition stages. */ @@ -98,8 +91,8 @@ interface WithContainer { * only. Every dash (-) character must be immediately preceded and followed by a letter or number * @return the next definition stage */ - WithImmutabilityPeriodSinceCreationInDays withExistingContainer( - String resourceGroupName, String accountName, String containerName); + WithImmutabilityPeriodSinceCreationInDays withExistingContainer(String resourceGroupName, + String accountName, String containerName); } /** The stage of the immutabilitypolicy definition allowing to specify ImmutabilityPeriodSinceCreationInDays. */ @@ -131,11 +124,10 @@ interface WithETagCheck { interface WithCreate extends WithETagCheck, Creatable { } } + /** The template for a ImmutabilityPolicy update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithETagCheck, - UpdateStages.WithImmutabilityPeriodSinceCreationInDays { + interface Update extends Appliable, UpdateStages.WithETagCheck, + UpdateStages.WithImmutabilityPeriodSinceCreationInDays { } /** Grouping of ImmutabilityPolicy update stages. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicies.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicies.java index 3629beec48d0f..be114fda93947 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicies.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicies.java @@ -9,8 +9,7 @@ /** Type representing ManagementPolicies. */ @Fluent -public interface ManagementPolicies - extends SupportsCreating { +public interface ManagementPolicies extends SupportsCreating { /** * Gets the managementpolicy associated with the specified storage account. * diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicy.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicy.java index 2d35f47c023c6..c53bd70b85b7d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ManagementPolicy.java @@ -18,12 +18,8 @@ /** Type representing ManagementPolicy. */ @Fluent -public interface ManagementPolicy - extends HasInnerModel, - Indexable, - Refreshable, - Updatable, - HasManager { +public interface ManagementPolicy extends HasInnerModel, Indexable, + Refreshable, Updatable, HasManager { /** @return the id value. */ String id(); @@ -43,11 +39,8 @@ public interface ManagementPolicy List rules(); /** The entirety of the ManagementPolicy definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithStorageAccount, - DefinitionStages.WithRule, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithStorageAccount, DefinitionStages.WithRule, + DefinitionStages.WithCreate { } /** Grouping of ManagementPolicy definition stages. */ @@ -88,6 +81,7 @@ interface WithRule { interface WithCreate extends Creatable, ManagementPolicy.DefinitionStages.WithRule { } } + /** The template for a ManagementPolicy update operation, containing all the settings that can be modified. */ interface Update extends Appliable, UpdateStages.WithPolicy, UpdateStages.Rule { } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PolicyRule.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PolicyRule.java index a72c5e3cd7b35..f98bbf41bf863 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PolicyRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PolicyRule.java @@ -60,21 +60,14 @@ public interface PolicyRule extends HasInnerModel { /** Container interface for all of the definitions related to a rule in a management policy. */ interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithPolicyRuleType, - DefinitionStages.WithBlobTypesToFilterFor, - DefinitionStages.PrefixActionFork, - DefinitionStages.WithPrefixesToFilterFor, - DefinitionStages.WithRuleActions, - DefinitionStages.WithPolicyRuleAttachable { + extends DefinitionStages.Blank, DefinitionStages.WithPolicyRuleType, DefinitionStages.WithBlobTypesToFilterFor, + DefinitionStages.PrefixActionFork, DefinitionStages.WithPrefixesToFilterFor, DefinitionStages.WithRuleActions, + DefinitionStages.WithPolicyRuleAttachable { } /** Container interface for all of the updates related to a rule in a management policy. */ - interface Update - extends UpdateStages.WithBlobTypesToFilterFor, - UpdateStages.WithPrefixesToFilterFor, - UpdateStages.WithActions, - Settable { + interface Update extends UpdateStages.WithBlobTypesToFilterFor, UpdateStages.WithPrefixesToFilterFor, + UpdateStages.WithActions, Settable { } /** Grouping of management policy rule definition stages. */ @@ -165,8 +158,8 @@ interface WithRuleActions { * until it is archived. * @return the next stage of the management policy rule definition. */ - WithPolicyRuleAttachable withTierToArchiveActionOnBaseBlob( - float daysAfterBaseBlobModificationUntilArchiving); + WithPolicyRuleAttachable + withTierToArchiveActionOnBaseBlob(float daysAfterBaseBlobModificationUntilArchiving); /** * The function that specifies a delete action on the selected base blobs. @@ -208,9 +201,8 @@ WithPolicyRuleAttachable withTierToArchiveActionOnBaseBlob( * attached, but also allows for any other optional settings to be specified. */ interface WithPolicyRuleAttachable - extends PolicyRule.DefinitionStages.WithRuleActions, - PolicyRule.DefinitionStages.WithPrefixesToFilterFor, - Attachable { + extends PolicyRule.DefinitionStages.WithRuleActions, PolicyRule.DefinitionStages.WithPrefixesToFilterFor, + Attachable { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccount.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccount.java index 1cca646cbb47a..ed8e9af3ea577 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccount.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccount.java @@ -25,13 +25,9 @@ /** An immutable client-side representation of an Azure storage account. */ @Fluent -public interface StorageAccount - extends GroupableResource, - Refreshable, - Updatable, - SupportsListingPrivateLinkResource, - SupportsListingPrivateEndpointConnection, - SupportsUpdatingPrivateEndpointConnection { +public interface StorageAccount extends GroupableResource, + Refreshable, Updatable, SupportsListingPrivateLinkResource, + SupportsListingPrivateEndpointConnection, SupportsUpdatingPrivateEndpointConnection { /** * @return the status indicating whether the primary and secondary location of the storage account is available or @@ -252,6 +248,7 @@ public interface StorageAccount * {@link StorageAccount#identityTypeForCustomerEncryptionKey()} is not {@link IdentityType#USER_ASSIGNED} */ String userAssignedIdentityIdForCustomerEncryptionKey(); + /** * Whether the storage account can be accessed from public network. * @@ -260,11 +257,8 @@ public interface StorageAccount PublicNetworkAccess publicNetworkAccess(); /** Container interface for all the definitions that need to be implemented. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithGroup, - DefinitionStages.WithCreate, - DefinitionStages.WithCreateAndAccessTier { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate, + DefinitionStages.WithCreateAndAccessTier { } /** Grouping of all the storage account definition stages. */ @@ -430,7 +424,8 @@ interface WithEncryption { * @param userAssignedIdentity user-assigned identity to access the KeyVault * @return the next stage of storage account update */ - WithCreate withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, Identity userAssignedIdentity); + WithCreate withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + Identity userAssignedIdentity); /** * Specifies the KeyVault key to be used as key for encryption and the user-assigned identity to access the KeyVault, @@ -447,7 +442,8 @@ interface WithEncryption { * @param userAssignedIdentityId ID of the user-assigned identity to access the KeyVault * @return the next stage of storage account update */ - WithCreate withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, String userAssignedIdentityId); + WithCreate withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + String userAssignedIdentityId); } /** The stage of a storage account definition allowing to associate custom domain with the account. */ @@ -571,6 +567,7 @@ interface WithNetworkAccess { * @return the next stage of the definition */ WithCreate disablePublicNetworkAccess(); + /** * Specifies that by default access to storage account should be allowed from all networks. * @@ -694,7 +691,7 @@ interface WithAllowCrossTenantReplication { } /** The stage of storage account definition allowing to configure default to oauth authentication. */ - interface WithDefaultToOAuthAuthentication { + interface WithDefaultToOAuthAuthentication { /** * Allows default to oauth authentication, configured by individual containers. * @@ -707,26 +704,15 @@ interface WithDefaultToOAuthAuthentication { * A storage account definition with sufficient inputs to create a new storage account in the cloud, but * exposing additional optional inputs to specify. */ - interface WithCreate - extends Creatable, - DefinitionStages.WithSku, - DefinitionStages.WithBlobStorageAccountKind, - DefinitionStages.WithGeneralPurposeAccountKind, - DefinitionStages.WithBlockBlobStorageAccountKind, - DefinitionStages.WithFileStorageAccountKind, - DefinitionStages.WithEncryption, - DefinitionStages.WithCustomDomain, - DefinitionStages.WithManagedServiceIdentity, - DefinitionStages.WithUserAssignedManagedServiceIdentity, - DefinitionStages.WithAccessTraffic, - DefinitionStages.WithNetworkAccess, - DefinitionStages.WithAzureFilesAadIntegration, - DefinitionStages.WithLargeFileShares, - DefinitionStages.WithHns, - DefinitionStages.WithBlobAccess, - DefinitionStages.WithAllowCrossTenantReplication, - DefinitionStages.WithDefaultToOAuthAuthentication, - Resource.DefinitionWithTags { + interface WithCreate extends Creatable, DefinitionStages.WithSku, + DefinitionStages.WithBlobStorageAccountKind, DefinitionStages.WithGeneralPurposeAccountKind, + DefinitionStages.WithBlockBlobStorageAccountKind, DefinitionStages.WithFileStorageAccountKind, + DefinitionStages.WithEncryption, DefinitionStages.WithCustomDomain, + DefinitionStages.WithManagedServiceIdentity, DefinitionStages.WithUserAssignedManagedServiceIdentity, + DefinitionStages.WithAccessTraffic, DefinitionStages.WithNetworkAccess, + DefinitionStages.WithAzureFilesAadIntegration, DefinitionStages.WithLargeFileShares, + DefinitionStages.WithHns, DefinitionStages.WithBlobAccess, DefinitionStages.WithAllowCrossTenantReplication, + DefinitionStages.WithDefaultToOAuthAuthentication, Resource.DefinitionWithTags { } /** The stage of storage account definition allowing to set access tier. */ @@ -853,7 +839,8 @@ interface WithEncryption { * @param userAssignedIdentity user-assigned identity to access the KeyVault * @return the next stage of storage account update */ - Update withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, Identity userAssignedIdentity); + Update withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + Identity userAssignedIdentity); /** * Specifies the KeyVault key to be used as key for encryption and the user-assigned identity to access the KeyVault, @@ -870,7 +857,8 @@ interface WithEncryption { * @param userAssignedIdentityId ID of the user-assigned identity to access the KeyVault * @return the next stage of storage account update */ - Update withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, String userAssignedIdentityId); + Update withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion, + String userAssignedIdentityId); /** * Specifies the Microsoft-managed key to be used as key for encryption. This is the default encryption type. @@ -1174,7 +1162,7 @@ interface WithAllowCrossTenantReplication { } /** The stage of storage account update allowing to configure default to oauth authentication. */ - interface WithDefaultToOAuthAuthentication { + interface WithDefaultToOAuthAuthentication { /** * Allows default to oauth authentication, configured by individual containers. * @@ -1195,20 +1183,11 @@ interface WithDefaultToOAuthAuthentication { } /** The template for a storage account update operation, containing all the settings that can be modified. */ - interface Update - extends Appliable, - UpdateStages.WithSku, - UpdateStages.WithCustomDomain, - UpdateStages.WithEncryption, - UpdateStages.WithAccessTier, - UpdateStages.WithManagedServiceIdentity, - UpdateStages.WithUserAssignedManagedServiceIdentity, - UpdateStages.WithAccessTraffic, - UpdateStages.WithNetworkAccess, - UpdateStages.WithUpgrade, - UpdateStages.WithBlobAccess, - UpdateStages.WithAllowCrossTenantReplication, - UpdateStages.WithDefaultToOAuthAuthentication, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithSku, UpdateStages.WithCustomDomain, + UpdateStages.WithEncryption, UpdateStages.WithAccessTier, UpdateStages.WithManagedServiceIdentity, + UpdateStages.WithUserAssignedManagedServiceIdentity, UpdateStages.WithAccessTraffic, + UpdateStages.WithNetworkAccess, UpdateStages.WithUpgrade, UpdateStages.WithBlobAccess, + UpdateStages.WithAllowCrossTenantReplication, UpdateStages.WithDefaultToOAuthAuthentication, + Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccounts.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccounts.java index f723d089017c0..e515b7ee24593 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccounts.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccounts.java @@ -19,17 +19,11 @@ /** Entry point for storage accounts management API. */ @Fluent -public interface StorageAccounts - extends SupportsListing, - SupportsCreating, - SupportsDeletingById, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { +public interface StorageAccounts extends SupportsListing, + SupportsCreating, SupportsDeletingById, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, + SupportsBatchDeletion, HasManager { /** * Checks that account name is valid and is not in use. * diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageSku.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageSku.java index f0bf640883c8a..092281db1c1e9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageSku.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageSku.java @@ -14,18 +14,25 @@ public interface StorageSku extends HasInnerModel { /** @return the sku name */ SkuName name(); + /** @return the sku tier */ SkuTier tier(); + /** @return the storage resource type that the sku describes */ StorageResourceType resourceType(); + /** @return the regions that the sku is available */ List regions(); + /** @return the capability information in the specified sku */ List capabilities(); + /** @return restrictions because of which sku cannot be used */ List restrictions(); + /** @return the storage account kind if the sku describes a storage account resource */ Kind storageAccountKind(); + /** @return the storage account sku type if the sku describes a storage account resource */ StorageAccountSkuType storageAccountSku(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/ImmutabilityPolicyTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/ImmutabilityPolicyTests.java index 6729655daed32..47dcde7253dd6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/ImmutabilityPolicyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/ImmutabilityPolicyTests.java @@ -33,18 +33,21 @@ protected void cleanUpResources() { public void canCRUDImmutabilityPolicy() { String saName = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount = storageManager.storageAccounts().define(saName) + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); - BlobContainer container = storageManager.blobContainers().defineContainer("container") + BlobContainer container = storageManager.blobContainers() + .defineContainer("container") .withExistingStorageAccount(storageAccount) .withPublicAccess(PublicAccess.NONE) .create(); // immutability policy - ImmutabilityPolicy policy = storageManager.blobContainers().defineImmutabilityPolicy() + ImmutabilityPolicy policy = storageManager.blobContainers() + .defineImmutabilityPolicy() .withExistingContainer(storageAccount.resourceGroupName(), storageAccount.name(), container.name()) .withImmutabilityPeriodSinceCreationInDays(7) .create(); @@ -55,20 +58,22 @@ public void canCRUDImmutabilityPolicy() { policy.refresh(); Assertions.assertEquals(ImmutabilityPolicyState.UNLOCKED, policy.state()); - policy = storageManager.blobContainers().getImmutabilityPolicy(storageAccount.resourceGroupName(), storageAccount.name(), container.name()); + policy = storageManager.blobContainers() + .getImmutabilityPolicy(storageAccount.resourceGroupName(), storageAccount.name(), container.name()); // update - policy.update() - .withImmutabilityPeriodSinceCreationInDays(14) - .apply(); + policy.update().withImmutabilityPeriodSinceCreationInDays(14).apply(); Assertions.assertEquals(14, policy.immutabilityPeriodSinceCreationInDays()); // delete - storageManager.blobContainers().deleteImmutabilityPolicy(storageAccount.resourceGroupName(), storageAccount.name(), container.name(), policy.etag()); + storageManager.blobContainers() + .deleteImmutabilityPolicy(storageAccount.resourceGroupName(), storageAccount.name(), container.name(), + policy.etag()); // new immutability policy - policy = storageManager.blobContainers().defineImmutabilityPolicy() + policy = storageManager.blobContainers() + .defineImmutabilityPolicy() .withExistingContainer(storageAccount.resourceGroupName(), storageAccount.name(), container.name()) .withImmutabilityPeriodSinceCreationInDays(7) .create(); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountNetworkRuleTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountNetworkRuleTests.java index a2dc3892b38a8..52a99df4a1f9c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountNetworkRuleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountNetworkRuleTests.java @@ -34,13 +34,11 @@ public void canConfigureNetworkRulesWithCreate() throws Exception { String saName3 = generateRandomResourceName("javacsmsa", 15); String saName4 = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount1 = - storageManager - .storageAccounts() - .define(saName1) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount1 = storageManager.storageAccounts() + .define(saName1) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); Assertions.assertNotNull(storageAccount1.networkSubnetsWithAccess()); Assertions.assertEquals(0, storageAccount1.networkSubnetsWithAccess().size()); @@ -58,18 +56,17 @@ public void canConfigureNetworkRulesWithCreate() throws Exception { ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(storageAccount1.resourceGroupName()); - StorageAccount storageAccount2 = - storageManager - .storageAccounts() - .define(saName2) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withAccessFromIpAddress("23.20.0.0") - .create(); + StorageAccount storageAccount2 = storageManager.storageAccounts() + .define(saName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withAccessFromIpAddress("23.20.0.0") + .create(); Assertions.assertNotNull(storageAccount2.innerModel().networkRuleSet()); Assertions.assertNotNull(storageAccount2.innerModel().networkRuleSet().defaultAction()); - Assertions.assertNotNull(storageAccount2.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.DENY)); + Assertions + .assertNotNull(storageAccount2.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.DENY)); Assertions.assertNotNull(storageAccount2.networkSubnetsWithAccess()); Assertions.assertEquals(0, storageAccount2.networkSubnetsWithAccess().size()); @@ -85,19 +82,18 @@ public void canConfigureNetworkRulesWithCreate() throws Exception { Assertions.assertFalse(storageAccount2.canReadMetricsFromAnyNetwork()); Assertions.assertFalse(storageAccount2.canReadMetricsFromAnyNetwork()); - StorageAccount storageAccount3 = - storageManager - .storageAccounts() - .define(saName3) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withAccessFromAllNetworks() - .withAccessFromIpAddress("23.20.0.0") - .create(); + StorageAccount storageAccount3 = storageManager.storageAccounts() + .define(saName3) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAccessFromAllNetworks() + .withAccessFromIpAddress("23.20.0.0") + .create(); Assertions.assertNotNull(storageAccount3.innerModel().networkRuleSet()); Assertions.assertNotNull(storageAccount3.innerModel().networkRuleSet().defaultAction()); - Assertions.assertNotNull(storageAccount3.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.ALLOW)); + Assertions + .assertNotNull(storageAccount3.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.ALLOW)); Assertions.assertNotNull(storageAccount3.networkSubnetsWithAccess()); Assertions.assertEquals(0, storageAccount3.networkSubnetsWithAccess().size()); @@ -113,19 +109,18 @@ public void canConfigureNetworkRulesWithCreate() throws Exception { Assertions.assertTrue(storageAccount3.canReadMetricsFromAnyNetwork()); Assertions.assertTrue(storageAccount3.canReadLogEntriesFromAnyNetwork()); - StorageAccount storageAccount4 = - storageManager - .storageAccounts() - .define(saName4) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .withReadAccessToLogEntriesFromAnyNetwork() - .withReadAccessToMetricsFromAnyNetwork() - .create(); + StorageAccount storageAccount4 = storageManager.storageAccounts() + .define(saName4) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .withReadAccessToLogEntriesFromAnyNetwork() + .withReadAccessToMetricsFromAnyNetwork() + .create(); Assertions.assertNotNull(storageAccount4.innerModel().networkRuleSet()); Assertions.assertNotNull(storageAccount4.innerModel().networkRuleSet().defaultAction()); - Assertions.assertNotNull(storageAccount4.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.DENY)); + Assertions + .assertNotNull(storageAccount4.innerModel().networkRuleSet().defaultAction().equals(DefaultAction.DENY)); Assertions.assertNotNull(storageAccount4.networkSubnetsWithAccess()); Assertions.assertEquals(0, storageAccount4.networkSubnetsWithAccess().size()); @@ -146,13 +141,11 @@ public void canConfigureNetworkRulesWithCreate() throws Exception { public void canConfigureNetworkRulesWithUpdate() throws Exception { String saName1 = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount1 = - storageManager - .storageAccounts() - .define(saName1) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount1 = storageManager.storageAccounts() + .define(saName1) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); Assertions.assertNotNull(storageAccount1.networkSubnetsWithAccess()); Assertions.assertEquals(0, storageAccount1.networkSubnetsWithAccess().size()); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java index 2d23a3ccd3ab0..9197458707964 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java @@ -51,18 +51,16 @@ public void canCRUDStorageAccount() throws Exception { // .checkNameAvailability(SA_NAME); // Assertions.assertEquals(true, result.isAvailable()); // Create - Mono resourceStream = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup(rgName) - .withGeneralPurposeAccountKindV2() - .withTag("tag1", "value1") - .withHnsEnabled(true) - .withAzureFilesAadIntegrationEnabled(false) - .withInfrastructureEncryption() - .createAsync(); + Mono resourceStream = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup(rgName) + .withGeneralPurposeAccountKindV2() + .withTag("tag1", "value1") + .withHnsEnabled(true) + .withAzureFilesAadIntegrationEnabled(false) + .withInfrastructureEncryption() + .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); @@ -118,23 +116,21 @@ public void canCRUDStorageAccount() throws Exception { Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); // Service will enable this by default // Update - storageAccount = storageAccount.update() - .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); + storageAccount + = storageAccount.update().withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS) - .withLargeFileShares(true) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS) + .withLargeFileShares(true) + .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @@ -144,7 +140,8 @@ public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); // default - StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) + StorageAccount storageAccountDefault = storageManager.storageAccounts() + .define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); @@ -170,7 +167,8 @@ public void storageAccountDefault() { Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); // new storage account configured as non-default - storageAccount = storageManager.storageAccounts().define(saName2) + storageAccount = storageManager.storageAccounts() + .define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) @@ -191,82 +189,66 @@ public void storageAccountDefault() { @Test public void canAllowCrossTenantReplicationOnStorageAccount() { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS) + .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); - storageAccount.update() - .allowCrossTenantReplication() - .apply(); + storageAccount.update().allowCrossTenantReplication().apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test public void canDisallowCrossTenantReplicationOnStorageAccount() { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS) - .allowCrossTenantReplication() - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS) + .allowCrossTenantReplication() + .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); - storageAccount.update() - .disallowCrossTenantReplication() - .apply(); + storageAccount.update().disallowCrossTenantReplication().apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); } @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS) + .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); - storageAccount.update() - .enableDefaultToOAuthAuthentication() - .apply(); + storageAccount.update().enableDefaultToOAuthAuthentication().apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.STANDARD_LRS) - .enableDefaultToOAuthAuthentication() - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS) + .enableDefaultToOAuthAuthentication() + .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); - storageAccount.update() - .disableDefaultToOAuthAuthentication() - .apply(); + storageAccount.update().disableDefaultToOAuthAuthentication().apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @@ -275,8 +257,7 @@ public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -291,8 +272,7 @@ public void createStorageAccountWithSystemAssigned() { @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -309,12 +289,10 @@ public void updateStorageAccountWithSystemAssigned() { Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } - @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -336,15 +314,12 @@ public void updateStorageAccountWithoutSystemAssigned() { public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - Creatable identityCreatable = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName); + Creatable identityCreatable = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -361,15 +336,12 @@ public void createStorageAccountWithNewUserAssigned() { public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - Creatable identityCreatable = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName); + Creatable identityCreatable = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -380,8 +352,7 @@ public void updateStorageAccountWithNewUserAssigned() { Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); - storageAccount.update() - .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); + storageAccount.update().withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); @@ -392,16 +363,13 @@ public void updateStorageAccountWithNewUserAssigned() { @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -417,16 +385,13 @@ public void createStorageAccountWithExistUserAssigned() { @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -437,8 +402,7 @@ public void updateStorageAccountWithExistUserAssigned() { Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); - storageAccount.update() - .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); + storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); @@ -449,16 +413,13 @@ public void updateStorageAccountWithExistUserAssigned() { @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -479,22 +440,20 @@ public void updateStorageAccountWithoutUserAssigned() { @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); @@ -509,22 +468,20 @@ public void updateIdentityFromSystemUserAssignedToSystemAssigned() { @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); @@ -539,28 +496,28 @@ public void updateIdentityFromSystemUserAssignedToUserAssigned() { @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); - storageAccount.update().withoutSystemAssignedManagedServiceIdentity() - .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); + storageAccount.update() + .withoutSystemAssignedManagedServiceIdentity() + .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) + .apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); @@ -570,15 +527,12 @@ public void updateIdentityFromSystemUserAssignedToNone() { @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -602,15 +556,12 @@ public void updateIdentityFromSystemAssignedToUserAssigned() { @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -634,15 +585,12 @@ public void updateIdentityFromUserAssignedToSystemAssigned() { @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -654,7 +602,8 @@ public void updateIdentityFromUserAssignedToSystemUserAssigned() { Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); @@ -663,15 +612,12 @@ public void updateIdentityFromUserAssignedToSystemUserAssigned() { @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -683,7 +629,8 @@ public void updateIdentityFromSystemAssignedToSystemUserAssigned() { Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); @@ -692,15 +639,12 @@ public void updateIdentityFromSystemAssignedToSystemUserAssigned() { @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - com.azure.resourcemanager.msi.models.Identity defaultIdentity = - msiManager - .identities() - .define(generateRandomResourceName("javacsmmsi", 15)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager.identities() + .define(generateRandomResourceName("javacsmmsi", 15)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .create(); + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -710,7 +654,8 @@ public void updateIdentityFromNoneToSystemUserAssigned() { .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); @@ -719,8 +664,7 @@ public void updateIdentityFromNoneToSystemUserAssigned() { @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) @@ -733,8 +677,7 @@ public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); - StorageAccount storageAccount = storageManager - .storageAccounts() + StorageAccount storageAccount = storageManager.storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobContainersTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobContainersTests.java index 00060388ac18b..6dcb37b8b506d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobContainersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobContainersTests.java @@ -50,23 +50,19 @@ public void canCreateBlobContainer() { metadataTest.put("a", "b"); metadataTest.put("c", "d"); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobContainers blobContainers = this.storageManager.blobContainers(); - BlobContainer blobContainer = - blobContainers - .defineContainer("blob-test") - .withExistingStorageAccount(rgName, saName) - .withPublicAccess(PublicAccess.CONTAINER) - .withMetadata("a", "b") - .withMetadata("c", "d") - .create(); + BlobContainer blobContainer = blobContainers.defineContainer("blob-test") + .withExistingStorageAccount(rgName, saName) + .withPublicAccess(PublicAccess.CONTAINER) + .withMetadata("a", "b") + .withMetadata("c", "d") + .create(); Assertions.assertEquals("blob-test", blobContainer.name()); Assertions.assertEquals(PublicAccess.CONTAINER, blobContainer.publicAccess()); @@ -84,25 +80,20 @@ public void canUpdateBlobContainer() { metadataTest.put("c", "d"); metadataTest.put("e", "f"); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobContainers blobContainers = this.storageManager.blobContainers(); - BlobContainer blobContainer = - blobContainers - .defineContainer("blob-test") - .withExistingStorageAccount(rgName, saName) - .withPublicAccess(PublicAccess.CONTAINER) - .withMetadata(metadataInitial) - .create(); - - blobContainer - .update() + BlobContainer blobContainer = blobContainers.defineContainer("blob-test") + .withExistingStorageAccount(rgName, saName) + .withPublicAccess(PublicAccess.CONTAINER) + .withMetadata(metadataInitial) + .create(); + + blobContainer.update() .withPublicAccess(PublicAccess.BLOB) .withMetadata("c", "d") .withMetadata("e", "f") @@ -121,24 +112,21 @@ public void canShareHttpPipelineInDataPlane() { String saName = generateRandomResourceName("javacmsa", 15); String containerName = "blob-test"; - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobContainers blobContainers = this.storageManager.blobContainers(); - BlobContainer blobContainer = - blobContainers - .defineContainer(containerName) - .withExistingStorageAccount(rgName, saName) - .withPublicAccess(PublicAccess.CONTAINER) - .create(); + BlobContainer blobContainer = blobContainers.defineContainer(containerName) + .withExistingStorageAccount(rgName, saName) + .withPublicAccess(PublicAccess.CONTAINER) + .create(); // assign data-plane blob role - RoleAssignment roleAssignment = msiManager.authorizationManager().roleAssignments() + RoleAssignment roleAssignment = msiManager.authorizationManager() + .roleAssignments() .define(UUID.randomUUID().toString()) .forUser(userName) .withBuiltInRole(BuiltInRole.STORAGE_BLOB_DATA_CONTRIBUTOR) @@ -146,7 +134,9 @@ public void canShareHttpPipelineInDataPlane() { .create(); // let the role assignment propagate - msiManager.authorizationManager().roleAssignments().getByIdAsync(roleAssignment.id()) + msiManager.authorizationManager() + .roleAssignments() + .getByIdAsync(roleAssignment.id()) .retryWhen(Retry // 10 + 20 = 30 seconds .backoff(2, ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(10))) @@ -163,8 +153,7 @@ public void canShareHttpPipelineInDataPlane() { // do not convert to RetryExhaustedException .onRetryExhaustedThrow((spec, signal) -> signal.failure())); - BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() - .pipeline(storageManager.httpPipeline()) + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().pipeline(storageManager.httpPipeline()) .endpoint(storageAccount.endPoints().primary().blob()) .buildClient(); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobServicesTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobServicesTests.java index 5fa13fc307470..7ff681a69e404 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobServicesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageBlobServicesTests.java @@ -36,23 +36,19 @@ protected void cleanUpResources() { public void canCreateBlobServices() { String saName = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobServices blobServices = this.storageManager.blobServices(); - BlobServiceProperties blobService = - blobServices - .define("blobServicesTest") - .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) - .withDeleteRetentionPolicyEnabled(5) - .withContainerDeleteRetentionPolicyEnabled(10) - .withBlobVersioningEnabled() - .create(); + BlobServiceProperties blobService = blobServices.define("blobServicesTest") + .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) + .withDeleteRetentionPolicyEnabled(5) + .withContainerDeleteRetentionPolicyEnabled(10) + .withBlobVersioningEnabled() + .create(); Assertions.assertTrue(blobService.deleteRetentionPolicy().enabled()); Assertions.assertEquals(5, blobService.deleteRetentionPolicy().days().intValue()); @@ -65,23 +61,19 @@ public void canCreateBlobServices() { public void canUpdateBlobServices() { String saName = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobServices blobServices = this.storageManager.blobServices(); - BlobServiceProperties blobService = - blobServices - .define("blobServicesTest") - .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) - .withDeleteRetentionPolicyEnabled(5) - .withContainerDeleteRetentionPolicyEnabled(10) - .withBlobVersioningEnabled() - .create(); + BlobServiceProperties blobService = blobServices.define("blobServicesTest") + .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) + .withDeleteRetentionPolicyEnabled(5) + .withContainerDeleteRetentionPolicyEnabled(10) + .withBlobVersioningEnabled() + .create(); Assertions.assertTrue(blobService.isBlobVersioningEnabled()); Assertions.assertTrue(blobService.containerDeleteRetentionPolicy().enabled()); @@ -101,23 +93,19 @@ public void canUpdateBlobServices() { public void canSpecifyLATTrackingPolicy() { String saName = generateRandomResourceName("javacsmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .create(); BlobServices blobServices = this.storageManager.blobServices(); // can create with LAT policy enabled - BlobServiceProperties blobService = - blobServices - .define("blobServicesTest") - .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) - .withLastAccessTimeTrackingPolicyEnabled() - .create(); + BlobServiceProperties blobService = blobServices.define("blobServicesTest") + .withExistingStorageAccount(storageAccount.resourceGroupName(), storageAccount.name()) + .withLastAccessTimeTrackingPolicyEnabled() + .create(); Assertions.assertFalse(ResourceManagerUtils.toPrimitiveBoolean(blobService.isBlobVersioningEnabled())); Assertions.assertTrue(blobService.isLastAccessTimeTrackingPolicyEnabled()); @@ -129,9 +117,7 @@ public void canSpecifyLATTrackingPolicy() { blobService.refresh(); // can update with LAT policy disabled - blobService.update() - .withLastAccessTimeTrackingPolicyDisabled() - .apply(); + blobService.update().withLastAccessTimeTrackingPolicyDisabled().apply(); Assertions.assertFalse(blobService.isLastAccessTimeTrackingPolicyEnabled()); blobService.refresh(); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementPoliciesTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementPoliciesTests.java index eb90036fb7221..2ea210ef15147 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementPoliciesTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementPoliciesTests.java @@ -42,31 +42,27 @@ protected void cleanUpResources() { @Test public void canCreateManagementPolicies() { String saName = generateRandomResourceName("javacmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withBlobStorageAccountKind() - .withAccessTier(AccessTier.COOL) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withBlobStorageAccountKind() + .withAccessTier(AccessTier.COOL) + .create(); ManagementPolicies managementPolicies = this.storageManager.managementPolicies(); - ManagementPolicy managementPolicy = - managementPolicies - .define("management-test") - .withExistingStorageAccount(rgName, saName) - .defineRule("rule1") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withPrefixToFilterFor("container1/foo") - .withTierToCoolActionOnBaseBlob(30) - .withTierToArchiveActionOnBaseBlob(90) - .withDeleteActionOnBaseBlob(2555) - .withDeleteActionOnSnapShot(90) - .attach() - .create(); + ManagementPolicy managementPolicy = managementPolicies.define("management-test") + .withExistingStorageAccount(rgName, saName) + .defineRule("rule1") + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withPrefixToFilterFor("container1/foo") + .withTierToCoolActionOnBaseBlob(30) + .withTierToArchiveActionOnBaseBlob(90) + .withDeleteActionOnBaseBlob(2555) + .withDeleteActionOnSnapShot(90) + .attach() + .create(); List blobTypesToFilterFor = new ArrayList<>(); blobTypesToFilterFor.add("blockBlob"); @@ -76,94 +72,76 @@ public void canCreateManagementPolicies() { // Assertions.assertEquals("management-test", managementPolicy.policy().); Assertions.assertEquals("rule1", managementPolicy.policy().rules().get(0).name()); - Assertions - .assertEquals( - blobTypesToFilterFor, managementPolicy.policy().rules().get(0).definition().filters().blobTypes()); - Assertions - .assertEquals( - prefixesToFilterFor, managementPolicy.policy().rules().get(0).definition().filters().prefixMatch()); - Assertions - .assertEquals( - 30, - managementPolicy - .policy() - .rules() - .get(0) - .definition() - .actions() - .baseBlob() - .tierToCool() - .daysAfterModificationGreaterThan(), - 0.001); - Assertions - .assertEquals( - 90, - managementPolicy - .policy() - .rules() - .get(0) - .definition() - .actions() - .baseBlob() - .tierToArchive() - .daysAfterModificationGreaterThan(), - 0.001); - Assertions - .assertEquals( - 2555, - managementPolicy - .policy() - .rules() - .get(0) - .definition() - .actions() - .baseBlob() - .delete() - .daysAfterModificationGreaterThan(), - 0.001); - Assertions - .assertEquals( - 90, - managementPolicy - .policy() - .rules() - .get(0) - .definition() - .actions() - .snapshot() - .delete() - .daysAfterCreationGreaterThan(), - 0.001); + Assertions.assertEquals(blobTypesToFilterFor, + managementPolicy.policy().rules().get(0).definition().filters().blobTypes()); + Assertions.assertEquals(prefixesToFilterFor, + managementPolicy.policy().rules().get(0).definition().filters().prefixMatch()); + Assertions.assertEquals(30, + managementPolicy.policy() + .rules() + .get(0) + .definition() + .actions() + .baseBlob() + .tierToCool() + .daysAfterModificationGreaterThan(), + 0.001); + Assertions.assertEquals(90, + managementPolicy.policy() + .rules() + .get(0) + .definition() + .actions() + .baseBlob() + .tierToArchive() + .daysAfterModificationGreaterThan(), + 0.001); + Assertions.assertEquals(2555, + managementPolicy.policy() + .rules() + .get(0) + .definition() + .actions() + .baseBlob() + .delete() + .daysAfterModificationGreaterThan(), + 0.001); + Assertions.assertEquals(90, + managementPolicy.policy() + .rules() + .get(0) + .definition() + .actions() + .snapshot() + .delete() + .daysAfterCreationGreaterThan(), + 0.001); } @Test public void managementPolicyGetters() { String saName = generateRandomResourceName("javacmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withBlobStorageAccountKind() - .withAccessTier(AccessTier.COOL) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withBlobStorageAccountKind() + .withAccessTier(AccessTier.COOL) + .create(); ManagementPolicies managementPolicies = this.storageManager.managementPolicies(); - ManagementPolicy managementPolicy = - managementPolicies - .define("management-test") - .withExistingStorageAccount(rgName, saName) - .defineRule("rule1") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withPrefixToFilterFor("container1/foo") - .withTierToCoolActionOnBaseBlob(30) - .withTierToArchiveActionOnBaseBlob(90) - .withDeleteActionOnBaseBlob(2555) - .withDeleteActionOnSnapShot(90) - .attach() - .create(); + ManagementPolicy managementPolicy = managementPolicies.define("management-test") + .withExistingStorageAccount(rgName, saName) + .defineRule("rule1") + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withPrefixToFilterFor("container1/foo") + .withTierToCoolActionOnBaseBlob(30) + .withTierToArchiveActionOnBaseBlob(90) + .withDeleteActionOnBaseBlob(2555) + .withDeleteActionOnSnapShot(90) + .attach() + .create(); List blobTypesToFilterFor = new ArrayList<>(); blobTypesToFilterFor.add(BlobTypes.BLOCK_BLOB); @@ -173,14 +151,10 @@ public void managementPolicyGetters() { List rules = managementPolicy.rules(); Assertions.assertEquals("rule1", rules.get(0).name()); - Assertions - .assertArrayEquals( - Collections.unmodifiableList(blobTypesToFilterFor).toArray(), - rules.get(0).blobTypesToFilterFor().toArray()); - Assertions - .assertArrayEquals( - Collections.unmodifiableList(prefixesToFilterFor).toArray(), - rules.get(0).prefixesToFilterFor().toArray()); + Assertions.assertArrayEquals(Collections.unmodifiableList(blobTypesToFilterFor).toArray(), + rules.get(0).blobTypesToFilterFor().toArray()); + Assertions.assertArrayEquals(Collections.unmodifiableList(prefixesToFilterFor).toArray(), + rules.get(0).prefixesToFilterFor().toArray()); Assertions.assertEquals(30, rules.get(0).daysAfterBaseBlobModificationUntilCooling().intValue()); Assertions.assertTrue(rules.get(0).tierToCoolActionOnBaseBlobEnabled()); Assertions.assertEquals(90, rules.get(0).daysAfterBaseBlobModificationUntilArchiving().intValue()); @@ -200,36 +174,31 @@ public void canUpdateManagementPolicy() { List prefixesToFilterFor = new ArrayList<>(); prefixesToFilterFor.add("container1/foo"); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withBlobStorageAccountKind() - .withAccessTier(AccessTier.COOL) - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withBlobStorageAccountKind() + .withAccessTier(AccessTier.COOL) + .create(); ManagementPolicies managementPolicies = this.storageManager.managementPolicies(); - ManagementPolicy managementPolicy = - managementPolicies - .define("management-test") - .withExistingStorageAccount(rgName, saName) - .defineRule("rule1") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withPrefixToFilterFor("asdf") - .withDeleteActionOnSnapShot(100) - .attach() - .defineRule("rule2") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withDeleteActionOnBaseBlob(30) - .attach() - .create(); + ManagementPolicy managementPolicy = managementPolicies.define("management-test") + .withExistingStorageAccount(rgName, saName) + .defineRule("rule1") + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withPrefixToFilterFor("asdf") + .withDeleteActionOnSnapShot(100) + .attach() + .defineRule("rule2") + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withDeleteActionOnBaseBlob(30) + .attach() + .create(); - managementPolicy - .update() + managementPolicy.update() .updateRule("rule1") .withPrefixesToFilterFor(prefixesToFilterFor) .withTierToCoolActionOnBaseBlob(30) @@ -243,14 +212,10 @@ public void canUpdateManagementPolicy() { List rules = managementPolicy.rules(); Assertions.assertEquals(1, rules.size()); Assertions.assertEquals("rule1", rules.get(0).name()); - Assertions - .assertArrayEquals( - Collections.unmodifiableList(blobTypesToFilterFor).toArray(), - rules.get(0).blobTypesToFilterFor().toArray()); - Assertions - .assertArrayEquals( - Collections.unmodifiableList(prefixesToFilterFor).toArray(), - rules.get(0).prefixesToFilterFor().toArray()); + Assertions.assertArrayEquals(Collections.unmodifiableList(blobTypesToFilterFor).toArray(), + rules.get(0).blobTypesToFilterFor().toArray()); + Assertions.assertArrayEquals(Collections.unmodifiableList(prefixesToFilterFor).toArray(), + rules.get(0).prefixesToFilterFor().toArray()); Assertions.assertEquals(30, rules.get(0).daysAfterBaseBlobModificationUntilCooling().intValue()); Assertions.assertTrue(rules.get(0).tierToCoolActionOnBaseBlobEnabled()); Assertions.assertEquals(90, rules.get(0).daysAfterBaseBlobModificationUntilArchiving().intValue()); @@ -265,15 +230,13 @@ public void canUpdateManagementPolicy() { public void testLcmBaseBlobActionsWithPremiumAccount() { String saName = generateRandomResourceName("javacmsa", 15); - StorageAccount storageAccount = - storageManager - .storageAccounts() - .define(saName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withSku(StorageAccountSkuType.PREMIUM_LRS) - .withBlockBlobStorageAccountKind() - .create(); + StorageAccount storageAccount = storageManager.storageAccounts() + .define(saName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withSku(StorageAccountSkuType.PREMIUM_LRS) + .withBlockBlobStorageAccountKind() + .create(); Assertions.assertEquals(StorageAccountSkuType.PREMIUM_LRS.name(), storageAccount.skuType().name()); Assertions.assertEquals(Kind.BLOCK_BLOB_STORAGE, storageAccount.kind()); @@ -289,66 +252,107 @@ public void testLcmBaseBlobActionsWithPremiumAccount() { ManagementPolicy managementPolicy = managementPolicies.define("management-test") .withExistingStorageAccount(rgName, saName) .defineRule("tierToHotLMT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToHot(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToHot(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) + .attach() .defineRule("tierToCoolLMT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToCool(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToCool(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) + .attach() .defineRule("tierToArchiveLMT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToArchive(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToArchive(new DateAfterModification().withDaysAfterModificationGreaterThan(50f))) + .attach() .defineRule("tierToHotCreated") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToHot(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToHot(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) + .attach() .defineRule("tierToCoolCreated") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToCool(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToCool(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) + .attach() .defineRule("tierToArchiveCreated") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToArchive(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToArchive(new DateAfterModification().withDaysAfterCreationGreaterThan(50f))) + .attach() .defineRule("tierToHotLAT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToHot(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToHot(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) + .attach() .defineRule("tierToCoolLAT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToCool(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToCool(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) + .attach() .defineRule("tierToArchiveLAT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToArchive(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToArchive(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f))) + .attach() .defineRule("tierToCoolAutoUpTierLAT") - .withLifecycleRuleType() - .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) - .withActionsOnBaseBlob(new ManagementPolicyBaseBlob().withTierToCool(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f)).withEnableAutoTierToHotFromCool(true)) - .attach() + .withLifecycleRuleType() + .withBlobTypeToFilterFor(BlobTypes.BLOCK_BLOB) + .withActionsOnBaseBlob(new ManagementPolicyBaseBlob() + .withTierToCool(new DateAfterModification().withDaysAfterLastAccessTimeGreaterThan(50f)) + .withEnableAutoTierToHotFromCool(true)) + .attach() .create(); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> ResourceManagerUtils.toPrimitiveBoolean(rule.actionsOnBaseBlob().enableAutoTierToHotFromCool()))); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null && rule.actionsOnBaseBlob().tierToHot().daysAfterModificationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null && rule.actionsOnBaseBlob().tierToCool().daysAfterModificationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null && rule.actionsOnBaseBlob().tierToArchive().daysAfterModificationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null && rule.actionsOnBaseBlob().tierToHot().daysAfterCreationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null && rule.actionsOnBaseBlob().tierToCool().daysAfterCreationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null && rule.actionsOnBaseBlob().tierToArchive().daysAfterCreationGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null && rule.actionsOnBaseBlob().tierToHot().daysAfterLastAccessTimeGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null && rule.actionsOnBaseBlob().tierToCool().daysAfterLastAccessTimeGreaterThan() != null)); - Assertions.assertTrue(managementPolicy.rules().stream().anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null && rule.actionsOnBaseBlob().tierToArchive().daysAfterLastAccessTimeGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> ResourceManagerUtils + .toPrimitiveBoolean(rule.actionsOnBaseBlob().enableAutoTierToHotFromCool()))); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null + && rule.actionsOnBaseBlob().tierToHot().daysAfterModificationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null + && rule.actionsOnBaseBlob().tierToCool().daysAfterModificationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null + && rule.actionsOnBaseBlob().tierToArchive().daysAfterModificationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null + && rule.actionsOnBaseBlob().tierToHot().daysAfterCreationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null + && rule.actionsOnBaseBlob().tierToCool().daysAfterCreationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null + && rule.actionsOnBaseBlob().tierToArchive().daysAfterCreationGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToHot() != null + && rule.actionsOnBaseBlob().tierToHot().daysAfterLastAccessTimeGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToCool() != null + && rule.actionsOnBaseBlob().tierToCool().daysAfterLastAccessTimeGreaterThan() != null)); + Assertions.assertTrue(managementPolicy.rules() + .stream() + .anyMatch(rule -> rule.actionsOnBaseBlob().tierToArchive() != null + && rule.actionsOnBaseBlob().tierToArchive().daysAfterLastAccessTimeGreaterThan() != null)); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementTest.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementTest.java index 530bedb4b6a78..e31ea3165786a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageManagementTest.java @@ -27,21 +27,10 @@ public abstract class StorageManagementTest extends ResourceManagerTestProxyTest protected MsiManager msiManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-test/pom.xml b/sdk/resourcemanager/azure-resourcemanager-test/pom.xml index 93b8634c79762..4ca6aa7978d5f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-test/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-test/pom.xml @@ -39,6 +39,7 @@ 0.10 0.10 + false diff --git a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java index 8dc780c3decc7..1a4671c17d324 100644 --- a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java @@ -96,12 +96,9 @@ public abstract class ResourceManagerTestProxyTestBase extends TestProxyTestBase 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, + 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))) - ); + .collect(Collectors.toMap(AzureEnvironment.Endpoint::identifier, endpoint -> PLAYBACK_URI)))); private static final OutputStream EMPTY_OUTPUT_STREAM = new OutputStream() { @Override public void write(int b) { @@ -132,7 +129,8 @@ public void write(byte[] b, int off, int len) { * bound. */ @RegisterExtension - final PlaybackTimeoutInterceptor playbackTimeoutInterceptor = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(60)); + final PlaybackTimeoutInterceptor playbackTimeoutInterceptor + = new PlaybackTimeoutInterceptor(() -> Duration.ofSeconds(60)); /** * Initializes ResourceManagerTestProxyTestBase class. @@ -194,7 +192,8 @@ public static String sshPublicKey() { 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); + 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)); @@ -214,7 +213,8 @@ public static String sshPublicKey() { protected void assertResourceIdEquals(String expected, String actual) { String sanitizedExpected = SUBSCRIPTION_ID_PATTERN.matcher(expected).replaceAll(ZERO_UUID); String sanitizedActual = SUBSCRIPTION_ID_PATTERN.matcher(actual).replaceAll(ZERO_UUID); - Assertions.assertTrue(sanitizedExpected.equalsIgnoreCase(sanitizedActual), String.format("expected: %s but was: %s", expected, actual)); + Assertions.assertTrue(sanitizedExpected.equalsIgnoreCase(sanitizedActual), + String.format("expected: %s but was: %s", expected, actual)); } /** @@ -258,8 +258,8 @@ protected AzureUser azureCliSignedInUser() { Process process = builder.start(); StringBuilder output = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), - StandardCharsets.UTF_8))) { + try (BufferedReader reader + = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); @@ -269,9 +269,10 @@ protected AzureUser azureCliSignedInUser() { if (windowsProcessErrorMessage.matcher(line).find() || shProcessErrorMessage.matcher(line).find()) { - throw LOGGER.logExceptionAsError(new RuntimeException("AzureCliCredential authentication unavailable. Azure CLI not installed." - + "To mitigate this issue, please refer to the troubleshooting guidelines here at " - + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); + throw LOGGER.logExceptionAsError(new RuntimeException( + "AzureCliCredential authentication unavailable. Azure CLI not installed." + + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); } output.append(line); } @@ -284,19 +285,22 @@ protected AzureUser azureCliSignedInUser() { if (process.exitValue() != 0) { if (processOutput.length() > 0) { if (processOutput.contains("az login") || processOutput.contains("az account set")) { - throw LOGGER.logExceptionAsError(new RuntimeException("AzureCliCredential authentication unavailable. Azure CLI not installed." - + "To mitigate this issue, please refer to the troubleshooting guidelines here at " - + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); + throw LOGGER.logExceptionAsError(new RuntimeException( + "AzureCliCredential authentication unavailable. Azure CLI not installed." + + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); } - throw LOGGER.logExceptionAsError(new ClientAuthenticationException("get Azure CLI current signed-in user failed", null)); + throw LOGGER.logExceptionAsError( + new ClientAuthenticationException("get Azure CLI current signed-in user failed", null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } - LOGGER.verbose("Get Azure CLI signed-in user => A response was received from Azure CLI, deserializing the" - + " response into an signed-in user."); + LOGGER + .verbose("Get Azure CLI signed-in user => A response was received from Azure CLI, deserializing the" + + " response into an signed-in user."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { Map signedInUserInfo = reader.readMap(JsonReader::readUntyped); String userPrincipalName = (String) signedInUserInfo.get("userPrincipalName"); @@ -358,10 +362,13 @@ protected void beforeTest() { } 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); + 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); + LOGGER.error( + "Environment variable '{}' has not been set yet. Using 'BODY_AND_HEADERS' for RECORD/LIVE.", + AZURE_TEST_LOG_LEVEL); } } @@ -376,29 +383,26 @@ protected void beforeTest() { if (isPlaybackMode()) { testProfile = PLAYBACK_PROFILE; List policies = new ArrayList<>(); - httpPipeline = buildHttpPipeline( - new MockTokenCredential(), - testProfile, - new HttpLogOptions().setLogLevel(httpLogDetailLevel), - policies, - interceptorManager.getPlaybackClient()); + httpPipeline = buildHttpPipeline(new MockTokenCredential(), testProfile, + new HttpLogOptions().setLogLevel(httpLogDetailLevel), policies, interceptorManager.getPlaybackClient()); if (!testContextManager.doNotRecordTest()) { // don't match api-version when matching url - interceptorManager.addMatchers(Collections.singletonList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")).setExcludedHeaders(Arrays.asList("If-Match")))); + interceptorManager.addMatchers(Collections + .singletonList(new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("api-version")) + .setExcludedHeaders(Arrays.asList("If-Match")))); addSanitizers(); removeSanitizers(); } } else { Configuration configuration = Configuration.getGlobalConfiguration(); - String tenantId = Objects.requireNonNull( - configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), + String tenantId = Objects.requireNonNull(configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), "'AZURE_TENANT_ID' environment variable cannot be null."); - String subscriptionId = Objects.requireNonNull( - configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID), - "'AZURE_SUBSCRIPTION_ID' environment variable cannot be null."); - credential = new DefaultAzureCredentialBuilder() - .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) - .build(); + String subscriptionId + = Objects.requireNonNull(configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID), + "'AZURE_SUBSCRIPTION_ID' environment variable cannot be null."); + credential + = new DefaultAzureCredentialBuilder().authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) + .build(); testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); List policies = new ArrayList<>(); @@ -411,12 +415,9 @@ protected void beforeTest() { policies.add(new HttpDebugLoggingPolicy()); httpLogDetailLevel = HttpLogDetailLevel.NONE; } - httpPipeline = buildHttpPipeline( - credential, - testProfile, - new HttpLogOptions().setLogLevel(httpLogDetailLevel), - policies, - generateHttpClientWithProxy(null, null)); + httpPipeline + = buildHttpPipeline(credential, testProfile, new HttpLogOptions().setLogLevel(httpLogDetailLevel), + policies, generateHttpClientWithProxy(null, null)); } initializeClients(httpPipeline, testProfile); } @@ -428,7 +429,8 @@ protected void beforeTest() { * @param proxyOptions The proxy. * @return An HttpClient with a proxy. */ - protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, ProxyOptions proxyOptions) { + protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder clientBuilder, + ProxyOptions proxyOptions) { if (clientBuilder == null) { clientBuilder = new NettyAsyncHttpClientBuilder(); } @@ -437,7 +439,8 @@ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder cli } else { try { System.setProperty(USE_SYSTEM_PROXY, VALUE_TRUE); - List proxies = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); + List proxies + = ProxySelector.getDefault().select(new URI(AzureEnvironment.AZURE.getResourceManagerEndpoint())); if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { if (proxy.address() instanceof InetSocketAddress) { @@ -445,9 +448,17 @@ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder cli int port = ((InetSocketAddress) proxy.address()).getPort(); switch (proxy.type()) { case HTTP: - return clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))).build(); + 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(); + return clientBuilder + .proxy(new ProxyOptions(ProxyOptions.Type.SOCKS5, + new InetSocketAddress(host, port))) + .build(); + default: } } @@ -465,7 +476,8 @@ protected HttpClient generateHttpClientWithProxy(NettyAsyncHttpClientBuilder cli if (host != null) { clientBuilder.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(host, port))); } - } catch (URISyntaxException ignored) { } + } catch (URISyntaxException ignored) { + } } return clientBuilder.build(); } @@ -548,12 +560,8 @@ protected T buildManager(Class manager, HttpPipeline httpPipeline, AzureP * @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 policies, - HttpClient httpClient); + protected abstract HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient); /** * Initializes service clients used in testing. @@ -585,19 +593,25 @@ private void addSanitizers() { new TestProxySanitizer("$..adminPassword", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..Password", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..accessSAS", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$.properties.osProfile.customData", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), // likely a false positive + new TestProxySanitizer("$.properties.osProfile.customData", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), // likely a false positive // SQL password - new TestProxySanitizer("$..administratorLoginPassword", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..administratorLoginPassword", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..hubDatabasePassword", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), // EH/SB key and connection string - new TestProxySanitizer("$..aliasPrimaryConnectionString", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$..aliasSecondaryConnectionString", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..aliasPrimaryConnectionString", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..aliasSecondaryConnectionString", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..primaryKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..secondaryKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..primaryMasterKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), new TestProxySanitizer("$..secondaryMasterKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$..primaryReadonlyMasterKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$..secondaryReadonlyMasterKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..primaryReadonlyMasterKey", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$..secondaryReadonlyMasterKey", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), // ContainerRegistry new TestProxySanitizer("$..passwords[*].value", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), // ContainerService @@ -605,13 +619,17 @@ private void addSanitizers() { // ContainerInstance new TestProxySanitizer("$..storageAccountKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), // AppService - new TestProxySanitizer("$.properties.siteConfig.machineKey.decryptionKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$.properties.siteConfig.machineKey.decryptionKey", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), // Replace "AccountKey=;" with "AccountKey=REDACTED;" - new TestProxySanitizer("(?:AccountKey=)(?.*?)(?:;)", REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("accountKey"), - new TestProxySanitizer("$.properties.WEBSITE_AUTH_ENCRYPTION_KEY", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$.properties.DOCKER_REGISTRY_SERVER_PASSWORD", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$.properties.protectedSettings.storageAccountKey", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) - )); + new TestProxySanitizer("(?:AccountKey=)(?.*?)(?:;)", REDACTED_VALUE, + TestProxySanitizerType.BODY_REGEX).setGroupForReplace("accountKey"), + new TestProxySanitizer("$.properties.WEBSITE_AUTH_ENCRYPTION_KEY", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$.properties.DOCKER_REGISTRY_SERVER_PASSWORD", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY), + new TestProxySanitizer("$.properties.protectedSettings.storageAccountKey", null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY))); sanitizers.addAll(this.sanitizers); interceptorManager.addSanitizers(sanitizers); } @@ -644,8 +662,7 @@ private PlaybackTimeoutInterceptor(Supplier timeoutSupplier) { @Override public void interceptTestMethod(Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) throws Throwable { + ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { if (isPlaybackMode()) { Assertions.assertTimeoutPreemptively(duration, invocation::proceed); } else { diff --git a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/policy/HttpDebugLoggingPolicy.java b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/policy/HttpDebugLoggingPolicy.java index 24ae11c7d29cd..31842323ba9da 100644 --- a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/policy/HttpDebugLoggingPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/policy/HttpDebugLoggingPolicy.java @@ -61,7 +61,7 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN } private Mono logRequest(final Logger logger, final HttpRequest request, - final Optional optionalRetryCount) { + final Optional optionalRetryCount) { if (!logger.isInfoEnabled()) { return Mono.empty(); } @@ -73,9 +73,8 @@ private Mono logRequest(final Logger logger, final HttpRequest request, .append(request.getUrl()) .append(System.lineSeparator()); - optionalRetryCount.ifPresent(o -> requestLogMessage.append("Try count: ") - .append(o) - .append(System.lineSeparator())); + optionalRetryCount + .ifPresent(o -> requestLogMessage.append("Try count: ").append(o).append(System.lineSeparator())); addHeadersToLogMessage(logger, request.getHeaders(), requestLogMessage); @@ -97,22 +96,20 @@ private Mono logRequest(final Logger logger, final HttpRequest request, WritableByteChannel bodyContentChannel = Channels.newChannel(outputStream); // Add non-mutating operators to the data stream. - request.setBody( - request.getBody() - .flatMap(byteBuffer -> writeBufferToBodyStream(bodyContentChannel, byteBuffer)) - .doFinally(ignored -> { - requestLogMessage.append(contentLength) - .append("-byte body:") - .append(System.lineSeparator()) - .append(prettyPrintIfNeeded(logger, contentType, - convertStreamToString(outputStream, logger))) - .append(System.lineSeparator()) - .append("--> END ") - .append(request.getHttpMethod()) - .append(System.lineSeparator()); - - logger.info(requestLogMessage.toString()); - })); + request.setBody(request.getBody() + .flatMap(byteBuffer -> writeBufferToBodyStream(bodyContentChannel, byteBuffer)) + .doFinally(ignored -> { + requestLogMessage.append(contentLength) + .append("-byte body:") + .append(System.lineSeparator()) + .append(prettyPrintIfNeeded(logger, contentType, convertStreamToString(outputStream, logger))) + .append(System.lineSeparator()) + .append("--> END ") + .append(request.getHttpMethod()) + .append(System.lineSeparator()); + + logger.info(requestLogMessage.toString()); + })); return Mono.empty(); } else { @@ -173,13 +170,14 @@ private Mono logResponse(final Logger logger, final HttpResponse r .doFinally(ignored -> { responseLogMessage.append("Response body:") .append(System.lineSeparator()) - .append(prettyPrintIfNeeded(logger, contentTypeHeader, - convertStreamToString(outputStream, logger))) + .append( + prettyPrintIfNeeded(logger, contentTypeHeader, convertStreamToString(outputStream, logger))) .append(System.lineSeparator()) .append("<-- END HTTP"); logger.info(responseLogMessage.toString()); - }).then(Mono.just(bufferedResponse)); + }) + .then(Mono.just(bufferedResponse)); } else { responseLogMessage.append("(body content not logged)") .append(System.lineSeparator()) @@ -209,7 +207,8 @@ private void addHeadersToLogMessage(Logger logger, HttpHeaders headers, StringBu private String prettyPrintIfNeeded(Logger logger, String contentType, String body) { String result = body; - if (PRETTY_PRINT_BODY && contentType != null + if (PRETTY_PRINT_BODY + && contentType != null && (contentType.startsWith(ContentType.APPLICATION_JSON) || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); @@ -232,16 +231,14 @@ private long getContentLength(Logger logger, HttpHeaders headers) { try { contentLength = Long.parseLong(contentLengthString); } catch (NumberFormatException | NullPointerException e) { - logger.warn("Could not parse the HTTP header content-length: '{}'.", - headers.getValue("content-length"), e); + logger.warn("Could not parse the HTTP header content-length: '{}'.", headers.getValue("content-length"), e); } return contentLength; } private boolean shouldBodyBeLogged(String contentTypeHeader, long contentLength) { - return !ContentType.APPLICATION_OCTET_STREAM.equalsIgnoreCase(contentTypeHeader) - && contentLength != 0; + return !ContentType.APPLICATION_OCTET_STREAM.equalsIgnoreCase(contentTypeHeader) && contentLength != 0; } private static String convertStreamToString(ByteArrayOutputStream stream, Logger logger) { diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml index 554e64d8eecbe..50d653088f9c0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml @@ -46,6 +46,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/TrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/TrafficManager.java index 1fa46211b6a71..09d29a04b52ab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/TrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/TrafficManager.java @@ -77,11 +77,8 @@ public TrafficManager authenticate(TokenCredential credential, AzureProfile prof } private TrafficManager(HttpPipeline httpPipeline, AzureProfile profile) { - super( - httpPipeline, - profile, - new TrafficManagerManagementClientBuilder() - .pipeline(httpPipeline) + super(httpPipeline, profile, + new TrafficManagerManagementClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) .subscriptionId(profile.getSubscriptionId()) .buildClient()); diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerAzureEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerAzureEndpointImpl.java index 3cbbce35325ac..77275ff0e568b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerAzureEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerAzureEndpointImpl.java @@ -11,8 +11,8 @@ /** Implementation for {@link TrafficManagerAzureEndpoint}. */ class TrafficManagerAzureEndpointImpl extends TrafficManagerEndpointImpl implements TrafficManagerAzureEndpoint { - TrafficManagerAzureEndpointImpl( - String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { + TrafficManagerAzureEndpointImpl(String name, TrafficManagerProfileImpl parent, EndpointInner inner, + EndpointsClient client) { super(name, parent, inner, client); } @@ -23,8 +23,7 @@ public String targetAzureResourceId() { @Override public TargetAzureResourceType targetResourceType() { - return new TargetAzureResourceType( - ResourceUtils.resourceProviderFromResourceId(targetAzureResourceId()), + return new TargetAzureResourceType(ResourceUtils.resourceProviderFromResourceId(targetAzureResourceId()), ResourceUtils.resourceTypeFromResourceId(targetAzureResourceId())); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointImpl.java index c9e25a42e479b..55bf85c61c1d9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointImpl.java @@ -28,20 +28,17 @@ import reactor.core.publisher.Mono; /** Implementation for {@link TrafficManagerEndpoint}. */ -class TrafficManagerEndpointImpl - extends ExternalChildResourceImpl< - TrafficManagerEndpoint, EndpointInner, TrafficManagerProfileImpl, TrafficManagerProfile> +class TrafficManagerEndpointImpl extends + ExternalChildResourceImpl implements TrafficManagerEndpoint, - TrafficManagerEndpoint.Definition, - TrafficManagerEndpoint.UpdateDefinition, - TrafficManagerEndpoint.UpdateAzureEndpoint, - TrafficManagerEndpoint.UpdateExternalEndpoint, - TrafficManagerEndpoint.UpdateNestedProfileEndpoint { + TrafficManagerEndpoint.Definition, + TrafficManagerEndpoint.UpdateDefinition, TrafficManagerEndpoint.UpdateAzureEndpoint, + TrafficManagerEndpoint.UpdateExternalEndpoint, TrafficManagerEndpoint.UpdateNestedProfileEndpoint { private final EndpointsClient client; private EndpointType endpointType; - TrafficManagerEndpointImpl( - String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { + TrafficManagerEndpointImpl(String name, TrafficManagerProfileImpl parent, EndpointInner inner, + EndpointsClient client) { super(name, parent, inner); this.client = client; } @@ -243,8 +240,9 @@ public TrafficManagerEndpointImpl withSubnet(String subnetStartIp, int mask) { } } if (!found) { - this.innerModel().subnets().add( - new EndpointPropertiesSubnetsItem().withFirst(subnetStartIp).withScope(mask)); + this.innerModel() + .subnets() + .add(new EndpointPropertiesSubnetsItem().withFirst(subnetStartIp).withScope(mask)); } return this; } @@ -265,8 +263,7 @@ public TrafficManagerEndpointImpl withSubnet(String subnetStartIp, String subnet } } if (!found) { - this - .innerModel() + this.innerModel() .subnets() .add(new EndpointPropertiesSubnetsItem().withFirst(subnetStartIp).withLast(subnetEndIp)); } @@ -277,14 +274,11 @@ public TrafficManagerEndpointImpl withSubnet(String subnetStartIp, String subnet public TrafficManagerEndpointImpl withSubnets(List subnets) { this.innerModel().withSubnets(new ArrayList<>()); for (EndpointPropertiesSubnetsItem subnet : subnets) { - this - .innerModel() + this.innerModel() .subnets() - .add( - new EndpointPropertiesSubnetsItem() - .withFirst(subnet.first()) - .withLast(subnet.last()) - .withScope(subnet.scope())); + .add(new EndpointPropertiesSubnetsItem().withFirst(subnet.first()) + .withLast(subnet.last()) + .withScope(subnet.scope())); } return this; } @@ -350,8 +344,9 @@ public TrafficManagerEndpointImpl withCustomHeader(String name, String value) { } } if (!found) { - this.innerModel().customHeaders().add( - new EndpointPropertiesCustomHeadersItem().withName(name).withValue(value)); + this.innerModel() + .customHeaders() + .add(new EndpointPropertiesCustomHeadersItem().withName(name).withValue(value)); } return this; } @@ -360,8 +355,7 @@ public TrafficManagerEndpointImpl withCustomHeader(String name, String value) { public TrafficManagerEndpointImpl withCustomHeaders(Map headers) { this.innerModel().withCustomHeaders(new ArrayList<>()); for (Map.Entry entry : headers.entrySet()) { - this - .innerModel() + this.innerModel() .customHeaders() .add(new EndpointPropertiesCustomHeadersItem().withName(entry.getKey()).withValue(entry.getValue())); } @@ -391,19 +385,13 @@ public TrafficManagerEndpointImpl withoutCustomHeader(String name) { @Override public Mono createResourceAsync() { - return this - .client - .createOrUpdateAsync( - this.parent().resourceGroupName(), - this.parent().name(), - EndpointTypes.fromString(this.endpointType().localName()), - this.name(), - this.innerModel()) - .map( - inner -> { - setInner(inner); - return this; - }); + return this.client + .createOrUpdateAsync(this.parent().resourceGroupName(), this.parent().name(), + EndpointTypes.fromString(this.endpointType().localName()), this.name(), this.innerModel()) + .map(inner -> { + setInner(inner); + return this; + }); } @Override @@ -413,13 +401,9 @@ public Mono updateResourceAsync() { @Override public Mono deleteResourceAsync() { - return this - .client - .deleteAsync( - this.parent().resourceGroupName(), - this.parent().name(), - EndpointTypes.fromString(this.endpointType().localName()), - this.name()) + return this.client + .deleteAsync(this.parent().resourceGroupName(), this.parent().name(), + EndpointTypes.fromString(this.endpointType().localName()), this.name()) .then(); } @@ -430,13 +414,8 @@ public TrafficManagerProfileImpl attach() { @Override protected Mono getInnerAsync() { - return this - .client - .getAsync( - this.parent().resourceGroupName(), - this.parent().name(), - EndpointTypes.fromString(this.endpointType().toString()), - this.name()); + return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), + EndpointTypes.fromString(this.endpointType().toString()), this.name()); } void withEndpointType(EndpointType endpointType) { diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointsImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointsImpl.java index 08830df7d5f2a..1ae08707a0b64 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointsImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerEndpointsImpl.java @@ -21,13 +21,8 @@ import reactor.core.publisher.Flux; /** Represents an endpoint collection associated with a traffic manager profile. */ -class TrafficManagerEndpointsImpl - extends ExternalChildResourcesCachedImpl< - TrafficManagerEndpointImpl, - TrafficManagerEndpoint, - EndpointInner, - TrafficManagerProfileImpl, - TrafficManagerProfile> { +class TrafficManagerEndpointsImpl extends + ExternalChildResourcesCachedImpl { private final ClientLogger logger = new ClientLogger(this.getClass()); @@ -59,9 +54,8 @@ Map azureEndpointsAsMap() { for (Map.Entry entry : this.collection().entrySet()) { TrafficManagerEndpointImpl endpoint = entry.getValue(); if (endpoint.endpointType() == EndpointType.AZURE) { - TrafficManagerAzureEndpoint azureEndpoint = - new TrafficManagerAzureEndpointImpl( - entry.getKey(), this.getParent(), endpoint.innerModel(), this.client); + TrafficManagerAzureEndpoint azureEndpoint = new TrafficManagerAzureEndpointImpl(entry.getKey(), + this.getParent(), endpoint.innerModel(), this.client); result.put(entry.getKey(), azureEndpoint); } } @@ -74,9 +68,8 @@ Map externalEndpointsAsMap() { for (Map.Entry entry : this.collection().entrySet()) { TrafficManagerEndpointImpl endpoint = entry.getValue(); if (endpoint.endpointType() == EndpointType.EXTERNAL) { - TrafficManagerExternalEndpoint externalEndpoint = - new TrafficManagerExternalEndpointImpl( - entry.getKey(), this.getParent(), endpoint.innerModel(), this.client); + TrafficManagerExternalEndpoint externalEndpoint = new TrafficManagerExternalEndpointImpl(entry.getKey(), + this.getParent(), endpoint.innerModel(), this.client); result.put(entry.getKey(), externalEndpoint); } } @@ -89,9 +82,8 @@ Map nestedProfileEndpointsAsMap() { for (Map.Entry entry : this.collection().entrySet()) { TrafficManagerEndpointImpl endpoint = entry.getValue(); if (endpoint.endpointType() == EndpointType.NESTED_PROFILE) { - TrafficManagerNestedProfileEndpoint nestedProfileEndpoint = - new TrafficManagerNestedProfileEndpointImpl( - entry.getKey(), this.getParent(), endpoint.innerModel(), this.client); + TrafficManagerNestedProfileEndpoint nestedProfileEndpoint = new TrafficManagerNestedProfileEndpointImpl( + entry.getKey(), this.getParent(), endpoint.innerModel(), this.client); result.put(entry.getKey(), nestedProfileEndpoint); } } @@ -178,6 +170,7 @@ public TrafficManagerEndpointImpl updateNestedProfileEndpoint(String name) { } return endpoint; } + /** * Mark the endpoint with given name as to be removed. * @@ -214,8 +207,8 @@ protected Flux listChildResourcesAsync() { @Override protected TrafficManagerEndpointImpl newChildResource(String name) { - TrafficManagerEndpointImpl endpoint = - new TrafficManagerEndpointImpl(name, this.getParent(), new EndpointInner(), this.client); + TrafficManagerEndpointImpl endpoint + = new TrafficManagerEndpointImpl(name, this.getParent(), new EndpointInner(), this.client); return endpoint.withRoutingWeight(1).withTrafficEnabled(); } } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerExternalEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerExternalEndpointImpl.java index 67387049ade16..3a826f94a281b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerExternalEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerExternalEndpointImpl.java @@ -10,8 +10,8 @@ /** Implementation for {@link TrafficManagerExternalEndpoint}. */ class TrafficManagerExternalEndpointImpl extends TrafficManagerEndpointImpl implements TrafficManagerExternalEndpoint { - TrafficManagerExternalEndpointImpl( - String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { + TrafficManagerExternalEndpointImpl(String name, TrafficManagerProfileImpl parent, EndpointInner inner, + EndpointsClient client) { super(name, parent, inner, client); } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java index 984295a8824c0..80977b7998196 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java @@ -12,8 +12,8 @@ /** Implementation for {@link TrafficManagerNestedProfileEndpoint}. */ class TrafficManagerNestedProfileEndpointImpl extends TrafficManagerEndpointImpl implements TrafficManagerNestedProfileEndpoint { - TrafficManagerNestedProfileEndpointImpl( - String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { + TrafficManagerNestedProfileEndpointImpl(String name, TrafficManagerProfileImpl parent, EndpointInner inner, + EndpointsClient client) { super(name, parent, inner, client); } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfileImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfileImpl.java index 1361039472902..8d27336f95766 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfileImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfileImpl.java @@ -88,19 +88,18 @@ public Map nestedProfileEndpoints() @Override public Mono refreshAsync() { - return super - .refreshAsync() - .map( - trafficManagerProfile -> { - TrafficManagerProfileImpl impl = (TrafficManagerProfileImpl) trafficManagerProfile; - impl.endpoints.refresh(); - return impl; - }); + return super.refreshAsync().map(trafficManagerProfile -> { + TrafficManagerProfileImpl impl = (TrafficManagerProfileImpl) trafficManagerProfile; + impl.endpoints.refresh(); + return impl; + }); } @Override protected Mono getInnerAsync() { - return this.manager().serviceClient().getProfiles() + return this.manager() + .serviceClient() + .getProfiles() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @@ -231,8 +230,7 @@ public TrafficManagerProfileImpl update() { @Override public Mono createResourceAsync() { - return this - .manager() + return this.manager() .serviceClient() .getProfiles() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) @@ -246,20 +244,13 @@ public Mono updateResourceAsync() { // method. We cannot update the routing method of the profile until existing endpoints contains the properties // required for the new routing method. final ProfilesClient innerCollection = this.manager().serviceClient().getProfiles(); - return this - .endpoints - .commitAndGetAllAsync() - .flatMap( - endpoints -> { - innerModel().withEndpoints(this.endpoints.allEndpointsInners()); - return innerCollection - .createOrUpdateAsync(resourceGroupName(), name(), innerModel()) - .map( - profileInner -> { - this.setInner(profileInner); - return this; - }); - }); + return this.endpoints.commitAndGetAllAsync().flatMap(endpoints -> { + innerModel().withEndpoints(this.endpoints.allEndpointsInners()); + return innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel()).map(profileInner -> { + this.setInner(profileInner); + return this; + }); + }); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfilesImpl.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfilesImpl.java index 321ae6b870881..3f9aee995392a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfilesImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerProfilesImpl.java @@ -20,16 +20,15 @@ import reactor.core.publisher.Mono; /** Implementation for TrafficManagerProfiles. */ -public class TrafficManagerProfilesImpl - extends TopLevelModifiableResourcesImpl< - TrafficManagerProfile, TrafficManagerProfileImpl, ProfileInner, ProfilesClient, TrafficManager> +public class TrafficManagerProfilesImpl extends + TopLevelModifiableResourcesImpl implements TrafficManagerProfiles { private GeographicHierarchies geographicHierarchies; public TrafficManagerProfilesImpl(final TrafficManager trafficManager) { super(trafficManager.serviceClient().getProfiles(), trafficManager); - this.geographicHierarchies = - new GeographicHierarchiesImpl(trafficManager, trafficManager.serviceClient().getGeographicHierarchies()); + this.geographicHierarchies + = new GeographicHierarchiesImpl(trafficManager, trafficManager.serviceClient().getGeographicHierarchies()); } @Override @@ -39,12 +38,10 @@ public CheckProfileDnsNameAvailabilityResult checkDnsNameAvailability(String dns @Override public Mono checkDnsNameAvailabilityAsync(String dnsNameLabel) { - CheckTrafficManagerRelativeDnsNameAvailabilityParameters parameter = - new CheckTrafficManagerRelativeDnsNameAvailabilityParameters() - .withName(dnsNameLabel) + CheckTrafficManagerRelativeDnsNameAvailabilityParameters parameter + = new CheckTrafficManagerRelativeDnsNameAvailabilityParameters().withName(dnsNameLabel) .withType("Microsoft.Network/trafficManagerProfiles"); - return this - .inner() + return this.inner() .checkTrafficManagerRelativeDnsNameAvailabilityAsync(parameter) .map(CheckProfileDnsNameAvailabilityResult::new); } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/GeographicLocation.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/GeographicLocation.java index ff0bfcf969992..6408c47292955 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/GeographicLocation.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/GeographicLocation.java @@ -11,8 +11,10 @@ public interface GeographicLocation extends HasName, HasInnerModel { /** @return the location code. */ String code(); + /** @return list of immediate child locations grouped under this location in the Geographic Hierarchy. */ List childLocations(); + /** @return list of all descendant locations grouped under this location in the Geographic Hierarchy. */ List descendantLocations(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/ProfileDnsNameUnavailableReason.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/ProfileDnsNameUnavailableReason.java index 37bb93db787cf..d59142e50cf81 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/ProfileDnsNameUnavailableReason.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/ProfileDnsNameUnavailableReason.java @@ -9,8 +9,8 @@ public class ProfileDnsNameUnavailableReason { public static final ProfileDnsNameUnavailableReason INVALID = new ProfileDnsNameUnavailableReason("Invalid"); /** Static value AlreadyExists for ProfileDnsNameUnavailableReason. */ - public static final ProfileDnsNameUnavailableReason ALREADYEXISTS = - new ProfileDnsNameUnavailableReason("AlreadyExists"); + public static final ProfileDnsNameUnavailableReason ALREADYEXISTS + = new ProfileDnsNameUnavailableReason("AlreadyExists"); private final String value; diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TargetAzureResourceType.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TargetAzureResourceType.java index f377f68fefa50..228ea8685ff2f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TargetAzureResourceType.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TargetAzureResourceType.java @@ -6,15 +6,15 @@ /** Target Azure resource types supported for an Azure endpoint in a traffic manager profile. */ public class TargetAzureResourceType { /** Static value Microsoft.Network/publicIPAddresses for TargetAzureResourceType. */ - public static final TargetAzureResourceType PUBLICIP = - new TargetAzureResourceType("Microsoft.Network", "publicIPAddresses"); + public static final TargetAzureResourceType PUBLICIP + = new TargetAzureResourceType("Microsoft.Network", "publicIPAddresses"); /** Static value Microsoft.Web/sites for TargetAzureResourceType. */ public static final TargetAzureResourceType WEBAPP = new TargetAzureResourceType("Microsoft.Web", "sites"); /** Static value Microsoft.ClassicCompute/domainNames for TargetAzureResourceType. */ - public static final TargetAzureResourceType CLOUDSERVICE = - new TargetAzureResourceType("Microsoft.ClassicCompute", "domainNames"); + public static final TargetAzureResourceType CLOUDSERVICE + = new TargetAzureResourceType("Microsoft.ClassicCompute", "domainNames"); private final String value; diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerEndpoint.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerEndpoint.java index b24de1cbaf370..e1b1431d37809 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerEndpoint.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerEndpoint.java @@ -52,16 +52,12 @@ public interface TrafficManagerEndpoint * * @param the return type of the final {@link Attachable#attach()} */ - interface Definition - extends DefinitionStages.AzureTargetEndpointBlank, - DefinitionStages.ExternalTargetEndpointBlank, - DefinitionStages.NestedProfileTargetEndpointBlank, - DefinitionStages.WithAzureResource, - DefinitionStages.WithFqdn, - DefinitionStages.WithSourceTrafficRegion, - DefinitionStages.WithSourceTrafficRegionThenThreshold, - DefinitionStages.WithEndpointThreshold, - DefinitionStages.WithAttach { + interface Definition extends DefinitionStages.AzureTargetEndpointBlank, + DefinitionStages.ExternalTargetEndpointBlank, + DefinitionStages.NestedProfileTargetEndpointBlank, DefinitionStages.WithAzureResource, + DefinitionStages.WithFqdn, DefinitionStages.WithSourceTrafficRegion, + DefinitionStages.WithSourceTrafficRegionThenThreshold, DefinitionStages.WithEndpointThreshold, + DefinitionStages.WithAttach { } /** @@ -246,6 +242,7 @@ interface WithGeographicLocation { * @return the next stage of the definition */ WithAttach withGeographicLocations(List geographicLocations); + /** * Specifies the geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method {@link TrafficRoutingMethod#GEOGRAPHIC}. @@ -254,6 +251,7 @@ interface WithGeographicLocation { * @return the next stage of the definition */ WithAttach withGeographicLocation(String geographicLocationCode); + /** * Specifies the list of geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method {@link TrafficRoutingMethod#GEOGRAPHIC}. @@ -344,14 +342,10 @@ interface WithCustomHeader { * * @param the return type of {@link TrafficManagerEndpoint.DefinitionStages.WithAttach#attach()} */ - interface WithAttach - extends Attachable.InDefinition, - DefinitionStages.WithRoutingWeight, - DefinitionStages.WithRoutingPriority, - DefinitionStages.WithGeographicLocation, - DefinitionStages.WithTrafficDisabled, - DefinitionStages.WithSubnet, - DefinitionStages.WithCustomHeader { + interface WithAttach extends Attachable.InDefinition, + DefinitionStages.WithRoutingWeight, DefinitionStages.WithRoutingPriority, + DefinitionStages.WithGeographicLocation, DefinitionStages.WithTrafficDisabled, + DefinitionStages.WithSubnet, DefinitionStages.WithCustomHeader { } } @@ -360,16 +354,13 @@ interface WithAttach * * @param the return type of the final {@link Attachable#attach()} */ - interface UpdateDefinition - extends UpdateDefinitionStages.AzureTargetEndpointBlank, - UpdateDefinitionStages.ExternalTargetEndpointBlank, - UpdateDefinitionStages.NestedProfileTargetEndpointBlank, - UpdateDefinitionStages.WithAzureResource, - UpdateDefinitionStages.WithFqdn, - UpdateDefinitionStages.WithSourceTrafficRegion, - UpdateDefinitionStages.WithSourceTrafficRegionThenThreshold, - UpdateDefinitionStages.WithEndpointThreshold, - UpdateDefinitionStages.WithAttach { + interface UpdateDefinition extends UpdateDefinitionStages.AzureTargetEndpointBlank, + UpdateDefinitionStages.ExternalTargetEndpointBlank, + UpdateDefinitionStages.NestedProfileTargetEndpointBlank, + UpdateDefinitionStages.WithAzureResource, UpdateDefinitionStages.WithFqdn, + UpdateDefinitionStages.WithSourceTrafficRegion, + UpdateDefinitionStages.WithSourceTrafficRegionThenThreshold, + UpdateDefinitionStages.WithEndpointThreshold, UpdateDefinitionStages.WithAttach { } /** @@ -545,6 +536,7 @@ interface WithGeographicLocation { * @return the next stage of the definition */ WithAttach withGeographicLocation(GeographicLocation geographicLocation); + /** * Specifies the list of geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method. @@ -553,6 +545,7 @@ interface WithGeographicLocation { * @return the next stage of the definition */ WithAttach withGeographicLocations(List geographicLocations); + /** * Specifies the geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method. @@ -561,6 +554,7 @@ interface WithGeographicLocation { * @return the next stage of the definition */ WithAttach withGeographicLocation(String geographicLocationCode); + /** * Specifies the list of geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method. @@ -652,14 +646,10 @@ interface WithCustomHeader { * * @param the return type of {@link TrafficManagerEndpoint.DefinitionStages.WithAttach#attach()} */ - interface WithAttach - extends Attachable.InUpdate, - UpdateDefinitionStages.WithRoutingWeight, - UpdateDefinitionStages.WithRoutingPriority, - UpdateDefinitionStages.WithGeographicLocation, - UpdateDefinitionStages.WithTrafficDisabled, - UpdateDefinitionStages.WithSubnet, - UpdateDefinitionStages.WithCustomHeader { + interface WithAttach extends Attachable.InUpdate, + UpdateDefinitionStages.WithRoutingWeight, UpdateDefinitionStages.WithRoutingPriority, + UpdateDefinitionStages.WithGeographicLocation, UpdateDefinitionStages.WithTrafficDisabled, + UpdateDefinitionStages.WithSubnet, UpdateDefinitionStages.WithCustomHeader { } } @@ -680,14 +670,9 @@ interface UpdateNestedProfileEndpoint * the set of configurations that can be updated for all endpoint irrespective of their type (Azure, external, * nested profile). */ - interface Update - extends Settable, - UpdateStages.WithRoutingWeight, - UpdateStages.WithRoutingPriority, - UpdateStages.WithGeographicLocation, - UpdateStages.WithTrafficDisabledOrEnabled, - UpdateStages.WithSubnet, - UpdateStages.WithCustomHeader { + interface Update extends Settable, UpdateStages.WithRoutingWeight, + UpdateStages.WithRoutingPriority, UpdateStages.WithGeographicLocation, + UpdateStages.WithTrafficDisabledOrEnabled, UpdateStages.WithSubnet, UpdateStages.WithCustomHeader { } /** Grouping of traffic manager profile endpoint update stages. */ @@ -784,6 +769,7 @@ interface WithGeographicLocation { * @return the next stage of the update */ Update withGeographicLocation(GeographicLocation geographicLocation); + /** * Specifies the list of geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method. @@ -792,6 +778,7 @@ interface WithGeographicLocation { * @return the next stage of the update */ Update withGeographicLocations(List geographicLocations); + /** * Specifies the geographic location to be removed from the endpoint's geographic location entries. * @@ -799,6 +786,7 @@ interface WithGeographicLocation { * @return the next stage of the update */ Update withoutGeographicLocation(GeographicLocation geographicLocation); + /** * Specifies the geographic location for the endpoint that will be used when the parent profile is * configured with geographic based routing method. @@ -816,6 +804,7 @@ interface WithGeographicLocation { * @return the next stage of the update */ Update withGeographicLocations(Collection geographicLocationCodes); + /** * Specifies the geographic location to be removed from the endpoint's geographic location entries. * diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfile.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfile.java index ead92a9e8e21c..41725831846dd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfile.java @@ -14,10 +14,8 @@ import java.util.Map; /** An immutable client-side representation of an Azure traffic manager profile. */ -public interface TrafficManagerProfile - extends GroupableResource, - Refreshable, - Updatable { +public interface TrafficManagerProfile extends GroupableResource, + Refreshable, Updatable { /** @return the relative DNS name of the traffic manager profile */ String dnsLabel(); @@ -55,11 +53,8 @@ public interface TrafficManagerProfile Map nestedProfileEndpoints(); /** The entirety of the traffic manager profile definition. */ - interface Definition - extends DefinitionStages.Blank, - DefinitionStages.WithLeafDomainLabel, - DefinitionStages.WithTrafficRoutingMethod, - DefinitionStages.WithCreate { + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLeafDomainLabel, + DefinitionStages.WithTrafficRoutingMethod, DefinitionStages.WithCreate { } /** Grouping of traffic manager profile definition stages. */ @@ -152,8 +147,8 @@ interface WithEndpoint { * @param name the name for the endpoint * @return the stage representing configuration for the endpoint */ - TrafficManagerEndpoint.DefinitionStages.AzureTargetEndpointBlank defineAzureTargetEndpoint( - String name); + TrafficManagerEndpoint.DefinitionStages.AzureTargetEndpointBlank + defineAzureTargetEndpoint(String name); /** * Specifies definition of an external endpoint to be attached to the traffic manager profile. @@ -243,13 +238,9 @@ interface WithProfileStatus { * The stage of the definition which contains all the minimum required inputs for the resource to be created * (via {@link WithCreate#create()}), but also allows for any other optional settings to be specified. */ - interface WithCreate - extends Creatable, - Resource.DefinitionWithTags, - DefinitionStages.WithMonitoringConfiguration, - DefinitionStages.WithTtl, - DefinitionStages.WithProfileStatus, - DefinitionStages.WithEndpoint { + interface WithCreate extends Creatable, Resource.DefinitionWithTags, + DefinitionStages.WithMonitoringConfiguration, DefinitionStages.WithTtl, DefinitionStages.WithProfileStatus, + DefinitionStages.WithEndpoint { } } @@ -366,8 +357,8 @@ interface WithEndpoint { * @param name the name for the endpoint * @return the stage representing configuration for the endpoint */ - TrafficManagerEndpoint.UpdateDefinitionStages.AzureTargetEndpointBlank defineAzureTargetEndpoint( - String name); + TrafficManagerEndpoint.UpdateDefinitionStages.AzureTargetEndpointBlank + defineAzureTargetEndpoint(String name); /** * Begins the definition of an external endpoint to be attached to the traffic manager profile. @@ -459,13 +450,8 @@ interface WithProfileStatus { * *

Call {@link Update#apply()} to apply the changes to the resource in Azure. */ - interface Update - extends Appliable, - UpdateStages.WithTrafficRoutingMethod, - UpdateStages.WithMonitoringConfiguration, - UpdateStages.WithEndpoint, - UpdateStages.WithTtl, - UpdateStages.WithProfileStatus, - Resource.UpdateWithTags { + interface Update extends Appliable, UpdateStages.WithTrafficRoutingMethod, + UpdateStages.WithMonitoringConfiguration, UpdateStages.WithEndpoint, UpdateStages.WithTtl, + UpdateStages.WithProfileStatus, Resource.UpdateWithTags { } } diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfiles.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfiles.java index 7a598d5f8cd11..e0208a701ccfa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfiles.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/models/TrafficManagerProfiles.java @@ -18,16 +18,10 @@ /** Entry point to traffic manager profile management API in Azure. */ public interface TrafficManagerProfiles - extends SupportsCreating, - SupportsListing, - SupportsListingByResourceGroup, - SupportsGettingByResourceGroup, - SupportsGettingById, - SupportsDeletingById, - SupportsDeletingByResourceGroup, - SupportsBatchCreation, - SupportsBatchDeletion, - HasManager { + extends SupportsCreating, SupportsListing, + SupportsListingByResourceGroup, SupportsGettingByResourceGroup, + SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, + SupportsBatchCreation, SupportsBatchDeletion, HasManager { /** * Checks that the DNS name is valid for traffic manager profile and is not in use. diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/test/java/com/azure/resourcemanager/trafficmanager/TrafficManagerTests.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/test/java/com/azure/resourcemanager/trafficmanager/TrafficManagerTests.java index ef7967d7d0a33..c55287d4904ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/test/java/com/azure/resourcemanager/trafficmanager/TrafficManagerTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/test/java/com/azure/resourcemanager/trafficmanager/TrafficManagerTests.java @@ -33,22 +33,10 @@ public class TrafficManagerTests extends ResourceManagerTestProxyTestBase { protected TrafficManager trafficManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider - .buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -101,23 +89,20 @@ public void canCreateUpdateProfileWithGeographicEndpoint() { Assertions.assertNotNull(california); Assertions.assertNotNull(bangladesh); - TrafficManagerProfile profile = - this - .trafficManager - .profiles() - .define(tmProfileName) - .withNewResourceGroup(rgName, Region.US_EAST) - .withLeafDomainLabel(tmProfileDnsLabel) - .withGeographicBasedRouting() - .defineExternalTargetEndpoint("external-ep-1") - .toFqdn("www.gitbook.com") - .fromRegion(Region.ASIA_EAST) - .withGeographicLocation(california) - .withGeographicLocation(bangladesh) - .attach() - .withHttpsMonitoring() - .withTimeToLive(500) - .create(); + TrafficManagerProfile profile = this.trafficManager.profiles() + .define(tmProfileName) + .withNewResourceGroup(rgName, Region.US_EAST) + .withLeafDomainLabel(tmProfileDnsLabel) + .withGeographicBasedRouting() + .defineExternalTargetEndpoint("external-ep-1") + .toFqdn("www.gitbook.com") + .fromRegion(Region.ASIA_EAST) + .withGeographicLocation(california) + .withGeographicLocation(bangladesh) + .attach() + .withHttpsMonitoring() + .withTimeToLive(500) + .create(); Assertions.assertNotNull(profile.innerModel()); Assertions.assertTrue(profile.trafficRoutingMethod().equals(TrafficRoutingMethod.GEOGRAPHIC)); @@ -126,8 +111,7 @@ public void canCreateUpdateProfileWithGeographicEndpoint() { Assertions.assertNotNull(endpoint.geographicLocationCodes()); Assertions.assertEquals(2, endpoint.geographicLocationCodes().size()); - profile - .update() + profile.update() .updateExternalTargetEndpoint("external-ep-1") .withoutGeographicLocation(california) .parent() @@ -152,21 +136,18 @@ public void canCreateTrafficManagerWithSubnetRouting() { EndpointPropertiesSubnetsItem subnetRange = new EndpointPropertiesSubnetsItem(); subnetRange.withFirst("25.26.27.28").withLast("29.30.31.32"); - TrafficManagerProfile profile = - this - .trafficManager - .profiles() - .define(tmProfileName) - .withNewResourceGroup(rgName, Region.US_EAST) - .withLeafDomainLabel(tmProfileDnsLabel) - .withTrafficRoutingMethod(TrafficRoutingMethod.SUBNET) - .defineExternalTargetEndpoint("external-ep-1") - .toFqdn("www.gitbook.com") - .fromRegion(Region.ASIA_EAST) - .withSubnet(subnetCidr.first(), subnetCidr.scope()) - .withSubnet(subnetRange.first(), subnetRange.last()) - .attach() - .create(); + TrafficManagerProfile profile = this.trafficManager.profiles() + .define(tmProfileName) + .withNewResourceGroup(rgName, Region.US_EAST) + .withLeafDomainLabel(tmProfileDnsLabel) + .withTrafficRoutingMethod(TrafficRoutingMethod.SUBNET) + .defineExternalTargetEndpoint("external-ep-1") + .toFqdn("www.gitbook.com") + .fromRegion(Region.ASIA_EAST) + .withSubnet(subnetCidr.first(), subnetCidr.scope()) + .withSubnet(subnetRange.first(), subnetRange.last()) + .attach() + .create(); Assertions.assertNotNull(profile.innerModel()); Assertions.assertEquals(TrafficRoutingMethod.SUBNET, profile.trafficRoutingMethod()); @@ -189,24 +170,16 @@ public void canCreateTrafficManagerWithSubnetRouting() { } } - Assertions - .assertTrue( - foundCidr, - String.format("The subnet %s/%d not found in the endpoint.", subnetCidr.first(), subnetCidr.scope())); - Assertions - .assertTrue( - foundRange, - String - .format( - "The subnet range %s-%s not found in the endpoint.", subnetCidr.first(), subnetCidr.last())); - - profile = - profile - .update() - .updateExternalTargetEndpoint("external-ep-1") - .withoutSubnet(subnetRange.first(), subnetRange.last()) - .parent() - .apply(); + Assertions.assertTrue(foundCidr, + String.format("The subnet %s/%d not found in the endpoint.", subnetCidr.first(), subnetCidr.scope())); + Assertions.assertTrue(foundRange, + String.format("The subnet range %s-%s not found in the endpoint.", subnetCidr.first(), subnetCidr.last())); + + profile = profile.update() + .updateExternalTargetEndpoint("external-ep-1") + .withoutSubnet(subnetRange.first(), subnetRange.last()) + .parent() + .apply(); endpoint = profile.externalEndpoints().get("external-ep-1"); Assertions.assertTrue(endpoint.subnets().size() == 1); diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index 26bb0b930d649..e4cc904211818 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -59,6 +59,7 @@ --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - + false diff --git a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java index e0257a983e2d6..89ccf6eb7a139 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java @@ -378,15 +378,15 @@ public RoleAssignments roleAssignments() { public Authenticated withTenantId(String tenantId) { Objects.requireNonNull(tenantId); this.tenantId = tenantId; - this.authorizationManager = AuthorizationManager.authenticate( - this.httpPipeline, new AzureProfile(tenantId, subscriptionId, environment)); + this.authorizationManager = AuthorizationManager.authenticate(this.httpPipeline, + new AzureProfile(tenantId, subscriptionId, environment)); return this; } @Override public AzureResourceManager withSubscription(String subscriptionId) { - return new AzureResourceManager( - httpPipeline, new AzureProfile(tenantId, subscriptionId, environment), this); + return new AzureResourceManager(httpPipeline, new AzureProfile(tenantId, subscriptionId, environment), + this); } @Override @@ -394,8 +394,8 @@ public AzureResourceManager withDefaultSubscription() { if (subscriptionId == null) { subscriptionId = ResourceManagerUtils.getDefaultSubscription(this.subscriptions().list()); } - return new AzureResourceManager( - httpPipeline, new AzureProfile(tenantId, subscriptionId, environment), this); + return new AzureResourceManager(httpPipeline, new AzureProfile(tenantId, subscriptionId, environment), + this); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java index b481cdee77270..a27adc088642e 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java @@ -53,21 +53,10 @@ public class ApplicationGatewayTests extends ResourceManagerTestProxyTestBase { private AzureResourceManager azureResourceManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -91,8 +80,9 @@ protected void cleanUpResources() { @Test @Disabled("TODO refactor to avoid pfx") public void testAppGatewaysInternalComplex() throws Exception { - new TestApplicationGateway().new PrivateComplex(azureResourceManager.resourceGroups().manager().internalContext()) - .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); + new TestApplicationGateway().new PrivateComplex( + azureResourceManager.resourceGroups().manager().internalContext()) + .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); } /** @@ -109,7 +99,11 @@ public void testAppGatewaysPublicUrlPathBased() throws Exception { @Disabled("WAF_V2 currently does not support private endpoint, and we do not want to have accessible public IP on VM. Enable it after WAF_V2 supports private endpoint.") @Test public void testAppGatewayBackendHealthCheck() throws Exception { - String testId = azureResourceManager.applicationGateways().manager().resourceManager().internalContext().randomResourceName("", 15); + String testId = azureResourceManager.applicationGateways() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("", 15); String name = "ag" + testId; Region region = Region.US_EAST; String password = ResourceManagerTestProxyTestBase.password(); @@ -118,34 +112,29 @@ public void testAppGatewayBackendHealthCheck() throws Exception { try { // Create a vnet - Network network = - azureResourceManager - .networks() - .define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); + Network network = azureResourceManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); // Create VMs for the backend in the network to connect to List> vmsDefinitions = new ArrayList<>(); for (int i = 0; i < 2; i++) { - vmsDefinitions - .add( - azureResourceManager - .virtualMachines() - .define("vm" + i + testId) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet2") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tester") - .withRootPassword(password)); + vmsDefinitions.add(azureResourceManager.virtualMachines() + .define("vm" + i + testId) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet2") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tester") + .withRootPassword(password)); } CreatedResources createdVms = azureResourceManager.virtualMachines().create(vmsDefinitions); @@ -160,36 +149,33 @@ public void testAppGatewayBackendHealthCheck() throws Exception { } // Create the app gateway in the other subnet of the same vnet and point the backend at the VMs - ApplicationGateway appGateway = - azureResourceManager - .applicationGateways() - .define(name) - .withRegion(region) - .withExistingResourceGroup(rgName) - .defineRequestRoutingRule("rule1") - .fromPrivateFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddresses(ipAddresses) // Connect the VMs via IP addresses - .attach() - .defineRequestRoutingRule("rule2") - .fromPrivateFrontend() - .fromFrontendHttpPort(25) - .toBackendHttpPort(22) - .toBackend("nicBackend") - .attach() - .withExistingSubnet(network.subnets().get("subnet1")) // Backend for connecting the VMs via NICs - .withTier(ApplicationGatewayTier.WAF_V2) - .withSize(ApplicationGatewaySkuName.WAF_V2) - .create(); + ApplicationGateway appGateway = azureResourceManager.applicationGateways() + .define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineRequestRoutingRule("rule1") + .fromPrivateFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddresses(ipAddresses) // Connect the VMs via IP addresses + .attach() + .defineRequestRoutingRule("rule2") + .fromPrivateFrontend() + .fromFrontendHttpPort(25) + .toBackendHttpPort(22) + .toBackend("nicBackend") + .attach() + .withExistingSubnet(network.subnets().get("subnet1")) // Backend for connecting the VMs via NICs + .withTier(ApplicationGatewayTier.WAF_V2) + .withSize(ApplicationGatewaySkuName.WAF_V2) + .create(); // Connect the 1st VM via NIC IP config NetworkInterface nic = vms[0].getPrimaryNetworkInterface(); Assertions.assertNotNull(nic); ApplicationGatewayBackend appGatewayBackend = appGateway.backends().get("nicBackend"); Assertions.assertNotNull(appGatewayBackend); - nic - .update() + nic.update() .updateIPConfiguration(nic.primaryIPConfiguration().name()) .withExistingApplicationGatewayBackend(appGateway, appGatewayBackend.name()) .parent() @@ -202,26 +188,24 @@ public void testAppGatewayBackendHealthCheck() throws Exception { StringBuilder info = new StringBuilder(); info.append("\nApplication gateway backend healths: ").append(backendHealths.size()); for (ApplicationGatewayBackendHealth backendHealth : backendHealths.values()) { - info - .append("\n\tApplication gateway backend name: ") + info.append("\n\tApplication gateway backend name: ") .append(backendHealth.name()) .append("\n\t\tHTTP configuration healths: ") .append(backendHealth.httpConfigurationHealths().size()); Assertions.assertNotNull(backendHealth.backend()); - for (ApplicationGatewayBackendHttpConfigurationHealth backendConfigHealth - : backendHealth.httpConfigurationHealths().values()) { - info - .append("\n\t\t\tHTTP configuration name: ") + for (ApplicationGatewayBackendHttpConfigurationHealth backendConfigHealth : backendHealth + .httpConfigurationHealths() + .values()) { + info.append("\n\t\t\tHTTP configuration name: ") .append(backendConfigHealth.name()) .append("\n\t\t\tServers: ") .append(backendConfigHealth.innerModel().servers().size()); Assertions.assertNotNull(backendConfigHealth.backendHttpConfiguration()); - for (ApplicationGatewayBackendServerHealth serverHealth - : backendConfigHealth.serverHealths().values()) { + for (ApplicationGatewayBackendServerHealth serverHealth : backendConfigHealth.serverHealths() + .values()) { NicIpConfiguration ipConfig = serverHealth.getNetworkInterfaceIPConfiguration(); if (ipConfig != null) { - info - .append("\n\t\t\t\tServer NIC ID: ") + info.append("\n\t\t\t\tServer NIC ID: ") .append(ipConfig.parent().id()) .append("\n\t\t\t\tIP Config name: ") .append(ipConfig.name()); @@ -261,12 +245,12 @@ public void testAppGatewayBackendHealthCheck() throws Exception { Assertions.assertNotNull(backendHealth2.backend()); Assertions.assertEquals(backend2.name(), backendHealth2.name()); Assertions.assertEquals(1, backendHealth2.httpConfigurationHealths().size()); - ApplicationGatewayBackendHttpConfigurationHealth httpConfigHealth2 = - backendHealth2.httpConfigurationHealths().values().iterator().next(); + ApplicationGatewayBackendHttpConfigurationHealth httpConfigHealth2 + = backendHealth2.httpConfigurationHealths().values().iterator().next(); Assertions.assertNotNull(httpConfigHealth2.backendHttpConfiguration()); Assertions.assertEquals(1, httpConfigHealth2.serverHealths().size()); - ApplicationGatewayBackendServerHealth serverHealth = - httpConfigHealth2.serverHealths().values().iterator().next(); + ApplicationGatewayBackendServerHealth serverHealth + = httpConfigHealth2.serverHealths().values().iterator().next(); NicIpConfiguration ipConfig2 = serverHealth.getNetworkInterfaceIPConfiguration(); Assertions.assertEquals(nic.primaryIPConfiguration().name(), ipConfig2.name()); } catch (Exception e) { @@ -286,8 +270,9 @@ public void testAppGatewayBackendHealthCheck() throws Exception { @Test @Disabled("TODO refactor to avoid pfx") public void testAppGatewaysInternalMinimal() throws Exception { - new TestApplicationGateway().new PrivateMinimal(azureResourceManager.resourceGroups().manager().internalContext()) - .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); + new TestApplicationGateway().new PrivateMinimal( + azureResourceManager.resourceGroups().manager().internalContext()) + .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); } @Test @@ -297,24 +282,22 @@ public void testAppGatewaysStartStop() throws Exception { String name = azureResourceManager.resourceGroups().manager().internalContext().randomResourceName("ag", 15); azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); PublicIpAddress pip = createPublicIpAddress(rgName); - ApplicationGateway appGateway = - azureResourceManager - .applicationGateways() - .define(name) - .withRegion(region) - .withExistingResourceGroup(rgName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withExistingPublicIpAddress(pip) - .withTier(ApplicationGatewayTier.STANDARD_V2) - .withSize(ApplicationGatewaySkuName.STANDARD_V2) - .create(); + ApplicationGateway appGateway = azureResourceManager.applicationGateways() + .define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withExistingPublicIpAddress(pip) + .withTier(ApplicationGatewayTier.STANDARD_V2) + .withSize(ApplicationGatewaySkuName.STANDARD_V2) + .create(); // Test stop/start appGateway.stop(); @@ -327,48 +310,54 @@ public void testAppGatewaysStartStop() throws Exception { @Test public void testApplicationGatewaysInParallel() throws Exception { - String rgName = azureResourceManager.applicationGateways().manager().resourceManager().internalContext().randomResourceName("rg", 13); + String rgName = azureResourceManager.applicationGateways() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("rg", 13); Region region = Region.US_EAST; ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); PublicIpAddress pip1 = createPublicIpAddress(rgName); PublicIpAddress pip2 = createPublicIpAddress(rgName); List> agCreatables = new ArrayList<>(); - agCreatables - .add( - azureResourceManager - .applicationGateways() - .define(azureResourceManager.applicationGateways().manager().resourceManager().internalContext().randomResourceName("ag", 13)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("10.0.0.1") - .toBackendIPAddress("10.0.0.2") - .attach() - .withExistingPublicIpAddress(pip1) - .withTier(ApplicationGatewayTier.STANDARD_V2) - .withSize(ApplicationGatewaySkuName.STANDARD_V2)); - - agCreatables - .add( - azureResourceManager - .applicationGateways() - .define(azureResourceManager.applicationGateways().manager().resourceManager().internalContext().randomResourceName("ag", 13)) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(resourceGroup) - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("10.0.0.3") - .toBackendIPAddress("10.0.0.4") - .attach() - .withExistingPublicIpAddress(pip2) - .withTier(ApplicationGatewayTier.STANDARD_V2) - .withSize(ApplicationGatewaySkuName.STANDARD_V2)); + agCreatables.add(azureResourceManager.applicationGateways() + .define(azureResourceManager.applicationGateways() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("ag", 13)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("10.0.0.1") + .toBackendIPAddress("10.0.0.2") + .attach() + .withExistingPublicIpAddress(pip1) + .withTier(ApplicationGatewayTier.STANDARD_V2) + .withSize(ApplicationGatewaySkuName.STANDARD_V2)); + + agCreatables.add(azureResourceManager.applicationGateways() + .define(azureResourceManager.applicationGateways() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("ag", 13)) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(resourceGroup) + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("10.0.0.3") + .toBackendIPAddress("10.0.0.4") + .attach() + .withExistingPublicIpAddress(pip2) + .withTier(ApplicationGatewayTier.STANDARD_V2) + .withSize(ApplicationGatewaySkuName.STANDARD_V2)); CreatedResources created = azureResourceManager.applicationGateways().create(agCreatables); List ags = new ArrayList<>(); @@ -413,8 +402,9 @@ public void testApplicationGatewaysInParallel() throws Exception { @Test @Disabled("TODO refactor to avoid pfx") public void testAppGatewaysInternetFacingMinimal() throws Exception { - new TestApplicationGateway().new PublicMinimal(azureResourceManager.resourceGroups().manager().internalContext()) - .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); + new TestApplicationGateway().new PublicMinimal( + azureResourceManager.resourceGroups().manager().internalContext()) + .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); } /** @@ -425,21 +415,20 @@ public void testAppGatewaysInternetFacingMinimal() throws Exception { @Test @Disabled("Refactor to avoid to use pfx") public void testAppGatewaysInternetFacingComplex() throws Exception { - new TestApplicationGateway().new PublicComplex(azureResourceManager.resourceGroups().manager().internalContext()) - .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); + new TestApplicationGateway().new PublicComplex( + azureResourceManager.resourceGroups().manager().internalContext()) + .runTest(azureResourceManager.applicationGateways(), azureResourceManager.resourceGroups()); } private PublicIpAddress createPublicIpAddress(String rgName) { String appPublicIp = generateRandomResourceName("pip", 15); - PublicIpAddress pip = - azureResourceManager - .publicIpAddresses() - .define(appPublicIp) - .withRegion(Region.US_EAST) - .withExistingResourceGroup(rgName) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP() - .create(); + PublicIpAddress pip = azureResourceManager.publicIpAddresses() + .define(appPublicIp) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP() + .create(); return pip; } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java index fb6113059449c..33740bfca0e32 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java @@ -103,26 +103,14 @@ public AzureResourceManagerTests() { addSanitizers( // Search key new TestProxySanitizer("$.key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), - new TestProxySanitizer("$.value[*].key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY) - ); + new TestProxySanitizer("$.value[*].key", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)); } @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -146,70 +134,66 @@ protected void cleanUpResources() { public void testExpandableEnum() throws Exception { // Define some threads that read from enum - Runnable reader1 = - new Runnable() { - @Override - public void run() { - Assertions.assertEquals(CountryIsoCode.AFGHANISTAN, CountryIsoCode.fromString("AF")); - Assertions.assertEquals(CountryIsoCode.ANTARCTICA, CountryIsoCode.fromString("AQ")); - Assertions.assertEquals(CountryIsoCode.ANDORRA, CountryIsoCode.fromString("AD")); - Assertions.assertEquals(CountryIsoCode.ARGENTINA, CountryIsoCode.fromString("AR")); - Assertions.assertEquals(CountryIsoCode.ALBANIA, CountryIsoCode.fromString("AL")); - Assertions.assertEquals(CountryIsoCode.ALGERIA, CountryIsoCode.fromString("DZ")); - Assertions.assertEquals(CountryIsoCode.AMERICAN_SAMOA, CountryIsoCode.fromString("AS")); - Assertions.assertEquals(CountryIsoCode.ANGOLA, CountryIsoCode.fromString("AO")); - Assertions.assertEquals(CountryIsoCode.ANGUILLA, CountryIsoCode.fromString("AI")); - Assertions.assertEquals(CountryIsoCode.ANTIGUA_AND_BARBUDA, CountryIsoCode.fromString("AG")); - Assertions.assertEquals(CountryIsoCode.ARMENIA, CountryIsoCode.fromString("AM")); - Assertions.assertEquals(CountryIsoCode.ARUBA, CountryIsoCode.fromString("AW")); - Assertions.assertEquals(CountryIsoCode.AUSTRALIA, CountryIsoCode.fromString("AU")); - Assertions.assertEquals(CountryIsoCode.AUSTRIA, CountryIsoCode.fromString("AT")); - Assertions.assertEquals(CountryIsoCode.AZERBAIJAN, CountryIsoCode.fromString("AZ")); - Assertions.assertEquals(PowerState.DEALLOCATED, PowerState.fromString("PowerState/deallocated")); - Assertions.assertEquals(PowerState.DEALLOCATING, PowerState.fromString("PowerState/deallocating")); - Assertions.assertEquals(PowerState.RUNNING, PowerState.fromString("PowerState/running")); - } - }; - - Runnable reader2 = - new Runnable() { - @Override - public void run() { - Assertions.assertEquals(CountryIsoCode.BAHAMAS, CountryIsoCode.fromString("BS")); - Assertions.assertEquals(CountryIsoCode.BAHRAIN, CountryIsoCode.fromString("BH")); - Assertions.assertEquals(CountryIsoCode.BANGLADESH, CountryIsoCode.fromString("BD")); - Assertions.assertEquals(CountryIsoCode.BARBADOS, CountryIsoCode.fromString("BB")); - Assertions.assertEquals(CountryIsoCode.BELARUS, CountryIsoCode.fromString("BY")); - Assertions.assertEquals(CountryIsoCode.BELGIUM, CountryIsoCode.fromString("BE")); - Assertions.assertEquals(PowerState.STARTING, PowerState.fromString("PowerState/starting")); - Assertions.assertEquals(PowerState.STOPPED, PowerState.fromString("PowerState/stopped")); - Assertions.assertEquals(PowerState.STOPPING, PowerState.fromString("PowerState/stopping")); - Assertions.assertEquals(PowerState.UNKNOWN, PowerState.fromString("PowerState/unknown")); - } - }; + Runnable reader1 = new Runnable() { + @Override + public void run() { + Assertions.assertEquals(CountryIsoCode.AFGHANISTAN, CountryIsoCode.fromString("AF")); + Assertions.assertEquals(CountryIsoCode.ANTARCTICA, CountryIsoCode.fromString("AQ")); + Assertions.assertEquals(CountryIsoCode.ANDORRA, CountryIsoCode.fromString("AD")); + Assertions.assertEquals(CountryIsoCode.ARGENTINA, CountryIsoCode.fromString("AR")); + Assertions.assertEquals(CountryIsoCode.ALBANIA, CountryIsoCode.fromString("AL")); + Assertions.assertEquals(CountryIsoCode.ALGERIA, CountryIsoCode.fromString("DZ")); + Assertions.assertEquals(CountryIsoCode.AMERICAN_SAMOA, CountryIsoCode.fromString("AS")); + Assertions.assertEquals(CountryIsoCode.ANGOLA, CountryIsoCode.fromString("AO")); + Assertions.assertEquals(CountryIsoCode.ANGUILLA, CountryIsoCode.fromString("AI")); + Assertions.assertEquals(CountryIsoCode.ANTIGUA_AND_BARBUDA, CountryIsoCode.fromString("AG")); + Assertions.assertEquals(CountryIsoCode.ARMENIA, CountryIsoCode.fromString("AM")); + Assertions.assertEquals(CountryIsoCode.ARUBA, CountryIsoCode.fromString("AW")); + Assertions.assertEquals(CountryIsoCode.AUSTRALIA, CountryIsoCode.fromString("AU")); + Assertions.assertEquals(CountryIsoCode.AUSTRIA, CountryIsoCode.fromString("AT")); + Assertions.assertEquals(CountryIsoCode.AZERBAIJAN, CountryIsoCode.fromString("AZ")); + Assertions.assertEquals(PowerState.DEALLOCATED, PowerState.fromString("PowerState/deallocated")); + Assertions.assertEquals(PowerState.DEALLOCATING, PowerState.fromString("PowerState/deallocating")); + Assertions.assertEquals(PowerState.RUNNING, PowerState.fromString("PowerState/running")); + } + }; + + Runnable reader2 = new Runnable() { + @Override + public void run() { + Assertions.assertEquals(CountryIsoCode.BAHAMAS, CountryIsoCode.fromString("BS")); + Assertions.assertEquals(CountryIsoCode.BAHRAIN, CountryIsoCode.fromString("BH")); + Assertions.assertEquals(CountryIsoCode.BANGLADESH, CountryIsoCode.fromString("BD")); + Assertions.assertEquals(CountryIsoCode.BARBADOS, CountryIsoCode.fromString("BB")); + Assertions.assertEquals(CountryIsoCode.BELARUS, CountryIsoCode.fromString("BY")); + Assertions.assertEquals(CountryIsoCode.BELGIUM, CountryIsoCode.fromString("BE")); + Assertions.assertEquals(PowerState.STARTING, PowerState.fromString("PowerState/starting")); + Assertions.assertEquals(PowerState.STOPPED, PowerState.fromString("PowerState/stopped")); + Assertions.assertEquals(PowerState.STOPPING, PowerState.fromString("PowerState/stopping")); + Assertions.assertEquals(PowerState.UNKNOWN, PowerState.fromString("PowerState/unknown")); + } + }; // Define some threads that write to enum - Runnable writer1 = - new Runnable() { - @Override - public void run() { - for (int i = 1; i <= 10; i++) { - CountryIsoCode.fromString("CountryIsoCode" + i); - PowerState.fromString("PowerState" + i); - } + Runnable writer1 = new Runnable() { + @Override + public void run() { + for (int i = 1; i <= 10; i++) { + CountryIsoCode.fromString("CountryIsoCode" + i); + PowerState.fromString("PowerState" + i); } - }; - - Runnable writer2 = - new Runnable() { - @Override - public void run() { - for (int i = 1; i <= 20; i++) { - CountryIsoCode.fromString("CountryIsoCode" + i); - PowerState.fromString("PowerState" + i); - } + } + }; + + Runnable writer2 = new Runnable() { + @Override + public void run() { + for (int i = 1; i <= 20; i++) { + CountryIsoCode.fromString("CountryIsoCode" + i); + PowerState.fromString("PowerState" + i); } - }; + } + }; // Start the threads and repeat a few times ExecutorService threadPool = Executors.newFixedThreadPool(4); @@ -240,8 +224,10 @@ public void run() { Assertions.assertEquals(27, powerStates.size()); } - private static final String TEMPLATE_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; - private static final String PARAMETERS_URI = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; + private static final String TEMPLATE_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.json"; + private static final String PARAMETERS_URI + = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/vnet-two-subnets/azuredeploy.parameters.json"; private static final String CONTENT_VERSION = "1.0.0.0"; /** @@ -251,18 +237,20 @@ public void run() { @DoNotRecord(skipInPlayback = true) // response contains token in hostpoolToken @Test public void testDeployments() { - String testId = azureResourceManager.deployments().manager().resourceManager().internalContext().randomResourceName("", 8); + String testId = azureResourceManager.deployments() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("", 8); PagedIterable deployments = azureResourceManager.deployments().list(); LOGGER.log(LogLevel.VERBOSE, () -> "Deployments: " + TestUtilities.getSize(deployments)); - Deployment deployment = - azureResourceManager - .deployments() - .define("depl" + testId) - .withNewResourceGroup("rg" + testId, Region.US_WEST) - .withTemplateLink(TEMPLATE_URI, CONTENT_VERSION) - .withParametersLink(PARAMETERS_URI, CONTENT_VERSION) - .withMode(DeploymentMode.COMPLETE) - .create(); + Deployment deployment = azureResourceManager.deployments() + .define("depl" + testId) + .withNewResourceGroup("rg" + testId, Region.US_WEST) + .withTemplateLink(TEMPLATE_URI, CONTENT_VERSION) + .withParametersLink(PARAMETERS_URI, CONTENT_VERSION) + .withMode(DeploymentMode.COMPLETE) + .create(); LOGGER.log(LogLevel.VERBOSE, () -> "Created deployment: " + deployment.correlationId()); azureResourceManager.resourceGroups().beginDeleteByName("rg" + testId); @@ -275,34 +263,34 @@ public void testDeployments() { @Test public void testGenericResources() { // Create some resources - NetworkSecurityGroup nsg = - azureResourceManager - .networkSecurityGroups() - .define(azureResourceManager.networkSecurityGroups().manager().resourceManager().internalContext().randomResourceName("nsg", 13)) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .create(); - azureResourceManager - .publicIpAddresses() - .define(azureResourceManager.networkSecurityGroups().manager().resourceManager().internalContext().randomResourceName("pip", 13)) + NetworkSecurityGroup nsg = azureResourceManager.networkSecurityGroups() + .define(azureResourceManager.networkSecurityGroups() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("nsg", 13)) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .create(); + azureResourceManager.publicIpAddresses() + .define(azureResourceManager.networkSecurityGroups() + .manager() + .resourceManager() + .internalContext() + .randomResourceName("pip", 13)) .withRegion(Region.US_EAST) .withExistingResourceGroup(nsg.resourceGroupName()) .create(); - PagedIterable resources = - azureResourceManager.genericResources().listByResourceGroup(nsg.resourceGroupName()); + PagedIterable resources + = azureResourceManager.genericResources().listByResourceGroup(nsg.resourceGroupName()); Assertions.assertEquals(2, TestUtilities.getSize(resources)); GenericResource firstResource = resources.iterator().next(); GenericResource resourceById = azureResourceManager.genericResources().getById(firstResource.id()); - GenericResource resourceByDetails = - azureResourceManager - .genericResources() - .get( - firstResource.resourceGroupName(), - firstResource.resourceProviderNamespace(), - firstResource.resourceType(), - firstResource.name()); + GenericResource resourceByDetails = azureResourceManager.genericResources() + .get(firstResource.resourceGroupName(), firstResource.resourceProviderNamespace(), + firstResource.resourceType(), firstResource.name()); Assertions.assertTrue(resourceById.id().equalsIgnoreCase(resourceByDetails.id())); azureResourceManager.resourceGroups().beginDeleteByName(nsg.resourceGroupName()); } @@ -324,53 +312,49 @@ public void testManagementLocks() { final Region region = Region.US_WEST; ResourceGroup resourceGroup = null; - ManagementLock lockGroup = null, - lockVM = null, - lockStorage = null, - lockDiskRO = null, - lockDiskDel = null, - lockSubnet = null; + ManagementLock lockGroup = null, lockVM = null, lockStorage = null, lockDiskRO = null, lockDiskDel = null, + lockSubnet = null; try { - resourceGroup = azureResourceManager.resourceGroups().define(rgName) - .withRegion(region) - .create(); + resourceGroup = azureResourceManager.resourceGroups().define(rgName).withRegion(region).create(); Assertions.assertNotNull(resourceGroup); - Creatable netDefinition = azureResourceManager.networks().define(netName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withAddressSpace("10.0.0.0/28"); + Creatable netDefinition = azureResourceManager.networks() + .define(netName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withAddressSpace("10.0.0.0/28"); // Define a VM for testing VM locks - Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewPrimaryNetwork(netDefinition) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tester") - .withRootPassword(password) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable vmDefinition = azureResourceManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork(netDefinition) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tester") + .withRootPassword(password) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); // Define a managed disk for testing locks on that - Creatable diskDefinition = azureResourceManager.disks().define(diskName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withData() - .withSizeInGB(100); + Creatable diskDefinition = azureResourceManager.disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withData() + .withSizeInGB(100); // Define a storage account for testing locks on that - Creatable storageDefinition = azureResourceManager.storageAccounts().define(storageName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup); + Creatable storageDefinition = azureResourceManager.storageAccounts() + .define(storageName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup); // Create resources in parallel to save time and money - Flux.merge( - storageDefinition.createAsync().subscribeOn(Schedulers.parallel()), - vmDefinition.createAsync().subscribeOn(Schedulers.parallel()), - diskDefinition.createAsync().subscribeOn(Schedulers.parallel())) - .blockLast(); + Flux.merge(storageDefinition.createAsync().subscribeOn(Schedulers.parallel()), + vmDefinition.createAsync().subscribeOn(Schedulers.parallel()), + diskDefinition.createAsync().subscribeOn(Schedulers.parallel())).blockLast(); VirtualMachine vm = (VirtualMachine) vmDefinition; StorageAccount storage = (StorageAccount) storageDefinition; @@ -379,49 +363,55 @@ public void testManagementLocks() { Subnet subnet = network.subnets().values().iterator().next(); // Lock subnet - Creatable lockSubnetDef = azureResourceManager.managementLocks().define("subnetLock") - .withLockedResource(subnet.innerModel().id()) - .withLevel(LockLevel.READ_ONLY); + Creatable lockSubnetDef = azureResourceManager.managementLocks() + .define("subnetLock") + .withLockedResource(subnet.innerModel().id()) + .withLevel(LockLevel.READ_ONLY); // Lock VM - Creatable lockVMDef = azureResourceManager.managementLocks().define("vmlock") - .withLockedResource(vm) - .withLevel(LockLevel.READ_ONLY) - .withNotes("vm readonly lock"); + Creatable lockVMDef = azureResourceManager.managementLocks() + .define("vmlock") + .withLockedResource(vm) + .withLevel(LockLevel.READ_ONLY) + .withNotes("vm readonly lock"); // Lock resource group - Creatable lockGroupDef = azureResourceManager.managementLocks().define("rglock") - .withLockedResource(resourceGroup.id()) - .withLevel(LockLevel.CAN_NOT_DELETE); + Creatable lockGroupDef = azureResourceManager.managementLocks() + .define("rglock") + .withLockedResource(resourceGroup.id()) + .withLevel(LockLevel.CAN_NOT_DELETE); // Lock storage - Creatable lockStorageDef = azureResourceManager.managementLocks().define("stLock") - .withLockedResource(storage) - .withLevel(LockLevel.CAN_NOT_DELETE); + Creatable lockStorageDef = azureResourceManager.managementLocks() + .define("stLock") + .withLockedResource(storage) + .withLevel(LockLevel.CAN_NOT_DELETE); // Create locks in parallel @SuppressWarnings("unchecked") - CreatedResources created = azureResourceManager.managementLocks().create( - lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef); + CreatedResources created + = azureResourceManager.managementLocks().create(lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef); lockVM = created.get(lockVMDef.key()); lockStorage = created.get(lockStorageDef.key()); lockGroup = created.get(lockGroupDef.key()); lockSubnet = created.get(lockSubnetDef.key()); // Lock disk synchronously - lockDiskRO = azureResourceManager.managementLocks().define("diskLockRO") - .withLockedResource(disk) - .withLevel(LockLevel.READ_ONLY) - .create(); + lockDiskRO = azureResourceManager.managementLocks() + .define("diskLockRO") + .withLockedResource(disk) + .withLevel(LockLevel.READ_ONLY) + .create(); - lockDiskDel = azureResourceManager.managementLocks().define("diskLockDel") - .withLockedResource(disk) - .withLevel(LockLevel.CAN_NOT_DELETE) - .create(); + lockDiskDel = azureResourceManager.managementLocks() + .define("diskLockDel") + .withLockedResource(disk) + .withLevel(LockLevel.CAN_NOT_DELETE) + .create(); // Verify VM lock - Assertions.assertEquals(2, TestUtilities.getSize( - azureResourceManager.managementLocks().listForResource(vm.id()))); + Assertions.assertEquals(2, + TestUtilities.getSize(azureResourceManager.managementLocks().listForResource(vm.id()))); Assertions.assertNotNull(lockVM); lockVM = azureResourceManager.managementLocks().getById(lockVM.id()); @@ -439,8 +429,8 @@ public void testManagementLocks() { Assertions.assertTrue(resourceGroup.id().equalsIgnoreCase(lockGroup.lockedResourceId())); // Verify storage account lock - Assertions.assertEquals(2, TestUtilities.getSize( - azureResourceManager.managementLocks().listForResource(storage.id()))); + Assertions.assertEquals(2, + TestUtilities.getSize(azureResourceManager.managementLocks().listForResource(storage.id()))); Assertions.assertNotNull(lockStorage); lockStorage = azureResourceManager.managementLocks().getById(lockStorage.id()); @@ -450,8 +440,8 @@ public void testManagementLocks() { Assertions.assertTrue(storage.id().equalsIgnoreCase(lockStorage.lockedResourceId())); // Verify disk lock - Assertions.assertEquals(3, TestUtilities.getSize( - azureResourceManager.managementLocks().listForResource(disk.id()))); + Assertions.assertEquals(3, + TestUtilities.getSize(azureResourceManager.managementLocks().listForResource(disk.id()))); Assertions.assertNotNull(lockDiskRO); lockDiskRO = azureResourceManager.managementLocks().getById(lockDiskRO.id()); @@ -468,8 +458,8 @@ public void testManagementLocks() { Assertions.assertTrue(disk.id().equalsIgnoreCase(lockDiskDel.lockedResourceId())); // Verify subnet lock - Assertions.assertEquals(2, TestUtilities.getSize( - azureResourceManager.managementLocks().listForResource(network.id()))); + Assertions.assertEquals(2, + TestUtilities.getSize(azureResourceManager.managementLocks().listForResource(network.id()))); lockSubnet = azureResourceManager.managementLocks().getById(lockSubnet.id()); Assertions.assertNotNull(lockSubnet); @@ -479,8 +469,8 @@ public void testManagementLocks() { // Verify lock collection PagedIterable locksSubscription = azureResourceManager.managementLocks().list(); - PagedIterable locksGroup = azureResourceManager.managementLocks() - .listByResourceGroup(vm.resourceGroupName()); + PagedIterable locksGroup + = azureResourceManager.managementLocks().listByResourceGroup(vm.resourceGroupName()); Assertions.assertNotNull(locksSubscription); Assertions.assertNotNull(locksGroup); @@ -518,7 +508,6 @@ public void testManagementLocks() { } } - /** * Tests VM images. * @@ -526,8 +515,8 @@ public void testManagementLocks() { @DoNotRecord(skipInPlayback = true) @Test public void testVMImages() throws ManagementException { - PagedIterable publishers = - azureResourceManager.virtualMachineImages().publishers().listByRegion(Region.US_WEST); + PagedIterable publishers + = azureResourceManager.virtualMachineImages().publishers().listByRegion(Region.US_WEST); Assertions.assertTrue(TestUtilities.getSize(publishers) > 0); for (VirtualMachinePublisher p : publishers.stream().limit(5).toArray(VirtualMachinePublisher[]::new)) { LOGGER.log(LogLevel.VERBOSE, () -> "Publisher name: " + p.name() + ", region: " + p.region()); @@ -539,7 +528,8 @@ public void testVMImages() throws ManagementException { } } // TODO: limit vm images by filter - PagedIterable images = azureResourceManager.virtualMachineImages().listByRegion(Region.US_WEST); + PagedIterable images + = azureResourceManager.virtualMachineImages().listByRegion(Region.US_WEST); Assertions.assertTrue(TestUtilities.getSize(images) > 0); // Seems to help avoid connection refused error on subsequent mock test ResourceManagerUtils.sleep(Duration.ofSeconds(2)); @@ -619,28 +609,27 @@ public void testLoadBalancersInternalWithAvailabilityZone() throws Exception { @Test public void testManagedDiskVMUpdate() { - ResourceManagerUtils.InternalRuntimeContext context = azureResourceManager.disks().manager().resourceManager().internalContext(); + ResourceManagerUtils.InternalRuntimeContext context + = azureResourceManager.disks().manager().resourceManager().internalContext(); final String rgName = context.randomResourceName("rg", 13); final String linuxVM2Name = context.randomResourceName("vm" + "-", 10); final String linuxVM2Pip = context.randomResourceName("pip" + "-", 18); - VirtualMachine linuxVM2 = - azureResourceManager - .virtualMachines() - .define(linuxVM2Name) - .withRegion(Region.US_WEST2) - .withNewResourceGroup(rgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(linuxVM2Pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("tester") - .withRootPassword(password()) - // Begin: Managed data disks - .withNewDataDisk(100) - .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) - // End: Managed data disks - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine linuxVM2 = azureResourceManager.virtualMachines() + .define(linuxVM2Name) + .withRegion(Region.US_WEST2) + .withNewResourceGroup(rgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(linuxVM2Pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("tester") + .withRootPassword(password()) + // Begin: Managed data disks + .withNewDataDisk(100) + .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) + // End: Managed data disks + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); linuxVM2.deallocate(); linuxVM2.update().withoutDataDisk(2).withNewDataDisk(200).apply(); @@ -653,7 +642,8 @@ public void testManagedDiskVMUpdate() { */ @Test public void testPublicIPAddresses() throws Exception { - new TestPublicIPAddress().runTest(azureResourceManager.publicIpAddresses(), azureResourceManager.resourceGroups()); + new TestPublicIPAddress().runTest(azureResourceManager.publicIpAddresses(), + azureResourceManager.resourceGroups()); } /** @@ -662,7 +652,8 @@ public void testPublicIPAddresses() throws Exception { */ @Test public void testPublicIPPrefixes() throws Exception { - new TestPublicIPPrefix().runTest(azureResourceManager.publicIpPrefixes(), azureResourceManager.resourceGroups()); + new TestPublicIPPrefix().runTest(azureResourceManager.publicIpPrefixes(), + azureResourceManager.resourceGroups()); } /** @@ -671,7 +662,8 @@ public void testPublicIPPrefixes() throws Exception { */ @Test public void testAvailabilitySets() throws Exception { - new TestAvailabilitySet().runTest(azureResourceManager.availabilitySets(), azureResourceManager.resourceGroups()); + new TestAvailabilitySet().runTest(azureResourceManager.availabilitySets(), + azureResourceManager.resourceGroups()); } /** @@ -680,7 +672,8 @@ public void testAvailabilitySets() throws Exception { */ @Test public void testNetworks() throws Exception { - new TestNetwork().new WithSubnets().runTest(azureResourceManager.networks(), azureResourceManager.resourceGroups()); + new TestNetwork().new WithSubnets().runTest(azureResourceManager.networks(), + azureResourceManager.resourceGroups()); } /** @@ -689,7 +682,8 @@ public void testNetworks() throws Exception { */ @Test public void testNetworkWithAccessFromServiceToSubnet() throws Exception { - new TestNetwork().new WithAccessFromServiceToSubnet().runTest(azureResourceManager.networks(), azureResourceManager.resourceGroups()); + new TestNetwork().new WithAccessFromServiceToSubnet().runTest(azureResourceManager.networks(), + azureResourceManager.resourceGroups()); } /** @@ -698,7 +692,8 @@ public void testNetworkWithAccessFromServiceToSubnet() throws Exception { */ @Test public void testNetworkPeerings() throws Exception { - new TestNetwork().new WithPeering().runTest(azureResourceManager.networks(), azureResourceManager.resourceGroups()); + new TestNetwork().new WithPeering().runTest(azureResourceManager.networks(), + azureResourceManager.resourceGroups()); } /** @@ -707,7 +702,8 @@ public void testNetworkPeerings() throws Exception { */ @Test public void testDdosAndVmProtection() throws Exception { - new TestNetwork().new WithDDosProtectionPlanAndVmProtection().runTest(azureResourceManager.networks(), azureResourceManager.resourceGroups()); + new TestNetwork().new WithDDosProtectionPlanAndVmProtection().runTest(azureResourceManager.networks(), + azureResourceManager.resourceGroups()); } /** @@ -716,7 +712,8 @@ public void testDdosAndVmProtection() throws Exception { */ @Test public void testNetworkUpdateTags() throws Exception { - new TestNetwork().new WithUpdateTags().runTest(azureResourceManager.networks(), azureResourceManager.resourceGroups()); + new TestNetwork().new WithUpdateTags().runTest(azureResourceManager.networks(), + azureResourceManager.resourceGroups()); } /** @@ -725,7 +722,8 @@ public void testNetworkUpdateTags() throws Exception { */ @Test public void testRouteTables() throws Exception { - new TestRouteTables().new Minimal().runTest(azureResourceManager.routeTables(), azureResourceManager.resourceGroups()); + new TestRouteTables().new Minimal().runTest(azureResourceManager.routeTables(), + azureResourceManager.resourceGroups()); } /** Tests the regions enum. */ @@ -758,7 +756,8 @@ public void testRegions() { */ @Test public void testNetworkInterfaces() throws Exception { - new TestNetworkInterface().runTest(azureResourceManager.networkInterfaces(), azureResourceManager.resourceGroups()); + new TestNetworkInterface().runTest(azureResourceManager.networkInterfaces(), + azureResourceManager.resourceGroups()); } /** @@ -784,24 +783,19 @@ public void testNetworkWatcherFunctions() throws Exception { nwrg = nw.resourceGroupName(); // pre-create VMs to show topology on - VirtualMachine[] virtualMachines = - tnw - .ensureNetwork( - azureResourceManager.networkWatchers().manager().networks(), - azureResourceManager.virtualMachines(), - azureResourceManager.networkInterfaces()); - - ConnectionMonitor connectionMonitor = - nw - .connectionMonitors() - .define("NewConnectionMonitor") - .withSourceId(virtualMachines[0].id()) - .withDestinationId(virtualMachines[1].id()) - .withDestinationPort(80) - .withTag("tag1", "value1") - .withoutAutoStart() - .withMonitoringInterval(35) - .create(); + VirtualMachine[] virtualMachines + = tnw.ensureNetwork(azureResourceManager.networkWatchers().manager().networks(), + azureResourceManager.virtualMachines(), azureResourceManager.networkInterfaces()); + + ConnectionMonitor connectionMonitor = nw.connectionMonitors() + .define("NewConnectionMonitor") + .withSourceId(virtualMachines[0].id()) + .withDestinationId(virtualMachines[1].id()) + .withDestinationPort(80) + .withTag("tag1", "value1") + .withoutAutoStart() + .withMonitoringInterval(35) + .create(); Assertions.assertEquals("value1", connectionMonitor.tags().get("tag1")); Assertions.assertEquals(35, connectionMonitor.monitoringIntervalInSeconds()); Assertions.assertEquals("NotStarted", connectionMonitor.monitoringStatus()); @@ -811,27 +805,20 @@ public void testNetworkWatcherFunctions() throws Exception { Assertions.assertEquals("Running", connectionMonitor.monitoringStatus()); Topology topology = nw.topology().withTargetResourceGroup(virtualMachines[0].resourceGroupName()).execute(); Assertions.assertEquals(11, topology.resources().size()); - Assertions - .assertTrue( - topology - .resources() - .containsKey(virtualMachines[0].getPrimaryNetworkInterface().networkSecurityGroupId())); - Assertions - .assertEquals( - 4, topology.resources().get(virtualMachines[0].primaryNetworkInterfaceId()).associations().size()); + Assertions.assertTrue(topology.resources() + .containsKey(virtualMachines[0].getPrimaryNetworkInterface().networkSecurityGroupId())); + Assertions.assertEquals(4, + topology.resources().get(virtualMachines[0].primaryNetworkInterfaceId()).associations().size()); SecurityGroupView sgViewResult = nw.getSecurityGroupView(virtualMachines[0].id()); Assertions.assertEquals(1, sgViewResult.networkInterfaces().size()); - Assertions - .assertEquals( - virtualMachines[0].primaryNetworkInterfaceId(), - sgViewResult.networkInterfaces().keySet().iterator().next()); + Assertions.assertEquals(virtualMachines[0].primaryNetworkInterfaceId(), + sgViewResult.networkInterfaces().keySet().iterator().next()); - FlowLogSettings flowLogSettings = - nw.getFlowLogSettings(virtualMachines[0].getPrimaryNetworkInterface().networkSecurityGroupId()); + FlowLogSettings flowLogSettings + = nw.getFlowLogSettings(virtualMachines[0].getPrimaryNetworkInterface().networkSecurityGroupId()); StorageAccount storageAccount = tnw.ensureStorageAccount(azureResourceManager.storageAccounts()); - flowLogSettings - .update() + flowLogSettings.update() .withLogging() .withStorageAccount(storageAccount.id()) .withRetentionPolicyDays(5) @@ -841,48 +828,41 @@ public void testNetworkWatcherFunctions() throws Exception { Assertions.assertEquals(5, flowLogSettings.retentionDays()); Assertions.assertEquals(storageAccount.id(), flowLogSettings.storageId()); - NextHop nextHop = - nw - .nextHop() - .withTargetResourceId(virtualMachines[0].id()) - .withSourceIpAddress("10.0.0.4") - .withDestinationIpAddress("8.8.8.8") - .execute(); + NextHop nextHop = nw.nextHop() + .withTargetResourceId(virtualMachines[0].id()) + .withSourceIpAddress("10.0.0.4") + .withDestinationIpAddress("8.8.8.8") + .execute(); Assertions.assertEquals("System Route", nextHop.routeTableId()); Assertions.assertEquals(NextHopType.INTERNET, nextHop.nextHopType()); Assertions.assertNull(nextHop.nextHopIpAddress()); - VerificationIPFlow verificationIPFlow = - nw - .verifyIPFlow() - .withTargetResourceId(virtualMachines[0].id()) - .withDirection(Direction.OUTBOUND) - .withProtocol(IpFlowProtocol.TCP) - .withLocalIPAddress("10.0.0.4") - .withRemoteIPAddress("8.8.8.8") - .withLocalPort("443") - .withRemotePort("443") - .execute(); + VerificationIPFlow verificationIPFlow = nw.verifyIPFlow() + .withTargetResourceId(virtualMachines[0].id()) + .withDirection(Direction.OUTBOUND) + .withProtocol(IpFlowProtocol.TCP) + .withLocalIPAddress("10.0.0.4") + .withRemoteIPAddress("8.8.8.8") + .withLocalPort("443") + .withRemotePort("443") + .execute(); Assertions.assertEquals(Access.ALLOW, verificationIPFlow.access()); - Assertions - .assertTrue( - "defaultSecurityRules/AllowInternetOutBound".equalsIgnoreCase(verificationIPFlow.ruleName())); + Assertions.assertTrue( + "defaultSecurityRules/AllowInternetOutBound".equalsIgnoreCase(verificationIPFlow.ruleName())); // test packet capture PagedIterable packetCaptures = nw.packetCaptures().list(); Assertions.assertEquals(0, TestUtilities.getSize(packetCaptures)); - PacketCapture packetCapture = - nw - .packetCaptures() - .define("NewPacketCapture") - .withTarget(virtualMachines[0].id()) - .withStorageAccountId(storageAccount.id()) - .withTimeLimitInSeconds(1500) - .definePacketCaptureFilter() - .withProtocol(PcProtocol.TCP) - .withLocalIpAddresses(Arrays.asList("127.0.0.1", "127.0.0.5")) - .attach() - .create(); + PacketCapture packetCapture = nw.packetCaptures() + .define("NewPacketCapture") + .withTarget(virtualMachines[0].id()) + .withStorageAccountId(storageAccount.id()) + .withTimeLimitInSeconds(1500) + .definePacketCaptureFilter() + .withProtocol(PcProtocol.TCP) + .withLocalIpAddresses(Arrays.asList("127.0.0.1", "127.0.0.5")) + .attach() + .create(); packetCaptures = nw.packetCaptures().list(); Assertions.assertEquals(1, TestUtilities.getSize(packetCaptures)); Assertions.assertEquals("NewPacketCapture", packetCapture.name()); @@ -895,13 +875,11 @@ public void testNetworkWatcherFunctions() throws Exception { Assertions.assertEquals(PcStatus.STOPPED, packetCapture.getStatus().packetCaptureStatus()); nw.packetCaptures().deleteByName(packetCapture.name()); - ConnectivityCheck connectivityCheck = - nw - .checkConnectivity() - .toDestinationResourceId(virtualMachines[1].id()) - .toDestinationPort(80) - .fromSourceVirtualMachine(virtualMachines[0].id()) - .execute(); + ConnectivityCheck connectivityCheck = nw.checkConnectivity() + .toDestinationResourceId(virtualMachines[1].id()) + .toDestinationPort(80) + .fromSourceVirtualMachine(virtualMachines[0].id()) + .execute(); // Assertions.assertEquals("Reachable", connectivityCheck.connectionStatus().toString()); // // not sure why it is Unknown now @@ -927,7 +905,8 @@ public void testNetworkWatcherFunctions() throws Exception { @DoNotRecord(skipInPlayback = true) // TODO(weidxu) @Test public void testLocalNetworkGateways() throws Exception { - new TestLocalNetworkGateway().runTest(azureResourceManager.localNetworkGateways(), azureResourceManager.resourceGroups()); + new TestLocalNetworkGateway().runTest(azureResourceManager.localNetworkGateways(), + azureResourceManager.resourceGroups()); } /** @@ -937,7 +916,8 @@ public void testLocalNetworkGateways() throws Exception { @Test @Disabled("Failed to provision ExpressRoute circuit as the service provider does not have sufficient capacity at this location.") public void testExpressRouteCircuits() throws Exception { - new TestExpressRouteCircuit().new Basic().runTest(azureResourceManager.expressRouteCircuits(), azureResourceManager.resourceGroups()); + new TestExpressRouteCircuit().new Basic().runTest(azureResourceManager.expressRouteCircuits(), + azureResourceManager.resourceGroups()); } /** @@ -969,7 +949,8 @@ public void testVirtualMachines() throws Exception { */ @Test public void testVirtualMachineDataDisk() throws Exception { - new TestVirtualMachineDataDisk().runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestVirtualMachineDataDisk().runTest(azureResourceManager.virtualMachines(), + azureResourceManager.resourceGroups()); } /** @@ -978,7 +959,8 @@ public void testVirtualMachineDataDisk() throws Exception { */ @Test public void testVirtualMachineNics() throws Exception { - new TestVirtualMachineNics(azureResourceManager.networks().manager()).runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestVirtualMachineNics(azureResourceManager.networks().manager()) + .runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); } /** @@ -987,7 +969,8 @@ public void testVirtualMachineNics() throws Exception { */ @Test public void testVirtualMachineSSh() throws Exception { - new TestVirtualMachineSsh(azureResourceManager.publicIpAddresses()).runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestVirtualMachineSsh(azureResourceManager.publicIpAddresses()) + .runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); } /** @@ -996,7 +979,8 @@ public void testVirtualMachineSSh() throws Exception { */ @Test public void testVirtualMachineSizes() throws Exception { - new TestVirtualMachineSizes().runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestVirtualMachineSizes().runTest(azureResourceManager.virtualMachines(), + azureResourceManager.resourceGroups()); } @Test @@ -1007,7 +991,8 @@ public void testVirtualMachineCustomData() throws Exception { @Test public void testVirtualMachineInAvailabilitySet() throws Exception { - new TestVirtualMachineInAvailabilitySet().runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestVirtualMachineInAvailabilitySet().runTest(azureResourceManager.virtualMachines(), + azureResourceManager.resourceGroups()); } @Test @@ -1026,7 +1011,8 @@ public void listSubscriptions() { Subscription subscription = azureResourceManager.getCurrentSubscription(); Assertions.assertNotNull(subscription); if (!isPlaybackMode()) { - Assertions.assertTrue(azureResourceManager.subscriptionId().equalsIgnoreCase(subscription.subscriptionId())); + Assertions + .assertTrue(azureResourceManager.subscriptionId().equalsIgnoreCase(subscription.subscriptionId())); } } @@ -1073,14 +1059,12 @@ public void listStorageAccounts() { @Test public void createStorageAccount() { String storageAccountName = generateRandomResourceName("testsa", 12); - StorageAccount storageAccount = - azureResourceManager - .storageAccounts() - .define(storageAccountName) - .withRegion(Region.ASIA_EAST) - .withNewResourceGroup() - .withSku(StorageAccountSkuType.PREMIUM_LRS) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.ASIA_EAST) + .withNewResourceGroup() + .withSku(StorageAccountSkuType.PREMIUM_LRS) + .create(); Assertions.assertEquals(storageAccount.name(), storageAccountName); @@ -1095,7 +1079,7 @@ public void createStorageAccount() { @Test public void testTrafficManager() throws Exception { new TestTrafficManager(azureResourceManager.publicIpAddresses(), isPlaybackMode()) - .runTest(azureResourceManager.trafficManagerProfiles(), azureResourceManager.resourceGroups()); + .runTest(azureResourceManager.trafficManagerProfiles(), azureResourceManager.resourceGroups()); } @Test @@ -1105,8 +1089,7 @@ public void testRedis() throws Exception { @Test public void testCdnManager() throws Exception { - new TestCdn() - .runTest(azureResourceManager.cdnProfiles(), azureResourceManager.resourceGroups()); + new TestCdn().runTest(azureResourceManager.cdnProfiles(), azureResourceManager.resourceGroups()); } @Test @@ -1126,12 +1109,14 @@ public void testSqlServer() throws Exception { @Test public void testResourceStreaming() throws Exception { - new TestResourceStreaming(azureResourceManager.storageAccounts()).runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); + new TestResourceStreaming(azureResourceManager.storageAccounts()) + .runTest(azureResourceManager.virtualMachines(), azureResourceManager.resourceGroups()); } @Test public void testKubernetesCluster() throws Exception { - new TestKubernetesCluster().runTest(azureResourceManager.kubernetesClusters(), azureResourceManager.resourceGroups()); + new TestKubernetesCluster().runTest(azureResourceManager.kubernetesClusters(), + azureResourceManager.resourceGroups()); } @Test @@ -1147,51 +1132,45 @@ public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() { String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); - final Identity createdIdentity = - azureResourceManager - .identities() - .define(identityName1) - .withRegion(Region.US_WEST) - .withNewResourceGroup(rgName) - .withAccessToCurrentResourceGroup(BuiltInRole.READER) - .create(); + final Identity createdIdentity = azureResourceManager.identities() + .define(identityName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAccessToCurrentResourceGroup(BuiltInRole.READER) + .create(); - Creatable creatableIdentity = - azureResourceManager - .identities() - .define(identityName2) - .withRegion(Region.US_WEST) - .withExistingResourceGroup(rgName) - .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + Creatable creatableIdentity = azureResourceManager.identities() + .define(identityName2) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); List dnsServers = new ArrayList<>(); dnsServers.add("dnsServer1"); - ContainerGroup containerGroup = - azureResourceManager - .containerGroups() - .define(cgName) - .withRegion(Region.US_EAST2) - .withExistingResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withEmptyDirectoryVolume("emptydir1") - .defineContainerInstance("tomcat") - .withImage("tomcat") - .withExternalTcpPort(8080) - .withCpuCoreCount(1) - .withEnvironmentVariable("ENV1", "value1") - .attach() - .defineContainerInstance("nginx") - .withImage("nginx") - .withExternalTcpPort(80) - .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") - .attach() - .withExistingUserAssignedManagedServiceIdentity(createdIdentity) - .withNewUserAssignedManagedServiceIdentity(creatableIdentity) - .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) - .withDnsPrefix(cgName) - .withTag("tag1", "value1") - .create(); + ContainerGroup containerGroup = azureResourceManager.containerGroups() + .define(cgName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withEmptyDirectoryVolume("emptydir1") + .defineContainerInstance("tomcat") + .withImage("tomcat") + .withExternalTcpPort(8080) + .withCpuCoreCount(1) + .withEnvironmentVariable("ENV1", "value1") + .attach() + .defineContainerInstance("nginx") + .withImage("nginx") + .withExternalTcpPort(80) + .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") + .attach() + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withDnsPrefix(cgName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cgName, containerGroup.name()); Assertions.assertEquals("Linux", containerGroup.osType().toString()); @@ -1247,21 +1226,22 @@ public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() { ContainerGroup containerGroup2 = azureResourceManager.containerGroups().getByResourceGroup(rgName, cgName); - List containerGroupList = - azureResourceManager.containerGroups().listByResourceGroup(rgName).stream().collect(Collectors.toList()); + List containerGroupList + = azureResourceManager.containerGroups().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertFalse(containerGroupList.isEmpty()); containerGroup.refresh(); - Set containerGroupOperations = - azureResourceManager.containerGroups().listOperations().stream().collect(Collectors.toSet()); + Set containerGroupOperations + = azureResourceManager.containerGroups().listOperations().stream().collect(Collectors.toSet()); // Number of supported operation can change hence don't assert with a predefined number. Assertions.assertFalse(containerGroupOperations.isEmpty()); } @Test public void testContainerRegistry() throws Exception { - new TestContainerRegistry().runTest(azureResourceManager.containerRegistries(), azureResourceManager.resourceGroups()); + new TestContainerRegistry().runTest(azureResourceManager.containerRegistries(), + azureResourceManager.resourceGroups()); } @Disabled("Often encounters service does not have enough resource in target region. cosmos module should have similar tests.") @@ -1272,28 +1252,28 @@ public void testCosmosDB() throws Exception { @Test public void testSearchServiceFreeSku() throws Exception { - new TestSearchService.SearchServiceFreeSku() - .runTest(azureResourceManager.searchServices(), azureResourceManager.resourceGroups()); + new TestSearchService.SearchServiceFreeSku().runTest(azureResourceManager.searchServices(), + azureResourceManager.resourceGroups()); } @Test public void testSearchServiceBasicSku() throws Exception { - new TestSearchService.SearchServiceBasicSku() - .runTest(azureResourceManager.searchServices(), azureResourceManager.resourceGroups()); + new TestSearchService.SearchServiceBasicSku().runTest(azureResourceManager.searchServices(), + azureResourceManager.resourceGroups()); } @Test public void testSearchServiceStandardSku() throws Exception { - new TestSearchService.SearchServiceStandardSku() - .runTest(azureResourceManager.searchServices(), azureResourceManager.resourceGroups()); + new TestSearchService.SearchServiceStandardSku().runTest(azureResourceManager.searchServices(), + azureResourceManager.resourceGroups()); } // secret in URL on API deleteQueryKey @DoNotRecord(skipInPlayback = true) @Test public void testSearchServiceAnySku() throws Exception { - new TestSearchService.SearchServiceAnySku() - .runTest(azureResourceManager.searchServices(), azureResourceManager.resourceGroups()); + new TestSearchService.SearchServiceAnySku().runTest(azureResourceManager.searchServices(), + azureResourceManager.resourceGroups()); } @Test @@ -1303,16 +1283,13 @@ public void generateMissingRegion() { StringBuilder sb = new StringBuilder(); - List locations = - azureResourceManager - .getCurrentSubscription() - .listLocations() - .stream().collect(Collectors.toList()); + List locations + = azureResourceManager.getCurrentSubscription().listLocations().stream().collect(Collectors.toList()); // note the region is not complete since it depends on current subscription List locationGroupByGeography = new ArrayList<>(); - List geographies = Arrays.asList( - "US", "Canada", "South America", "Europe", "Asia Pacific", "Middle East", "Africa"); + List geographies + = Arrays.asList("US", "Canada", "South America", "Europe", "Asia Pacific", "Middle East", "Africa"); for (String geography : geographies) { for (Location location : locations) { if (location.regionType() == RegionType.PHYSICAL) { @@ -1334,20 +1311,19 @@ public void generateMissingRegion() { if (location.regionType() == RegionType.PHYSICAL) { Region region = findByLabelOrName(location.name()); if (region == null) { - sb - .append("\n").append("/**") - .append("\n").append(MessageFormat.format( - " * {0} ({1})", - location.displayName(), + sb.append("\n") + .append("/**") + .append("\n") + .append(MessageFormat.format(" * {0} ({1})", location.displayName(), location.innerModel().metadata().geographyGroup())) .append(location.innerModel().metadata().regionCategory() == RegionCategory.RECOMMENDED - ? " (recommended)" : "") - .append("\n").append(" */") - .append("\n").append(MessageFormat.format( - "public static final Region {0} = new Region(\"{1}\", \"{2}\");", - getLocationVariableName(location), - location.name(), - location.displayName())); + ? " (recommended)" + : "") + .append("\n") + .append(" */") + .append("\n") + .append(MessageFormat.format("public static final Region {0} = new Region(\"{1}\", \"{2}\");", + getLocationVariableName(location), location.name(), location.displayName())); } } } @@ -1360,7 +1336,8 @@ private static Region findByLabelOrName(String labelOrName) { return null; } String nameLowerCase = labelOrName.toLowerCase(Locale.ROOT).replace(" ", ""); - return Region.values().stream() + return Region.values() + .stream() .filter(r -> nameLowerCase.equals(r.name().toLowerCase(Locale.ROOT))) .findFirst() .orElse(null); @@ -1393,7 +1370,8 @@ private static String getLocationVariableName(Location location) { displayName = displayName.replace("South Africa", "SouthAfrica"); } } - if (displayName.length() > 2 && displayName.charAt(displayName.length() - 1) >= '0' + if (displayName.length() > 2 + && displayName.charAt(displayName.length() - 1) >= '0' && displayName.charAt(displayName.length() - 1) <= '9' && displayName.charAt(displayName.length() - 2) == ' ') { displayName = displayName.replace(displayName.substring(displayName.length() - 2), diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DiskEncryptionTestBase.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DiskEncryptionTestBase.java index 9a8241418c416..f1b7a66fa1cb8 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DiskEncryptionTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DiskEncryptionTestBase.java @@ -37,21 +37,10 @@ public class DiskEncryptionTestBase extends ResourceManagerTestProxyTestBase { protected final Region region = Region.US_WEST2; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -61,10 +50,10 @@ protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { if (!testContextManager.doNotRecordTest()) { // don't match api-version when matching url - interceptorManager.addMatchers(new CustomMatcher() - .setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) - .setExcludedHeaders(Collections.singletonList("Accept-Language")) - .setIgnoredQueryParameters(Collections.singletonList("api-version"))); + interceptorManager + .addMatchers(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) + .setExcludedHeaders(Collections.singletonList("Accept-Language")) + .setIgnoredQueryParameters(Collections.singletonList("api-version"))); } } } @@ -100,7 +89,8 @@ private VaultAndKey(Vault vault, Key key) { protected VaultAndKey createVaultAndKey(String name, String userPrincipalName) { // create vault - Vault vault = azureResourceManager.vaults().define(name) + Vault vault = azureResourceManager.vaults() + .define(name) .withRegion(region) .withNewResourceGroup(rgName) .withRoleBasedAccessControl() @@ -109,7 +99,9 @@ protected VaultAndKey createVaultAndKey(String name, String userPrincipalName) { // RBAC for this app String rbacName = generateRandomUuid(); - azureResourceManager.accessManagement().roleAssignments().define(rbacName) + azureResourceManager.accessManagement() + .roleAssignments() + .define(rbacName) .forUser(userPrincipalName) .withBuiltInRole(BuiltInRole.KEY_VAULT_ADMINISTRATOR) .withResourceScope(vault) @@ -118,15 +110,13 @@ protected VaultAndKey createVaultAndKey(String name, String userPrincipalName) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); // create key - Key key = vault.keys().define("key1") - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key key = vault.keys().define("key1").withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); return new VaultAndKey(vault, key); } - protected DiskEncryptionSet createDiskEncryptionSet(String name, DiskEncryptionSetType type, VaultAndKey vaultAndKey) { + protected DiskEncryptionSet createDiskEncryptionSet(String name, DiskEncryptionSetType type, + VaultAndKey vaultAndKey) { return azureResourceManager.diskEncryptionSets() .define(name) .withRegion(region) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DocsTest.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DocsTest.java index 215c0e7f81e0b..b8b0441fcd5ef 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DocsTest.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/DocsTest.java @@ -27,21 +27,10 @@ public class DocsTest extends ResourceManagerTestProxyTestBase { private DesignPreviewSamples samples = new DesignPreviewSamples(); @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/GenericResourceTest.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/GenericResourceTest.java index ad4e28eae4eaa..7b4504d6eabe1 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/GenericResourceTest.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/GenericResourceTest.java @@ -42,24 +42,14 @@ public class GenericResourceTest extends ResourceManagerTestProxyTestBase { protected String rgName = ""; protected final Region region = Region.US_EAST; - private final String policyRule = "{\"if\":{\"not\":{\"field\":\"location\",\"in\":[\"southcentralus\",\"eastus\"]}},\"then\":{\"effect\":\"deny\"}}"; + private final String policyRule + = "{\"if\":{\"not\":{\"field\":\"location\",\"in\":[\"southcentralus\",\"eastus\"]}},\"then\":{\"effect\":\"deny\"}}"; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -94,19 +84,18 @@ public void testResourceWithSpaceInName() { pool = pool.refresh(); Assertions.assertEquals(poolName, pool.name()); - pool.update() - .withTag("keyInSpaceTest", "value") - .apply(); + pool.update().withTag("keyInSpaceTest", "value").apply(); Assertions.assertEquals(poolName, pool.name()); Assertions.assertTrue(pool.tags().containsKey("keyInSpaceTest")); // status code 405 -// Assertions.assertTrue(azureResourceManager.genericResources().checkExistenceById(poolId)); + // Assertions.assertTrue(azureResourceManager.genericResources().checkExistenceById(poolId)); // policy assignment String policyName = generateRandomResourceName("policy", 15); String assignmentName = generateRandomResourceName("assign", 15); - PolicyDefinition definition = azureResourceManager.policyDefinitions().define(policyName) + PolicyDefinition definition = azureResourceManager.policyDefinitions() + .define(policyName) .withPolicyRuleJson(policyRule) .withPolicyType(PolicyType.CUSTOM) .withDisplayName(policyName) @@ -126,8 +115,7 @@ public void testResourceWithSpaceInName() { // tags Map tags = new HashMap<>(); tags.put("myTagKey", "myTagValue"); - azureResourceManager.tagOperations() - .updateTags(pool, tags); + azureResourceManager.tagOperations().updateTags(pool, tags); pool = pool.refresh(); Assertions.assertTrue(pool.tags().containsKey("myTagKey")); @@ -142,14 +130,16 @@ public void canGetDefaultApiVersionForChildResources() { String topLevelDomain = "www.contoso" + generateRandomResourceName("z", 10) + ".com"; String vnetLinkName = generateRandomResourceName("pdvnl", 15); - Network network = azureResourceManager.networks().define(vnetName) + Network network = azureResourceManager.networks() + .define(vnetName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .withSubnet("subnetA", "10.0.0.0/29") .create(); - PrivateDnsZone pdz = azureResourceManager.privateDnsZones().define(topLevelDomain) + PrivateDnsZone pdz = azureResourceManager.privateDnsZones() + .define(topLevelDomain) .withExistingResourceGroup(rgName) .defineVirtualNetworkLink(vnetLinkName) .disableAutoRegistration() @@ -175,8 +165,7 @@ public void canGetDefaultApiVersionForChildResources() { .withMinTlsVersion(SupportedTlsVersions.ONE_ONE) .create(); - SiteConfigResourceInner configInner = azureResourceManager - .webApps() + SiteConfigResourceInner configInner = azureResourceManager.webApps() .manager() .serviceClient() .getWebApps() @@ -189,8 +178,7 @@ public void canGetDefaultApiVersionForChildResources() { private SqlElasticPool ensureElasticPoolWithSpace() { String sqlServerName = generateRandomResourceName("JMonitorSql-", 18); - SqlServer sqlServer = azureResourceManager - .sqlServers() + SqlServer sqlServer = azureResourceManager.sqlServers() .define(sqlServerName) .withRegion(region) .withNewResourceGroup(rgName) @@ -199,10 +187,7 @@ private SqlElasticPool ensureElasticPoolWithSpace() { .create(); // white space in pool name - SqlElasticPool pool = sqlServer.elasticPools() - .define("name with space") - .withBasicPool() - .create(); + SqlElasticPool pool = sqlServer.elasticPools().define("name with space").withBasicPool().create(); return pool; } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesAadTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesAadTests.java index a0a96a4b2b165..6644217ab1e74 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesAadTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesAadTests.java @@ -36,21 +36,10 @@ public class KubernetesAadTests extends ResourceManagerTestProxyTestBase { private final Region region = Region.US_WEST3; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List< HttpPipelinePolicy > policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -86,15 +75,15 @@ public void testKubernetesClusterAadIntegration() { ActiveDirectoryGroup group = null; try { // Azure AD integration with AAD group - group = azureResourceManager.accessManagement().activeDirectoryGroups() + group = azureResourceManager.accessManagement() + .activeDirectoryGroups() .define(groupName) .withEmailAlias(groupName) .withMember(userId) .create(); // create - KubernetesCluster kubernetesCluster = azureResourceManager - .kubernetesClusters() + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() .define(aksName) .withRegion(region) .withNewResourceGroup(rgName) @@ -103,11 +92,11 @@ public void testKubernetesClusterAadIntegration() { .withAzureActiveDirectoryGroup(group.id()) .disableLocalAccounts() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withOSDiskSizeInGB(30) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withOSDiskSizeInGB(30) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -119,29 +108,25 @@ public void testKubernetesClusterAadIntegration() { List credentialResults = kubernetesCluster.userKubeConfigs(); Assertions.assertFalse(credentialResults.isEmpty()); - kubernetesCluster.update() - .enableLocalAccounts() - .apply(); + kubernetesCluster.update().enableLocalAccounts().apply(); Assertions.assertTrue(kubernetesCluster.isLocalAccountsEnabled()); azureResourceManager.kubernetesClusters().deleteById(kubernetesCluster.id()); - // create and then update - kubernetesCluster = azureResourceManager - .kubernetesClusters() + kubernetesCluster = azureResourceManager.kubernetesClusters() .define(aksName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withOSDiskSizeInGB(30) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withOSDiskSizeInGB(30) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); @@ -149,10 +134,7 @@ public void testKubernetesClusterAadIntegration() { Assertions.assertTrue(kubernetesCluster.isLocalAccountsEnabled()); // Since kubernetes version 1.25, disableLocalAccounts can only be set on Azure AD integration enabled cluster. - kubernetesCluster.update() - .withAzureActiveDirectoryGroup(group.id()) - .disableLocalAccounts() - .apply(); + kubernetesCluster.update().withAzureActiveDirectoryGroup(group.id()).disableLocalAccounts().apply(); Assertions.assertFalse(kubernetesCluster.isLocalAccountsEnabled()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesCniTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesCniTests.java index a23b23598ae63..eca4e20d6d255 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesCniTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesCniTests.java @@ -37,21 +37,10 @@ public class KubernetesCniTests extends ResourceManagerTestProxyTestBase { private final Region region = Region.US_EAST; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -82,37 +71,41 @@ public void testKubernetesClusterCni() { final String agentPoolName = generateRandomResourceName("ap0", 10); final String roleAssignmentName = generateRandomUuid(); - Network vnet = azureResourceManager.networks().define(vnetName) + Network vnet = azureResourceManager.networks() + .define(vnetName) .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/8") .withSubnet(subnetName, "10.240.0.0/16") .create(); - KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() + .define(aksName) .withRegion(region) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(3) - .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withMaxPodsCount(30) - .withAvailabilityZones(1, 2, 3) - .withVirtualNetwork(vnet.id(), subnetName) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(3) + .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withMaxPodsCount(30) + .withAvailabilityZones(1, 2, 3) + .withVirtualNetwork(vnet.id(), subnetName) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .defineNetworkProfile() - .withNetworkPlugin(NetworkPlugin.AZURE) - .withServiceCidr("10.0.0.0/16") - .withDnsServiceIP("10.0.0.10") - .withLoadBalancerSku(LoadBalancerSku.STANDARD) - .attach() + .withNetworkPlugin(NetworkPlugin.AZURE) + .withServiceCidr("10.0.0.0/16") + .withDnsServiceIP("10.0.0.10") + .withLoadBalancerSku(LoadBalancerSku.STANDARD) + .attach() .create(); - azureResourceManager.accessManagement().roleAssignments().define(roleAssignmentName) + azureResourceManager.accessManagement() + .roleAssignments() + .define(roleAssignmentName) .forObjectId(kubernetesCluster.systemAssignedManagedServiceIdentityPrincipalId()) .withBuiltInRole(BuiltInRole.NETWORK_CONTRIBUTOR) .withScope(vnet.subnets().get(subnetName).id()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesEncryptionTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesEncryptionTests.java index bc6a6817ee008..7227b80ab1a83 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesEncryptionTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/KubernetesEncryptionTests.java @@ -29,8 +29,7 @@ public void canCreateClusterWithDiskEncryption() { final String agentPoolName = generateRandomResourceName("ap0", 10); // create - KubernetesCluster kubernetesCluster = azureResourceManager - .kubernetesClusters() + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters() .define(aksName) .withRegion(region) .withNewResourceGroup(rgName) @@ -38,11 +37,11 @@ public void canCreateClusterWithDiskEncryption() { .withSystemAssignedManagedServiceIdentity() .withDiskEncryptionSet(diskEncryptionSet.id()) .defineAgentPool(agentPoolName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) - .withOSDiskSizeInGB(30) - .attach() + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withOSDiskSizeInGB(30) + .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ManagerLiveTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ManagerLiveTests.java index fecf3d9d92116..f08a335acf5ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ManagerLiveTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ManagerLiveTests.java @@ -46,21 +46,10 @@ public class ManagerLiveTests extends ResourceManagerTestProxyTestBase { private HttpPipeline httpPipeline; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -78,7 +67,11 @@ protected void cleanUpResources() { public void testAuthentication() { AppPlatformManager.authenticate(httpPipeline, profile()).springServices().list().stream().count(); AppServiceManager.authenticate(httpPipeline, profile()).appServicePlans().list().stream().count(); - AuthorizationManager.authenticate(httpPipeline, profile()).roleDefinitions().listByScope("/subscriptions/" + profile().getSubscriptionId()).stream().count(); + AuthorizationManager.authenticate(httpPipeline, profile()) + .roleDefinitions() + .listByScope("/subscriptions/" + profile().getSubscriptionId()) + .stream() + .count(); CdnManager.authenticate(httpPipeline, profile()).profiles().list().stream().count(); ComputeManager.authenticate(httpPipeline, profile()).disks().list().stream().count(); ContainerInstanceManager.authenticate(httpPipeline, profile()).containerGroups().list().stream().count(); @@ -94,14 +87,22 @@ public void testAuthentication() { PrivateDnsZoneManager.authenticate(httpPipeline, profile()).privateZones().list().stream().count(); RedisManager.authenticate(httpPipeline, profile()).redisCaches().list().stream().count(); ResourceManager.authenticate(httpPipeline, profile()).subscriptions().list().stream().count(); - ResourceManager.authenticate(httpPipeline, profile()).withDefaultSubscription().resourceGroups().list().stream().count(); + ResourceManager.authenticate(httpPipeline, profile()) + .withDefaultSubscription() + .resourceGroups() + .list() + .stream() + .count(); SearchServiceManager.authenticate(httpPipeline, profile()).searchServices().list().stream().count(); ServiceBusManager.authenticate(httpPipeline, profile()).namespaces().list().stream().count(); SqlServerManager.authenticate(httpPipeline, profile()).sqlServers().list().stream().count(); StorageManager.authenticate(httpPipeline, profile()).storageAccounts().list().stream().count(); TrafficManager.authenticate(httpPipeline, profile()).profiles().list().stream().count(); - Assertions.assertNotNull(AzureResourceManager.authenticate(httpPipeline, profile()).withDefaultSubscription() - .genericResources().manager().httpPipeline()); + Assertions.assertNotNull(AzureResourceManager.authenticate(httpPipeline, profile()) + .withDefaultSubscription() + .genericResources() + .manager() + .httpPipeline()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/NetworkSecurityGroupTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/NetworkSecurityGroupTests.java index 3662a7f814013..f75a85a1d3cdb 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/NetworkSecurityGroupTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/NetworkSecurityGroupTests.java @@ -37,21 +37,10 @@ public class NetworkSecurityGroupTests extends ResourceManagerTestProxyTestBase protected final Region region = Region.US_EAST; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -73,10 +62,10 @@ protected void cleanUpResources() { } } - @Test public void testDeleteByResourceGroup() { - Network network = azureResourceManager.networks().define("vmssvnet") + Network network = azureResourceManager.networks() + .define("vmssvnet") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") @@ -85,7 +74,8 @@ public void testDeleteByResourceGroup() { final String nsgName = generateRandomResourceName("nsg", 8); - NetworkSecurityGroup nsg = azureResourceManager.networkSecurityGroups().define(nsgName) + NetworkSecurityGroup nsg = azureResourceManager.networkSecurityGroups() + .define(nsgName) .withRegion(region) .withExistingResourceGroup(rgName) .defineRule("rule1") @@ -100,7 +90,8 @@ public void testDeleteByResourceGroup() { final String vmssName = generateRandomResourceName("vmss", 10); - VirtualMachineScaleSet vmss = azureResourceManager.virtualMachineScaleSets().define(vmssName) + VirtualMachineScaleSet vmss = azureResourceManager.virtualMachineScaleSets() + .define(vmssName) .withRegion(region) .withExistingResourceGroup(rgName) .withFlexibleOrchestrationMode() diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java index 8a8c58f186b58..5b8e2bf5011dd 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java @@ -71,21 +71,10 @@ public class PrivateLinkTests extends ResourceManagerTestProxyTestBase { private final String vnAddressSpace = "10.0.0.0/28"; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -114,121 +103,137 @@ protected void cleanUpResources() { @Test public void testPrivateEndpoint() { -// String saName2 = generateRandomResourceName("sa", 10); + // String saName2 = generateRandomResourceName("sa", 10); String peName2 = generateRandomResourceName("pe", 10); -// String pecName2 = generateRandomResourceName("pec", 10); + // String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; LOGGER.log(LogLevel.VERBOSE, () -> "storage account domain name: " + saDomainName); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); - Network network = azureResourceManager.networks().define(vnName) + Network network = azureResourceManager.networks() + .define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) - .withAddressPrefix(vnAddressSpace) - .disableNetworkPoliciesOnPrivateEndpoint() - .attach() + .withAddressPrefix(vnAddressSpace) + .disableNetworkPoliciesOnPrivateEndpoint() + .attach() .create(); // private endpoint with manual approval - PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) + PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints() + .define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) - .withResource(storageAccount) - .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) - .withManualApproval("request message") - .attach() + .withResource(storageAccount) + .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) + .withManualApproval("request message") + .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); - Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); - Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); - Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); - Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); + Assertions + .assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); + Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), + privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); + Assertions.assertEquals("Pending", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions.assertEquals("request message", + privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); // approve the connection - List storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); + List storageAccountConnections + = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); Assertions.assertNotNull(storageAccountConnection.id()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint().id()); Assertions.assertNotNull(storageAccountConnection.privateLinkServiceConnectionState()); - Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, storageAccountConnection.privateLinkServiceConnectionState().status()); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, + storageAccountConnection.privateLinkServiceConnectionState().status()); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); // check again privateEndpoint.refresh(); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); - -// // update private endpoint -// StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .create(); -// -// privateEndpoint.update() -// .updatePrivateLinkServiceConnection(pecName) -// .withRequestMessage("request2") -// .parent() -// .apply(); -// -// Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); -// Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); -// -// privateEndpoint.update() -// .withoutPrivateLinkServiceConnection(pecName) -// .definePrivateLinkServiceConnection(pecName2) -// .withResource(storageAccount2) -// .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) -// .attach() -// .apply(); -// -// Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); -// Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + + // // update private endpoint + // StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) + // .withRegion(region) + // .withNewResourceGroup(rgName) + // .create(); + // + // privateEndpoint.update() + // .updatePrivateLinkServiceConnection(pecName) + // .withRequestMessage("request2") + // .parent() + // .apply(); + // + // Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + // Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); + // + // privateEndpoint.update() + // .withoutPrivateLinkServiceConnection(pecName) + // .definePrivateLinkServiceConnection(pecName2) + // .withResource(storageAccount2) + // .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) + // .attach() + // .apply(); + // + // Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); + // Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); // delete azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); // private endpoint with auto-approval (RBAC based) - privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) + privateEndpoint = azureResourceManager.privateEndpoints() + .define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) - .withResourceId(storageAccount.id()) - .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) - .attach() + .withResourceId(storageAccount.id()) + .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) + .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); - assertResourceIdEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); - Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); + assertResourceIdEquals(storageAccount.id(), + privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); + Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), + privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); // auto-approved - Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions + .assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); LOGGER.log(LogLevel.VERBOSE, () -> "storage account private ip: " + saPrivateIp); // verify list - List privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); + List privateEndpoints + = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); } @@ -247,43 +252,50 @@ public void testPrivateEndpointE2E() { String saDomainName = saName + ".blob.core.windows.net"; LOGGER.log(LogLevel.VERBOSE, () -> "storage account domain name: " + saDomainName); - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); - Network network = azureResourceManager.networks().define(vnName) + Network network = azureResourceManager.networks() + .define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) - .withAddressPrefix(vnAddressSpace) - .disableNetworkPoliciesOnPrivateEndpoint() - .attach() + .withAddressPrefix(vnAddressSpace) + .disableNetworkPoliciesOnPrivateEndpoint() + .attach() .create(); // private endpoint - PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) + PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints() + .define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) - .withResourceId(storageAccount.id()) - .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) - .attach() + .withResourceId(storageAccount.id()) + .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) + .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); - assertResourceIdEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); - Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); + assertResourceIdEquals(storageAccount.id(), + privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); + Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), + privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); // auto-approved - Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions + .assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); LOGGER.log(LogLevel.VERBOSE, () -> "storage account private ip: " + saPrivateIp); @@ -291,7 +303,8 @@ public void testPrivateEndpointE2E() { VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { // create a test virtual machine - virtualMachine = azureResourceManager.virtualMachines().define(vmName) + virtualMachine = azureResourceManager.virtualMachines() + .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) @@ -305,44 +318,52 @@ public void testPrivateEndpointE2E() { .create(); // verify private endpoint not yet works - RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); + RunCommandResult commandResult + = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { LOGGER.log(LogLevel.VERBOSE, () -> status.message()); } - Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); + Assertions + .assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } // private dns zone - PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") + PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones() + .define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) - .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) - .attach() + .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) + .attach() .defineVirtualNetworkLink(vnlName) - .withVirtualNetworkId(network.id()) - .attach() + .withVirtualNetworkId(network.id()) + .attach() .create(); // private dns zone group on private endpoint - PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) + PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups() + .define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { // verify private endpoint works - RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); + RunCommandResult commandResult + = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { LOGGER.log(LogLevel.VERBOSE, () -> status.message()); } - Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); + Assertions + .assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } // verify list and get for private dns zone group Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); - Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); + Assertions.assertEquals(pdzgName, + privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); // update private dns zone group - PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") + PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones() + .define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); @@ -357,7 +378,8 @@ public void testPrivateEndpointE2E() { @Test public void testStoragePrivateLinkResources() { - StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); @@ -370,7 +392,8 @@ public void testPrivateEndpointVault() { String vaultName = generateRandomResourceName("vault", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.VAULT; - Vault vault = azureResourceManager.vaults().define(vaultName) + Vault vault = azureResourceManager.vaults() + .define(vaultName) .withRegion(region) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() @@ -387,7 +410,8 @@ public void testPrivateEndpointCosmos() { String cosmosName = generateRandomResourceName("cosmos", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.COSMOS_SQL; - CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) + CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts() + .define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() @@ -396,11 +420,13 @@ public void testPrivateEndpointCosmos() { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(cosmosDBAccount, subResourceName); - com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); + com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection + = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); cosmosDBAccount.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } @Test @@ -411,15 +437,16 @@ public void testPrivateEndpointAKS() { PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.KUBERNETES_MANAGEMENT; - KubernetesCluster cluster = azureResourceManager.kubernetesClusters().define(clusterName) + KubernetesCluster cluster = azureResourceManager.kubernetesClusters() + .define(clusterName) .withRegion(region) .withNewResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(apName) - .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) - .withAgentPoolVirtualMachineCount(1) - .withAgentPoolMode(AgentPoolMode.SYSTEM) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(dnsPrefix) .enablePrivateCluster() @@ -429,10 +456,12 @@ public void testPrivateEndpointAKS() { // private dns zone and private endpoint connection is created by AKS - List connections = cluster.listPrivateEndpointConnections().stream().collect(Collectors.toList()); + List connections + = cluster.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); - Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, connection.privateLinkServiceConnectionState().status()); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, + connection.privateLinkServiceConnectionState().status()); } @Test @@ -440,7 +469,8 @@ public void testPrivateEndpointRedis() { String redisName = generateRandomResourceName("redis", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.REDIS_CACHE; - RedisCache redisCache = azureResourceManager.redisCaches().define(redisName) + RedisCache redisCache = azureResourceManager.redisCaches() + .define(redisName) .withRegion(region) .withNewResourceGroup(rgName) .withPremiumSku() @@ -458,7 +488,8 @@ public void testPrivateEndpointWeb() { PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.WEB_SITES; - WebApp webapp = azureResourceManager.webApps().define(webappName) + WebApp webapp = azureResourceManager.webApps() + .define(webappName) .withRegion(region) .withNewResourceGroup(rgName) .withNewLinuxPlan(PricingTier.PREMIUM_P2V3) // requires P2 or P3 @@ -470,28 +501,28 @@ public void testPrivateEndpointWeb() { validateListAndApprovePrivatePrivateEndpointConnection(webapp, subResourceName); } -// @Test -// public void testPrivateEndpointWebSlot() { -// String webappName = generateRandomResourceName("webapp", 20); -// String webappSlotName = generateRandomResourceName("webappslot", 20); -// -// PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.WEB_SITES; -// -// WebApp webapp = azureResourceManager.webApps().define(webappName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withNewLinuxPlan(PricingTier.PREMIUM_P2V3) // requires P2 or P3 -// .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) -// .create(); -// -// DeploymentSlot slot = webapp.deploymentSlots().define(webappSlotName) -// .withConfigurationFromParent() -// .create(); -// -// validatePrivateLinkResource(slot, subResourceName.toString()); -// -// validateListAndApprovePrivatePrivateEndpointConnection(slot, subResourceName); -// } + // @Test + // public void testPrivateEndpointWebSlot() { + // String webappName = generateRandomResourceName("webapp", 20); + // String webappSlotName = generateRandomResourceName("webappslot", 20); + // + // PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.WEB_SITES; + // + // WebApp webapp = azureResourceManager.webApps().define(webappName) + // .withRegion(region) + // .withNewResourceGroup(rgName) + // .withNewLinuxPlan(PricingTier.PREMIUM_P2V3) // requires P2 or P3 + // .withBuiltInImage(RuntimeStack.JAVA_11_JAVA11) + // .create(); + // + // DeploymentSlot slot = webapp.deploymentSlots().define(webappSlotName) + // .withConfigurationFromParent() + // .create(); + // + // validatePrivateLinkResource(slot, subResourceName.toString()); + // + // validateListAndApprovePrivatePrivateEndpointConnection(slot, subResourceName); + // } private void validatePrivateLinkResource(SupportsListingPrivateLinkResource resource, String requiredGroupId) { PagedIterable privateLinkResources = resource.listPrivateLinkResources(); @@ -501,8 +532,10 @@ private void validatePrivateLinkResource(SupportsListingPrivateLinkResource reso Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> requiredGroupId.equals(r.groupId()))); } - private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, PrivateLinkSubResourceName subResourceName) { - Network network = azureResourceManager.networks().define(vnName) + private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, + PrivateLinkSubResourceName subResourceName) { + Network network = azureResourceManager.networks() + .define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) @@ -513,7 +546,8 @@ private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource .create(); // private endpoint with manual approval - PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) + PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints() + .define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) @@ -523,25 +557,31 @@ private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource .withManualApproval("request message") .attach() .create(); - Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions.assertEquals("Pending", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); return privateEndpoint; } - private void validateApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { + private void + validateApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); resource.approvePrivateEndpointConnection(pecName); // check again privateEndpoint.refresh(); - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } - private void validateListAndApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { + private + void + validateListAndApprovePrivatePrivateEndpointConnection(T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); - List connections = resource.listPrivateEndpointConnections().stream().collect(Collectors.toList()); + List connections + = resource.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, connections.size()); PrivateEndpointConnection connection = connections.iterator().next(); @@ -550,11 +590,13 @@ private = 0 && !"Approved".equals(privateEndpoint.privateLinkServiceConnections().get(pecName).state().status())) { + while (retry >= 0 + && !"Approved".equals(privateEndpoint.privateLinkServiceConnections().get(pecName).state().status())) { ResourceManagerUtils.sleep(Duration.ofSeconds(30)); privateEndpoint.refresh(); retry--; } - Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); + Assertions.assertEquals("Approved", + privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ProviderRegistrationPolicyTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ProviderRegistrationPolicyTests.java index 6f33232dff7c3..1c67b165d1e30 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ProviderRegistrationPolicyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ProviderRegistrationPolicyTests.java @@ -32,21 +32,10 @@ public class ProviderRegistrationPolicyTests extends ResourceManagerTestProxyTes private String rgName; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -82,16 +71,14 @@ public void testProviderRegistrationPolicy() { } Assertions.assertEquals("Unregistered", provider.registrationState()); - Registry registry = - azureResourceManager - .containerRegistries() - .define(acrName) - .withRegion(Region.US_WEST_CENTRAL) - .withNewResourceGroup(rgName) - .withPremiumSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = azureResourceManager.containerRegistries() + .define(acrName) + .withRegion(Region.US_WEST_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); // above should success even when namespace "Microsoft.ContainerRegistry" not registered Assertions.assertNotNull(registry); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/StorageAccountCmkTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/StorageAccountCmkTests.java index dbc4aa013af2a..a59b460b7cde3 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/StorageAccountCmkTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/StorageAccountCmkTests.java @@ -36,20 +36,10 @@ public class StorageAccountCmkTests extends ResourceManagerTestProxyTestBase { private AzureResourceManager azureResourceManager; @Override - protected HttpPipeline buildHttpPipeline(TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -62,7 +52,8 @@ protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile } @Override - protected void cleanUpResources() {} + protected void cleanUpResources() { + } @Test // involves key vault key @@ -108,40 +99,38 @@ public void testCmkAndMmk() { Assertions.assertNull(storageAccount.identityTypeForCustomerEncryptionKey()); Assertions.assertNull(storageAccount.userAssignedIdentityIdForCustomerEncryptionKey()); - Assertions.assertEquals(KeySource.MICROSOFT_STORAGE.toString(), storageAccount.encryptionKeySource().toString()); + Assertions.assertEquals(KeySource.MICROSOFT_STORAGE.toString(), + storageAccount.encryptionKeySource().toString()); // assign access policy to the three MSIs vault.update() .defineAccessPolicy() // access policy for this sample client to generate key - .forUser(azureCliSignedInUser().userPrincipalName()) - .allowKeyAllPermissions() - .attach() + .forUser(azureCliSignedInUser().userPrincipalName()) + .allowKeyAllPermissions() + .attach() .defineAccessPolicy() - .forObjectId(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .defineAccessPolicy() - .forObjectId(identity1.principalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(identity1.principalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .defineAccessPolicy() - .forObjectId(identity2.principalId()) - .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) - .attach() + .forObjectId(identity2.principalId()) + .allowKeyPermissions(KeyPermissions.GET, KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY) + .attach() .apply(); // create key vault key - Key key = vault.keys().define("key1") - .withKeyTypeToCreate(KeyType.RSA) - .withKeySize(4096) - .create(); + Key key = vault.keys().define("key1").withKeyTypeToCreate(KeyType.RSA).withKeySize(4096).create(); // update Storage Account to CMK with system-assigned MSI - storageAccount.update() - .withEncryptionKeyFromKeyVault(vault.vaultUri(), key.name(), "") - .apply(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.identityTypeForCustomerEncryptionKey()); - Assertions.assertEquals(KeySource.MICROSOFT_KEYVAULT.toString(), storageAccount.encryptionKeySource().toString()); + storageAccount.update().withEncryptionKeyFromKeyVault(vault.vaultUri(), key.name(), "").apply(); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, + storageAccount.identityTypeForCustomerEncryptionKey()); + Assertions.assertEquals(KeySource.MICROSOFT_KEYVAULT.toString(), + storageAccount.encryptionKeySource().toString()); // update Storage Account to CMK with user-assigned MSI storageAccount.update() @@ -161,17 +150,15 @@ public void testCmkAndMmk() { Assertions.assertEquals(identity2.id(), storageAccount.userAssignedIdentityIdForCustomerEncryptionKey()); // update Storage Account to CMK with system-assigned MSI - storageAccount.update() - .withEncryptionKeyFromKeyVault(vault.vaultUri(), key.name(), "") - .apply(); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.identityTypeForCustomerEncryptionKey()); + storageAccount.update().withEncryptionKeyFromKeyVault(vault.vaultUri(), key.name(), "").apply(); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, + storageAccount.identityTypeForCustomerEncryptionKey()); Assertions.assertNull(storageAccount.userAssignedIdentityIdForCustomerEncryptionKey()); // update Storage Account to MMK - storageAccount.update() - .withMicrosoftManagedEncryptionKey() - .apply(); - Assertions.assertEquals(KeySource.MICROSOFT_STORAGE.toString(), storageAccount.encryptionKeySource().toString()); + storageAccount.update().withMicrosoftManagedEncryptionKey().apply(); + Assertions.assertEquals(KeySource.MICROSOFT_STORAGE.toString(), + storageAccount.encryptionKeySource().toString()); Assertions.assertNull(storageAccount.identityTypeForCustomerEncryptionKey()); } finally { azureResourceManager.resourceGroups().beginDeleteByName(rgName); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java index 190280a546ebf..ad96f1e5cfbd2 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java @@ -48,12 +48,11 @@ public class TestApplicationGateway { String groupName = ""; String appGatewayName = ""; String[] pipNames = null; - static final String ID_TEMPLATE = - "/subscriptions/${subId}/resourceGroups/${rgName}/providers/Microsoft.Network/applicationGateways/${resourceName}"; + static final String ID_TEMPLATE + = "/subscriptions/${subId}/resourceGroups/${rgName}/providers/Microsoft.Network/applicationGateways/${resourceName}"; String createResourceId(String subscriptionId) { - return ID_TEMPLATE - .replace("${subId}", subscriptionId) + return ID_TEMPLATE.replace("${subId}", subscriptionId) .replace("${rgName}", groupName) .replace("${resourceName}", appGatewayName); } @@ -62,7 +61,7 @@ void initializeResourceNames(ResourceManagerUtils.InternalRuntimeContext interna testId = internalContext.randomResourceName("", 8); groupName = "rg" + testId; appGatewayName = "ag" + testId; - pipNames = new String[] {"pipa" + testId, "pipb" + testId}; + pipNames = new String[] { "pipa" + testId, "pipb" + testId }; } /** Minimalistic internal (private) app gateway test. */ @@ -79,30 +78,27 @@ public void print(ApplicationGateway resource) { @Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { // Prepare a separate thread for resource creation - Thread creationThread = - new Thread( - new Runnable() { - @Override - public void run() { - // Create an application gateway - resources - .define(appGatewayName) - .withRegion(REGION) - .withNewResourceGroup(groupName) - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .withNewPublicIpAddress() - .withTier(ApplicationGatewayTier.STANDARD_V2) - .withSize(ApplicationGatewaySkuName.STANDARD_V2) - .create(); - } - }); + Thread creationThread = new Thread(new Runnable() { + @Override + public void run() { + // Create an application gateway + resources.define(appGatewayName) + .withRegion(REGION) + .withNewResourceGroup(groupName) + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .withNewPublicIpAddress() + .withTier(ApplicationGatewayTier.STANDARD_V2) + .withSize(ApplicationGatewaySkuName.STANDARD_V2) + .create(); + } + }); // Start the creation... creationThread.start(); @@ -159,8 +155,7 @@ public void run() { @Override public ApplicationGateway updateResource(final ApplicationGateway resource) throws Exception { - resource - .update() + resource.update() .withInstanceCount(2) .withFrontendPort(81, "port81") // Add a new port .withoutBackendIPAddress("11.1.1.1") // Remove from all existing backends @@ -258,18 +253,16 @@ public void print(ApplicationGateway resource) { @Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { String appPublicIp = "pip" + testId; - PublicIpAddress pip = - resources.manager() - .publicIpAddresses() - .define(appPublicIp) - .withRegion(REGION) - .withNewResourceGroup(groupName) - .withSku(PublicIPSkuType.STANDARD) - .withStaticIP() - .create(); + PublicIpAddress pip = resources.manager() + .publicIpAddresses() + .define(appPublicIp) + .withRegion(REGION) + .withNewResourceGroup(groupName) + .withSku(PublicIPSkuType.STANDARD) + .withStaticIP() + .create(); // Create an application gateway - resources - .define(appGatewayName) + resources.define(appGatewayName) .withRegion(REGION) .withExistingResourceGroup(groupName) .definePathBasedRoutingRule("pathMap") @@ -337,8 +330,7 @@ public ApplicationGateway createResource(final ApplicationGateways resources) th @Override public ApplicationGateway updateResource(final ApplicationGateway resource) throws Exception { - resource - .update() + resource.update() .withoutUrlPathMap("pathMap") // Request routing rules .definePathBasedRoutingRule("rule2") @@ -399,133 +391,125 @@ public void print(ApplicationGateway resource) { public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { ensurePIPs(resources.manager().publicIpAddresses()); - final Network vnet = - resources - .manager() - .networks() - .define("net" + testId) - .withRegion(REGION) - .withNewResourceGroup(groupName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); - - Thread.UncaughtExceptionHandler threadException = - new Thread.UncaughtExceptionHandler() { - public void uncaughtException(Thread th, Throwable ex) { - LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", ex); - } - }; + final Network vnet = resources.manager() + .networks() + .define("net" + testId) + .withRegion(REGION) + .withNewResourceGroup(groupName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); + + Thread.UncaughtExceptionHandler threadException = new Thread.UncaughtExceptionHandler() { + public void uncaughtException(Thread th, Throwable ex) { + LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", ex); + } + }; // Prepare for execution in a separate thread to shorten the test - Thread creationThread = - new Thread( - new Runnable() { - @Override - public void run() { - // Create an application gateway - try { - resources - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(groupName) - - // Request routing rules - .defineRequestRoutingRule("rule80") - .fromPrivateFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .withCookieBasedAffinity() - .attach() - .defineRequestRoutingRule("rule443") - .fromPrivateFrontend() - .fromFrontendHttpsPort(443) - .withSslCertificateFromPfxFile( - new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) - .withSslCertificatePassword("Abc123") - .toBackendHttpConfiguration("config1") - .toBackend("backend1") - .attach() - .defineRequestRoutingRule("rule9000") - .fromListener("listener1") - .toBackendHttpConfiguration("config1") - .toBackend("backend1") - .attach() - .defineRequestRoutingRule("ruleRedirect") - .fromPrivateFrontend() - .fromFrontendHttpsPort(444) - .withSslCertificate("cert1") - .withRedirectConfiguration("redirect1") - .attach() - - // Additional/explicit backends - .defineBackend("backend1") - .withIPAddress("11.1.1.3") - .withIPAddress("11.1.1.4") - .attach() - .defineBackend("backend2") - .attach() - - // Additional/explicit frontend listeners - .defineListener("listener1") - .withPrivateFrontend() - .withFrontendPort(9000) - .withHttp() - .attach() - - // Additional/explicit certificates - .defineSslCertificate("cert1") - .withPfxFromFile( - new File(getClass().getClassLoader().getResource("myTest2.pfx").getFile())) - .withPfxPassword("Abc123") - .attach() - - // Authentication certificates - .defineAuthenticationCertificate("auth2") - .fromFile( - new File(getClass().getClassLoader().getResource("myTest2.cer").getFile())) - .attach() - - // Additional/explicit backend HTTP setting configs - .defineBackendHttpConfiguration("config1") - .withPort(8081) - .withRequestTimeout(45) - .withHttps() - .withAuthenticationCertificateFromFile( - new File(getClass().getClassLoader().getResource("myTest.cer").getFile())) - .attach() - .defineBackendHttpConfiguration("config2") - .withPort(8082) - .withHttps() - .withAuthenticationCertificate("auth2") - // Add the same cert, so only one should be added - .withAuthenticationCertificateFromFile( - new File(getClass().getClassLoader().getResource("myTest2.cer").getFile())) - .attach() - - // Redirect configurations - .defineRedirectConfiguration("redirect1") - .withType(ApplicationGatewayRedirectType.PERMANENT) - .withTargetListener("listener1") - .withPathIncluded() - .attach() - .defineRedirectConfiguration("redirect2") - .withType(ApplicationGatewayRedirectType.TEMPORARY) - .withTargetUrl("http://www.microsoft.com") - .withQueryStringIncluded() - .attach() - .withExistingSubnet(vnet, "subnet1") - .withSize(ApplicationGatewaySkuName.STANDARD_MEDIUM) - .withInstanceCount(2) - .create(); - } catch (IOException e) { - LOGGER.log(LogLevel.VERBOSE, () -> "Error creating application gateway", e); - } - } - }); + Thread creationThread = new Thread(new Runnable() { + @Override + public void run() { + // Create an application gateway + try { + resources.define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(groupName) + + // Request routing rules + .defineRequestRoutingRule("rule80") + .fromPrivateFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .withCookieBasedAffinity() + .attach() + .defineRequestRoutingRule("rule443") + .fromPrivateFrontend() + .fromFrontendHttpsPort(443) + .withSslCertificateFromPfxFile( + new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) + .withSslCertificatePassword("Abc123") + .toBackendHttpConfiguration("config1") + .toBackend("backend1") + .attach() + .defineRequestRoutingRule("rule9000") + .fromListener("listener1") + .toBackendHttpConfiguration("config1") + .toBackend("backend1") + .attach() + .defineRequestRoutingRule("ruleRedirect") + .fromPrivateFrontend() + .fromFrontendHttpsPort(444) + .withSslCertificate("cert1") + .withRedirectConfiguration("redirect1") + .attach() + + // Additional/explicit backends + .defineBackend("backend1") + .withIPAddress("11.1.1.3") + .withIPAddress("11.1.1.4") + .attach() + .defineBackend("backend2") + .attach() + + // Additional/explicit frontend listeners + .defineListener("listener1") + .withPrivateFrontend() + .withFrontendPort(9000) + .withHttp() + .attach() + + // Additional/explicit certificates + .defineSslCertificate("cert1") + .withPfxFromFile(new File(getClass().getClassLoader().getResource("myTest2.pfx").getFile())) + .withPfxPassword("Abc123") + .attach() + + // Authentication certificates + .defineAuthenticationCertificate("auth2") + .fromFile(new File(getClass().getClassLoader().getResource("myTest2.cer").getFile())) + .attach() + + // Additional/explicit backend HTTP setting configs + .defineBackendHttpConfiguration("config1") + .withPort(8081) + .withRequestTimeout(45) + .withHttps() + .withAuthenticationCertificateFromFile( + new File(getClass().getClassLoader().getResource("myTest.cer").getFile())) + .attach() + .defineBackendHttpConfiguration("config2") + .withPort(8082) + .withHttps() + .withAuthenticationCertificate("auth2") + // Add the same cert, so only one should be added + .withAuthenticationCertificateFromFile( + new File(getClass().getClassLoader().getResource("myTest2.cer").getFile())) + .attach() + + // Redirect configurations + .defineRedirectConfiguration("redirect1") + .withType(ApplicationGatewayRedirectType.PERMANENT) + .withTargetListener("listener1") + .withPathIncluded() + .attach() + .defineRedirectConfiguration("redirect2") + .withType(ApplicationGatewayRedirectType.TEMPORARY) + .withTargetUrl("http://www.microsoft.com") + .withQueryStringIncluded() + .attach() + .withExistingSubnet(vnet, "subnet1") + .withSize(ApplicationGatewaySkuName.STANDARD_MEDIUM) + .withInstanceCount(2) + .create(); + } catch (IOException e) { + LOGGER.log(LogLevel.VERBOSE, () -> "Error creating application gateway", e); + } + } + }); // Start creating in a separate thread... creationThread.setUncaughtExceptionHandler(threadException); @@ -610,18 +594,18 @@ public void run() { // Verify authentication certificates Assertions.assertEquals(2, appGateway.authenticationCertificates().size()); - ApplicationGatewayAuthenticationCertificate authCert2 = - appGateway.authenticationCertificates().get("auth2"); + ApplicationGatewayAuthenticationCertificate authCert2 + = appGateway.authenticationCertificates().get("auth2"); Assertions.assertNotNull(authCert2); Assertions.assertNotNull(authCert2.data()); - ApplicationGatewayAuthenticationCertificate authCert = - config.authenticationCertificates().values().iterator().next(); + ApplicationGatewayAuthenticationCertificate authCert + = config.authenticationCertificates().values().iterator().next(); Assertions.assertNotNull(authCert); Assertions.assertEquals(1, config2.authenticationCertificates().size()); - Assertions - .assertEquals(authCert2.name(), config2.authenticationCertificates().values().iterator().next().name()); + Assertions.assertEquals(authCert2.name(), + config2.authenticationCertificates().values().iterator().next().name()); // Verify backends Assertions.assertEquals(3, appGateway.backends().size()); @@ -686,14 +670,12 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro final int configCount = resource.backendHttpConfigurations().size(); final int sslCertCount = resource.sslCertificates().size(); final int authCertCount = resource.authenticationCertificates().size(); - final ApplicationGatewayAuthenticationCertificate authCert1 = - resource - .backendHttpConfigurations() - .get("config1") - .authenticationCertificates() - .values() - .iterator() - .next(); + final ApplicationGatewayAuthenticationCertificate authCert1 = resource.backendHttpConfigurations() + .get("config1") + .authenticationCertificates() + .values() + .iterator() + .next(); Assertions.assertNotNull(authCert1); PublicIpAddress pip = resource.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); @@ -702,8 +684,7 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro ApplicationGatewayListener listenerRedirect = resource.requestRoutingRules().get("ruleRedirect").listener(); Assertions.assertNotNull(listenerRedirect); - resource - .update() + resource.update() .withSize(ApplicationGatewaySkuName.STANDARD_SMALL) .withInstanceCount(1) .withoutFrontendPort(9000) @@ -773,15 +754,8 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro // Verify frontends Assertions.assertEquals(frontendCount + 1, resource.frontends().size()); Assertions.assertEquals(1, resource.publicFrontends().size()); - Assertions - .assertTrue( - resource - .publicFrontends() - .values() - .iterator() - .next() - .publicIpAddressId() - .equalsIgnoreCase(pip.id())); + Assertions.assertTrue( + resource.publicFrontends().values().iterator().next().publicIpAddressId().equalsIgnoreCase(pip.id())); Assertions.assertEquals(1, resource.privateFrontends().size()); ApplicationGatewayFrontend frontend = resource.privateFrontends().values().iterator().next(); Assertions.assertFalse(frontend.isPublic()); @@ -859,115 +833,111 @@ public void print(ApplicationGateway resource) { @Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { ensurePIPs(resources.manager().publicIpAddresses()); - Thread.UncaughtExceptionHandler threadException = - new Thread.UncaughtExceptionHandler() { - public void uncaughtException(Thread th, Throwable ex) { - LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", ex); - } - }; + Thread.UncaughtExceptionHandler threadException = new Thread.UncaughtExceptionHandler() { + public void uncaughtException(Thread th, Throwable ex) { + LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", ex); + } + }; - final PublicIpAddress pip = - resources.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); + final PublicIpAddress pip + = resources.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); // Prepare for execution in a separate thread to shorten the test - Thread creationThread = - new Thread( - new Runnable() { - @Override - public void run() { - // Create an application gateway - try { - resources - .define(appGatewayName) - .withRegion(REGION) - .withExistingResourceGroup(groupName) - - // Request routing rules - .defineRequestRoutingRule("rule80") - .fromPublicFrontend() - .fromFrontendHttpPort(80) - .toBackendHttpPort(8080) - .toBackendFqdn("www.microsoft.com") - .toBackendFqdn("www.example.com") - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .withCookieBasedAffinity() - .attach() - .defineRequestRoutingRule("rule443") - .fromPublicFrontend() - .fromFrontendHttpsPort(443) - .withSslCertificateFromPfxFile( - new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) - .withSslCertificatePassword("Abc123") - .toBackendHttpConfiguration("config1") - .toBackend("backend1") - .attach() - .defineRequestRoutingRule("rule9000") - .fromListener("listener1") - .toBackendHttpConfiguration("config1") - .toBackend("backend1") - .attach() - - // Additional/explicit frontend listeners - .defineListener("listener1") - .withPublicFrontend() - .withFrontendPort(9000) - .withHttps() - .withSslCertificateFromPfxFile( - new File(getClass().getClassLoader().getResource("myTest2.pfx").getFile())) - .withSslCertificatePassword("Abc123") - .withServerNameIndication() - .withHostname("www.fabricam.com") - .attach() - - // Additional/explicit backends - .defineBackend("backend1") - .withIPAddress("11.1.1.1") - .withIPAddress("11.1.1.2") - .attach() - .withExistingPublicIpAddress(pip) - .withSize(ApplicationGatewaySkuName.STANDARD_MEDIUM) - .withInstanceCount(2) - - // Probes - .defineProbe("probe1") - .withHost("microsoft.com") - .withPath("/") - .withHttp() - .withTimeoutInSeconds(10) - .withTimeBetweenProbesInSeconds(9) - .withRetriesBeforeUnhealthy(5) - .withHealthyHttpResponseStatusCodeRange(200, 249) - .attach() - .defineProbe("probe2") - .withHost("microsoft.com") - .withPath("/") - .withHttps() - .withTimeoutInSeconds(11) - .withHealthyHttpResponseStatusCodeRange(600, 610) - .withHealthyHttpResponseStatusCodeRange(650, 660) - .withHealthyHttpResponseBodyContents("I am too healthy for this test.") - .attach() - - // Additional/explicit backend HTTP setting configs - .defineBackendHttpConfiguration("config1") - .withPort(8081) - .withRequestTimeout(45) - .withProbe("probe1") - .withHostHeader("foo") - .withConnectionDrainingTimeoutInSeconds(100) - .withPath("path") - .withAffinityCookieName("cookie") - .attach() - .withDisabledSslProtocols( - ApplicationGatewaySslProtocol.TLSV1_0, ApplicationGatewaySslProtocol.TLSV1_1) - .withHttp2() - .create(); - } catch (IOException e) { - LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", e); - } - } - }); + Thread creationThread = new Thread(new Runnable() { + @Override + public void run() { + // Create an application gateway + try { + resources.define(appGatewayName) + .withRegion(REGION) + .withExistingResourceGroup(groupName) + + // Request routing rules + .defineRequestRoutingRule("rule80") + .fromPublicFrontend() + .fromFrontendHttpPort(80) + .toBackendHttpPort(8080) + .toBackendFqdn("www.microsoft.com") + .toBackendFqdn("www.example.com") + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .withCookieBasedAffinity() + .attach() + .defineRequestRoutingRule("rule443") + .fromPublicFrontend() + .fromFrontendHttpsPort(443) + .withSslCertificateFromPfxFile( + new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) + .withSslCertificatePassword("Abc123") + .toBackendHttpConfiguration("config1") + .toBackend("backend1") + .attach() + .defineRequestRoutingRule("rule9000") + .fromListener("listener1") + .toBackendHttpConfiguration("config1") + .toBackend("backend1") + .attach() + + // Additional/explicit frontend listeners + .defineListener("listener1") + .withPublicFrontend() + .withFrontendPort(9000) + .withHttps() + .withSslCertificateFromPfxFile( + new File(getClass().getClassLoader().getResource("myTest2.pfx").getFile())) + .withSslCertificatePassword("Abc123") + .withServerNameIndication() + .withHostname("www.fabricam.com") + .attach() + + // Additional/explicit backends + .defineBackend("backend1") + .withIPAddress("11.1.1.1") + .withIPAddress("11.1.1.2") + .attach() + .withExistingPublicIpAddress(pip) + .withSize(ApplicationGatewaySkuName.STANDARD_MEDIUM) + .withInstanceCount(2) + + // Probes + .defineProbe("probe1") + .withHost("microsoft.com") + .withPath("/") + .withHttp() + .withTimeoutInSeconds(10) + .withTimeBetweenProbesInSeconds(9) + .withRetriesBeforeUnhealthy(5) + .withHealthyHttpResponseStatusCodeRange(200, 249) + .attach() + .defineProbe("probe2") + .withHost("microsoft.com") + .withPath("/") + .withHttps() + .withTimeoutInSeconds(11) + .withHealthyHttpResponseStatusCodeRange(600, 610) + .withHealthyHttpResponseStatusCodeRange(650, 660) + .withHealthyHttpResponseBodyContents("I am too healthy for this test.") + .attach() + + // Additional/explicit backend HTTP setting configs + .defineBackendHttpConfiguration("config1") + .withPort(8081) + .withRequestTimeout(45) + .withProbe("probe1") + .withHostHeader("foo") + .withConnectionDrainingTimeoutInSeconds(100) + .withPath("path") + .withAffinityCookieName("cookie") + .attach() + .withDisabledSslProtocols(ApplicationGatewaySslProtocol.TLSV1_0, + ApplicationGatewaySslProtocol.TLSV1_1) + .withHttp2() + .create(); + } catch (IOException e) { + LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", e); + } + } + }); // Start creating in a separate thread... creationThread.setUncaughtExceptionHandler(threadException); @@ -1114,8 +1084,7 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro ApplicationGatewayBackendHttpConfiguration backendConfig80 = rule80.backendHttpConfiguration(); Assertions.assertNotNull(backendConfig80); - resource - .update() + resource.update() .withSize(ApplicationGatewaySkuName.STANDARD_SMALL) .withInstanceCount(1) .updateListener("listener1") @@ -1139,8 +1108,8 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro .withoutHealthyHttpResponseStatusCodeRanges() .withHealthyHttpResponseBodyContents(null) .parent() - .withoutDisabledSslProtocols( - ApplicationGatewaySslProtocol.TLSV1_0, ApplicationGatewaySslProtocol.TLSV1_1) + .withoutDisabledSslProtocols(ApplicationGatewaySslProtocol.TLSV1_0, + ApplicationGatewaySslProtocol.TLSV1_1) .withoutHttp2() .withTag("tag1", "value1") .withTag("tag2", "value2") @@ -1173,8 +1142,8 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro Assertions.assertNull(probe.healthyHttpResponseBodyContents()); // Verify backend configs - ApplicationGatewayBackendHttpConfiguration backendConfig = - resource.backendHttpConfigurations().get("config1"); + ApplicationGatewayBackendHttpConfiguration backendConfig + = resource.backendHttpConfigurations().get("config1"); Assertions.assertNotNull(backendConfig); Assertions.assertNull(backendConfig.probe()); Assertions.assertFalse(backendConfig.isHostHeaderFromBackend()); @@ -1210,35 +1179,32 @@ public void print(ApplicationGateway resource) { @Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { // Prepare a separate thread for resource creation - Thread creationThread = - new Thread( - new Runnable() { - @Override - public void run() { - // Create an application gateway - try { - resources - .define(appGatewayName) - .withRegion(REGION) - .withNewResourceGroup(groupName) - - // Request routing rules - .defineRequestRoutingRule("rule1") - .fromPublicFrontend() - .fromFrontendHttpsPort(443) - .withSslCertificateFromPfxFile( - new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) - .withSslCertificatePassword("Abc123") - .toBackendHttpPort(8080) - .toBackendIPAddress("11.1.1.1") - .toBackendIPAddress("11.1.1.2") - .attach() - .create(); - } catch (IOException e) { - LOGGER.log(LogLevel.VERBOSE, () -> "Error occurred", e); - } - } - }); + Thread creationThread = new Thread(new Runnable() { + @Override + public void run() { + // Create an application gateway + try { + resources.define(appGatewayName) + .withRegion(REGION) + .withNewResourceGroup(groupName) + + // Request routing rules + .defineRequestRoutingRule("rule1") + .fromPublicFrontend() + .fromFrontendHttpsPort(443) + .withSslCertificateFromPfxFile( + new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) + .withSslCertificatePassword("Abc123") + .toBackendHttpPort(8080) + .toBackendIPAddress("11.1.1.1") + .toBackendIPAddress("11.1.1.2") + .attach() + .create(); + } catch (IOException e) { + LOGGER.log(LogLevel.VERBOSE, () -> "Error occurred", e); + } + } + }); // Start the creation... creationThread.start(); @@ -1296,8 +1262,7 @@ public void run() { @Override public ApplicationGateway updateResource(final ApplicationGateway resource) throws Exception { - resource - .update() + resource.update() .withInstanceCount(2) .withSize(ApplicationGatewaySkuName.STANDARD_MEDIUM) .withoutBackendIPAddress("11.1.1.1") @@ -1386,8 +1351,7 @@ private Map ensurePIPs(PublicIpAddresses pips) { // Print app gateway info static void printAppGateway(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); - info - .append("Application gateway: ") + info.append("Application gateway: ") .append(resource.id()) .append("Name: ") .append(resource.name()) @@ -1416,8 +1380,7 @@ static void printAppGateway(ApplicationGateway resource) { Map ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(ipConfig.name()) .append("\n\t\t\tNetwork id: ") .append(ipConfig.networkId()) @@ -1438,8 +1401,7 @@ static void printAppGateway(ApplicationGateway resource) { if (frontend.isPrivate()) { // Show private frontend info - info - .append("\n\t\t\tPrivate IP address: ") + info.append("\n\t\t\tPrivate IP address: ") .append(frontend.privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ") .append(frontend.privateIpAllocationMethod()) @@ -1454,8 +1416,7 @@ static void printAppGateway(ApplicationGateway resource) { Map backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(backend.name()) .append("\n\t\t\tAssociated NIC IP configuration IDs: ") .append(backend.backendNicIPConfigurationNames().keySet()); @@ -1464,8 +1425,7 @@ static void printAppGateway(ApplicationGateway resource) { Collection addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { - info - .append("\n\t\t\t\tFQDN: ") + info.append("\n\t\t\t\tFQDN: ") .append(address.fqdn()) .append("\n\t\t\t\tIP: ") .append(address.ipAddress()); @@ -1476,8 +1436,7 @@ static void printAppGateway(ApplicationGateway resource) { Map httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(httpConfig.name()) .append("\n\t\t\tCookie based affinity: ") .append(httpConfig.cookieBasedAffinity()) @@ -1515,8 +1474,7 @@ static void printAppGateway(ApplicationGateway resource) { Map listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(listener.name()) .append("\n\t\t\tHost name: ") .append(listener.hostname()) @@ -1539,8 +1497,7 @@ static void printAppGateway(ApplicationGateway resource) { Map probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(probe.name()) .append("\n\t\tProtocol:") .append(probe.protocol().toString()) @@ -1569,8 +1526,7 @@ static void printAppGateway(ApplicationGateway resource) { Map redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(redirect.name()) .append("\n\t\tTarget URL: ") .append(redirect.type()) @@ -1590,8 +1546,7 @@ static void printAppGateway(ApplicationGateway resource) { Map rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(rule.name()) .append("\n\t\tType: ") .append(rule.ruleType()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestAvailabilitySet.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestAvailabilitySet.java index 62982c15344ee..39ecb7b344ea6 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestAvailabilitySet.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestAvailabilitySet.java @@ -13,16 +13,15 @@ public class TestAvailabilitySet extends TestTemplate { @Override public AvailabilitySet createResource(AvailabilitySets availabilitySets) throws Exception { - final String newName = availabilitySets.manager().resourceManager().internalContext().randomResourceName("as", 10); - AvailabilitySet aset = - availabilitySets - .define(newName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withFaultDomainCount(2) - .withUpdateDomainCount(4) - .withTag("tag1", "value1") - .create(); + final String newName + = availabilitySets.manager().resourceManager().internalContext().randomResourceName("as", 10); + AvailabilitySet aset = availabilitySets.define(newName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withFaultDomainCount(2) + .withUpdateDomainCount(4) + .withTag("tag1", "value1") + .create(); PagedIterable vmSizes = aset.listVirtualMachineSizes(); Assertions.assertTrue(TestUtilities.getSize(vmSizes) > 0); for (VirtualMachineSize vmSize : vmSizes) { @@ -43,24 +42,20 @@ public AvailabilitySet updateResource(AvailabilitySet resource) throws Exception @Override public void print(AvailabilitySet resource) { - System - .out - .println( - new StringBuilder() - .append("Availability Set: ") - .append(resource.id()) - .append("Name: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.region()) - .append("\n\tTags: ") - .append(resource.tags()) - .append("\n\tFault domain count: ") - .append(resource.faultDomainCount()) - .append("\n\tUpdate domain count: ") - .append(resource.updateDomainCount()) - .toString()); + System.out.println(new StringBuilder().append("Availability Set: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tFault domain count: ") + .append(resource.faultDomainCount()) + .append("\n\tUpdate domain count: ") + .append(resource.updateDomainCount()) + .toString()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java index e896eea3d65cd..ec04d961cc211 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java @@ -32,9 +32,13 @@ public class TestCdn extends TestTemplate { public CdnProfile createResource(CdnProfiles profiles) throws Exception { final Region region = Region.US_EAST; final String groupName = profiles.manager().resourceManager().internalContext().randomResourceName("rg", 10); - final String cdnProfileName = profiles.manager().resourceManager().internalContext().randomResourceName("cdnProfile", 20); - final String cdnEndpointName = profiles.manager().resourceManager().internalContext().randomResourceName("cdnEndpoint", 20); - final String cdnOriginHostName = profiles.manager().resourceManager().internalContext().randomResourceName("my", 10) + ".azurewebsites.net"; + final String cdnProfileName + = profiles.manager().resourceManager().internalContext().randomResourceName("cdnProfile", 20); + final String cdnEndpointName + = profiles.manager().resourceManager().internalContext().randomResourceName("cdnEndpoint", 20); + final String cdnOriginHostName + = profiles.manager().resourceManager().internalContext().randomResourceName("my", 10) + + ".azurewebsites.net"; CdnProfile cdnProfile = profiles.define(cdnProfileName) .withRegion(region) @@ -69,7 +73,8 @@ public CdnProfile createResource(CdnProfiles profiles) throws Exception { Assertions.assertNotNull(endpoint.geoFilters()); Assertions.assertEquals(QueryStringCachingBehavior.BYPASS_CACHING, endpoint.queryStringCachingBehavior()); - Assertions.assertTrue(profiles.listResourceUsage().stream().anyMatch(usage -> usage.resourceType().equals("profile"))); + Assertions.assertTrue( + profiles.listResourceUsage().stream().anyMatch(usage -> usage.resourceType().equals("profile"))); for (EdgeNode node : profiles.listEdgeNodes()) { Assertions.assertNotNull(node); @@ -81,8 +86,7 @@ public CdnProfile createResource(CdnProfiles profiles) throws Exception { } for (CdnEndpoint ep : cdnProfile.endpoints().values()) { - Assertions.assertEquals( - Arrays.asList("customdomain", "geofilter", "deliveryrule"), + Assertions.assertEquals(Arrays.asList("customdomain", "geofilter", "deliveryrule"), ep.listResourceUsage().stream().map(ResourceUsage::resourceType).collect(Collectors.toList())); } return cdnProfile; @@ -120,33 +124,54 @@ public CdnProfile updateResource(CdnProfile profile) throws Exception { @Override public void print(CdnProfile profile) { StringBuilder info = new StringBuilder(); - info.append("CDN Profile: ").append(profile.id()) - .append("\n\tName: ").append(profile.name()) - .append("\n\tResource group: ").append(profile.resourceGroupName()) - .append("\n\tRegion: ").append(profile.regionName()) - .append("\n\tSku: ").append(profile.sku().name()) - .append("\n\tTags: ").append(profile.tags()); + info.append("CDN Profile: ") + .append(profile.id()) + .append("\n\tName: ") + .append(profile.name()) + .append("\n\tResource group: ") + .append(profile.resourceGroupName()) + .append("\n\tRegion: ") + .append(profile.regionName()) + .append("\n\tSku: ") + .append(profile.sku().name()) + .append("\n\tTags: ") + .append(profile.tags()); Map cdnEndpoints = profile.endpoints(); if (!cdnEndpoints.isEmpty()) { info.append("\n\tCDN endpoints:"); int idx = 1; for (CdnEndpoint endpoint : cdnEndpoints.values()) { - info.append("\n\t\tCDN endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tName: ").append(endpoint.name()) - .append("\n\t\t\tState: ").append(endpoint.resourceState()) - .append("\n\t\t\tHost name: ").append(endpoint.hostname()) - .append("\n\t\t\tOrigin host name: ").append(endpoint.originHostName()) - .append("\n\t\t\tOrigin host header: ").append(endpoint.originHostHeader()) - .append("\n\t\t\tOrigin path: ").append(endpoint.originPath()) - .append("\n\t\t\tOptimization type: ").append(endpoint.optimizationType()) - .append("\n\t\t\tQuery string caching behavior: ").append(endpoint.queryStringCachingBehavior()) - .append("\n\t\t\tHttp allowed: ").append(endpoint.isHttpAllowed()) - .append("\t\tHttp port: ").append(endpoint.httpPort()) - .append("\n\t\t\tHttps allowed: ").append(endpoint.isHttpsAllowed()) - .append("\t\tHttps port: ").append(endpoint.httpsPort()) - .append("\n\t\t\tCompression enabled: ").append(endpoint.isCompressionEnabled()); + info.append("\n\t\tCDN endpoint: #") + .append(idx++) + .append("\n\t\t\tId: ") + .append(endpoint.id()) + .append("\n\t\t\tName: ") + .append(endpoint.name()) + .append("\n\t\t\tState: ") + .append(endpoint.resourceState()) + .append("\n\t\t\tHost name: ") + .append(endpoint.hostname()) + .append("\n\t\t\tOrigin host name: ") + .append(endpoint.originHostName()) + .append("\n\t\t\tOrigin host header: ") + .append(endpoint.originHostHeader()) + .append("\n\t\t\tOrigin path: ") + .append(endpoint.originPath()) + .append("\n\t\t\tOptimization type: ") + .append(endpoint.optimizationType()) + .append("\n\t\t\tQuery string caching behavior: ") + .append(endpoint.queryStringCachingBehavior()) + .append("\n\t\t\tHttp allowed: ") + .append(endpoint.isHttpAllowed()) + .append("\t\tHttp port: ") + .append(endpoint.httpPort()) + .append("\n\t\t\tHttps allowed: ") + .append(endpoint.isHttpsAllowed()) + .append("\t\tHttps port: ") + .append(endpoint.httpsPort()) + .append("\n\t\t\tCompression enabled: ") + .append(endpoint.isCompressionEnabled()); info.append("\n\t\t\tContent types to compress: "); for (String contentTypeToCompress : endpoint.contentTypesToCompress()) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java index f5349b048003a..42817f32bfb9a 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java @@ -31,36 +31,36 @@ public class TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI @Override public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { - final String cgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); - final String rgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); + final String cgName + = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); + final String rgName + = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); List dnsServers = new ArrayList(); dnsServers.add("dnsServer1"); - ContainerGroup containerGroup = - containerGroups - .define(cgName) - .withRegion(Region.US_EAST2) - .withNewResourceGroup(rgName) - .withLinux() - .withPublicImageRegistryOnly() - .withEmptyDirectoryVolume("emptydir1") - .defineContainerInstance("tomcat") - .withImage("tomcat") - .withExternalTcpPort(8080) - .withCpuCoreCount(1) - .withEnvironmentVariable("ENV1", "value1") - .attach() - .defineContainerInstance("nginx") - .withImage("nginx") - .withExternalTcpPort(80) - .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") - .attach() - .withSystemAssignedManagedServiceIdentity() - .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) - .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) - .withDnsPrefix(cgName) - .withTag("tag1", "value1") - .create(); + ContainerGroup containerGroup = containerGroups.define(cgName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withEmptyDirectoryVolume("emptydir1") + .defineContainerInstance("tomcat") + .withImage("tomcat") + .withExternalTcpPort(8080) + .withCpuCoreCount(1) + .withEnvironmentVariable("ENV1", "value1") + .attach() + .defineContainerInstance("nginx") + .withImage("nginx") + .withExternalTcpPort(80) + .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") + .attach() + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withDnsPrefix(cgName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(cgName, containerGroup.name()); Assertions.assertEquals("Linux", containerGroup.osType().toString()); @@ -106,8 +106,8 @@ public ContainerGroup createResource(ContainerGroups containerGroups) throws Exc Assertions.assertEquals(cgName, containerGroup.dnsPrefix()); ContainerGroup containerGroup2 = containerGroups.getByResourceGroup(rgName, cgName); - List containerGroupList = - containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); + List containerGroupList + = containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertFalse(containerGroupList.isEmpty()); containerGroup.refresh(); @@ -133,20 +133,18 @@ public ContainerGroup updateResource(ContainerGroup containerGroup) throws Excep @Override public void print(ContainerGroup resource) { - StringBuilder info = - new StringBuilder() - .append("Container Group: ") - .append(resource.id()) - .append("Name: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.region()) - .append("\n\tTags: ") - .append(resource.tags()) - .append("\n\tOS type: ") - .append(resource.osType()); + StringBuilder info = new StringBuilder().append("Container Group: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tOS type: ") + .append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); @@ -172,14 +170,12 @@ public void print(ContainerGroup resource) { if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry entry : resource.volumes().entrySet()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(entry.getKey()) .append(" -> ") - .append( - entry.getValue().azureFile() != null - ? entry.getValue().azureFile().shareName() - : "empty direcory volume"); + .append(entry.getValue().azureFile() != null + ? entry.getValue().azureFile().shareName() + : "empty direcory volume"); } } if (resource.containers() != null) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java index 5d1ab1d0e528e..07ef74439a550 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java @@ -18,15 +18,13 @@ public Registry createResource(Registries registries) throws Exception { final String testId = registries.manager().resourceManager().internalContext().randomResourceName("", 8); final String newName = "acr" + testId; final String rgName = "rgacr" + testId; - Registry registry = - registries - .define(newName + "1") - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withStandardSku() - .withRegistryNameAsAdminUser() - .withTag("tag1", "value1") - .create(); + Registry registry = registries.define(newName + "1") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withStandardSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); Assertions.assertTrue(registry.adminUserEnabled()); @@ -38,30 +36,28 @@ public Registry createResource(Registries registries) throws Exception { Assertions.assertEquals(2, registryCredentials.accessKeys().size()); Assertions.assertEquals(0, registry.webhooks().list().stream().count()); - Registry registry2 = - registries - .define(newName + "2") - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgName) - .withBasicSku() - .withRegistryNameAsAdminUser() - .defineWebhook("webhookbing1") - .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) - .withServiceUri("https://www.bing.com") - .withRepositoriesScope("") - .withTag("tag", "value") - .withCustomHeader("name", "value") - .attach() - .defineWebhook("webhookbing2") - .withTriggerWhen(WebhookAction.PUSH) - .withServiceUri("https://www.bing.com") - .enabled(false) - .withRepositoriesScope("") - .withTag("tag", "value") - .withCustomHeader("name", "value") - .attach() - .withTag("tag1", "value1") - .create(); + Registry registry2 = registries.define(newName + "2") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .defineWebhook("webhookbing1") + .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) + .withServiceUri("https://www.bing.com") + .withRepositoriesScope("") + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() + .defineWebhook("webhookbing2") + .withTriggerWhen(WebhookAction.PUSH) + .withServiceUri("https://www.bing.com") + .enabled(false) + .withRepositoriesScope("") + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() + .withTag("tag1", "value1") + .create(); Assertions.assertTrue(registry2.adminUserEnabled()); @@ -97,8 +93,7 @@ public Registry createResource(Registries registries) throws Exception { @Override public Registry updateResource(Registry resource) throws Exception { - resource - .update() + resource.update() .withoutWebhook("webhookbing1") .defineWebhook("webhookms") .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) @@ -133,8 +128,7 @@ public Registry updateResource(Registry resource) throws Exception { webhook.enable(); Assertions.assertTrue(webhook.isEnabled()); - webhook - .update() + webhook.update() .withCustomHeader("header1", "value1") .enabled(false) .withServiceUri("https://www.msn.com") @@ -161,20 +155,16 @@ public Registry updateResource(Registry resource) throws Exception { @Override public void print(Registry resource) { - System - .out - .println( - new StringBuilder() - .append("Regsitry: ") - .append(resource.id()) - .append("Name: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.region()) - .append("\n\tTags: ") - .append(resource.tags()) - .toString()); + System.out.println(new StringBuilder().append("Regsitry: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .toString()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCosmosDB.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCosmosDB.java index d6934841277bc..22ee0be928a97 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCosmosDB.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCosmosDB.java @@ -13,18 +13,17 @@ public class TestCosmosDB extends TestTemplate txtRecordSets = dnsZone.txtRecordSets().list(); @@ -267,8 +275,8 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { Assertions.assertEquals(cnameRecordSets.stream().count(), 2); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { Assertions.assertTrue(cnameRecordSet.canonicalName().startsWith("doc.contoso.com")); - Assertions.assertTrue(cnameRecordSet.name().startsWith("documents") - || cnameRecordSet.name().startsWith("help")); + Assertions + .assertTrue(cnameRecordSet.name().startsWith("documents") || cnameRecordSet.name().startsWith("help")); } // Check NS records @@ -315,14 +323,14 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { Assertions.assertEquals(2, mxRecordSets.stream().count()); dnsZone.update() - .updateMXRecordSet("email") - .withoutMailExchange("mail.contoso-mail-exchange2.com", 2) - .withoutMetadata("mxa") - .withMetadata("mxc", "mxcc") - .withMetadata("mxd", "mxdd") - .parent() - .withTag("d", "dd") - .apply(); + .updateMXRecordSet("email") + .withoutMailExchange("mail.contoso-mail-exchange2.com", 2) + .withoutMetadata("mxa") + .withMetadata("mxc", "mxcc") + .withMetadata("mxd", "mxdd") + .parent() + .withTag("d", "dd") + .apply(); Assertions.assertEquals(3, dnsZone.tags().size()); // Check "mail" MX record @@ -337,32 +345,47 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { @Override public void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); - info.append("Dns Zone: ").append(dnsZone.id()) - .append("\n\tName (Top level domain): ").append(dnsZone.name()) - .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) - .append("\n\tRegion: ").append(dnsZone.regionName()) - .append("\n\tTags: ").append(dnsZone.tags()) - .append("\n\tName servers:"); - for (String nameServer: dnsZone.nameServers()) { + info.append("Dns Zone: ") + .append(dnsZone.id()) + .append("\n\tName (Top level domain): ") + .append(dnsZone.name()) + .append("\n\tResource group: ") + .append(dnsZone.resourceGroupName()) + .append("\n\tRegion: ") + .append(dnsZone.regionName()) + .append("\n\tTags: ") + .append(dnsZone.tags()) + .append("\n\tName servers:"); + for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") - .append("\n\t\tHost:").append(soaRecord.host()) - .append("\n\t\tEmail:").append(soaRecord.email()) - .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) - .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) - .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) - .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) - .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); + .append("\n\t\tHost:") + .append(soaRecord.host()) + .append("\n\t\tEmail:") + .append(soaRecord.email()) + .append("\n\t\tExpire time (seconds):") + .append(soaRecord.expireTime()) + .append("\n\t\tRefresh time (seconds):") + .append(soaRecord.refreshTime()) + .append("\n\t\tRetry time (seconds):") + .append(soaRecord.retryTime()) + .append("\n\t\tNegative response cache ttl (seconds):") + .append(soaRecord.minimumTtl()) + .append("\n\t\tTTL (seconds):") + .append(soaRecordSet.timeToLive()); PagedIterable aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { - info.append("\n\t\tId: ").append(aRecordSet.id()) - .append("\n\t\tName: ").append(aRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(aRecordSet.id()) + .append("\n\t\tName: ") + .append(aRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); @@ -372,10 +395,13 @@ public void print(DnsZone dnsZone) { PagedIterable aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { - info.append("\n\t\tId: ").append(aaaaRecordSet.id()) - .append("\n\t\tName: ").append(aaaaRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) - .append("\n\t\tIP v6 addresses: "); + info.append("\n\t\tId: ") + .append(aaaaRecordSet.id()) + .append("\n\t\tName: ") + .append(aaaaRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aaaaRecordSet.timeToLive()) + .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } @@ -384,34 +410,44 @@ public void print(DnsZone dnsZone) { PagedIterable cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { - info.append("\n\t\tId: ").append(cnameRecordSet.id()) - .append("\n\t\tName: ").append(cnameRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) - .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); + info.append("\n\t\tId: ") + .append(cnameRecordSet.id()) + .append("\n\t\tName: ") + .append(cnameRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(cnameRecordSet.timeToLive()) + .append("\n\t\tCanonical name: ") + .append(cnameRecordSet.canonicalName()); } PagedIterable mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { - info.append("\n\t\tId: ").append(mxRecordSet.id()) - .append("\n\t\tName: ").append(mxRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(mxRecordSet.id()) + .append("\n\t\tName: ") + .append(mxRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(mxRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") - .append(mxRecord.exchange()) - .append(" ") - .append(mxRecord.preference()); + .append(mxRecord.exchange()) + .append(" ") + .append(mxRecord.preference()); } } PagedIterable nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { - info.append("\n\t\tId: ").append(nsRecordSet.id()) - .append("\n\t\tName: ").append(nsRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) - .append("\n\t\tName servers: "); + info.append("\n\t\tId: ") + .append(nsRecordSet.id()) + .append("\n\t\tName: ") + .append(nsRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(nsRecordSet.timeToLive()) + .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } @@ -420,10 +456,13 @@ public void print(DnsZone dnsZone) { PagedIterable ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { - info.append("\n\t\tId: ").append(ptrRecordSet.id()) - .append("\n\t\tName: ").append(ptrRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) - .append("\n\t\tTarget domain names: "); + info.append("\n\t\tId: ") + .append(ptrRecordSet.id()) + .append("\n\t\tName: ") + .append(ptrRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(ptrRecordSet.timeToLive()) + .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } @@ -432,29 +471,35 @@ public void print(DnsZone dnsZone) { PagedIterable srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { - info.append("\n\t\tId: ").append(srvRecordSet.id()) - .append("\n\t\tName: ").append(srvRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(srvRecordSet.id()) + .append("\n\t\tName: ") + .append(srvRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(srvRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") - .append(srvRecord.target()) - .append(", ") - .append(srvRecord.port()) - .append(", ") - .append(srvRecord.priority()) - .append(", ") - .append(srvRecord.weight()); + .append(srvRecord.target()) + .append(", ") + .append(srvRecord.port()) + .append(", ") + .append(srvRecord.priority()) + .append(", ") + .append(srvRecord.weight()); } } PagedIterable txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { - info.append("\n\t\tId: ").append(txtRecordSet.id()) - .append("\n\t\tName: ").append(txtRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) - .append("\n\t\tRecords: "); + info.append("\n\t\tId: ") + .append(txtRecordSet.id()) + .append("\n\t\tName: ") + .append(txtRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(txtRecordSet.timeToLive()) + .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (!txtRecord.value().isEmpty()) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java index 6c0edc1c24992..decebef347f5f 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java @@ -33,24 +33,21 @@ public ExpressRouteCircuit createResource(ExpressRouteCircuits expressRouteCircu initializeResourceNames(expressRouteCircuits.manager().resourceManager().internalContext()); // create Express Route Circuit - ExpressRouteCircuit erc = - expressRouteCircuits - .define(circuitName) - .withRegion(REGION) - .withNewResourceGroup() - .withServiceProvider("Microsoft ER Test") - .withPeeringLocation("Area51") - .withBandwidthInMbps(50) - .withSku(ExpressRouteCircuitSkuType.STANDARD_METEREDDATA) - .withTag("tag1", "value1") - .create(); + ExpressRouteCircuit erc = expressRouteCircuits.define(circuitName) + .withRegion(REGION) + .withNewResourceGroup() + .withServiceProvider("Microsoft ER Test") + .withPeeringLocation("Area51") + .withBandwidthInMbps(50) + .withSku(ExpressRouteCircuitSkuType.STANDARD_METEREDDATA) + .withTag("tag1", "value1") + .create(); return erc; } @Override public ExpressRouteCircuit updateResource(ExpressRouteCircuit resource) throws Exception { - resource - .update() + resource.update() .withTag("tag2", "value2") .withoutTag("tag1") .withBandwidthInMbps(200) @@ -85,19 +82,16 @@ public ExpressRouteCircuit createResource(ExpressRouteCircuits expressRouteCircu initializeResourceNames(expressRouteCircuits.manager().resourceManager().internalContext()); // create Express Route Circuit - ExpressRouteCircuit erc = - expressRouteCircuits - .define(circuitName) - .withRegion(REGION) - .withNewResourceGroup() - .withServiceProvider("Microsoft ER Test") - .withPeeringLocation("Area51") - .withBandwidthInMbps(50) - .withSku(ExpressRouteCircuitSkuType.PREMIUM_METEREDDATA) - .withTag("tag1", "value1") - .create(); - erc - .peerings() + ExpressRouteCircuit erc = expressRouteCircuits.define(circuitName) + .withRegion(REGION) + .withNewResourceGroup() + .withServiceProvider("Microsoft ER Test") + .withPeeringLocation("Area51") + .withBandwidthInMbps(50) + .withSku(ExpressRouteCircuitSkuType.PREMIUM_METEREDDATA) + .withTag("tag1", "value1") + .create(); + erc.peerings() .defineMicrosoftPeering() .withAdvertisedPublicPrefixes("123.1.0.0/24") .withPrimaryPeerAddressPrefix("123.0.0.0/30") @@ -113,15 +107,13 @@ public ExpressRouteCircuit createResource(ExpressRouteCircuits expressRouteCircu public ExpressRouteCircuit updateResource(ExpressRouteCircuit resource) throws Exception { Assertions .assertTrue(resource.peeringsMap().containsKey(ExpressRoutePeeringType.MICROSOFT_PEERING.toString())); - com.azure.resourcemanager.network.models.ExpressRouteCircuitPeering peering = - resource - .peeringsMap() - .get(ExpressRoutePeeringType.MICROSOFT_PEERING.toString()) - .update() - .withVlanId(300) - .withPeerAsn(101) - .withSecondaryPeerAddressPrefix("123.0.0.8/30") - .apply(); + com.azure.resourcemanager.network.models.ExpressRouteCircuitPeering peering = resource.peeringsMap() + .get(ExpressRoutePeeringType.MICROSOFT_PEERING.toString()) + .update() + .withVlanId(300) + .withPeerAsn(101) + .withSecondaryPeerAddressPrefix("123.0.0.8/30") + .apply(); Assertions.assertEquals(300, peering.vlanId()); Assertions.assertEquals(101, peering.peerAsn()); Assertions.assertEquals("123.0.0.8/30", peering.secondaryPeerAddressPrefix()); @@ -135,8 +127,9 @@ public void print(ExpressRouteCircuit resource) { } private static void printExpressRouteCircuit(ExpressRouteCircuit resource) { - LOGGER.log(LogLevel.VERBOSE, () -> "Express Route Circuit: " + resource.id() + "\n\tName: " + resource.name() - + "\n\tResource group: " + resource.resourceGroupName() + "\n\tRegion: " + resource.regionName() - + "\n\tTags: " + resource.tags()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Express Route Circuit: " + resource.id() + "\n\tName: " + resource.name() + "\n\tResource group: " + + resource.resourceGroupName() + "\n\tRegion: " + resource.regionName() + "\n\tTags: " + + resource.tags()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestKubernetesCluster.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestKubernetesCluster.java index 0e971a8f1d6c0..ea41dbc1bc668 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestKubernetesCluster.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestKubernetesCluster.java @@ -25,7 +25,8 @@ public class TestKubernetesCluster extends TestTemplate(resource.agentPools().keySet()).get(0); // Modify existing container service - resource = - resource - .update() - .updateAgentPool(agentPoolName) - .withAgentPoolVirtualMachineCount(5) - .parent() - .withTag("tag2", "value2") - .withTag("tag3", "value3") - .withoutTag("tag1") - .apply(); + resource = resource.update() + .updateAgentPool(agentPoolName) + .withAgentPoolVirtualMachineCount(5) + .parent() + .withTag("tag2", "value2") + .withTag("tag3", "value3") + .withoutTag("tag1") + .apply(); Assertions.assertEquals(1, resource.agentPools().size()); - Assertions - .assertTrue(resource.agentPools().get(agentPoolName).count() == 5, "Agent pool count was not updated."); + Assertions.assertTrue(resource.agentPools().get(agentPoolName).count() == 5, + "Agent pool count was not updated."); Assertions.assertTrue(resource.tags().containsKey("tag2")); Assertions.assertTrue(!resource.tags().containsKey("tag1")); return resource; @@ -111,21 +107,17 @@ public KubernetesCluster updateResource(KubernetesCluster resource) throws Excep @Override public void print(KubernetesCluster resource) { - System - .out - .println( - new StringBuilder() - .append("Container Service: ") - .append(resource.id()) - .append("Name: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.region()) - .append("\n\tTags: ") - .append(resource.tags()) - .toString()); + System.out.println(new StringBuilder().append("Container Service: ") + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .toString()); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java index 5683b621229c4..4fa04c03ef7b8 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java @@ -59,7 +59,7 @@ private void initializeResourceNames(ResourceManagerUtils.InternalRuntimeContext testId = internalContext.randomResourceName("", 8); groupName = "rg" + testId; lbName = "lb" + testId; - pipNames = new String[] {"pipa" + testId, "pipb" + testId}; + pipNames = new String[] { "pipa" + testId, "pipb" + testId }; } /** Internet-facing LB test with NAT pool test. */ @@ -88,49 +88,47 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { PublicIpAddress pip0 = resources.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[0]); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - - // Load balancing rules - .defineLoadBalancingRule("rule1") - .withProtocol(TransportProtocol.TCP) // Required - .fromExistingPublicIPAddress(pip0) - .fromFrontendPort(81) - .toBackend("backend1") - .toBackendPort(82) // Optionals - .withProbe("tcpProbe1") - .withIdleTimeoutInMinutes(10) - .withLoadDistribution(LoadDistribution.SOURCE_IP) - .attach() - - // Inbound NAT pools - .defineInboundNatPool("natpool1") - .withProtocol(TransportProtocol.TCP) - .fromExistingPublicIPAddress(pip0) - .fromFrontendPortRange(2000, 2001) - .toBackendPort(8080) - .attach() - - // Probes (Optional) - .defineTcpProbe("tcpProbe1") - .withPort(25) // Required - .withIntervalInSeconds(15) // Optionals - .withNumberOfProbes(5) - .attach() - .defineHttpProbe("httpProbe1") - .withRequestPath("/") // Required - .withIntervalInSeconds(13) // Optionals - .withNumberOfProbes(4) - .attach() - - // Backends - .defineBackend("backend1") - .withExistingVirtualMachines(existingVMs) - .attach() - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + + // Load balancing rules + .defineLoadBalancingRule("rule1") + .withProtocol(TransportProtocol.TCP) // Required + .fromExistingPublicIPAddress(pip0) + .fromFrontendPort(81) + .toBackend("backend1") + .toBackendPort(82) // Optionals + .withProbe("tcpProbe1") + .withIdleTimeoutInMinutes(10) + .withLoadDistribution(LoadDistribution.SOURCE_IP) + .attach() + + // Inbound NAT pools + .defineInboundNatPool("natpool1") + .withProtocol(TransportProtocol.TCP) + .fromExistingPublicIPAddress(pip0) + .fromFrontendPortRange(2000, 2001) + .toBackendPort(8080) + .attach() + + // Probes (Optional) + .defineTcpProbe("tcpProbe1") + .withPort(25) // Required + .withIntervalInSeconds(15) // Optionals + .withNumberOfProbes(5) + .attach() + .defineHttpProbe("httpProbe1") + .withRequestPath("/") // Required + .withIntervalInSeconds(13) // Optionals + .withNumberOfProbes(4) + .attach() + + // Backends + .defineBackend("backend1") + .withExistingVirtualMachines(existingVMs) + .attach() + .create(); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -170,17 +168,15 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { @Override public LoadBalancer updateResource(LoadBalancer resource) throws Exception { - resource = - resource - .update() - .withoutBackend("backend1") - .withoutLoadBalancingRule("rule1") - .withoutInboundNatPool("natpool1") - .withoutProbe("httpProbe1") - .withoutProbe("tcpProbe1") - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + resource = resource.update() + .withoutBackend("backend1") + .withoutLoadBalancingRule("rule1") + .withoutInboundNatPool("natpool1") + .withoutProbe("httpProbe1") + .withoutProbe("tcpProbe1") + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); resource.refresh(); Assertions.assertTrue(resource.tags().containsKey("tag1")); @@ -238,81 +234,69 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { NetworkInterface nic2 = existingVMs[1].getPrimaryNetworkInterface(); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - - // Load balancing rules - .defineLoadBalancingRule("rule1") - .withProtocol(TransportProtocol.TCP) // Required - .fromExistingPublicIPAddress(pip) - .fromFrontendPort(81) - .toBackend("backend1") - .toBackendPort(82) // Optionals - .withProbe("tcpProbe1") - .withIdleTimeoutInMinutes(10) - .withLoadDistribution(LoadDistribution.SOURCE_IP) - .attach() - - // Inbound NAT rules - .defineInboundNatRule("natrule1") - .withProtocol(TransportProtocol.TCP) - .fromExistingPublicIPAddress(pip) // Implicitly uses the same frontend because the PIP is the same - .fromFrontendPort(88) - .attach() - - // Probes (Optional) - .defineTcpProbe("tcpProbe1") - .withPort(25) // Required - .withIntervalInSeconds(15) // Optionals - .withNumberOfProbes(5) - .attach() - .defineHttpProbe("httpProbe1") - .withRequestPath("/") // Required - .withIntervalInSeconds(13) // Optionals - .withNumberOfProbes(4) - .attach() - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + + // Load balancing rules + .defineLoadBalancingRule("rule1") + .withProtocol(TransportProtocol.TCP) // Required + .fromExistingPublicIPAddress(pip) + .fromFrontendPort(81) + .toBackend("backend1") + .toBackendPort(82) // Optionals + .withProbe("tcpProbe1") + .withIdleTimeoutInMinutes(10) + .withLoadDistribution(LoadDistribution.SOURCE_IP) + .attach() + + // Inbound NAT rules + .defineInboundNatRule("natrule1") + .withProtocol(TransportProtocol.TCP) + .fromExistingPublicIPAddress(pip) // Implicitly uses the same frontend because the PIP is the same + .fromFrontendPort(88) + .attach() + + // Probes (Optional) + .defineTcpProbe("tcpProbe1") + .withPort(25) // Required + .withIntervalInSeconds(15) // Optionals + .withNumberOfProbes(5) + .attach() + .defineHttpProbe("httpProbe1") + .withRequestPath("/") // Required + .withIntervalInSeconds(13) // Optionals + .withNumberOfProbes(4) + .attach() + .create(); String backendName = lb.backends().values().iterator().next().name(); String frontendName = lb.frontends().values().iterator().next().name(); // Connect NICs explicitly - nic1 - .update() + nic1.update() .withExistingLoadBalancerBackend(lb, backendName) .withExistingLoadBalancerInboundNatRule(lb, "natrule1") .apply(); TestNetworkInterface.printNic(nic1); - Assertions - .assertTrue( - nic1 - .primaryIPConfiguration() - .listAssociatedLoadBalancerBackends() - .get(0) - .name() - .equalsIgnoreCase(backendName)); - Assertions - .assertTrue( - nic1 - .primaryIPConfiguration() - .listAssociatedLoadBalancerInboundNatRules() - .get(0) - .name() - .equalsIgnoreCase("natrule1")); + Assertions.assertTrue(nic1.primaryIPConfiguration() + .listAssociatedLoadBalancerBackends() + .get(0) + .name() + .equalsIgnoreCase(backendName)); + Assertions.assertTrue(nic1.primaryIPConfiguration() + .listAssociatedLoadBalancerInboundNatRules() + .get(0) + .name() + .equalsIgnoreCase("natrule1")); nic2.update().withExistingLoadBalancerBackend(lb, backendName).apply(); TestNetworkInterface.printNic(nic2); - Assertions - .assertTrue( - nic2 - .primaryIPConfiguration() - .listAssociatedLoadBalancerBackends() - .get(0) - .name() - .equalsIgnoreCase(backendName)); + Assertions.assertTrue(nic2.primaryIPConfiguration() + .listAssociatedLoadBalancerBackends() + .get(0) + .name() + .equalsIgnoreCase(backendName)); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -379,17 +363,15 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { // Update the load balancer ensurePIPs(resource.manager().publicIpAddresses()); PublicIpAddress pip = resource.manager().publicIpAddresses().getByResourceGroup(groupName, pipNames[1]); - resource = - resource - .update() - .updatePublicFrontend(frontendName) - .withExistingPublicIpAddress(pip) - .parent() - .withoutLoadBalancingRule("rule1") - .withoutInboundNatRule("natrule1") - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + resource = resource.update() + .updatePublicFrontend(frontendName) + .withExistingPublicIpAddress(pip) + .parent() + .withoutLoadBalancingRule("rule1") + .withoutInboundNatRule("natrule1") + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); Assertions.assertEquals(0, resource.inboundNatRules().size()); @@ -428,33 +410,29 @@ public void print(LoadBalancer resource) { @Override public LoadBalancer createResource(LoadBalancers resources) throws Exception { VirtualMachine[] existingVMs = ensureVMs(resources.manager().networks(), computeManager, 2); - Creatable pipDef = - resources - .manager() - .publicIpAddresses() - .define(pipNames[0]) - .withRegion(region) - .withExistingResourceGroup(groupName) - .withLeafDomainLabel(pipNames[0]); + Creatable pipDef = resources.manager() + .publicIpAddresses() + .define(pipNames[0]) + .withRegion(region) + .withExistingResourceGroup(groupName) + .withLeafDomainLabel(pipNames[0]); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - // Inbound NAT rule - .defineInboundNatRule("natrule1") - .withProtocol(TransportProtocol.TCP) - .fromNewPublicIPAddress(pipDef) - .fromFrontendPort(88) - .toBackendPort(80) - .attach() - // Backend - .defineBackend("backend1") - .withExistingVirtualMachines(existingVMs) - .attach() - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + // Inbound NAT rule + .defineInboundNatRule("natrule1") + .withProtocol(TransportProtocol.TCP) + .fromNewPublicIPAddress(pipDef) + .fromFrontendPort(88) + .toBackendPort(80) + .attach() + // Backend + .defineBackend("backend1") + .withExistingVirtualMachines(existingVMs) + .attach() + .create(); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -505,29 +483,25 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { LoadBalancerInboundNatRule natRule = resource.inboundNatRules().values().iterator().next(); Assertions.assertNotNull(natRule); LoadBalancerPublicFrontend publicFrontend = (LoadBalancerPublicFrontend) natRule.frontend(); - PublicIpAddress pip = - resource - .manager() - .publicIpAddresses() - .define(pipNames[1]) - .withRegion(region) - .withExistingResourceGroup(groupName) - .withLeafDomainLabel(pipNames[1]) - .create(); - - resource = - resource - .update() - .updatePublicFrontend(publicFrontend.name()) - .withExistingPublicIpAddress(pip) - .parent() - .defineBackend("backend2") - .attach() - .withoutBackend(backend.name()) - .withoutInboundNatRule("natrule1") - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + PublicIpAddress pip = resource.manager() + .publicIpAddresses() + .define(pipNames[1]) + .withRegion(region) + .withExistingResourceGroup(groupName) + .withLeafDomainLabel(pipNames[1]) + .create(); + + resource = resource.update() + .updatePublicFrontend(publicFrontend.name()) + .withExistingPublicIpAddress(pip) + .parent() + .defineBackend("backend2") + .attach() + .withoutBackend(backend.name()) + .withoutInboundNatRule("natrule1") + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); // Verify frontends @@ -583,19 +557,17 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { String pipDnsLabel = resources.manager().resourceManager().internalContext().randomResourceName("pip", 20); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - // LB rule - .defineLoadBalancingRule("lbrule1") - .withProtocol(TransportProtocol.TCP) - .fromNewPublicIPAddress(pipDnsLabel) - .fromFrontendPort(80) - .toExistingVirtualMachines(existingVMs) - .attach() - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + // LB rule + .defineLoadBalancingRule("lbrule1") + .withProtocol(TransportProtocol.TCP) + .fromNewPublicIPAddress(pipDnsLabel) + .fromFrontendPort(80) + .toExistingVirtualMachines(existingVMs) + .attach() + .create(); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -603,9 +575,8 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { Assertions.assertEquals(0, lb.privateFrontends().size()); LoadBalancerFrontend frontend = lb.frontends().values().iterator().next(); Assertions.assertEquals(1, frontend.loadBalancingRules().size()); - Assertions - .assertTrue( - "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); + Assertions.assertTrue( + "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); Assertions.assertTrue(frontend.isPublic()); LoadBalancerPublicFrontend publicFrontend = (LoadBalancerPublicFrontend) frontend; PublicIpAddress pip = publicFrontend.getPublicIpAddress(); @@ -651,36 +622,34 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { LoadBalancingRule lbRule = resource.loadBalancingRules().get("lbrule1"); Assertions.assertNotNull(lbRule); - resource = - resource - .update() - .updatePublicFrontend(lbRule.frontend().name()) - .withExistingPublicIpAddress(pip) - .parent() - .defineTcpProbe("tcpprobe") - .withPort(22) - .attach() - .defineHttpProbe("httpprobe") - .withRequestPath("/foo") - .withNumberOfProbes(3) - .withPort(443) - .attach() - .updateLoadBalancingRule("lbrule1") - .toBackendPort(8080) - .withIdleTimeoutInMinutes(11) - .withProbe("tcpprobe") - .parent() - .defineLoadBalancingRule("lbrule2") - .withProtocol(TransportProtocol.UDP) - .fromFrontend(lbRule.frontend().name()) - .fromFrontendPort(22) - .toBackend("backend2") - .withProbe("httpprobe") - .attach() - .withoutBackend(backend.name()) - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + resource = resource.update() + .updatePublicFrontend(lbRule.frontend().name()) + .withExistingPublicIpAddress(pip) + .parent() + .defineTcpProbe("tcpprobe") + .withPort(22) + .attach() + .defineHttpProbe("httpprobe") + .withRequestPath("/foo") + .withNumberOfProbes(3) + .withPort(443) + .attach() + .updateLoadBalancingRule("lbrule1") + .toBackendPort(8080) + .withIdleTimeoutInMinutes(11) + .withProbe("tcpprobe") + .parent() + .defineLoadBalancingRule("lbrule2") + .withProtocol(TransportProtocol.UDP) + .fromFrontend(lbRule.frontend().name()) + .fromFrontendPort(22) + .toBackend("backend2") + .withProbe("httpprobe") + .attach() + .withoutBackend(backend.name()) + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); // Verify frontends @@ -769,19 +738,17 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { this.network = existingVMs[0].getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - // LB rule - .defineLoadBalancingRule("lbrule1") - .withProtocol(TransportProtocol.TCP) - .fromExistingSubnet(network, "subnet1") - .fromFrontendPort(80) - .toExistingVirtualMachines(existingVMs) - .attach() - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + // LB rule + .defineLoadBalancingRule("lbrule1") + .withProtocol(TransportProtocol.TCP) + .fromExistingSubnet(network, "subnet1") + .fromFrontendPort(80) + .toExistingVirtualMachines(existingVMs) + .attach() + .create(); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -790,9 +757,8 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { LoadBalancerFrontend frontend = lb.frontends().values().iterator().next(); Assertions.assertEquals(1, frontend.loadBalancingRules().size()); Assertions.assertFalse(frontend.isPublic()); - Assertions - .assertTrue( - "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); + Assertions.assertTrue( + "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); LoadBalancerPrivateFrontend privateFrontend = (LoadBalancerPrivateFrontend) frontend; Assertions.assertTrue(network.id().equalsIgnoreCase(privateFrontend.networkId())); Assertions.assertNotNull(privateFrontend.privateIpAddress()); @@ -833,36 +799,34 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { Assertions.assertNotNull(backend); LoadBalancingRule lbRule = resource.loadBalancingRules().get("lbrule1"); Assertions.assertNotNull(lbRule); - resource = - resource - .update() - .updatePrivateFrontend(lbRule.frontend().name()) - .withExistingSubnet(this.network, "subnet2") - .withPrivateIpAddressStatic("10.0.0.13") - .parent() - .defineTcpProbe("tcpprobe") - .withPort(22) - .attach() - .defineHttpProbe("httpprobe") - .withRequestPath("/foo") - .withNumberOfProbes(3) - .withPort(443) - .attach() - .updateLoadBalancingRule("lbrule1") - .toBackendPort(8080) - .withIdleTimeoutInMinutes(11) - .withProbe("tcpprobe") - .parent() - .defineLoadBalancingRule("lbrule2") - .withProtocol(TransportProtocol.UDP) - .fromFrontend(lbRule.frontend().name()) - .fromFrontendPort(22) - .toBackend(backend.name()) - .withProbe("httpprobe") - .attach() - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + resource = resource.update() + .updatePrivateFrontend(lbRule.frontend().name()) + .withExistingSubnet(this.network, "subnet2") + .withPrivateIpAddressStatic("10.0.0.13") + .parent() + .defineTcpProbe("tcpprobe") + .withPort(22) + .attach() + .defineHttpProbe("httpprobe") + .withRequestPath("/foo") + .withNumberOfProbes(3) + .withPort(443) + .attach() + .updateLoadBalancingRule("lbrule1") + .toBackendPort(8080) + .withIdleTimeoutInMinutes(11) + .withProbe("tcpprobe") + .parent() + .defineLoadBalancingRule("lbrule2") + .withProtocol(TransportProtocol.UDP) + .fromFrontend(lbRule.frontend().name()) + .fromFrontendPort(22) + .toBackend(backend.name()) + .withProbe("httpprobe") + .attach() + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); // Verify frontends @@ -949,25 +913,23 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { this.network = existingVMs[0].getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); // Create a load balancer - LoadBalancer lb = - resources - .define(lbName) - .withRegion(region) - .withExistingResourceGroup(groupName) - // LB rule - .defineLoadBalancingRule("lbrule1") - .withProtocol(TransportProtocol.TCP) - .fromFrontend("frontend-1") - .fromFrontendPort(80) - .toExistingVirtualMachines(existingVMs) - .attach() - // Private zoned front-end - .definePrivateFrontend("frontend-1") - .withExistingSubnet(network, "subnet1") - .withAvailabilityZone(AvailabilityZoneId.ZONE_1) - .attach() - .withSku(LoadBalancerSkuType.BASIC) - .create(); + LoadBalancer lb = resources.define(lbName) + .withRegion(region) + .withExistingResourceGroup(groupName) + // LB rule + .defineLoadBalancingRule("lbrule1") + .withProtocol(TransportProtocol.TCP) + .fromFrontend("frontend-1") + .fromFrontendPort(80) + .toExistingVirtualMachines(existingVMs) + .attach() + // Private zoned front-end + .definePrivateFrontend("frontend-1") + .withExistingSubnet(network, "subnet1") + .withAvailabilityZone(AvailabilityZoneId.ZONE_1) + .attach() + .withSku(LoadBalancerSkuType.BASIC) + .create(); // Verify frontends Assertions.assertEquals(1, lb.frontends().size()); @@ -976,9 +938,8 @@ public LoadBalancer createResource(LoadBalancers resources) throws Exception { LoadBalancerFrontend frontend = lb.frontends().values().iterator().next(); Assertions.assertEquals(1, frontend.loadBalancingRules().size()); Assertions.assertFalse(frontend.isPublic()); - Assertions - .assertTrue( - "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); + Assertions.assertTrue( + "lbrule1".equalsIgnoreCase(frontend.loadBalancingRules().values().iterator().next().name())); LoadBalancerPrivateFrontend privateFrontend = (LoadBalancerPrivateFrontend) frontend; Assertions.assertTrue(network.id().equalsIgnoreCase(privateFrontend.networkId())); Assertions.assertNotNull(privateFrontend.privateIpAddress()); @@ -1040,23 +1001,19 @@ private Map ensurePIPs(PublicIpAddresses pips) { // Ensure VMs for the LB private VirtualMachine[] ensureVMs(Networks networks, ComputeManager computeManager, int count) { // Create a network for the VMs - Network network = - networks - .define("net" + testId) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); - - Creatable availabilitySetDefinition = - computeManager - .availabilitySets() - .define("as" + testId) - .withRegion(region) - .withExistingResourceGroup(groupName) - .withSku(AvailabilitySetSkuTypes.ALIGNED); + Network network = networks.define("net" + testId) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); + + Creatable availabilitySetDefinition = computeManager.availabilitySets() + .define("as" + testId) + .withRegion(region) + .withExistingResourceGroup(groupName) + .withSku(AvailabilitySetSkuTypes.ALIGNED); // Create the requested number of VM definitions String userName = "testuser" + testId; @@ -1064,21 +1021,19 @@ private VirtualMachine[] ensureVMs(Networks networks, ComputeManager computeMana for (int i = 0; i < count; i++) { String vmName = computeManager.resourceManager().internalContext().randomResourceName("vm", 15); - Creatable vm = - computeManager - .virtualMachines() - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(groupName) - .withExistingPrimaryNetwork(network) - .withSubnet(network.subnets().values().iterator().next().name()) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername(userName) - .withRootPassword(ResourceManagerTestProxyTestBase.password()) - .withNewAvailabilitySet(availabilitySetDefinition) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable vm = computeManager.virtualMachines() + .define(vmName) + .withRegion(region) + .withExistingResourceGroup(groupName) + .withExistingPrimaryNetwork(network) + .withSubnet(network.subnets().values().iterator().next().name()) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername(userName) + .withRootPassword(ResourceManagerTestProxyTestBase.password()) + .withNewAvailabilitySet(availabilitySetDefinition) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); vmDefinitions.add(vm); } @@ -1094,8 +1049,7 @@ private VirtualMachine[] ensureVMs(Networks networks, ComputeManager computeMana // Print LB info static void printLB(LoadBalancer resource) { StringBuilder info = new StringBuilder(); - info - .append("Load balancer: ") + info.append("Load balancer: ") .append(resource.id()) .append("Name: ") .append(resource.name()) @@ -1117,8 +1071,7 @@ static void printLB(LoadBalancer resource) { // Show TCP probes info.append("\n\tTCP probes: ").append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { - info - .append("\n\t\tProbe name: ") + info.append("\n\t\tProbe name: ") .append(probe.name()) .append("\n\t\t\tPort: ") .append(probe.port()) @@ -1137,8 +1090,7 @@ static void printLB(LoadBalancer resource) { // Show HTTP probes info.append("\n\tHTTP probes: ").append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { - info - .append("\n\t\tProbe name: ") + info.append("\n\t\tProbe name: ") .append(probe.name()) .append("\n\t\t\tPort: ") .append(probe.port()) @@ -1159,8 +1111,7 @@ static void printLB(LoadBalancer resource) { // Show load balancing rules info.append("\n\tLoad balancing rules: ").append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { - info - .append("\n\t\tLB rule name: ") + info.append("\n\t\tLB rule name: ") .append(rule.name()) .append("\n\t\t\tProtocol: ") .append(rule.protocol()) @@ -1203,18 +1154,15 @@ static void printLB(LoadBalancer resource) { // Show frontends info.append("\n\tFrontends: ").append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { - info - .append("\n\t\tFrontend name: ") + info.append("\n\t\tFrontend name: ") .append(frontend.name()) .append("\n\t\t\tInternet facing: ") .append(frontend.isPublic()); if (frontend.isPublic()) { - info - .append("\n\t\t\tPublic IP Address ID: ") + info.append("\n\t\t\tPublic IP Address ID: ") .append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { - info - .append("\n\t\t\tVirtual network ID: ") + info.append("\n\t\t\tVirtual network ID: ") .append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ") .append(((LoadBalancerPrivateFrontend) frontend).subnetName()) @@ -1246,8 +1194,7 @@ static void printLB(LoadBalancer resource) { // Show inbound NAT rules info.append("\n\tInbound NAT rules: ").append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { - info - .append("\n\t\tInbound NAT rule name: ") + info.append("\n\t\tInbound NAT rule name: ") .append(natRule.name()) .append("\n\t\t\tProtocol: ") .append(natRule.protocol().toString()) @@ -1270,8 +1217,7 @@ static void printLB(LoadBalancer resource) { // Show inbound NAT pools info.append("\n\tInbound NAT pools: ").append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { - info - .append("\n\t\tInbound NAT pool name: ") + info.append("\n\t\tInbound NAT pool name: ") .append(natPool.name()) .append("\n\t\t\tProtocol: ") .append(natPool.protocol().toString()) @@ -1293,8 +1239,7 @@ static void printLB(LoadBalancer resource) { // Show assigned backend NICs info.append("\n\t\t\tReferenced NICs: ").append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Entry entry : backend.backendNicIPConfigurationNames().entrySet()) { - info - .append("\n\t\t\t\tNIC ID: ") + info.append("\n\t\t\t\tNIC ID: ") .append(entry.getKey()) .append(" - IP Config: ") .append(entry.getValue()); @@ -1308,8 +1253,7 @@ static void printLB(LoadBalancer resource) { } // Show assigned load balancing rules - info - .append("\n\t\t\tReferenced load balancing rules: ") + info.append("\n\t\t\tReferenced load balancing rules: ") .append(new ArrayList<>(backend.loadBalancingRules().keySet())); } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java index 952f5b94bd8a8..bf4f352da981c 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java @@ -28,15 +28,13 @@ private void initializeResourceNames(ResourceManagerUtils.InternalRuntimeContext @Override public LocalNetworkGateway createResource(LocalNetworkGateways localNetworkGateways) throws Exception { initializeResourceNames(localNetworkGateways.manager().resourceManager().internalContext()); - LocalNetworkGateway gateway = - localNetworkGateways - .define(lngwName) - .withRegion(REGION) - .withNewResourceGroup(groupName) - .withIPAddress("40.71.184.214") - .withAddressSpace("192.168.3.0/24") - .withAddressSpace("192.168.4.0/27") - .create(); + LocalNetworkGateway gateway = localNetworkGateways.define(lngwName) + .withRegion(REGION) + .withNewResourceGroup(groupName) + .withIPAddress("40.71.184.214") + .withAddressSpace("192.168.3.0/24") + .withAddressSpace("192.168.4.0/27") + .create(); Assertions.assertEquals("40.71.184.214", gateway.ipAddress()); Assertions.assertEquals(2, gateway.addressSpaces().size()); Assertions.assertTrue(gateway.addressSpaces().contains("192.168.4.0/27")); @@ -45,8 +43,7 @@ public LocalNetworkGateway createResource(LocalNetworkGateways localNetworkGatew @Override public LocalNetworkGateway updateResource(LocalNetworkGateway gateway) throws Exception { - gateway - .update() + gateway.update() .withoutAddressSpace("192.168.3.0/24") .withIPAddress("40.71.184.216") .withTag("tag2", "value2") @@ -65,8 +62,7 @@ public LocalNetworkGateway updateResource(LocalNetworkGateway gateway) throws Ex @Override public void print(LocalNetworkGateway gateway) { StringBuilder info = new StringBuilder(); - info - .append("Local Network Gateway: ") + info.append("Local Network Gateway: ") .append(gateway.id()) .append("\n\tName: ") .append(gateway.name()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java index 233d88f9c0acc..e6926cf3c9cfc 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java @@ -30,56 +30,49 @@ public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Ex final String asgName = nsgs.manager().resourceManager().internalContext().randomResourceName("asg", 8); final Region region = Region.US_WEST; - ApplicationSecurityGroup asg = - nsgs - .manager() - .applicationSecurityGroups() - .define(asgName) - .withRegion(region) - .withNewResourceGroup(resourceGroupName) - .create(); + ApplicationSecurityGroup asg = nsgs.manager() + .applicationSecurityGroups() + .define(asgName) + .withRegion(region) + .withNewResourceGroup(resourceGroupName) + .create(); // Create - Mono resourceStream = - nsgs - .define(newName) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) - .defineRule("rule1") - .allowOutbound() - .fromAnyAddress() - .fromPort(80) - .toAnyAddress() - .toPort(80) - .withProtocol(SecurityRuleProtocol.TCP) - .attach() - .defineRule("rule2") - .allowInbound() - .withSourceApplicationSecurityGroup(asg.id()) - .fromAnyPort() - .toAnyAddress() - .toPortRange(22, 25) - .withAnyProtocol() - .withPriority(200) - .withDescription("foo!!") - .attach() - .createAsync(); - - resourceStream - .doOnSuccess((_ignore) -> LOGGER.log(LogLevel.VERBOSE, () -> "completed")); + Mono resourceStream = nsgs.define(newName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .defineRule("rule1") + .allowOutbound() + .fromAnyAddress() + .fromPort(80) + .toAnyAddress() + .toPort(80) + .withProtocol(SecurityRuleProtocol.TCP) + .attach() + .defineRule("rule2") + .allowInbound() + .withSourceApplicationSecurityGroup(asg.id()) + .fromAnyPort() + .toAnyAddress() + .toPortRange(22, 25) + .withAnyProtocol() + .withPriority(200) + .withDescription("foo!!") + .attach() + .createAsync(); + + resourceStream.doOnSuccess((_ignore) -> LOGGER.log(LogLevel.VERBOSE, () -> "completed")); NetworkSecurityGroup nsg = resourceStream.block(); - NetworkInterface nic = - nsgs - .manager() - .networkInterfaces() - .define(nicName) - .withRegion(region) - .withExistingResourceGroup(resourceGroupName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingNetworkSecurityGroup(nsg) - .create(); + NetworkInterface nic = nsgs.manager() + .networkInterfaces() + .define(nicName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingNetworkSecurityGroup(nsg) + .create(); nsg.refresh(); @@ -92,38 +85,35 @@ public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Ex Assertions.assertTrue(nsg.networkInterfaceIds().contains(nic.id())); Assertions.assertEquals(1, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size()); - Assertions - .assertEquals( - asg.id(), nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().iterator().next()); + Assertions.assertEquals(asg.id(), + nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().iterator().next()); return nsg; } @Override public NetworkSecurityGroup updateResource(NetworkSecurityGroup resource) throws Exception { - resource = - resource - .update() - .withoutRule("rule1") - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .defineRule("rule3") - .allowInbound() - .fromAnyAddress() - .fromAnyPort() - .toAnyAddress() - .toAnyPort() - .withProtocol(SecurityRuleProtocol.UDP) - .attach() - .withoutRule("rule1") - .updateRule("rule2") - .denyInbound() - .fromAddresses("100.0.0.0/29", "100.1.0.0/29") - .fromPortRanges("88-90") - .withPriority(300) - .withDescription("bar!!!") - .parent() - .apply(); + resource = resource.update() + .withoutRule("rule1") + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .defineRule("rule3") + .allowInbound() + .fromAnyAddress() + .fromAnyPort() + .toAnyAddress() + .toAnyPort() + .withProtocol(SecurityRuleProtocol.UDP) + .attach() + .withoutRule("rule1") + .updateRule("rule2") + .denyInbound() + .fromAddresses("100.0.0.0/29", "100.1.0.0/29") + .fromPortRanges("88-90") + .withPriority(300) + .withDescription("bar!!!") + .parent() + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); Assertions.assertTrue(resource.securityRules().get("rule2").sourceApplicationSecurityGroupIds().isEmpty()); Assertions.assertNull(resource.securityRules().get("rule2").sourceAddressPrefix()); @@ -139,8 +129,7 @@ public NetworkSecurityGroup updateResource(NetworkSecurityGroup resource) throws } private static StringBuilder printRule(NetworkSecurityRule rule, StringBuilder info) { - info - .append("\n\t\tRule: ") + info.append("\n\t\tRule: ") .append(rule.name()) .append("\n\t\t\tAccess: ") .append(rule.access()) @@ -165,8 +154,7 @@ private static StringBuilder printRule(NetworkSecurityRule rule, StringBuilder i public static void printNSG(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); - info - .append("NSG: ") + info.append("NSG: ") .append(resource.id()) .append("Name: ") .append(resource.name()) @@ -199,8 +187,7 @@ public static void printNSG(NetworkSecurityGroup resource) { info.append("(None)"); } else { for (Subnet subnet : subnets) { - info - .append("\n\t\tNetwork ID: ") + info.append("\n\t\tNetwork ID: ") .append(subnet.parent().id()) .append("\n\t\tSubnet name: ") .append(subnet.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java index 61e2ca7f1120e..7f01f2f4d4acf 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java @@ -38,29 +38,25 @@ public Network createResource(Networks networks) throws Exception { String groupName = "rg" + postFix; // Create an NSG - NetworkSecurityGroup nsg = - networks - .manager() - .networkSecurityGroups() - .define("nsg" + postFix) - .withRegion(region) - .withNewResourceGroup(groupName) - .create(); + NetworkSecurityGroup nsg = networks.manager() + .networkSecurityGroups() + .define("nsg" + postFix) + .withRegion(region) + .withNewResourceGroup(groupName) + .create(); // Create a network - final Network network = - networks - .define(newName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("10.0.0.0/28") - .withAddressSpace("10.1.0.0/28") - .withSubnet("subnetA", "10.0.0.0/29") - .defineSubnet("subnetB") - .withAddressPrefix("10.0.0.8/29") - .withExistingNetworkSecurityGroup(nsg) - .attach() - .create(); + final Network network = networks.define(newName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("10.0.0.0/28") + .withAddressSpace("10.1.0.0/28") + .withSubnet("subnetA", "10.0.0.0/29") + .defineSubnet("subnetB") + .withAddressPrefix("10.0.0.8/29") + .withExistingNetworkSecurityGroup(nsg) + .attach() + .create(); // Verify address spaces Assertions.assertEquals(2, network.addressSpaces().size()); @@ -91,33 +87,29 @@ public Network createResource(Networks networks) throws Exception { @Override public Network updateResource(Network resource) throws Exception { - NetworkSecurityGroup nsg = - resource - .manager() - .networkSecurityGroups() - .define(resource.manager().resourceManager().internalContext().randomResourceName("nsgB", 10)) - .withRegion(resource.region()) - .withExistingResourceGroup(resource.resourceGroupName()) - .create(); - - resource = - resource - .update() - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .withAddressSpace("141.25.0.0/16") - .withoutAddressSpace("10.1.0.0/28") - .withSubnet("subnetC", "141.25.0.0/29") - .withoutSubnet("subnetA") - .updateSubnet("subnetB") - .withAddressPrefix("141.25.0.8/29") - .withoutNetworkSecurityGroup() - .parent() - .defineSubnet("subnetD") - .withAddressPrefix("141.25.0.16/29") - .withExistingNetworkSecurityGroup(nsg) - .attach() - .apply(); + NetworkSecurityGroup nsg = resource.manager() + .networkSecurityGroups() + .define(resource.manager().resourceManager().internalContext().randomResourceName("nsgB", 10)) + .withRegion(resource.region()) + .withExistingResourceGroup(resource.resourceGroupName()) + .create(); + + resource = resource.update() + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .withAddressSpace("141.25.0.0/16") + .withoutAddressSpace("10.1.0.0/28") + .withSubnet("subnetC", "141.25.0.0/29") + .withoutSubnet("subnetA") + .updateSubnet("subnetB") + .withAddressPrefix("141.25.0.8/29") + .withoutNetworkSecurityGroup() + .parent() + .defineSubnet("subnetD") + .withAddressPrefix("141.25.0.16/29") + .withExistingNetworkSecurityGroup(nsg) + .attach() + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); // Verify address spaces @@ -163,18 +155,16 @@ public Network createResource(Networks networks) throws Exception { String groupName = "rg" + postfix; // Create a network - final Network network = - networks - .define(newName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnetA", "10.0.0.0/29") - .defineSubnet("subnetB") - .withAddressPrefix("10.0.0.8/29") - .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) - .attach() - .create(); + final Network network = networks.define(newName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnetA", "10.0.0.0/29") + .defineSubnet("subnetB") + .withAddressPrefix("10.0.0.8/29") + .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) + .attach() + .create(); // Verify address spaces Assertions.assertEquals(1, network.addressSpaces().size()); @@ -195,24 +185,22 @@ public Network createResource(Networks networks) throws Exception { @Override public Network updateResource(Network resource) throws Exception { - resource = - resource - .update() - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .withAddressSpace("141.25.0.0/16") - .withoutAddressSpace("10.1.0.0/28") - .withSubnet("subnetC", "141.25.0.0/29") - .withoutSubnet("subnetA") - .updateSubnet("subnetB") - .withAddressPrefix("141.25.0.8/29") - .withoutAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) - .parent() - .defineSubnet("subnetD") - .withAddressPrefix("141.25.0.16/29") - .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) - .attach() - .apply(); + resource = resource.update() + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .withAddressSpace("141.25.0.0/16") + .withoutAddressSpace("10.1.0.0/28") + .withSubnet("subnetC", "141.25.0.0/29") + .withoutSubnet("subnetA") + .updateSubnet("subnetB") + .withAddressPrefix("141.25.0.8/29") + .withoutAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) + .parent() + .defineSubnet("subnetD") + .withAddressPrefix("141.25.0.16/29") + .withAccessFromService(ServiceEndpointType.MICROSOFT_STORAGE) + .attach() + .apply(); Assertions.assertTrue(resource.tags().containsKey("tag1")); @@ -259,42 +247,36 @@ public Network createResource(Networks networks) throws Exception { String networkName = networks.manager().resourceManager().internalContext().randomResourceName("net", 15); String networkName2 = networks.manager().resourceManager().internalContext().randomResourceName("net", 15); - Creatable remoteNetworkDefinition = - networks - .define(networkName2) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("10.1.0.0/27") - .withSubnet("subnet3", "10.1.0.0/27"); - - Creatable localNetworkDefinition = - networks - .define(networkName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("10.0.0.0/27") - .withSubnet("subnet1", "10.0.0.0/28") - .withSubnet("subnet2", "10.0.0.16/28"); - - CreatedResources createdNetworks = - networks.create(Arrays.asList(remoteNetworkDefinition, localNetworkDefinition)); + Creatable remoteNetworkDefinition = networks.define(networkName2) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("10.1.0.0/27") + .withSubnet("subnet3", "10.1.0.0/27"); + + Creatable localNetworkDefinition = networks.define(networkName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("10.0.0.0/27") + .withSubnet("subnet1", "10.0.0.0/28") + .withSubnet("subnet2", "10.0.0.16/28"); + + CreatedResources createdNetworks + = networks.create(Arrays.asList(remoteNetworkDefinition, localNetworkDefinition)); Network localNetwork = createdNetworks.get(localNetworkDefinition.key()); Network remoteNetwork = createdNetworks.get(remoteNetworkDefinition.key()); Assertions.assertNotNull(localNetwork); Assertions.assertNotNull(remoteNetwork); // Create peering - NetworkPeering localPeering = - localNetwork - .peerings() - .define("peer0") - .withRemoteNetwork(remoteNetwork) - - // Optionals - .withTrafficForwardingBetweenBothNetworks() - .withoutAccessFromEitherNetwork() - .withGatewayUseByRemoteNetworkAllowed() - .create(); + NetworkPeering localPeering = localNetwork.peerings() + .define("peer0") + .withRemoteNetwork(remoteNetwork) + + // Optionals + .withTrafficForwardingBetweenBothNetworks() + .withoutAccessFromEitherNetwork() + .withGatewayUseByRemoteNetworkAllowed() + .create(); // Verify local peering Assertions.assertNotNull(localNetwork.peerings()); @@ -338,8 +320,7 @@ public Network updateResource(Network resource) throws Exception { String remoteTestIP = remoteAvailableIPs.iterator().next(); Assertions.assertFalse(resource.isPrivateIPAddressAvailable(remoteTestIP)); - localPeering - .update() + localPeering.update() .withoutTrafficForwardingFromEitherNetwork() .withAccessBetweenBothNetworks() .withoutAnyGatewayUse() @@ -382,13 +363,11 @@ public Network createResource(Networks networks) throws Exception { String networkName = networks.manager().resourceManager().internalContext().randomResourceName("net", 15); - Network network = - networks - .define(networkName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withNewDdosProtectionPlan() - .create(); + Network network = networks.define(networkName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withNewDdosProtectionPlan() + .create(); Assertions.assertTrue(network.isDdosProtectionEnabled()); Assertions.assertNotNull(network.ddosProtectionPlanId()); @@ -418,13 +397,11 @@ public Network createResource(Networks networks) throws Exception { String networkName = networks.manager().resourceManager().internalContext().randomResourceName("net", 15); - Network network = - networks - .define(networkName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withTag("tag1", "value1") - .create(); + Network network = networks.define(networkName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withTag("tag1", "value1") + .create(); Assertions.assertEquals("value1", network.tags().get("tag1")); return network; } @@ -450,8 +427,7 @@ public void print(Network resource) { */ public static void printNetwork(Network resource) { StringBuilder info = new StringBuilder(); - info - .append("Network: ") + info.append("Network: ") .append(resource.id()) .append("Name: ") .append(resource.name()) @@ -468,8 +444,7 @@ public static void printNetwork(Network resource) { // Output subnets for (Subnet subnet : resource.subnets().values()) { - info - .append("\n\tSubnet: ") + info.append("\n\tSubnet: ") .append(subnet.name()) .append("\n\t\tAddress prefix: ") .append(subnet.addressPrefix()); @@ -501,8 +476,7 @@ public static void printNetwork(Network resource) { // Output peerings for (NetworkPeering peering : resource.peerings().list()) { - info - .append("\n\tPeering: ") + info.append("\n\tPeering: ") .append(peering.name()) .append("\n\t\tRemote network ID: ") .append(peering.remoteNetworkId()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java index 49a9451b3333d..b3fcf42c7f967 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java @@ -28,30 +28,26 @@ public NetworkInterface createResource(NetworkInterfaces networkInterfaces) thro final String pipName = "pip" + postfix; final Region region = Region.US_EAST; - Network network = - networkInterfaces - .manager() - .networks() - .define(vnetName) - .withRegion(region) - .withNewResourceGroup() - .withAddressSpace("10.0.0.0/28") - .withSubnet("subnet1", "10.0.0.0/29") - .withSubnet("subnet2", "10.0.0.8/29") - .create(); - - NetworkInterface nic = - networkInterfaces - .define(nicName) - .withRegion(region) - .withExistingResourceGroup(network.resourceGroupName()) - .withExistingPrimaryNetwork(network) - .withSubnet("subnet1") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress(pipName) - .withIPForwarding() - .withAcceleratedNetworking() - .create(); + Network network = networkInterfaces.manager() + .networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup() + .withAddressSpace("10.0.0.0/28") + .withSubnet("subnet1", "10.0.0.0/29") + .withSubnet("subnet2", "10.0.0.8/29") + .create(); + + NetworkInterface nic = networkInterfaces.define(nicName) + .withRegion(region) + .withExistingResourceGroup(network.resourceGroupName()) + .withExistingPrimaryNetwork(network) + .withSubnet("subnet1") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(pipName) + .withIPForwarding() + .withAcceleratedNetworking() + .create(); // Verify NIC settings Assertions.assertTrue(nic.isAcceleratedNetworkingEnabled()); @@ -83,19 +79,17 @@ public NetworkInterface createResource(NetworkInterfaces networkInterfaces) thro @Override public NetworkInterface updateResource(NetworkInterface resource) throws Exception { - resource = - resource - .update() - .withoutIPForwarding() - .withoutAcceleratedNetworking() - .withSubnet("subnet2") - .updateIPConfiguration("primary") // Updating the primary IP configuration - .withPrivateIpAddressDynamic() // Equivalent to ..update().withPrimaryPrivateIPAddressDynamic() - .withoutPublicIpAddress() // Equivalent to ..update().withoutPrimaryPublicIPAddress() - .parent() - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .apply(); + resource = resource.update() + .withoutIPForwarding() + .withoutAcceleratedNetworking() + .withSubnet("subnet2") + .updateIPConfiguration("primary") // Updating the primary IP configuration + .withPrivateIpAddressDynamic() // Equivalent to ..update().withPrimaryPrivateIPAddressDynamic() + .withoutPublicIpAddress() // Equivalent to ..update().withoutPrimaryPublicIPAddress() + .parent() + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .apply(); // Verifications Assertions.assertFalse(resource.isAcceleratedNetworkingEnabled()); @@ -117,8 +111,7 @@ public NetworkInterface updateResource(NetworkInterface resource) throws Excepti public static void printNic(NetworkInterface resource) { StringBuilder info = new StringBuilder(); - info - .append("NetworkInterface: ") + info.append("NetworkInterface: ") .append(resource.id()) .append("Name: ") .append(resource.name()) @@ -145,8 +138,7 @@ public static void printNic(NetworkInterface resource) { info.append("\n\t\t").append(dnsServerIp); } - info - .append("\n\tIP forwarding enabled? ") + info.append("\n\tIP forwarding enabled? ") .append(resource.isIPForwardingEnabled()) .append("\n\tAccelerated networking enabled? ") .append(resource.isAcceleratedNetworkingEnabled()) @@ -164,8 +156,7 @@ public static void printNic(NetworkInterface resource) { // Output IP configs for (NicIpConfiguration ipConfig : resource.ipConfigurations().values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(ipConfig.name()) .append("\n\t\tPrivate IP: ") .append(ipConfig.privateIpAddress()) @@ -184,8 +175,7 @@ public static void printNic(NetworkInterface resource) { final List backends = ipConfig.listAssociatedLoadBalancerBackends(); info.append("\n\t\tAssociated load balancer backends: ").append(backends.size()); for (LoadBalancerBackend backend : backends) { - info - .append("\n\t\t\tLoad balancer ID: ") + info.append("\n\t\t\tLoad balancer ID: ") .append(backend.parent().id()) .append("\n\t\t\t\tBackend name: ") .append(backend.name()); @@ -195,8 +185,7 @@ public static void printNic(NetworkInterface resource) { final List natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules(); info.append("\n\t\tAssociated load balancer inbound NAT rules: ").append(natRules.size()); for (LoadBalancerInboundNatRule natRule : natRules) { - info - .append("\n\t\t\tLoad balancer ID: ") + info.append("\n\t\t\tLoad balancer ID: ") .append(natRule.parent().id()) .append("\n\t\t\tInbound NAT rule name: ") .append(natRule.name()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java index 27fe629849b1e..34c40aee2f5b2 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java @@ -56,8 +56,11 @@ public NetworkWatcher createResource(NetworkWatchers networkWatchers) throws Exc } } // create Network Watcher - NetworkWatcher nw = - networkWatchers.define(nwName).withRegion(REGION).withNewResourceGroup().withTag("tag1", "value1").create(); + NetworkWatcher nw = networkWatchers.define(nwName) + .withRegion(REGION) + .withNewResourceGroup() + .withTag("tag1", "value1") + .create(); return nw; } @@ -78,48 +81,41 @@ public NetworkWatcher updateResource(NetworkWatcher resource) throws Exception { VirtualMachine[] ensureNetwork(Networks networks, VirtualMachines vms, NetworkInterfaces networkInterfaces) throws Exception { // Create an NSG - NetworkSecurityGroup nsg = - networks - .manager() - .networkSecurityGroups() - .define("nsg" + testId) - .withRegion(REGION) - .withNewResourceGroup(groupName) - .create(); + NetworkSecurityGroup nsg = networks.manager() + .networkSecurityGroups() + .define("nsg" + testId) + .withRegion(REGION) + .withNewResourceGroup(groupName) + .create(); // Create a network for the VMs - Network network = - networks - .define("net" + testId) - .withRegion(REGION) - .withExistingResourceGroup(groupName) - .withAddressSpace("10.0.0.0/28") - .defineSubnet("subnet1") - .withAddressPrefix("10.0.0.0/29") - .withExistingNetworkSecurityGroup(nsg) - .attach() - .withSubnet("subnet2", "10.0.0.8/29") - .create(); - - NetworkInterface nic = - networkInterfaces - .define("ni" + testId) - .withRegion(REGION) - .withExistingResourceGroup(groupName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress("pipdns" + testId) - .withIPForwarding() - .withExistingNetworkSecurityGroup(nsg) - .create(); + Network network = networks.define("net" + testId) + .withRegion(REGION) + .withExistingResourceGroup(groupName) + .withAddressSpace("10.0.0.0/28") + .defineSubnet("subnet1") + .withAddressPrefix("10.0.0.0/29") + .withExistingNetworkSecurityGroup(nsg) + .attach() + .withSubnet("subnet2", "10.0.0.8/29") + .create(); + + NetworkInterface nic = networkInterfaces.define("ni" + testId) + .withRegion(REGION) + .withExistingResourceGroup(groupName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress("pipdns" + testId) + .withIPForwarding() + .withExistingNetworkSecurityGroup(nsg) + .create(); // Create the requested number of VM definitions String userName = "testuser" + testId; List> vmDefinitions = new ArrayList<>(); - Creatable vm1 = - vms - .define(networks.manager().resourceManager().internalContext().randomResourceName("vm", 15)) + Creatable vm1 + = vms.define(networks.manager().resourceManager().internalContext().randomResourceName("vm", 15)) .withRegion(REGION) .withExistingResourceGroup(groupName) .withExistingPrimaryNetworkInterface(nic) @@ -136,19 +132,17 @@ VirtualMachine[] ensureNetwork(Networks networks, VirtualMachines vms, NetworkIn String vmName = networks.manager().resourceManager().internalContext().randomResourceName("vm", 15); - Creatable vm2 = - vms - .define(vmName) - .withRegion(REGION) - .withExistingResourceGroup(groupName) - .withExistingPrimaryNetwork(network) - .withSubnet(network.subnets().values().iterator().next().name()) - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername(userName) - .withRootPassword(ResourceManagerTestProxyTestBase.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + Creatable vm2 = vms.define(vmName) + .withRegion(REGION) + .withExistingResourceGroup(groupName) + .withExistingPrimaryNetwork(network) + .withSubnet(network.subnets().values().iterator().next().name()) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername(userName) + .withRootPassword(ResourceManagerTestProxyTestBase.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); vmDefinitions.add(vm1); vmDefinitions.add(vm2); @@ -163,8 +157,7 @@ VirtualMachine[] ensureNetwork(Networks networks, VirtualMachines vms, NetworkIn // create a storage account StorageAccount ensureStorageAccount(StorageAccounts storageAccounts) { - return storageAccounts - .define("sa" + testId) + return storageAccounts.define("sa" + testId) .withRegion(REGION) .withExistingResourceGroup(groupName) .withGeneralPurposeAccountKindV2() @@ -173,9 +166,9 @@ StorageAccount ensureStorageAccount(StorageAccounts storageAccounts) { @Override public void print(NetworkWatcher nw) { - LOGGER.log(LogLevel.VERBOSE, () -> "Network Watcher: " + nw.id() + "\n\tName: " + nw.name() - + "\n\tResource group: " + nw.resourceGroupName() + "\n\tRegion: " + nw.regionName() + "\n\tTags: " - + nw.tags()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Network Watcher: " + nw.id() + "\n\tName: " + nw.name() + "\n\tResource group: " + + nw.resourceGroupName() + "\n\tRegion: " + nw.regionName() + "\n\tTags: " + nw.tags()); } public String groupName() { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java index 01ae80cd352f4..5fe459349c60d 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java @@ -121,8 +121,7 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception for (MxRecord mxRecord : mxRecordSet.records()) { Assertions.assertTrue(mxRecord.exchange().startsWith("mail.contoso-mail-exchange1.com") || mxRecord.exchange().startsWith("mail.contoso-mail-exchange2.com")); - Assertions.assertTrue(mxRecord.preference() == 1 - || mxRecord.preference() == 2); + Assertions.assertTrue(mxRecord.preference() == 1 || mxRecord.preference() == 2); } // Check TXT records @@ -160,41 +159,49 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception Assertions.assertNotNull(txtRS); typeToCount.put(TXT, typeToCount.get(TXT) + 1); break; + case SRV: SrvRecordSet srvRS = (SrvRecordSet) recordSet; Assertions.assertNotNull(srvRS); typeToCount.put(SRV, typeToCount.get(SRV) + 1); break; + case SOA: SoaRecordSet soaRS = (SoaRecordSet) recordSet; Assertions.assertNotNull(soaRS); typeToCount.put(SOA, typeToCount.get(SOA) + 1); break; + case PTR: PtrRecordSet ptrRS = (PtrRecordSet) recordSet; Assertions.assertNotNull(ptrRS); typeToCount.put(PTR, typeToCount.get(PTR) + 1); break; + case A: ARecordSet aRS = (ARecordSet) recordSet; Assertions.assertNotNull(aRS); typeToCount.put(RecordType.A, typeToCount.get(RecordType.A) + 1); break; + case AAAA: AaaaRecordSet aaaaRS = (AaaaRecordSet) recordSet; Assertions.assertNotNull(aaaaRS); typeToCount.put(AAAA, typeToCount.get(AAAA) + 1); break; + case CNAME: CnameRecordSet cnameRS = (CnameRecordSet) recordSet; Assertions.assertNotNull(cnameRS); typeToCount.put(RecordType.CNAME, typeToCount.get(RecordType.CNAME) + 1); break; + case MX: MxRecordSet mxRS = (MxRecordSet) recordSet; Assertions.assertNotNull(mxRS); typeToCount.put(MX, typeToCount.get(MX) + 1); break; + default: Assertions.assertNotNull(recordSet); } @@ -243,8 +250,8 @@ public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { Assertions.assertEquals(cnameRecordSets.stream().count(), 2); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { Assertions.assertTrue(cnameRecordSet.canonicalName().startsWith("doc.contoso.com")); - Assertions.assertTrue(cnameRecordSet.name().startsWith("documents") - || cnameRecordSet.name().startsWith("help")); + Assertions + .assertTrue(cnameRecordSet.name().startsWith("documents") || cnameRecordSet.name().startsWith("help")); } // Check A records @@ -300,28 +307,43 @@ public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { @Override public void print(PrivateDnsZone resource) { StringBuilder info = new StringBuilder(); - info.append("Dns Zone: ").append(resource.id()) - .append("\n\tName (Top level domain): ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.regionName()) - .append("\n\tTags: ").append(resource.tags()); + info.append("Dns Zone: ") + .append(resource.id()) + .append("\n\tName (Top level domain): ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.regionName()) + .append("\n\tTags: ") + .append(resource.tags()); SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") - .append("\n\t\tHost:").append(soaRecord.host()) - .append("\n\t\tEmail:").append(soaRecord.email()) - .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) - .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) - .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) - .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) - .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); + .append("\n\t\tHost:") + .append(soaRecord.host()) + .append("\n\t\tEmail:") + .append(soaRecord.email()) + .append("\n\t\tExpire time (seconds):") + .append(soaRecord.expireTime()) + .append("\n\t\tRefresh time (seconds):") + .append(soaRecord.refreshTime()) + .append("\n\t\tRetry time (seconds):") + .append(soaRecord.retryTime()) + .append("\n\t\tNegative response cache ttl (seconds):") + .append(soaRecord.minimumTtl()) + .append("\n\t\tTTL (seconds):") + .append(soaRecordSet.timeToLive()); PagedIterable aRecordSets = resource.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { - info.append("\n\t\tId: ").append(aRecordSet.id()) - .append("\n\t\tName: ").append(aRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(aRecordSet.id()) + .append("\n\t\tName: ") + .append(aRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); @@ -331,9 +353,12 @@ public void print(PrivateDnsZone resource) { PagedIterable aaaaRecordSets = resource.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { - info.append("\n\t\tId: ").append(aaaaRecordSet.id()) - .append("\n\t\tName: ").append(aaaaRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(aaaaRecordSet.id()) + .append("\n\t\tName: ") + .append(aaaaRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); @@ -343,18 +368,25 @@ public void print(PrivateDnsZone resource) { PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { - info.append("\n\t\tId: ").append(cnameRecordSet.id()) - .append("\n\t\tName: ").append(cnameRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) - .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); + info.append("\n\t\tId: ") + .append(cnameRecordSet.id()) + .append("\n\t\tName: ") + .append(cnameRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(cnameRecordSet.timeToLive()) + .append("\n\t\tCanonical name: ") + .append(cnameRecordSet.canonicalName()); } PagedIterable mxRecordSets = resource.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { - info.append("\n\t\tId: ").append(mxRecordSet.id()) - .append("\n\t\tName: ").append(mxRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(mxRecordSet.id()) + .append("\n\t\tName: ") + .append(mxRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") @@ -367,9 +399,12 @@ public void print(PrivateDnsZone resource) { PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { - info.append("\n\t\tId: ").append(ptrRecordSet.id()) - .append("\n\t\tName: ").append(ptrRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(ptrRecordSet.id()) + .append("\n\t\tName: ") + .append(ptrRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); @@ -379,9 +414,12 @@ public void print(PrivateDnsZone resource) { PagedIterable srvRecordSets = resource.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { - info.append("\n\t\tId: ").append(srvRecordSet.id()) - .append("\n\t\tName: ").append(srvRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(srvRecordSet.id()) + .append("\n\t\tName: ") + .append(srvRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") @@ -398,9 +436,12 @@ public void print(PrivateDnsZone resource) { PagedIterable txtRecordSets = resource.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { - info.append("\n\t\tId: ").append(txtRecordSet.id()) - .append("\n\t\tName: ").append(txtRecordSet.name()) - .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) + info.append("\n\t\tId: ") + .append(txtRecordSet.id()) + .append("\n\t\tName: ") + .append(txtRecordSet.name()) + .append("\n\t\tTTL (seconds): ") + .append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (!txtRecord.value().isEmpty()) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java index bcea20410bed5..d8d6119f616ad 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java @@ -21,15 +21,13 @@ public class TestPublicIPAddress extends TestTemplate { @Override public RedisCache createResource(RedisCaches resources) throws Exception { - final String redisName = resources.manager().resourceManager().internalContext().randomResourceName("redis", 10); + final String redisName + = resources.manager().resourceManager().internalContext().randomResourceName("redis", 10); final RedisCache[] redisCaches = new RedisCache[1]; - Mono resourceStream = - resources - .define(redisName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withStandardSku() - .withTag("mytag", "testtag") - .createAsync(); - + Mono resourceStream = resources.define(redisName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withStandardSku() + .withTag("mytag", "testtag") + .createAsync(); redisCaches[0] = resourceStream.block(); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestResourceStreaming.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestResourceStreaming.java index be37abce6cd6d..815b7c19164d5 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestResourceStreaming.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestResourceStreaming.java @@ -25,48 +25,48 @@ public TestResourceStreaming(StorageAccounts storageAccounts) { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); System.out.println("In createResource \n\n\n"); - Creatable rgCreatable = - virtualMachines - .manager() - .resourceManager() - .resourceGroups() - .define(virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg" + vmName, 20)) - .withRegion(Region.US_EAST); + Creatable rgCreatable = virtualMachines.manager() + .resourceManager() + .resourceGroups() + .define(virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg" + vmName, 20)) + .withRegion(Region.US_EAST); - Creatable storageCreatable = - this - .storageAccounts - .define(virtualMachines.manager().resourceManager().internalContext().randomResourceName("stg", 20)) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgCreatable); + Creatable storageCreatable = this.storageAccounts + .define(virtualMachines.manager().resourceManager().internalContext().randomResourceName("stg", 20)) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgCreatable); - VirtualMachine virtualMachine = - virtualMachines - .define(vmName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(rgCreatable) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withNewPrimaryPublicIPAddress( - virtualMachines.manager().resourceManager().internalContext().randomResourceName("pip", 20)) - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword(ResourceManagerTestProxyTestBase.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewStorageAccount(storageCreatable) - .withNewAvailabilitySet(virtualMachines.manager().resourceManager().internalContext().randomResourceName("avset", 10)) - .createAsync() - .block(); + VirtualMachine virtualMachine = virtualMachines.define(vmName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgCreatable) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress( + virtualMachines.manager().resourceManager().internalContext().randomResourceName("pip", 20)) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword(ResourceManagerTestProxyTestBase.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewStorageAccount(storageCreatable) + .withNewAvailabilitySet( + virtualMachines.manager().resourceManager().internalContext().randomResourceName("avset", 10)) + .createAsync() + .block(); ComputeManager manager = virtualMachines.manager(); - Assertions.assertEquals(1, manager.storageManager().storageAccounts().listByResourceGroup(rgCreatable.name()).stream().count()); - Assertions.assertEquals(1, manager.networkManager().publicIpAddresses().listByResourceGroup(rgCreatable.name()).stream().count()); - Assertions.assertEquals(1, manager.networkManager().networks().listByResourceGroup(rgCreatable.name()).stream().count()); - Assertions.assertEquals(1, manager.networkManager().networkInterfaces().listByResourceGroup(rgCreatable.name()).stream().count()); + Assertions.assertEquals(1, + manager.storageManager().storageAccounts().listByResourceGroup(rgCreatable.name()).stream().count()); + Assertions.assertEquals(1, + manager.networkManager().publicIpAddresses().listByResourceGroup(rgCreatable.name()).stream().count()); + Assertions.assertEquals(1, + manager.networkManager().networks().listByResourceGroup(rgCreatable.name()).stream().count()); + Assertions.assertEquals(1, + manager.networkManager().networkInterfaces().listByResourceGroup(rgCreatable.name()).stream().count()); Assertions.assertEquals(1, manager.availabilitySets().listByResourceGroup(rgCreatable.name()).stream().count()); return virtualMachine; diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java index 1ea70731a0eac..770cfa96c0972 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java @@ -31,7 +31,8 @@ public class Minimal extends TestTemplate { @Override public RouteTable createResource(RouteTables routeTables) throws Exception { netName = routeTables.manager().resourceManager().internalContext().randomResourceName("net", 10); - final String newName = routeTables.manager().resourceManager().internalContext().randomResourceName("rt", 10); + final String newName + = routeTables.manager().resourceManager().internalContext().randomResourceName("rt", 10); Region region = Region.US_WEST; String groupName = routeTables.manager().resourceManager().internalContext().randomResourceName("rg", 10); @@ -41,22 +42,20 @@ public RouteTable createResource(RouteTables routeTables) throws Exception { final RouteNextHopType hopType = RouteNextHopType.VNET_LOCAL; // Create a route table - final RouteTable routeTable = - routeTables - .define(newName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withRoute("10.0.3.0/29", RouteNextHopType.VNET_LOCAL) - .defineRoute(route1Name) - .withDestinationAddressPrefix(route1AddressPrefix) - .withNextHopToVirtualAppliance(virtualApplianceIp) - .attach() - .defineRoute(route2Name) - .withDestinationAddressPrefix(route2AddressPrefix) - .withNextHop(hopType) - .attach() - .withDisableBgpRoutePropagation() - .create(); + final RouteTable routeTable = routeTables.define(newName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withRoute("10.0.3.0/29", RouteNextHopType.VNET_LOCAL) + .defineRoute(route1Name) + .withDestinationAddressPrefix(route1AddressPrefix) + .withNextHopToVirtualAppliance(virtualApplianceIp) + .attach() + .defineRoute(route2Name) + .withDestinationAddressPrefix(route2AddressPrefix) + .withNextHop(hopType) + .attach() + .withDisableBgpRoutePropagation() + .create(); Assertions.assertTrue(routeTable.routes().containsKey(route1Name)); Route route1 = routeTable.routes().get(route1Name); @@ -73,8 +72,7 @@ public RouteTable createResource(RouteTables routeTables) throws Exception { Assertions.assertTrue(routeTable.isBgpRoutePropagationDisabled()); // Create a subnet that references the route table - routeTables - .manager() + routeTables.manager() .networks() .define(netName) .withRegion(region) @@ -94,23 +92,21 @@ public RouteTable createResource(RouteTables routeTables) throws Exception { @Override public RouteTable updateResource(RouteTable routeTable) throws Exception { - routeTable = - routeTable - .update() - .withTag("tag1", "value1") - .withTag("tag2", "value2") - .withoutRoute(route1Name) - .defineRoute(routeAddedName) - .withDestinationAddressPrefix("10.0.2.0/29") - .withNextHop(RouteNextHopType.NONE) - .attach() - .updateRoute(route2Name) - .withDestinationAddressPrefix("50.46.112.0/29") - .withNextHop(RouteNextHopType.INTERNET) - .parent() - .withRouteViaVirtualAppliance("10.0.5.0/29", virtualApplianceIp) - .withEnableBgpRoutePropagation() - .apply(); + routeTable = routeTable.update() + .withTag("tag1", "value1") + .withTag("tag2", "value2") + .withoutRoute(route1Name) + .defineRoute(routeAddedName) + .withDestinationAddressPrefix("10.0.2.0/29") + .withNextHop(RouteNextHopType.NONE) + .attach() + .updateRoute(route2Name) + .withDestinationAddressPrefix("50.46.112.0/29") + .withNextHop(RouteNextHopType.INTERNET) + .parent() + .withRouteViaVirtualAppliance("10.0.5.0/29", virtualApplianceIp) + .withEnableBgpRoutePropagation() + .apply(); Assertions.assertTrue(routeTable.tags().containsKey("tag1")); Assertions.assertTrue(routeTable.tags().containsKey("tag2")); @@ -119,8 +115,7 @@ public RouteTable updateResource(RouteTable routeTable) throws Exception { Assertions.assertTrue(routeTable.routes().containsKey(routeAddedName)); Assertions.assertFalse(routeTable.isBgpRoutePropagationDisabled()); - routeTable - .manager() + routeTable.manager() .networks() .getByResourceGroup(routeTable.resourceGroupName(), netName) .update() @@ -151,8 +146,7 @@ public void print(RouteTable resource) { */ public static void printRouteTable(RouteTable resource) { StringBuilder info = new StringBuilder(); - info - .append("Route table: ") + info.append("Route table: ") .append(resource.id()) .append("\n\tName: ") .append(resource.name()) @@ -167,8 +161,7 @@ public static void printRouteTable(RouteTable resource) { Map routes = resource.routes(); info.append("\n\tRoutes: ").append(routes.values().size()); for (Route route : routes.values()) { - info - .append("\n\t\tName: ") + info.append("\n\t\tName: ") .append(route.name()) .append("\n\t\t\tDestination address prefix: ") .append(route.destinationAddressPrefix()) @@ -182,8 +175,7 @@ public static void printRouteTable(RouteTable resource) { List subnets = resource.listAssociatedSubnets(); info.append("\n\tAssociated subnets: ").append(subnets.size()); for (Subnet subnet : subnets) { - info - .append("\n\t\tResource group: ") + info.append("\n\t\tResource group: ") .append(subnet.parent().resourceGroupName()) .append("\n\t\tNetwork name: ") .append(subnet.parent().name()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java index ef6b4a52d942b..79abfabba1e3b 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java @@ -26,7 +26,8 @@ public static class SearchServiceAnySku extends TestTemplate queryKeys = resource.listQueryKeys(); - StringBuilder stringBuilder = new StringBuilder().append(header).append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tSku: ").append(resource.sku().name()) - .append("\n\tStatus: ").append(resource.status()) - .append("\n\tStatus Details: ").append(resource.statusDetails()) - .append("\n\tProvisioning State: ").append(resource.provisioningState()) - .append("\n\tHosting Mode: ").append(resource.hostingMode()) - .append("\n\tReplicas: ").append(resource.replicaCount()) - .append("\n\tPartitions: ").append(resource.partitionCount()) - .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) - .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) + StringBuilder stringBuilder = new StringBuilder().append(header) + .append(resource.id()) + .append("Name: ") + .append(resource.name()) + .append("\n\tResource group: ") + .append(resource.resourceGroupName()) + .append("\n\tRegion: ") + .append(resource.region()) + .append("\n\tTags: ") + .append(resource.tags()) + .append("\n\tSku: ") + .append(resource.sku().name()) + .append("\n\tStatus: ") + .append(resource.status()) + .append("\n\tStatus Details: ") + .append(resource.statusDetails()) + .append("\n\tProvisioning State: ") + .append(resource.provisioningState()) + .append("\n\tHosting Mode: ") + .append(resource.hostingMode()) + .append("\n\tReplicas: ") + .append(resource.replicaCount()) + .append("\n\tPartitions: ") + .append(resource.partitionCount()) + .append("\n\tPrimary Admin Key: ") + .append(adminKeys.primaryKey()) + .append("\n\tSecondary Admin Key: ") + .append(adminKeys.secondaryKey()) .append("\n\tQuery keys:"); for (QueryKey queryKey : queryKeys) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java index eaedec8dce626..78047c22ae46b 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java @@ -12,22 +12,27 @@ public class TestSql extends TestTemplate { @Override public SqlServer createResource(SqlServers resources) throws Exception { - final String sqlServerName = resources.manager().resourceManager().internalContext().randomResourceName("sql", 10); + final String sqlServerName + = resources.manager().resourceManager().internalContext().randomResourceName("sql", 10); final SqlServer[] sqlServers = new SqlServer[1]; - Mono resourceStream = - resources - .define(sqlServerName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withAdministratorLogin("admin32") - .withAdministratorPassword("Password~1") - .defineDatabase("database1").attach() - .defineElasticPool("elasticPool1").withStandardPool().attach() - .defineDatabase("databaseInEP").withExistingElasticPool("elasticPool1").attach() - .defineFirewallRule("firewallRule1").withIpAddress("10.10.10.10").attach() - .withTag("mytag", "testtag") - .createAsync(); - + Mono resourceStream = resources.define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withAdministratorLogin("admin32") + .withAdministratorPassword("Password~1") + .defineDatabase("database1") + .attach() + .defineElasticPool("elasticPool1") + .withStandardPool() + .attach() + .defineDatabase("databaseInEP") + .withExistingElasticPool("elasticPool1") + .attach() + .defineFirewallRule("firewallRule1") + .withIpAddress("10.10.10.10") + .attach() + .withTag("mytag", "testtag") + .createAsync(); sqlServers[0] = resourceStream.block(); @@ -44,13 +49,11 @@ public SqlServer createResource(SqlServers resources) throws Exception { @Override public SqlServer updateResource(SqlServer sqlServer) throws Exception { - sqlServer = - sqlServer - .update() - .withoutDatabase("database1") - .withoutDatabase("databaseInEP") - .withoutElasticPool("elasticPool1") - .apply(); + sqlServer = sqlServer.update() + .withoutDatabase("database1") + .withoutDatabase("databaseInEP") + .withoutElasticPool("elasticPool1") + .apply(); Assertions.assertNotNull(sqlServer.innerModel()); // Just master database @@ -63,28 +66,16 @@ public SqlServer updateResource(SqlServer sqlServer) throws Exception { @Override public void print(SqlServer sqlServer) { - System - .out - .println( - new StringBuilder() - .append("SqlServer : ") - .append(sqlServer.id()) - .append(", Name: ") - .append(sqlServer.name()) - .toString()); - System - .out - .println( - new StringBuilder() - .append("Number of databases : ") - .append(sqlServer.databases().list().size()) - .toString()); - System - .out - .println( - new StringBuilder() - .append("Number of elastic pools : ") - .append(sqlServer.elasticPools().list().size()) - .toString()); + System.out.println(new StringBuilder().append("SqlServer : ") + .append(sqlServer.id()) + .append(", Name: ") + .append(sqlServer.name()) + .toString()); + System.out.println(new StringBuilder().append("Number of databases : ") + .append(sqlServer.databases().list().size()) + .toString()); + System.out.println(new StringBuilder().append("Number of elastic pools : ") + .append(sqlServer.elasticPools().list().size()) + .toString()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java index 0f0035d66adc3..c48a1b7866ac9 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java @@ -25,10 +25,7 @@ * @param Top level resource type * @param Type representing the collection of the top level resources */ -public abstract class TestTemplate, ?>, - CollectionT extends - SupportsListing & SupportsGettingByResourceGroup & SupportsDeletingById - & SupportsGettingById & HasManager> { +public abstract class TestTemplate, ?>, CollectionT extends SupportsListing & SupportsGettingByResourceGroup & SupportsDeletingById & SupportsGettingById & HasManager> { private static final ClientLogger LOGGER = new ClientLogger(TestTemplate.class); @@ -80,8 +77,8 @@ public int verifyListing() throws ManagementException, IOException { * @throws IOException if anything goes wrong */ public ResourceT verifyGetting() throws ManagementException, IOException { - ResourceT resourceByGroup = - this.collection.getByResourceGroup(this.resource.resourceGroupName(), this.resource.name()); + ResourceT resourceByGroup + = this.collection.getByResourceGroup(this.resource.resourceGroupName(), this.resource.name()); ResourceT resourceById = this.collection.getById(resourceByGroup.id()); Assertions.assertTrue(resourceById.id().equalsIgnoreCase(resourceByGroup.id())); return resourceById; diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java index 1eb38fdcd5e9a..6e6b52d1eab67 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java @@ -49,32 +49,33 @@ public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) thr final String groupName = profiles.manager().resourceManager().internalContext().randomResourceName("rg", 10); final String pipName = profiles.manager().resourceManager().internalContext().randomResourceName("pip", 10); - final String pipDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("contoso", 15); + final String pipDnsLabel + = profiles.manager().resourceManager().internalContext().randomResourceName("contoso", 15); - final String tmProfileName = profiles.manager().resourceManager().internalContext().randomResourceName("tm", 10); + final String tmProfileName + = profiles.manager().resourceManager().internalContext().randomResourceName("tm", 10); final String nestedTmProfileName = "nested" + tmProfileName; - final String tmProfileDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("tmdns", 10); + final String tmProfileDnsLabel + = profiles.manager().resourceManager().internalContext().randomResourceName("tmdns", 10); final String nestedTmProfileDnsLabel = "nested" + tmProfileDnsLabel; - ResourceGroup.DefinitionStages.WithCreate rgCreatable = - profiles.manager().resourceManager().resourceGroups().define(groupName).withRegion(region); + ResourceGroup.DefinitionStages.WithCreate rgCreatable + = profiles.manager().resourceManager().resourceGroups().define(groupName).withRegion(region); // Creates a TM profile that will be used as a nested profile endpoint in parent TM profile // - TrafficManagerProfile nestedProfile = - profiles - .define(nestedTmProfileName) - .withNewResourceGroup(rgCreatable) - .withLeafDomainLabel(nestedTmProfileDnsLabel) - .withPriorityBasedRouting() - .defineExternalTargetEndpoint(externalEndpointName21) - .toFqdn("www.gitbook.com") - .fromRegion(Region.INDIA_CENTRAL) - .attach() - .withHttpsMonitoring() - .withTimeToLive(500) - .create(); + TrafficManagerProfile nestedProfile = profiles.define(nestedTmProfileName) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(nestedTmProfileDnsLabel) + .withPriorityBasedRouting() + .defineExternalTargetEndpoint(externalEndpointName21) + .toFqdn("www.gitbook.com") + .fromRegion(Region.INDIA_CENTRAL) + .attach() + .withHttpsMonitoring() + .withTimeToLive(500) + .create(); Assertions.assertTrue(nestedProfile.isEnabled()); Assertions.assertNotNull(nestedProfile.monitorStatus()); @@ -88,29 +89,24 @@ public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) thr // Creates a public ip to be used as an Azure endpoint // - PublicIpAddress publicIPAddress = - this - .publicIpAddresses - .define(pipName) - .withRegion(region) - .withNewResourceGroup(rgCreatable) - .withLeafDomainLabel(pipDnsLabel) - .create(); + PublicIpAddress publicIPAddress = this.publicIpAddresses.define(pipName) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(pipDnsLabel) + .create(); Assertions.assertNotNull(publicIPAddress.fqdn()); // Creates a TM profile // // bugfix - TrafficManagerProfile updatedProfile = - nestedProfile - .update() - .defineAzureTargetEndpoint(azureEndpointName) - .toResourceId(publicIPAddress.id()) - .withTrafficDisabled() - .withRoutingPriority(11) - .attach() - .apply(); + TrafficManagerProfile updatedProfile = nestedProfile.update() + .defineAzureTargetEndpoint(azureEndpointName) + .toResourceId(publicIPAddress.id()) + .withTrafficDisabled() + .withRoutingPriority(11) + .attach() + .apply(); Assertions.assertEquals(1, updatedProfile.azureEndpoints().size()); Assertions.assertTrue(updatedProfile.azureEndpoints().containsKey(azureEndpointName)); @@ -137,37 +133,35 @@ public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) thr Assertions.assertTrue(updatedProfileFromGet.externalEndpoints().containsKey(externalEndpointName21)); // end of bugfix - TrafficManagerProfile profile = - profiles - .define(tmProfileName) - .withNewResourceGroup(rgCreatable) - .withLeafDomainLabel(tmProfileDnsLabel) - .withWeightBasedRouting() - .defineExternalTargetEndpoint(externalEndpointName21) - .toFqdn(externalFqdn21) - .fromRegion(Region.US_EAST) - .withRoutingPriority(1) - .withRoutingWeight(1) - .attach() - .defineExternalTargetEndpoint(externalEndpointName22) - .toFqdn(externalFqdn22) - .fromRegion(Region.US_EAST2) - .withRoutingPriority(2) - .withRoutingWeight(1) - .withTrafficDisabled() - .attach() - .defineAzureTargetEndpoint(azureEndpointName) - .toResourceId(publicIPAddress.id()) - .withRoutingPriority(3) - .attach() - .defineNestedTargetEndpoint(nestedProfileEndpointName) - .toProfile(nestedProfile) - .fromRegion(Region.INDIA_CENTRAL) - .withMinimumEndpointsToEnableTraffic(1) - .withRoutingPriority(4) - .attach() - .withHttpMonitoring() - .create(); + TrafficManagerProfile profile = profiles.define(tmProfileName) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(tmProfileDnsLabel) + .withWeightBasedRouting() + .defineExternalTargetEndpoint(externalEndpointName21) + .toFqdn(externalFqdn21) + .fromRegion(Region.US_EAST) + .withRoutingPriority(1) + .withRoutingWeight(1) + .attach() + .defineExternalTargetEndpoint(externalEndpointName22) + .toFqdn(externalFqdn22) + .fromRegion(Region.US_EAST2) + .withRoutingPriority(2) + .withRoutingWeight(1) + .withTrafficDisabled() + .attach() + .defineAzureTargetEndpoint(azureEndpointName) + .toResourceId(publicIPAddress.id()) + .withRoutingPriority(3) + .attach() + .defineNestedTargetEndpoint(nestedProfileEndpointName) + .toProfile(nestedProfile) + .fromRegion(Region.INDIA_CENTRAL) + .withMinimumEndpointsToEnableTraffic(1) + .withRoutingPriority(4) + .attach() + .withHttpMonitoring() + .create(); Assertions.assertTrue(profile.isEnabled()); Assertions.assertNotNull(profile.monitorStatus()); @@ -244,8 +238,7 @@ public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) thr public TrafficManagerProfile updateResource(TrafficManagerProfile profile) throws Exception { // Remove an endpoint, update two endpoints and add new one // - profile - .update() + profile.update() .withTimeToLive(600) .withHttpMonitoring(8080, "/") .withPerformanceBasedRouting() @@ -313,8 +306,7 @@ public TrafficManagerProfile updateResource(TrafficManagerProfile profile) throw @Override public void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); - info - .append("Traffic Manager Profile: ") + info.append("Traffic Manager Profile: ") .append(profile.id()) .append("\n\tName: ") .append(profile.name()) @@ -346,8 +338,7 @@ public void print(TrafficManagerProfile profile) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { - info - .append("\n\t\tAzure endpoint: #") + info.append("\n\t\tAzure endpoint: #") .append(idx++) .append("\n\t\t\tId: ") .append(endpoint.id()) @@ -358,8 +349,7 @@ public void print(TrafficManagerProfile profile) { if (!isPlaybackMode) { // targetResourceId sanitized // The specified ID `Sanitized` is not a valid Azure resource ID - info.append("\n\t\t\tTarget resourceType: ") - .append(endpoint.targetResourceType()); + info.append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()); } info.append("\n\t\t\tMonitor status: ") .append(endpoint.monitorStatus()) @@ -377,8 +367,7 @@ public void print(TrafficManagerProfile profile) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { - info - .append("\n\t\tExternal endpoint: #") + info.append("\n\t\tExternal endpoint: #") .append(idx++) .append("\n\t\t\tId: ") .append(endpoint.id()) @@ -404,8 +393,7 @@ public void print(TrafficManagerProfile profile) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { - info - .append("\n\t\tNested profile endpoint: #") + info.append("\n\t\tNested profile endpoint: #") .append(idx++) .append("\n\t\t\tId: ") .append(endpoint.id()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java index d9a0908fb063f..e9af2057de8dc 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java @@ -27,9 +27,12 @@ public static boolean isRecordMode() { public static void print(ManagementLock lock) { StringBuilder info = new StringBuilder(); - info.append("\nLock ID: ").append(lock.id()) - .append("\nLocked resource ID: ").append(lock.lockedResourceId()) - .append("\nLevel: ").append(lock.level()); + info.append("\nLock ID: ") + .append(lock.id()) + .append("\nLocked resource ID: ") + .append(lock.lockedResourceId()) + .append("\nLevel: ") + .append(lock.level()); LOGGER.log(LogLevel.VERBOSE, info::toString); } @@ -63,14 +66,11 @@ public static void print(VirtualMachine resource) { } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); - storageProfile - .append("\n\t\t\t\tEnabled: ") + storageProfile.append("\n\t\t\t\tEnabled: ") .append(resource.storageProfile().osDisk().encryptionSettings().enabled()); - storageProfile - .append("\n\t\t\t\tDiskEncryptionKey Uri: ") + storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ") .append(resource.storageProfile().osDisk().encryptionSettings().diskEncryptionKey().secretUrl()); - storageProfile - .append("\n\t\t\t\tKeyEncryptionKey Uri: ") + storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ") .append(resource.storageProfile().osDisk().encryptionSettings().keyEncryptionKey().keyUrl()); } } @@ -103,19 +103,16 @@ public static void print(VirtualMachine resource) { osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); - osProfile - .append("\n\t\t\t\tProvisionVMAgent: ") + osProfile.append("\n\t\t\t\tProvisionVMAgent: ") .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); - osProfile - .append("\n\t\t\t\tEnableAutomaticUpdates: ") + osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); osProfile.append("\n\t\t\t\tTimeZone: ").append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); - osProfile - .append("\n\t\t\t\tDisablePasswordAuthentication: ") + osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } @@ -124,9 +121,10 @@ public static void print(VirtualMachine resource) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } - LOGGER.log(LogLevel.VERBOSE, () -> "Virtual Machine: " + resource.id() + "Name: " + resource.name() - + "\n\tResource group: " + resource.resourceGroupName() + "\n\tRegion: " + resource.region() + "\n\tTags: " - + resource.tags() + "\n\tHardwareProfile: " + "\n\t\tSize: " + resource.size() + storageProfile + osProfile - + networkProfile); + LOGGER.log(LogLevel.VERBOSE, + () -> "Virtual Machine: " + resource.id() + "Name: " + resource.name() + "\n\tResource group: " + + resource.resourceGroupName() + "\n\tRegion: " + resource.region() + "\n\tTags: " + resource.tags() + + "\n\tHardwareProfile: " + "\n\t\tSize: " + resource.size() + storageProfile + osProfile + + networkProfile); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachine.java index 940b9e920979e..de01ff51fb406 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachine.java @@ -17,24 +17,23 @@ public class TestVirtualMachine extends TestTemplate { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); final VirtualMachine[] vms = new VirtualMachine[1]; - Mono resourceStream = - virtualMachines - .define(vmName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword(ResourceManagerTestProxyTestBase.password()) - .withNewDataDisk(150) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .createAsync(); + Mono resourceStream = virtualMachines.define(vmName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword(ResourceManagerTestProxyTestBase.password()) + .withNewDataDisk(150) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .createAsync(); vms[0] = resourceStream.block(); @@ -51,7 +50,10 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc @Override public VirtualMachine updateResource(VirtualMachine resource) throws Exception { - resource = resource.update().withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")).withNewDataDisk(100).apply(); + resource = resource.update() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewDataDisk(100) + .apply(); return resource; } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineCustomData.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineCustomData.java index dda9ecd3a582b..4f8d6db694678 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineCustomData.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineCustomData.java @@ -30,8 +30,10 @@ public TestVirtualMachineCustomData(PublicIpAddresses pips) { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); - final String publicIpDnsLabel = virtualMachines.manager().resourceManager().internalContext().randomResourceName("abc", 16); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String publicIpDnsLabel + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("abc", 16); final String password = ResourceManagerTestProxyTestBase.password(); // Prepare the custom data @@ -42,28 +44,24 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc byte[] cloudInitEncoded = Base64.getEncoder().encode(cloudInitAsBytes); String cloudInitEncodedString = new String(cloudInitEncoded); - PublicIpAddress pip = - pips - .define(publicIpDnsLabel) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withLeafDomainLabel(publicIpDnsLabel) - .create(); + PublicIpAddress pip = pips.define(publicIpDnsLabel) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withLeafDomainLabel(publicIpDnsLabel) + .create(); - VirtualMachine vm = - virtualMachines - .define(vmName) - .withRegion(pip.regionName()) - .withExistingResourceGroup(pip.resourceGroupName()) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("testuser") - .withRootPassword(password) - .withCustomData(cloudInitEncodedString) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine vm = virtualMachines.define(vmName) + .withRegion(pip.regionName()) + .withExistingResourceGroup(pip.resourceGroupName()) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("testuser") + .withRootPassword(password) + .withCustomData(cloudInitEncodedString) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); pip.refresh(); Assertions.assertTrue(pip.hasAssignedNetworkInterface()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineDataDisk.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineDataDisk.java index 1d718b5207d54..2c98917f8f297 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineDataDisk.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineDataDisk.java @@ -16,26 +16,25 @@ public class TestVirtualMachineDataDisk extends TestTemplate { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); - VirtualMachine virtualMachine = - virtualMachines - .define(vmName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword(ResourceManagerTestProxyTestBase.password()) - .withUnmanagedDisks() - .withNewUnmanagedDataDisk(30) - .defineUnmanagedDataDisk("disk2") - .withNewVhd(20) - .withCaching(CachingTypes.READ_ONLY) - .attach() - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + VirtualMachine virtualMachine = virtualMachines.define(vmName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword(ResourceManagerTestProxyTestBase.password()) + .withUnmanagedDisks() + .withNewUnmanagedDataDisk(30) + .defineUnmanagedDataDisk("disk2") + .withNewVhd(20) + .withCaching(CachingTypes.READ_ONLY) + .attach() + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); // Assertions.assertTrue(virtualMachine.size().equals(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))); Assertions.assertTrue(virtualMachine.unmanagedDataDisks().size() == 2); @@ -54,15 +53,13 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc @Override public VirtualMachine updateResource(VirtualMachine virtualMachine) throws Exception { - virtualMachine = - virtualMachine - .update() - .withoutUnmanagedDataDisk("disk2") - .defineUnmanagedDataDisk("disk3") - .withNewVhd(10) - .withLun(2) - .attach() - .apply(); + virtualMachine = virtualMachine.update() + .withoutUnmanagedDataDisk("disk2") + .defineUnmanagedDataDisk("disk3") + .withNewVhd(10) + .withLun(2) + .attach() + .apply(); Assertions.assertTrue(virtualMachine.unmanagedDataDisks().size() == 2); VirtualMachineUnmanagedDataDisk disk3 = null; for (VirtualMachineUnmanagedDataDisk dataDisk : virtualMachine.unmanagedDataDisks().values()) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineInAvailabilitySet.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineInAvailabilitySet.java index 3a89fb6910758..1fd413ddbefae 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineInAvailabilitySet.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineInAvailabilitySet.java @@ -14,25 +14,26 @@ public class TestVirtualMachineInAvailabilitySet extends TestTemplate { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); - final String newRgName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rgVmInAvail", 10); - final String newAvailSetName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("avai", 10); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String newRgName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rgVmInAvail", 10); + final String newAvailSetName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("avai", 10); - VirtualMachine vm = - virtualMachines - .define(vmName) - .withRegion(Region.US_EAST) - .withNewResourceGroup(newRgName) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) - .withRootUsername("testuser") - .withRootPassword(ResourceManagerTestProxyTestBase.password()) - .withComputerName("myvm123") - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .withNewAvailabilitySet(newAvailSetName) - .create(); + VirtualMachine vm = virtualMachines.define(vmName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(newRgName) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername("testuser") + .withRootPassword(ResourceManagerTestProxyTestBase.password()) + .withComputerName("myvm123") + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .withNewAvailabilitySet(newAvailSetName) + .create(); Assertions.assertNotNull(vm.availabilitySetId()); Assertions.assertNotNull(vm.computerName()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineNics.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineNics.java index 7ff6484dbe42c..e0e6bdf53651a 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineNics.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineNics.java @@ -30,70 +30,63 @@ public TestVirtualMachineNics(NetworkManager networkManager) { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { // Prepare the resource group definition - final String rgName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg", 10); + final String rgName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg", 10); - Creatable resourceGroupCreatable = - virtualMachines.manager().resourceManager().resourceGroups().define(rgName).withRegion(region); + Creatable resourceGroupCreatable + = virtualMachines.manager().resourceManager().resourceGroups().define(rgName).withRegion(region); // Prepare the virtual network definition [shared by primary and secondary network interfaces] - final String vnetName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vnet", 10); + final String vnetName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vnet", 10); - Creatable networkCreatable = - this - .networkManager - .networks() - .define(vnetName) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withAddressSpace("10.0.0.0/28"); + Creatable networkCreatable = this.networkManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withAddressSpace("10.0.0.0/28"); // Prepare the secondary network interface definition secondaryNicName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("nic", 10); - Creatable secondaryNetworkInterfaceCreatable = - this - .networkManager - .networkInterfaces() - .define(secondaryNicName) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.5"); + Creatable secondaryNetworkInterfaceCreatable = this.networkManager.networkInterfaces() + .define(secondaryNicName) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.5"); // .withNewPrimaryPublicIPAddress(); // [Secondary NIC cannot have PublicIP - Only primary network interface can reference a public IP address] // Prepare the secondary network interface definition - final String secondaryNicName2 = virtualMachines.manager().resourceManager().internalContext().randomResourceName("nic2", 10); - - Creatable secondaryNetworkInterfaceCreatable2 = - this - .networkManager - .networkInterfaces() - .define(secondaryNicName2) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.6"); + final String secondaryNicName2 + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("nic2", 10); + + Creatable secondaryNetworkInterfaceCreatable2 = this.networkManager.networkInterfaces() + .define(secondaryNicName2) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.6"); // Create Virtual Machine - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); final String primaryPipName = "pip" + vmName; - VirtualMachine virtualMachine = - virtualMachines - .define(vmName) - .withRegion(region) - .withNewResourceGroup(resourceGroupCreatable) - .withNewPrimaryNetwork(networkCreatable) - .withPrimaryPrivateIPAddressStatic("10.0.0.4") - .withNewPrimaryPublicIPAddress(primaryPipName) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("testuser") - .withRootPassword(ResourceManagerTestProxyTestBase.password()) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D8a_v4")) - .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) - .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable2) - .create(); + VirtualMachine virtualMachine = virtualMachines.define(vmName) + .withRegion(region) + .withNewResourceGroup(resourceGroupCreatable) + .withNewPrimaryNetwork(networkCreatable) + .withPrimaryPrivateIPAddressStatic("10.0.0.4") + .withNewPrimaryPublicIPAddress(primaryPipName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("testuser") + .withRootPassword(ResourceManagerTestProxyTestBase.password()) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D8a_v4")) + .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable) + .withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable2) + .create(); Assertions.assertTrue(virtualMachine.networkInterfaceIds().size() == 3); NetworkInterface primaryNetworkInterface = virtualMachine.getPrimaryNetworkInterface(); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSizes.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSizes.java index b1f41a917ed4c..ff65e733a8cf0 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSizes.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSizes.java @@ -20,20 +20,19 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc Assertions.assertTrue(TestUtilities.getSize(availableSizes) > 0); VirtualMachineSize availableSize = availableSizes.iterator().next(); System.out.println("VM Sizes: " + availableSizes); - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); - VirtualMachine vm = - virtualMachines - .define(vmName) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withoutPrimaryPublicIPAddress() - .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) - .withAdminUsername("testuser") - .withAdminPassword(ResourceManagerTestProxyTestBase.password()) - .withSize(availableSize.name()) // Use the first size - .create(); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + VirtualMachine vm = virtualMachines.define(vmName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername("testuser") + .withAdminPassword(ResourceManagerTestProxyTestBase.password()) + .withSize(availableSize.name()) // Use the first size + .create(); Assertions.assertTrue(vm.size().toString().equalsIgnoreCase(availableSize.name())); return vm; diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSsh.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSsh.java index eefd9445b8e47..7aab25f9ac022 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSsh.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSsh.java @@ -21,33 +21,29 @@ public TestVirtualMachineSsh(PublicIpAddresses pips) { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); - final String sshKey = - "ssh-rsa" - + " AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD" - + " azjava@javalib.com"; + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String sshKey = "ssh-rsa" + + " AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD" + + " azjava@javalib.com"; final String publicIpDnsLabel = vmName; - PublicIpAddress pip = - pips - .define(publicIpDnsLabel) - .withRegion(Region.US_EAST) - .withNewResourceGroup() - .withLeafDomainLabel(publicIpDnsLabel) - .create(); + PublicIpAddress pip = pips.define(publicIpDnsLabel) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withLeafDomainLabel(publicIpDnsLabel) + .create(); - VirtualMachine vm = - virtualMachines - .define(vmName) - .withRegion(pip.regionName()) - .withExistingResourceGroup(pip.resourceGroupName()) - .withNewPrimaryNetwork("10.0.0.0/28") - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(pip) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("testuser") - .withSsh(sshKey) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .create(); + VirtualMachine vm = virtualMachines.define(vmName) + .withRegion(pip.regionName()) + .withExistingResourceGroup(pip.resourceGroupName()) + .withNewPrimaryNetwork("10.0.0.0/28") + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(pip) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("testuser") + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .create(); pip.refresh(); Assertions.assertTrue(pip.hasAssignedNetworkInterface()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSyncPoller.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSyncPoller.java index d1b00064da5d2..27e09bc8a6d47 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSyncPoller.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualMachineSyncPoller.java @@ -38,33 +38,37 @@ public TestVirtualMachineSyncPoller(NetworkManager networkManager) { @Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { - final String rgName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg", 10); - final String vnetName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vnet", 10); - final String nicName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("nic", 10); + final String rgName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("rg", 10); + final String vnetName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vnet", 10); + final String nicName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("nic", 10); final String subnetName = "default"; - final String diskName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("disk", 10); - final String ipName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("ip", 10); - final String vmName = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); + final String diskName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("disk", 10); + final String ipName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("ip", 10); + final String vmName + = virtualMachines.manager().resourceManager().internalContext().randomResourceName("vm", 10); final Region region = Region.US_EAST; // network - Network network = - this.networkManager.networks() - .define(vnetName) - .withRegion(region) - .withNewResourceGroup(rgName) - .withAddressSpace("10.0.0.0/27") - .withSubnet(subnetName, "10.0.0.0/28") - .create(); + Network network = this.networkManager.networks() + .define(vnetName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAddressSpace("10.0.0.0/27") + .withSubnet(subnetName, "10.0.0.0/28") + .create(); // public ip address, poll till complete logger.info("{} {}", OffsetDateTime.now(), "begin create public IP"); - Accepted publicIpAddressAccepted = - this.networkManager.publicIpAddresses() - .define(ipName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .beginCreate(); + Accepted publicIpAddressAccepted = this.networkManager.publicIpAddresses() + .define(ipName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .beginCreate(); logger.info("{} {}", OffsetDateTime.now(), "polling public IP till complete"); PollResponse publicIpAddressResponse = publicIpAddressAccepted.getSyncPoller().waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, publicIpAddressResponse.getStatus()); @@ -73,30 +77,30 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc // nic and disk logger.info("{} {}", OffsetDateTime.now(), "begin create nic"); - Accepted networkInterfaceAccepted = - this.networkManager.networkInterfaces() - .define(nicName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetwork(network) - .withSubnet(subnetName) - .withPrimaryPrivateIPAddressDynamic() - .withExistingPrimaryPublicIPAddress(publicIpAddress) - .beginCreate(); + Accepted networkInterfaceAccepted = this.networkManager.networkInterfaces() + .define(nicName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnetName) + .withPrimaryPrivateIPAddressDynamic() + .withExistingPrimaryPublicIPAddress(publicIpAddress) + .beginCreate(); logger.info("{} {}", OffsetDateTime.now(), "begin create data disk"); - Accepted diskAccepted = - virtualMachines.manager().disks() - .define(diskName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withData() - .withSizeInGB(100) - .withSku(DiskSkuTypes.STANDARD_LRS) - .beginCreate(); + Accepted diskAccepted = virtualMachines.manager() + .disks() + .define(diskName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withData() + .withSizeInGB(100) + .withSku(DiskSkuTypes.STANDARD_LRS) + .beginCreate(); // poll nic and disk - LongRunningOperationStatus networkInterfaceLroStatus = networkInterfaceAccepted.getActivationResponse().getStatus(); + LongRunningOperationStatus networkInterfaceLroStatus + = networkInterfaceAccepted.getActivationResponse().getStatus(); LongRunningOperationStatus diskLroStatus = diskAccepted.getActivationResponse().getStatus(); SyncPoller networkInterfaceSyncPoller = networkInterfaceAccepted.getSyncPoller(); SyncPoller diskSyncPoller = diskAccepted.getSyncPoller(); @@ -121,18 +125,16 @@ public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exc // virtual machine, poll till complete logger.info("{} {}", OffsetDateTime.now(), "begin create vm"); - Accepted virtualMachineAccepted = - virtualMachines - .define(vmName) - .withRegion(region) - .withExistingResourceGroup(rgName) - .withExistingPrimaryNetworkInterface(networkInterface) - .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) - .withRootUsername("testuser") - .withRootPassword(ResourceManagerTestProxyTestBase.password()) - .withExistingDataDisk(disk) - .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) - .beginCreate(); + Accepted virtualMachineAccepted = virtualMachines.define(vmName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetworkInterface(networkInterface) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) + .withRootUsername("testuser") + .withRootPassword(ResourceManagerTestProxyTestBase.password()) + .withExistingDataDisk(disk) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) + .beginCreate(); logger.info("{} {}", OffsetDateTime.now(), "polling virtual machine till complete"); PollResponse virtualMachineResponse = virtualMachineAccepted.getSyncPoller().waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, virtualMachineResponse.getStatus()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java index 68448d74db779..40cd041a0bc06 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java @@ -62,23 +62,20 @@ public void print(VirtualNetworkGateway resource) { @Override public VirtualNetworkGateway createResource(VirtualNetworkGateways gateways) throws Exception { - VirtualNetworkGateway vngw = - gateways - .define(gatewayName1) - .withRegion(region) - .withNewResourceGroup(groupName) - .withNewNetwork("10.0.0.0/25", "10.0.0.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .withTag("tag1", "value1") - .create(); + VirtualNetworkGateway vngw = gateways.define(gatewayName1) + .withRegion(region) + .withNewResourceGroup(groupName) + .withNewNetwork("10.0.0.0/25", "10.0.0.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .withTag("tag1", "value1") + .create(); return vngw; } @Override public VirtualNetworkGateway updateResource(VirtualNetworkGateway resource) throws Exception { - resource - .update() + resource.update() .withSku(VirtualNetworkGatewaySkuName.VPN_GW2) .withTag("tag2", "value2") .withoutTag("tag1") @@ -113,36 +110,30 @@ public VirtualNetworkGateway createResource(VirtualNetworkGateways gateways) thr // Create virtual network gateway initializeResourceNames(gateways.manager().resourceManager().internalContext()); - VirtualNetworkGateway vngw = - gateways - .define(gatewayName1) - .withRegion(region) - .withNewResourceGroup() - .withNewNetwork("10.0.0.0/25", "10.0.0.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .withBgp(65010, "10.12.255.30") - .create(); - LocalNetworkGateway lngw = - gateways - .manager() - .localNetworkGateways() - .define("lngw" + testId) - .withRegion(vngw.region()) - .withExistingResourceGroup(vngw.resourceGroupName()) - .withIPAddress("40.71.184.214") - .withAddressSpace("192.168.3.0/24") - .withBgp(65050, "10.51.255.254") - .create(); - VirtualNetworkGatewayConnection connection = - vngw - .connections() - .define(connectionName) - .withSiteToSite() - .withLocalNetworkGateway(lngw) - .withSharedKey("MySecretKey") - .withTag("tag1", "value1") - .create(); + VirtualNetworkGateway vngw = gateways.define(gatewayName1) + .withRegion(region) + .withNewResourceGroup() + .withNewNetwork("10.0.0.0/25", "10.0.0.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .withBgp(65010, "10.12.255.30") + .create(); + LocalNetworkGateway lngw = gateways.manager() + .localNetworkGateways() + .define("lngw" + testId) + .withRegion(vngw.region()) + .withExistingResourceGroup(vngw.resourceGroupName()) + .withIPAddress("40.71.184.214") + .withAddressSpace("192.168.3.0/24") + .withBgp(65050, "10.51.255.254") + .create(); + VirtualNetworkGatewayConnection connection = vngw.connections() + .define(connectionName) + .withSiteToSite() + .withLocalNetworkGateway(lngw) + .withSharedKey("MySecretKey") + .withTag("tag1", "value1") + .create(); Assertions.assertEquals(1, vngw.ipConfigurations().size()); Subnet subnet = vngw.ipConfigurations().iterator().next().getSubnet(); @@ -202,49 +193,39 @@ public VirtualNetworkGateway createResource(final VirtualNetworkGateways gateway // Create virtual network gateway final List gws = new ArrayList<>(); - Mono vngwObservable = - gateways - .define(gatewayName1) - .withRegion(region) - .withNewResourceGroup(groupName) - .withNewNetwork(networkName, "10.11.0.0/16", "10.11.255.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .createAsync(); - - Mono vngw2Observable = - gateways - .define(gatewayName2) - .withRegion(region) - .withNewResourceGroup(groupName) - .withNewNetwork(networkName + "2", "10.41.0.0/16", "10.41.255.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .createAsync(); + Mono vngwObservable = gateways.define(gatewayName1) + .withRegion(region) + .withNewResourceGroup(groupName) + .withNewNetwork(networkName, "10.11.0.0/16", "10.11.255.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .createAsync(); + + Mono vngw2Observable = gateways.define(gatewayName2) + .withRegion(region) + .withNewResourceGroup(groupName) + .withNewNetwork(networkName + "2", "10.41.0.0/16", "10.41.255.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .createAsync(); Flux vngw2ObservableSleep = Mono.delay(Duration.ofSeconds(10)).thenMany(vngw2Observable); - Flux - .merge(vngwObservable, vngw2ObservableSleep) - .map( - obj -> { - if (obj instanceof VirtualNetworkGateway) { - gws.add((VirtualNetworkGateway) obj); - } - return obj; - }) - .blockLast(); + Flux.merge(vngwObservable, vngw2ObservableSleep).map(obj -> { + if (obj instanceof VirtualNetworkGateway) { + gws.add((VirtualNetworkGateway) obj); + } + return obj; + }).blockLast(); VirtualNetworkGateway vngw1 = gws.get(0); VirtualNetworkGateway vngw2 = gws.get(1); - vngw1 - .connections() + vngw1.connections() .define(connectionName) .withVNetToVNet() .withSecondVirtualNetworkGateway(vngw2) .withSharedKey("MySecretKey") .create(); - vngw2 - .connections() + vngw2.connections() .define(connectionName + "2") .withVNetToVNet() .withSecondVirtualNetworkGateway(vngw1) @@ -285,46 +266,39 @@ public VirtualNetworkGateway createResource(final VirtualNetworkGateways gateway // Create virtual network gateway initializeResourceNames(gateways.manager().resourceManager().internalContext()); - Network network = - gateways - .manager() - .networks() - .define(networkName) - .withRegion(region) - .withNewResourceGroup(groupName) - .withAddressSpace("192.168.0.0/16") - .withAddressSpace("10.254.0.0/16") - .withSubnet("GatewaySubnet", "192.168.200.0/24") - .withSubnet("FrontEnd", "192.168.1.0/24") - .withSubnet("BackEnd", "10.254.1.0/24") - .create(); - VirtualNetworkGateway vngw1 = - gateways - .define(gatewayName1) - .withRegion(region) - .withExistingResourceGroup(groupName) - .withExistingNetwork(network) - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); - - vngw1 - .update() + Network network = gateways.manager() + .networks() + .define(networkName) + .withRegion(region) + .withNewResourceGroup(groupName) + .withAddressSpace("192.168.0.0/16") + .withAddressSpace("10.254.0.0/16") + .withSubnet("GatewaySubnet", "192.168.200.0/24") + .withSubnet("FrontEnd", "192.168.1.0/24") + .withSubnet("BackEnd", "10.254.1.0/24") + .create(); + VirtualNetworkGateway vngw1 = gateways.define(gatewayName1) + .withRegion(region) + .withExistingResourceGroup(groupName) + .withExistingNetwork(network) + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); + + vngw1.update() .definePointToSiteConfiguration() .withAddressPool("172.16.201.0/24") - .withAzureCertificateFromFile( - certificateName, new File(getClass().getClassLoader().getResource(certificateName).getFile())) + .withAzureCertificateFromFile(certificateName, + new File(getClass().getClassLoader().getResource(certificateName).getFile())) .attach() .apply(); Assertions.assertNotNull(vngw1.vpnClientConfiguration()); - Assertions - .assertEquals( - "172.16.201.0/24", vngw1.vpnClientConfiguration().vpnClientAddressPool().addressPrefixes().get(0)); + Assertions.assertEquals("172.16.201.0/24", + vngw1.vpnClientConfiguration().vpnClientAddressPool().addressPrefixes().get(0)); Assertions.assertEquals(1, vngw1.vpnClientConfiguration().vpnClientRootCertificates().size()); - Assertions - .assertEquals( - certificateName, vngw1.vpnClientConfiguration().vpnClientRootCertificates().get(0).name()); + Assertions.assertEquals(certificateName, + vngw1.vpnClientConfiguration().vpnClientRootCertificates().get(0).name()); // contains credential in the profile string String profile = vngw1.generateVpnProfile(); @@ -334,15 +308,13 @@ certificateName, new File(getClass().getClassLoader().getResource(certificateNam @Override public VirtualNetworkGateway updateResource(VirtualNetworkGateway vngw1) throws Exception { - vngw1 - .update() + vngw1.update() .updatePointToSiteConfiguration() .withRevokedCertificate(certificateName, "bdf834528f0fff6eaae4c154e06b54322769276c") .parent() .apply(); - Assertions - .assertEquals( - certificateName, vngw1.vpnClientConfiguration().vpnClientRevokedCertificates().get(0).name()); + Assertions.assertEquals(certificateName, + vngw1.vpnClientConfiguration().vpnClientRevokedCertificates().get(0).name()); vngw1.update().updatePointToSiteConfiguration().withoutAzureCertificate(certificateName).parent().apply(); Assertions.assertEquals(0, vngw1.vpnClientConfiguration().vpnClientRootCertificates().size()); @@ -352,8 +324,7 @@ public VirtualNetworkGateway updateResource(VirtualNetworkGateway vngw1) throws static void printVirtualNetworkGateway(VirtualNetworkGateway gateway) { StringBuilder info = new StringBuilder(); - info - .append("Virtual Network Gateway: ") + info.append("Virtual Network Gateway: ") .append(gateway.id()) .append("\n\tName: ") .append(gateway.name()) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualMachineEncryptionTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualMachineEncryptionTests.java index ba9e3318ff6b5..db5de4bc96589 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualMachineEncryptionTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualMachineEncryptionTests.java @@ -29,11 +29,12 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { DiskEncryptionSet diskEncryptionSet = createDiskEncryptionSet("des1", DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, vaultAndKey); - DiskEncryptionSet diskEncryptionSet2 = createDiskEncryptionSet("des2", - DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vaultAndKey); + DiskEncryptionSet diskEncryptionSet2 + = createDiskEncryptionSet("des2", DiskEncryptionSetType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, vaultAndKey); // create disk - Disk disk1 = azureResourceManager.disks().define("disk1") + Disk disk1 = azureResourceManager.disks() + .define("disk1") .withRegion(region) .withExistingResourceGroup(rgName) .withData() @@ -41,13 +42,15 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { .withDiskEncryptionSet(diskEncryptionSet.id()) .create(); - Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, disk1.encryption().type()); + Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, + disk1.encryption().type()); assertResourceIdEquals(diskEncryptionSet.id(), disk1.encryption().diskEncryptionSetId()); final String vmName = "javavm"; // create virtual machine - VirtualMachine vm = azureResourceManager.virtualMachines().define(vmName) + VirtualMachine vm = azureResourceManager.virtualMachines() + .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/27") @@ -56,9 +59,8 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testuser") .withSsh(sshPublicKey()) - .withNewDataDisk(16, 0, new VirtualMachineDiskOptions() - .withDeleteOptions(DeleteOptions.DETACH) - .withDiskEncryptionSet(null)) + .withNewDataDisk(16, 0, + new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DETACH).withDiskEncryptionSet(null)) .withExistingDataDisk(disk1) .withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE) .withDataDiskDefaultDiskEncryptionSet(diskEncryptionSet.id()) @@ -75,7 +77,8 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { Assertions.assertEquals(DeleteOptions.DELETE, vm.dataDisks().get(1).deleteOptions()); // create disk with disk encryption set - Disk disk2 = azureResourceManager.disks().define("disk2") + Disk disk2 = azureResourceManager.disks() + .define("disk2") .withRegion(region) .withExistingResourceGroup(rgName) .withData() @@ -86,18 +89,19 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { Assertions.assertNull(disk2.encryption().diskEncryptionSetId()); disk2.update() - .withDiskEncryptionSet(diskEncryptionSet.id(), EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS) + .withDiskEncryptionSet(diskEncryptionSet.id(), + EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS) .apply(); - Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, disk2.encryption().type()); + Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, + disk2.encryption().type()); assertResourceIdEquals(diskEncryptionSet.id(), disk2.encryption().diskEncryptionSetId()); // update virtual machine vm.update() .withoutDataDisk(0) .withoutDataDisk(1) - .withExistingDataDisk(disk2, 32, 2, new VirtualMachineDiskOptions() - .withDeleteOptions(DeleteOptions.DELETE)) + .withExistingDataDisk(disk2, 32, 2, new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE)) .withNewDataDisk(16, 3, CachingTypes.NONE) .withDataDiskDefaultDeleteOptions(DeleteOptions.DETACH) .apply(); @@ -112,7 +116,8 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { vm.deallocate(); Disk disk = azureResourceManager.disks().getById(vm.dataDisks().get(3).id()); disk.update() - .withDiskEncryptionSet(diskEncryptionSet.id(), EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS) + .withDiskEncryptionSet(diskEncryptionSet.id(), + EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS) .apply(); vm.start(); vm.refresh(); @@ -122,9 +127,9 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { vm.update() .withoutDataDisk(2) .withoutDataDisk(3) - .withNewDataDisk(16, 0, new VirtualMachineDiskOptions() - .withDeleteOptions(DeleteOptions.DELETE) - .withDiskEncryptionSet(diskEncryptionSet.id())) + .withNewDataDisk(16, 0, + new VirtualMachineDiskOptions().withDeleteOptions(DeleteOptions.DELETE) + .withDiskEncryptionSet(diskEncryptionSet.id())) .withNewDataDisk(32, 1, CachingTypes.NONE) .withDataDiskDefaultDiskEncryptionSet(diskEncryptionSet2.id()) .apply(); @@ -135,7 +140,8 @@ public void canCreateVirtualMachineWithDiskEncryptionSet() { Assertions.assertEquals(DeleteOptions.DETACH, vm.dataDisks().get(1).deleteOptions()); disk = azureResourceManager.disks().getById(vm.dataDisks().get(0).id()); - Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, disk.encryption().type()); + Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_AND_CUSTOMER_KEYS, + disk.encryption().type()); disk = azureResourceManager.disks().getById(vm.dataDisks().get(1).id()); Assertions.assertEquals(EncryptionType.ENCRYPTION_AT_REST_WITH_CUSTOMER_KEY, disk.encryption().type()); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualNetworkGatewayTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualNetworkGatewayTests.java index 7852d3d8fc3f0..01d71c216a84a 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualNetworkGatewayTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/VirtualNetworkGatewayTests.java @@ -34,21 +34,10 @@ public class VirtualNetworkGatewayTests extends ResourceManagerTestProxyTestBase private AzureResourceManager azureResourceManager; @Override - protected HttpPipeline buildHttpPipeline( - TokenCredential credential, - AzureProfile profile, - HttpLogOptions httpLogOptions, - List policies, - HttpClient httpClient) { - return HttpPipelineProvider.buildHttpPipeline( - credential, - profile, - null, - httpLogOptions, - null, - new RetryPolicy("Retry-After", ChronoUnit.SECONDS), - policies, - httpClient); + protected HttpPipeline buildHttpPipeline(TokenCredential credential, AzureProfile profile, + HttpLogOptions httpLogOptions, List policies, HttpClient httpClient) { + return HttpPipelineProvider.buildHttpPipeline(credential, profile, null, httpLogOptions, null, + new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override @@ -75,71 +64,58 @@ public void testNetworkWatcherTroubleshooting() throws Exception { Region region = nw.region(); String resourceGroup = nw.resourceGroupName(); - VirtualNetworkGateway vngw1 = - azureResourceManager - .virtualNetworkGateways() - .define(gatewayName) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewNetwork("10.11.0.0/16", "10.11.255.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); - - VirtualNetworkGateway vngw2 = - azureResourceManager - .virtualNetworkGateways() - .define(gatewayName + "2") - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .withNewNetwork("10.41.0.0/16", "10.41.255.0/27") - .withRouteBasedVpn() - .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) - .create(); - VirtualNetworkGatewayConnection connection1 = - vngw1 - .connections() - .define(connectionName) - .withVNetToVNet() - .withSecondVirtualNetworkGateway(vngw2) - .withSharedKey("MySecretKey") - .create(); + VirtualNetworkGateway vngw1 = azureResourceManager.virtualNetworkGateways() + .define(gatewayName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewNetwork("10.11.0.0/16", "10.11.255.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); + + VirtualNetworkGateway vngw2 = azureResourceManager.virtualNetworkGateways() + .define(gatewayName + "2") + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewNetwork("10.41.0.0/16", "10.41.255.0/27") + .withRouteBasedVpn() + .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) + .create(); + VirtualNetworkGatewayConnection connection1 = vngw1.connections() + .define(connectionName) + .withVNetToVNet() + .withSecondVirtualNetworkGateway(vngw2) + .withSharedKey("MySecretKey") + .create(); // Create storage account to store troubleshooting information - StorageAccount storageAccount = - azureResourceManager - .storageAccounts() - .define("sa" + generateRandomResourceName("", 8)) - .withRegion(region) - .withExistingResourceGroup(resourceGroup) - .create(); + StorageAccount storageAccount = azureResourceManager.storageAccounts() + .define("sa" + generateRandomResourceName("", 8)) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .create(); // Troubleshoot connection - Troubleshooting troubleshooting = - nw - .troubleshoot() - .withTargetResourceId(connection1.id()) - .withStorageAccount(storageAccount.id()) - .withStoragePath(storageAccount.endPoints().primary().blob() + "results") - .execute(); + Troubleshooting troubleshooting = nw.troubleshoot() + .withTargetResourceId(connection1.id()) + .withStorageAccount(storageAccount.id()) + .withStoragePath(storageAccount.endPoints().primary().blob() + "results") + .execute(); Assertions.assertEquals("UnHealthy", troubleshooting.code()); // Create corresponding connection on second gateway to make it work - vngw2 - .connections() + vngw2.connections() .define(connectionName + "2") .withVNetToVNet() .withSecondVirtualNetworkGateway(vngw1) .withSharedKey("MySecretKey") .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(250)); - troubleshooting = - nw - .troubleshoot() - .withTargetResourceId(connection1.id()) - .withStorageAccount(storageAccount.id()) - .withStoragePath(storageAccount.endPoints().primary().blob() + "results") - .execute(); + troubleshooting = nw.troubleshoot() + .withTargetResourceId(connection1.id()) + .withStorageAccount(storageAccount.id()) + .withStoragePath(storageAccount.endPoints().primary().blob() + "results") + .execute(); Assertions.assertEquals("Healthy", troubleshooting.code()); azureResourceManager.resourceGroups().deleteByName(resourceGroup);