├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── pom.xml └── src └── main └── java └── com └── microsoft └── azure └── management ├── graphrbac └── samples │ └── ManageServicePrincipalCredentials.java └── samples └── Utils.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Auth filed 4 | *.auth 5 | *.azureauth 6 | 7 | # Mobile Tools for Java (J2ME) 8 | .mtj.tmp/ 9 | 10 | # Package Files # 11 | *.jar 12 | *.war 13 | *.ear 14 | 15 | # Azure Tooling # 16 | node_modules 17 | packages 18 | 19 | # Eclipse # 20 | *.pydevproject 21 | .project 22 | .metadata 23 | bin/** 24 | tmp/** 25 | tmp/**/* 26 | *.tmp 27 | *.bak 28 | *.swp 29 | *~.nib 30 | local.properties 31 | .classpath 32 | .settings/ 33 | .loadpath 34 | 35 | # Other Tooling # 36 | .classpath 37 | .project 38 | target/ 39 | .idea 40 | *.iml 41 | 42 | # Mac OS # 43 | .DS_Store 44 | .DS_Store? 45 | 46 | # Windows # 47 | Thumbs.db 48 | 49 | # reduced pom files should not be included 50 | dependency-reduced-pom.xml -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure samples 2 | 3 | Thank you for your interest in contributing to Azure samples! 4 | 5 | ## Ways to contribute 6 | 7 | You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways: 8 | 9 | - Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/aad-java-manage-passwords/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/aad-java-manage-passwords/issues) on GitHub. We are actively monitoring the issues and improving our samples. 11 | - If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - java 5 | products: 6 | - azure 7 | description: "Azure service principal sample for managing its credentials." 8 | urlFragment: getting-started-graphrbac 9 | --- 10 | 11 | # Getting Started with Graphrbac - Manage Service Principal Credentials - in Java 12 | 13 | 14 | Azure service principal sample for managing its credentials. 15 | - Create an application with 2 passwords and 1 certificate credentials 16 | - Create an associated service principal with contributor role 17 | - Verify all password credentials and certificate credentials are valid 18 | - Revoke access of a password credential 19 | - Verify the password credential is no longer valid 20 | - Revoke the role assignment 21 | - Verify the remaining password credential is invalid 22 | 23 | 24 | ## Running this Sample ## 25 | 26 | To run this sample: 27 | 28 | Set the environment variable `AZURE_AUTH_LOCATION` with the full path for an auth file. See [how to create an auth file](https://github.com/Azure/azure-libraries-for-java/blob/master/AUTH.md). 29 | 30 | git clone https://github.com/Azure-Samples/aad-java-manage-passwords.git 31 | 32 | cd aad-java-manage-passwords 33 | 34 | mvn clean compile exec:java 35 | 36 | ## More information ## 37 | 38 | [http://azure.com/java](http://azure.com/java) 39 | 40 | If you don't have a Microsoft Azure subscription you can get a FREE trial account [here](http://go.microsoft.com/fwlink/?LinkId=330212) 41 | 42 | --- 43 | 44 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 45 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.microsoft.azure 6 | aad-java-manage-passwords 7 | 0.0.1-SNAPSHOT 8 | ManageServicePrincipalCredentials.java 9 | 10 | https://github.com/Azure/aad-java-manage-passwords 11 | 12 | 13 | 14 | org.codehaus.mojo 15 | exec-maven-plugin 16 | 1.4.0 17 | 18 | com.microsoft.azure.management.graphrbac.samples.ManageServicePrincipalCredentials 19 | 20 | 21 | 22 | maven-compiler-plugin 23 | 3.0 24 | 25 | 1.7 26 | 1.7 27 | 28 | 29 | 30 | maven-assembly-plugin 31 | 32 | 33 | package 34 | 35 | attached 36 | 37 | 38 | 39 | jar-with-dependencies 40 | 41 | 42 | 43 | com.microsoft.azure.management.graphrbac.samples.ManageServicePrincipalCredentials.java 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | com.microsoft.azure 55 | azure 56 | 1.22.0 57 | 58 | 59 | commons-net 60 | commons-net 61 | 3.3 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /src/main/java/com/microsoft/azure/management/graphrbac/samples/ManageServicePrincipalCredentials.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for 4 | * license information. 5 | */ 6 | package com.microsoft.azure.management.graphrbac.samples; 7 | 8 | import com.google.common.io.ByteStreams; 9 | import com.microsoft.azure.AzureEnvironment; 10 | import com.microsoft.azure.credentials.ApplicationTokenCredentials; 11 | import com.microsoft.azure.management.Azure; 12 | import com.microsoft.azure.management.graphrbac.BuiltInRole; 13 | import com.microsoft.azure.management.graphrbac.RoleAssignment; 14 | import com.microsoft.azure.management.graphrbac.ServicePrincipal; 15 | import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; 16 | import com.microsoft.azure.management.samples.Utils; 17 | import com.microsoft.rest.LogLevel; 18 | import org.joda.time.Duration; 19 | 20 | import java.io.File; 21 | 22 | /** 23 | * Azure service principal sample for managing its credentials. 24 | * - Create an application with 2 passwords and 1 certificate credentials 25 | * - Create an associated service principal with contributor role 26 | * - Verify all password credentials and certificate credentials are valid 27 | * - Revoke access of a password credential 28 | * - Verify the password credential is no longer valid 29 | * - Revoke the role assignment 30 | * - Verify the remaining password credential is invalid 31 | */ 32 | public final class ManageServicePrincipalCredentials { 33 | /** 34 | * Main function which runs the actual sample. 35 | * 36 | * @param authenticated instance of Authenticated 37 | * @param defaultSubscription default subscription id 38 | * @param environment the environment the sample is running in 39 | * @return true if sample runs successfully 40 | */ 41 | public static boolean runSample(Azure.Authenticated authenticated, String defaultSubscription, AzureEnvironment environment) { 42 | final String spName = Utils.createRandomName("sp"); 43 | final String appName = SdkContext.randomResourceName("app", 20); 44 | final String appUrl = "https://" + appName; 45 | final String passwordName1 = SdkContext.randomResourceName("password", 20); 46 | final String password1 = "P@ssw0rd"; 47 | final String passwordName2 = SdkContext.randomResourceName("password", 20); 48 | final String password2 = "StrongP@ss!12"; 49 | final String certName1 = SdkContext.randomResourceName("cert", 20); 50 | final String raName = SdkContext.randomUuid(); 51 | String servicePrincipalId = ""; 52 | try { 53 | // ============================================================ 54 | // Create service principal 55 | 56 | System.out.println("Creating an Active Directory service principal " + spName + "..."); 57 | 58 | ServicePrincipal servicePrincipal = authenticated.servicePrincipals() 59 | .define(spName) 60 | .withNewApplication(appUrl) 61 | .definePasswordCredential(passwordName1) 62 | .withPasswordValue(password1) 63 | .attach() 64 | .definePasswordCredential(passwordName2) 65 | .withPasswordValue(password2) 66 | .attach() 67 | .defineCertificateCredential(certName1) 68 | .withAsymmetricX509Certificate() 69 | .withPublicKey(ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer"))) 70 | .withDuration(Duration.standardDays(1)) 71 | .attach() 72 | .create(); 73 | 74 | System.out.println("Created service principal " + spName + "."); 75 | Utils.print(servicePrincipal); 76 | servicePrincipalId = servicePrincipal.id(); 77 | 78 | // ============================================================ 79 | // Create role assignment 80 | 81 | System.out.println("Creating a Contributor role assignment " + raName + " for the service principal..."); 82 | 83 | SdkContext.sleep(15000); 84 | 85 | RoleAssignment roleAssignment = authenticated.roleAssignments() 86 | .define(raName) 87 | .forServicePrincipal(servicePrincipal) 88 | .withBuiltInRole(BuiltInRole.CONTRIBUTOR) 89 | .withSubscriptionScope(defaultSubscription) 90 | .create(); 91 | 92 | System.out.println("Created role assignment " + raName + "."); 93 | Utils.print(roleAssignment); 94 | 95 | // ============================================================ 96 | // Verify the credentials are valid 97 | 98 | System.out.println("Verifying password credential " + passwordName1 + " is valid..."); 99 | 100 | ApplicationTokenCredentials testCredential = new ApplicationTokenCredentials( 101 | servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment); 102 | try { 103 | Azure.authenticate(testCredential).withDefaultSubscription(); 104 | 105 | System.out.println("Verified " + passwordName1 + " is valid."); 106 | } catch (Exception e) { 107 | System.out.println("Failed to verify " + passwordName1 + " is valid."); 108 | } 109 | 110 | System.out.println("Verifying password credential " + passwordName2 + " is valid..."); 111 | 112 | testCredential = new ApplicationTokenCredentials( 113 | servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment); 114 | try { 115 | Azure.authenticate(testCredential).withDefaultSubscription(); 116 | 117 | System.out.println("Verified " + passwordName2 + " is valid."); 118 | } catch (Exception e) { 119 | System.out.println("Failed to verify " + passwordName2 + " is valid."); 120 | } 121 | 122 | System.out.println("Verifying certificate credential " + certName1 + " is valid..."); 123 | 124 | testCredential = new ApplicationTokenCredentials( 125 | servicePrincipal.applicationId(), 126 | authenticated.tenantId(), 127 | ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.pfx")), 128 | "Abc123", 129 | environment); 130 | try { 131 | Azure.authenticate(testCredential).withDefaultSubscription(); 132 | 133 | System.out.println("Verified " + certName1 + " is valid."); 134 | } catch (Exception e) { 135 | System.out.println("Failed to verify " + certName1 + " is valid."); 136 | } 137 | 138 | // ============================================================ 139 | // Revoke access of the 1st password credential 140 | System.out.println("Revoking access for password credential " + passwordName1 + "..."); 141 | 142 | servicePrincipal.update() 143 | .withoutCredential(passwordName1) 144 | .apply(); 145 | 146 | SdkContext.sleep(15000); 147 | 148 | System.out.println("Credential revoked."); 149 | 150 | // ============================================================ 151 | // Verify the revoked password credential is no longer valid 152 | 153 | System.out.println("Verifying password credential " + passwordName1 + " is revoked..."); 154 | 155 | testCredential = new ApplicationTokenCredentials( 156 | servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment); 157 | try { 158 | Azure.authenticate(testCredential).withDefaultSubscription(); 159 | 160 | System.out.println("Failed to verify " + passwordName1 + " is revoked."); 161 | } catch (Exception e) { 162 | System.out.println("Verified " + passwordName1 + " is revoked."); 163 | } 164 | 165 | // ============================================================ 166 | // Revoke the role assignment 167 | 168 | System.out.println("Revoking role assignment " + raName + "..."); 169 | 170 | authenticated.roleAssignments().deleteById(roleAssignment.id()); 171 | 172 | SdkContext.sleep(5000); 173 | 174 | // ============================================================ 175 | // Verify the revoked password credential is no longer valid 176 | 177 | System.out.println("Verifying password credential " + passwordName2 + " has no access to subscription..."); 178 | 179 | testCredential = new ApplicationTokenCredentials( 180 | servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment); 181 | try { 182 | Azure.authenticate(testCredential).withDefaultSubscription() 183 | .resourceGroups().list(); 184 | 185 | System.out.println("Failed to verify " + passwordName2 + " has no access to subscription."); 186 | } catch (Exception e) { 187 | System.out.println("Verified " + passwordName2 + " has no access to subscription."); 188 | } 189 | 190 | 191 | return true; 192 | } catch (Exception f) { 193 | System.out.println(f.getMessage()); 194 | f.printStackTrace(); 195 | } finally { 196 | try { 197 | System.out.println("Deleting application: " + appName); 198 | authenticated.servicePrincipals().deleteById(servicePrincipalId); 199 | System.out.println("Deleted application: " + appName); 200 | } 201 | catch (Exception e) { 202 | System.out.println("Did not create applications in Azure. No clean up is necessary"); 203 | } 204 | } 205 | return false; 206 | } 207 | 208 | /** 209 | * Main entry point. 210 | * 211 | * @param args the parameters 212 | */ 213 | public static void main(String[] args) { 214 | try { 215 | final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); 216 | ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile); 217 | Azure.Authenticated authenticated = Azure.configure() 218 | .withLogLevel(LogLevel.BASIC) 219 | .authenticate(credentials); 220 | 221 | runSample(authenticated, credentials.defaultSubscriptionId(), credentials.environment()); 222 | } catch (Exception e) { 223 | System.out.println(e.getMessage()); 224 | e.printStackTrace(); 225 | } 226 | } 227 | 228 | private ManageServicePrincipalCredentials() { 229 | } 230 | } -------------------------------------------------------------------------------- /src/main/java/com/microsoft/azure/management/samples/Utils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for 4 | * license information. 5 | */ 6 | 7 | package com.microsoft.azure.management.samples; 8 | 9 | import com.google.common.base.Joiner; 10 | import com.microsoft.azure.CloudException; 11 | import com.microsoft.azure.PagedList; 12 | import com.microsoft.azure.management.appservice.AppServiceCertificateOrder; 13 | import com.microsoft.azure.management.appservice.AppServiceDomain; 14 | import com.microsoft.azure.management.appservice.AppServicePlan; 15 | import com.microsoft.azure.management.appservice.AppSetting; 16 | import com.microsoft.azure.management.appservice.ConnectionString; 17 | import com.microsoft.azure.management.appservice.Contact; 18 | import com.microsoft.azure.management.appservice.HostNameBinding; 19 | import com.microsoft.azure.management.appservice.HostNameSslState; 20 | import com.microsoft.azure.management.appservice.PublishingProfile; 21 | import com.microsoft.azure.management.appservice.SslState; 22 | import com.microsoft.azure.management.appservice.WebAppBase; 23 | import com.microsoft.azure.management.batch.Application; 24 | import com.microsoft.azure.management.batch.ApplicationPackage; 25 | import com.microsoft.azure.management.batch.BatchAccount; 26 | import com.microsoft.azure.management.batch.BatchAccountKeys; 27 | import com.microsoft.azure.management.batchai.AzureFileShareReference; 28 | import com.microsoft.azure.management.batchai.BatchAICluster; 29 | import com.microsoft.azure.management.batchai.BatchAIJob; 30 | import com.microsoft.azure.management.compute.AvailabilitySet; 31 | import com.microsoft.azure.management.compute.DataDisk; 32 | import com.microsoft.azure.management.compute.ImageDataDisk; 33 | import com.microsoft.azure.management.compute.VirtualMachine; 34 | import com.microsoft.azure.management.compute.VirtualMachineCustomImage; 35 | import com.microsoft.azure.management.compute.VirtualMachineExtension; 36 | import com.microsoft.azure.management.containerinstance.Container; 37 | import com.microsoft.azure.management.containerinstance.ContainerGroup; 38 | import com.microsoft.azure.management.containerinstance.ContainerPort; 39 | import com.microsoft.azure.management.containerinstance.EnvironmentVariable; 40 | import com.microsoft.azure.management.containerinstance.Volume; 41 | import com.microsoft.azure.management.containerinstance.VolumeMount; 42 | import com.microsoft.azure.management.containerregistry.AccessKeyType; 43 | import com.microsoft.azure.management.containerregistry.Registry; 44 | import com.microsoft.azure.management.containerregistry.RegistryCredentials; 45 | import com.microsoft.azure.management.containerservice.ContainerService; 46 | import com.microsoft.azure.management.containerservice.ContainerServiceOrchestratorTypes; 47 | import com.microsoft.azure.management.containerservice.KubernetesCluster; 48 | import com.microsoft.azure.management.cosmosdb.CosmosDBAccount; 49 | import com.microsoft.azure.management.cosmosdb.DatabaseAccountListKeysResult; 50 | import com.microsoft.azure.management.cosmosdb.DatabaseAccountListReadOnlyKeysResult; 51 | import com.microsoft.azure.management.dns.ARecordSet; 52 | import com.microsoft.azure.management.dns.AaaaRecordSet; 53 | import com.microsoft.azure.management.dns.CNameRecordSet; 54 | import com.microsoft.azure.management.dns.DnsZone; 55 | import com.microsoft.azure.management.dns.MXRecordSet; 56 | import com.microsoft.azure.management.dns.MxRecord; 57 | import com.microsoft.azure.management.dns.NSRecordSet; 58 | import com.microsoft.azure.management.dns.PtrRecordSet; 59 | import com.microsoft.azure.management.dns.SoaRecord; 60 | import com.microsoft.azure.management.dns.SoaRecordSet; 61 | import com.microsoft.azure.management.dns.SrvRecord; 62 | import com.microsoft.azure.management.dns.SrvRecordSet; 63 | import com.microsoft.azure.management.dns.TxtRecord; 64 | import com.microsoft.azure.management.dns.TxtRecordSet; 65 | import com.microsoft.azure.management.eventhub.EventHubDisasterRecoveryPairing; 66 | import com.microsoft.azure.management.eventhub.EventHubNamespace; 67 | import com.microsoft.azure.management.eventhub.EventHub; 68 | import com.microsoft.azure.management.eventhub.DisasterRecoveryPairingAuthorizationRule; 69 | import com.microsoft.azure.management.eventhub.DisasterRecoveryPairingAuthorizationKey; 70 | import com.microsoft.azure.management.eventhub.EventHubConsumerGroup; 71 | import com.microsoft.azure.management.graphrbac.ActiveDirectoryApplication; 72 | import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; 73 | import com.microsoft.azure.management.graphrbac.ActiveDirectoryObject; 74 | import com.microsoft.azure.management.graphrbac.ActiveDirectoryUser; 75 | import com.microsoft.azure.management.graphrbac.RoleAssignment; 76 | import com.microsoft.azure.management.graphrbac.RoleDefinition; 77 | import com.microsoft.azure.management.graphrbac.ServicePrincipal; 78 | import com.microsoft.azure.management.graphrbac.Permission; 79 | import com.microsoft.azure.management.keyvault.AccessPolicy; 80 | import com.microsoft.azure.management.keyvault.Vault; 81 | import com.microsoft.azure.management.locks.ManagementLock; 82 | import com.microsoft.azure.management.monitor.ActionGroup; 83 | import com.microsoft.azure.management.monitor.ActivityLogAlert; 84 | import com.microsoft.azure.management.monitor.AutomationRunbookReceiver; 85 | import com.microsoft.azure.management.monitor.AzureAppPushReceiver; 86 | import com.microsoft.azure.management.monitor.AzureFunctionReceiver; 87 | import com.microsoft.azure.management.monitor.DiagnosticSetting; 88 | import com.microsoft.azure.management.monitor.EmailReceiver; 89 | import com.microsoft.azure.management.monitor.ItsmReceiver; 90 | import com.microsoft.azure.management.monitor.LogSettings; 91 | import com.microsoft.azure.management.monitor.LogicAppReceiver; 92 | import com.microsoft.azure.management.monitor.MetricAlert; 93 | import com.microsoft.azure.management.monitor.MetricAlertCondition; 94 | import com.microsoft.azure.management.monitor.MetricDimension; 95 | import com.microsoft.azure.management.monitor.MetricSettings; 96 | import com.microsoft.azure.management.monitor.SmsReceiver; 97 | import com.microsoft.azure.management.monitor.VoiceReceiver; 98 | import com.microsoft.azure.management.monitor.WebhookReceiver; 99 | import com.microsoft.azure.management.msi.Identity; 100 | import com.microsoft.azure.management.network.ApplicationGateway; 101 | import com.microsoft.azure.management.network.ApplicationGatewayBackend; 102 | import com.microsoft.azure.management.network.ApplicationGatewayBackendAddress; 103 | import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfiguration; 104 | import com.microsoft.azure.management.network.ApplicationGatewayFrontend; 105 | import com.microsoft.azure.management.network.ApplicationGatewayIPConfiguration; 106 | import com.microsoft.azure.management.network.ApplicationGatewayListener; 107 | import com.microsoft.azure.management.network.ApplicationGatewayProbe; 108 | import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration; 109 | import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule; 110 | import com.microsoft.azure.management.network.ApplicationGatewaySslCertificate; 111 | import com.microsoft.azure.management.network.EffectiveNetworkSecurityRule; 112 | import com.microsoft.azure.management.network.FlowLogSettings; 113 | import com.microsoft.azure.management.network.LoadBalancer; 114 | import com.microsoft.azure.management.network.LoadBalancerBackend; 115 | import com.microsoft.azure.management.network.LoadBalancerFrontend; 116 | import com.microsoft.azure.management.network.LoadBalancerHttpProbe; 117 | import com.microsoft.azure.management.network.LoadBalancerInboundNatPool; 118 | import com.microsoft.azure.management.network.LoadBalancerInboundNatRule; 119 | import com.microsoft.azure.management.network.LoadBalancerPrivateFrontend; 120 | import com.microsoft.azure.management.network.LoadBalancerProbe; 121 | import com.microsoft.azure.management.network.LoadBalancerPublicFrontend; 122 | import com.microsoft.azure.management.network.LoadBalancerTcpProbe; 123 | import com.microsoft.azure.management.network.LoadBalancingRule; 124 | import com.microsoft.azure.management.network.Network; 125 | import com.microsoft.azure.management.network.NetworkInterface; 126 | import com.microsoft.azure.management.network.NetworkPeering; 127 | import com.microsoft.azure.management.network.NetworkSecurityGroup; 128 | import com.microsoft.azure.management.network.NetworkSecurityRule; 129 | import com.microsoft.azure.management.network.NetworkWatcher; 130 | import com.microsoft.azure.management.network.NextHop; 131 | import com.microsoft.azure.management.network.PacketCapture; 132 | import com.microsoft.azure.management.network.PacketCaptureFilter; 133 | import com.microsoft.azure.management.network.PublicIPAddress; 134 | import com.microsoft.azure.management.network.RouteTable; 135 | import com.microsoft.azure.management.network.SecurityGroupNetworkInterface; 136 | import com.microsoft.azure.management.network.SecurityGroupView; 137 | import com.microsoft.azure.management.network.ServiceEndpointType; 138 | import com.microsoft.azure.management.network.Subnet; 139 | import com.microsoft.azure.management.network.Topology; 140 | import com.microsoft.azure.management.network.TopologyAssociation; 141 | import com.microsoft.azure.management.network.TopologyResource; 142 | import com.microsoft.azure.management.network.VerificationIPFlow; 143 | import com.microsoft.azure.management.network.implementation.SecurityRuleInner; 144 | import com.microsoft.azure.management.redis.RedisAccessKeys; 145 | import com.microsoft.azure.management.redis.RedisCache; 146 | import com.microsoft.azure.management.redis.RedisCachePremium; 147 | import com.microsoft.azure.management.redis.ScheduleEntry; 148 | import com.microsoft.azure.management.resources.ResourceGroup; 149 | import com.microsoft.azure.management.resources.fluentcore.arm.Region; 150 | import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; 151 | import com.microsoft.azure.management.search.AdminKeys; 152 | import com.microsoft.azure.management.search.QueryKey; 153 | import com.microsoft.azure.management.search.SearchService; 154 | import com.microsoft.azure.management.servicebus.AccessRights; 155 | import com.microsoft.azure.management.servicebus.AuthorizationKeys; 156 | import com.microsoft.azure.management.servicebus.NamespaceAuthorizationRule; 157 | import com.microsoft.azure.management.servicebus.Queue; 158 | import com.microsoft.azure.management.servicebus.QueueAuthorizationRule; 159 | import com.microsoft.azure.management.servicebus.ServiceBusNamespace; 160 | import com.microsoft.azure.management.servicebus.ServiceBusSubscription; 161 | import com.microsoft.azure.management.servicebus.Topic; 162 | import com.microsoft.azure.management.servicebus.TopicAuthorizationRule; 163 | import com.microsoft.azure.management.sql.ElasticPoolActivity; 164 | import com.microsoft.azure.management.sql.ElasticPoolDatabaseActivity; 165 | import com.microsoft.azure.management.sql.PartnerInfo; 166 | import com.microsoft.azure.management.sql.SqlDatabase; 167 | import com.microsoft.azure.management.sql.SqlDatabaseMetric; 168 | import com.microsoft.azure.management.sql.SqlDatabaseMetricValue; 169 | import com.microsoft.azure.management.sql.SqlDatabaseUsageMetric; 170 | import com.microsoft.azure.management.sql.SqlElasticPool; 171 | import com.microsoft.azure.management.sql.SqlFailoverGroup; 172 | import com.microsoft.azure.management.sql.SqlFirewallRule; 173 | import com.microsoft.azure.management.sql.SqlServer; 174 | import com.microsoft.azure.management.sql.SqlServerKey; 175 | import com.microsoft.azure.management.sql.SqlSubscriptionUsageMetric; 176 | import com.microsoft.azure.management.sql.SqlVirtualNetworkRule; 177 | import com.microsoft.azure.management.storage.StorageAccount; 178 | import com.microsoft.azure.management.storage.StorageAccountEncryptionStatus; 179 | import com.microsoft.azure.management.storage.StorageAccountKey; 180 | import com.microsoft.azure.management.storage.StorageService; 181 | import com.microsoft.azure.management.trafficmanager.TrafficManagerAzureEndpoint; 182 | import com.microsoft.azure.management.trafficmanager.TrafficManagerExternalEndpoint; 183 | import com.microsoft.azure.management.trafficmanager.TrafficManagerNestedProfileEndpoint; 184 | import com.microsoft.azure.management.trafficmanager.TrafficManagerProfile; 185 | import okhttp3.OkHttpClient; 186 | import okhttp3.Request; 187 | import org.apache.commons.lang3.StringUtils; 188 | import org.apache.commons.net.ftp.FTP; 189 | import org.apache.commons.net.ftp.FTPClient; 190 | 191 | import java.io.BufferedReader; 192 | import java.io.File; 193 | import java.io.FileInputStream; 194 | import java.io.IOException; 195 | import java.io.InputStream; 196 | import java.io.InputStreamReader; 197 | import java.util.ArrayList; 198 | import java.util.Collection; 199 | import java.util.List; 200 | import java.util.Map; 201 | import java.util.Properties; 202 | import java.util.Set; 203 | import java.util.concurrent.TimeUnit; 204 | 205 | /** 206 | * Common utils for Azure management samples. 207 | */ 208 | 209 | public final class Utils { 210 | /** 211 | * Print resource group info. 212 | * 213 | * @param resource a resource group 214 | */ 215 | public static void print(ResourceGroup resource) { 216 | StringBuilder info = new StringBuilder(); 217 | info.append("Resource Group: ").append(resource.id()) 218 | .append("\n\tName: ").append(resource.name()) 219 | .append("\n\tRegion: ").append(resource.region()) 220 | .append("\n\tTags: ").append(resource.tags()); 221 | System.out.println(info.toString()); 222 | } 223 | 224 | /** 225 | * Print User Assigned MSI info. 226 | * 227 | * @param resource a User Assigned MSI 228 | */ 229 | public static void print(Identity resource) { 230 | StringBuilder info = new StringBuilder(); 231 | info.append("Resource Group: ").append(resource.id()) 232 | .append("\n\tName: ").append(resource.name()) 233 | .append("\n\tRegion: ").append(resource.region()) 234 | .append("\n\tTags: ").append(resource.tags()) 235 | .append("\n\tService Principal Id: ").append(resource.principalId()) 236 | .append("\n\tClient Id: ").append(resource.clientId()) 237 | .append("\n\tTenant Id: ").append(resource.tenantId()) 238 | .append("\n\tClient Secret Url: ").append(resource.clientSecretUrl()); 239 | System.out.println(info.toString()); 240 | } 241 | 242 | /** 243 | * Print virtual machine info. 244 | * 245 | * @param resource a virtual machine 246 | */ 247 | public static void print(VirtualMachine resource) { 248 | 249 | StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: "); 250 | if (resource.storageProfile().imageReference() != null) { 251 | storageProfile.append("\n\t\tImageReference:"); 252 | storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher()); 253 | storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer()); 254 | storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku()); 255 | storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version()); 256 | } 257 | 258 | if (resource.storageProfile().osDisk() != null) { 259 | storageProfile.append("\n\t\tOSDisk:"); 260 | storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType()); 261 | storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name()); 262 | storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching()); 263 | storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption()); 264 | storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB()); 265 | if (resource.storageProfile().osDisk().image() != null) { 266 | storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri()); 267 | } 268 | if (resource.storageProfile().osDisk().vhd() != null) { 269 | storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri()); 270 | } 271 | if (resource.storageProfile().osDisk().encryptionSettings() != null) { 272 | storageProfile.append("\n\t\t\tEncryptionSettings: "); 273 | storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); 274 | storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource 275 | .storageProfile() 276 | .osDisk() 277 | .encryptionSettings() 278 | .diskEncryptionKey().secretUrl()); 279 | storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource 280 | .storageProfile() 281 | .osDisk() 282 | .encryptionSettings() 283 | .keyEncryptionKey().keyUrl()); 284 | } 285 | } 286 | 287 | if (resource.storageProfile().dataDisks() != null) { 288 | int i = 0; 289 | for (DataDisk disk : resource.storageProfile().dataDisks()) { 290 | storageProfile.append("\n\t\tDataDisk: #").append(i++); 291 | storageProfile.append("\n\t\t\tName: ").append(disk.name()); 292 | storageProfile.append("\n\t\t\tCaching: ").append(disk.caching()); 293 | storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption()); 294 | storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB()); 295 | storageProfile.append("\n\t\t\tLun: ").append(disk.lun()); 296 | if (resource.isManagedDiskEnabled()) { 297 | if (disk.managedDisk() != null) { 298 | storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); 299 | } 300 | } else { 301 | if (disk.vhd().uri() != null) { 302 | storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri()); 303 | } 304 | } 305 | if (disk.image() != null) { 306 | storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri()); 307 | } 308 | } 309 | } 310 | 311 | StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: "); 312 | if (resource.osProfile() != null) { 313 | osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); 314 | if (resource.osProfile().windowsConfiguration() != null) { 315 | osProfile.append("\n\t\t\tWindowsConfiguration: "); 316 | osProfile.append("\n\t\t\t\tProvisionVMAgent: ") 317 | .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); 318 | osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") 319 | .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); 320 | osProfile.append("\n\t\t\t\tTimeZone: ") 321 | .append(resource.osProfile().windowsConfiguration().timeZone()); 322 | } 323 | 324 | if (resource.osProfile().linuxConfiguration() != null) { 325 | osProfile.append("\n\t\t\tLinuxConfiguration: "); 326 | osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") 327 | .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); 328 | } 329 | } else { 330 | // OSProfile will be null for a VM attached to specialized VHD. 331 | osProfile.append("null"); 332 | } 333 | 334 | StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: "); 335 | for (String networkInterfaceId : resource.networkInterfaceIds()) { 336 | networkProfile.append("\n\t\tId:").append(networkInterfaceId); 337 | } 338 | 339 | StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); 340 | for (Map.Entry extensionEntry : resource.listExtensions().entrySet()) { 341 | VirtualMachineExtension extension = extensionEntry.getValue(); 342 | extensions.append("\n\t\tExtension: ").append(extension.id()) 343 | .append("\n\t\t\tName: ").append(extension.name()) 344 | .append("\n\t\t\tTags: ").append(extension.tags()) 345 | .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) 346 | .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) 347 | .append("\n\t\t\tPublisher: ").append(extension.publisherName()) 348 | .append("\n\t\t\tType: ").append(extension.typeName()) 349 | .append("\n\t\t\tVersion: ").append(extension.versionName()) 350 | .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); 351 | } 352 | 353 | StringBuilder msi = new StringBuilder().append("\n\tMSI: "); 354 | msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); 355 | msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); 356 | msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); 357 | 358 | StringBuilder zones = new StringBuilder().append("\n\tZones: "); 359 | zones.append(resource.availabilityZones()); 360 | 361 | System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) 362 | .append("Name: ").append(resource.name()) 363 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 364 | .append("\n\tRegion: ").append(resource.region()) 365 | .append("\n\tTags: ").append(resource.tags()) 366 | .append("\n\tHardwareProfile: ") 367 | .append("\n\t\tSize: ").append(resource.size()) 368 | .append(storageProfile) 369 | .append(osProfile) 370 | .append(networkProfile) 371 | .append(extensions) 372 | .append(msi) 373 | .append(zones) 374 | .toString()); 375 | } 376 | 377 | 378 | /** 379 | * Print availability set info. 380 | * 381 | * @param resource an availability set 382 | */ 383 | public static void print(AvailabilitySet resource) { 384 | 385 | System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) 386 | .append("Name: ").append(resource.name()) 387 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 388 | .append("\n\tRegion: ").append(resource.region()) 389 | .append("\n\tTags: ").append(resource.tags()) 390 | .append("\n\tFault domain count: ").append(resource.faultDomainCount()) 391 | .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) 392 | .toString()); 393 | } 394 | 395 | /** 396 | * Print network info. 397 | * 398 | * @param resource a network 399 | * @throws CloudException Cloud errors 400 | */ 401 | public static void print(Network resource) { 402 | StringBuilder info = new StringBuilder(); 403 | info.append("Network: ").append(resource.id()) 404 | .append("Name: ").append(resource.name()) 405 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 406 | .append("\n\tRegion: ").append(resource.region()) 407 | .append("\n\tTags: ").append(resource.tags()) 408 | .append("\n\tAddress spaces: ").append(resource.addressSpaces()) 409 | .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); 410 | 411 | // Output subnets 412 | for (Subnet subnet : resource.subnets().values()) { 413 | info.append("\n\tSubnet: ").append(subnet.name()) 414 | .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); 415 | 416 | // Output associated NSG 417 | NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); 418 | if (subnetNsg != null) { 419 | info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id()); 420 | } 421 | 422 | // Output associated route table 423 | RouteTable routeTable = subnet.getRouteTable(); 424 | if (routeTable != null) { 425 | info.append("\n\tRoute table ID: ").append(routeTable.id()); 426 | } 427 | 428 | // Output services with access 429 | Map> services = subnet.servicesWithAccess(); 430 | if (services.size() > 0) { 431 | info.append("\n\tServices with access"); 432 | for (Map.Entry> service : services.entrySet()) { 433 | info.append("\n\t\tService: ") 434 | .append(service.getKey()) 435 | .append(" Regions: " + service.getValue() + ""); 436 | } 437 | } 438 | } 439 | 440 | // Output peerings 441 | for (NetworkPeering peering : resource.peerings().list()) { 442 | info.append("\n\tPeering: ").append(peering.name()) 443 | .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) 444 | .append("\n\t\tPeering state: ").append(peering.state()) 445 | .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) 446 | .append("\n\t\tGateway use: ").append(peering.gatewayUse()); 447 | } 448 | System.out.println(info.toString()); 449 | } 450 | 451 | /** 452 | * Print network interface. 453 | * 454 | * @param resource a network interface 455 | */ 456 | public static void print(NetworkInterface resource) { 457 | StringBuilder info = new StringBuilder(); 458 | info.append("NetworkInterface: ").append(resource.id()) 459 | .append("Name: ").append(resource.name()) 460 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 461 | .append("\n\tRegion: ").append(resource.region()) 462 | .append("\n\tTags: ").append(resource.tags()) 463 | .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) 464 | .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) 465 | .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) 466 | .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) 467 | .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) 468 | .append("\n\tDNS server IPs: "); 469 | 470 | // Output dns servers 471 | for (String dnsServerIp : resource.dnsServers()) { 472 | info.append("\n\t\t").append(dnsServerIp); 473 | } 474 | 475 | info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) 476 | .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) 477 | .append("\n\tMAC Address:").append(resource.macAddress()) 478 | .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) 479 | .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIPAllocationMethod()) 480 | .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) 481 | .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); 482 | 483 | System.out.println(info.toString()); 484 | } 485 | 486 | /** 487 | * Print network security group. 488 | * 489 | * @param resource a network security group 490 | */ 491 | public static void print(NetworkSecurityGroup resource) { 492 | StringBuilder info = new StringBuilder(); 493 | info.append("NSG: ").append(resource.id()) 494 | .append("Name: ").append(resource.name()) 495 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 496 | .append("\n\tRegion: ").append(resource.region()) 497 | .append("\n\tTags: ").append(resource.tags()); 498 | 499 | // Output security rules 500 | for (NetworkSecurityRule rule : resource.securityRules().values()) { 501 | info.append("\n\tRule: ").append(rule.name()) 502 | .append("\n\t\tAccess: ").append(rule.access()) 503 | .append("\n\t\tDirection: ").append(rule.direction()) 504 | .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) 505 | .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) 506 | .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) 507 | .append("\n\t\tTo port: ").append(rule.destinationPortRange()) 508 | .append("\n\t\tProtocol: ").append(rule.protocol()) 509 | .append("\n\t\tPriority: ").append(rule.priority()); 510 | } 511 | 512 | System.out.println(info.toString()); 513 | } 514 | 515 | /** 516 | * Print public IP address. 517 | * 518 | * @param resource a public IP address 519 | */ 520 | public static void print(PublicIPAddress resource) { 521 | System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) 522 | .append("Name: ").append(resource.name()) 523 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 524 | .append("\n\tRegion: ").append(resource.region()) 525 | .append("\n\tTags: ").append(resource.tags()) 526 | .append("\n\tIP Address: ").append(resource.ipAddress()) 527 | .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) 528 | .append("\n\tFQDN: ").append(resource.fqdn()) 529 | .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) 530 | .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) 531 | .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) 532 | .append("\n\tZones: ").append(resource.availabilityZones()) 533 | .toString()); 534 | } 535 | 536 | /** 537 | * Print a key vault. 538 | * 539 | * @param vault the key vault resource 540 | */ 541 | public static void print(Vault vault) { 542 | StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) 543 | .append("Name: ").append(vault.name()) 544 | .append("\n\tResource group: ").append(vault.resourceGroupName()) 545 | .append("\n\tRegion: ").append(vault.region()) 546 | .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) 547 | .append("\n\tVault URI: ").append(vault.vaultUri()) 548 | .append("\n\tAccess policies: "); 549 | for (AccessPolicy accessPolicy : vault.accessPolicies()) { 550 | info.append("\n\t\tIdentity:").append(accessPolicy.objectId()) 551 | .append("\n\t\tKey permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().keys())) 552 | .append("\n\t\tSecret permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().secrets())); 553 | } 554 | System.out.println(info.toString()); 555 | } 556 | 557 | /** 558 | * Print storage account. 559 | * 560 | * @param storageAccount a storage account 561 | */ 562 | public static void print(StorageAccount storageAccount) { 563 | System.out.println(storageAccount.name() 564 | + " created @ " + storageAccount.creationTime()); 565 | 566 | StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) 567 | .append("Name: ").append(storageAccount.name()) 568 | .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) 569 | .append("\n\tRegion: ").append(storageAccount.region()) 570 | .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) 571 | .append("\n\tAccessTier: ").append(storageAccount.accessTier()) 572 | .append("\n\tKind: ").append(storageAccount.kind()); 573 | 574 | info.append("\n\tNetwork Rule Configuration: ") 575 | .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) 576 | .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) 577 | .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); 578 | 579 | if (storageAccount.networkSubnetsWithAccess().size() > 0) { 580 | info.append("\n\t\tNetwork subnets with access: "); 581 | for (String subnetId : storageAccount.networkSubnetsWithAccess()) { 582 | info.append("\n\t\t\t").append(subnetId); 583 | } 584 | } 585 | if (storageAccount.ipAddressesWithAccess().size() > 0) { 586 | info.append("\n\t\tIP addresses with access: "); 587 | for (String ipAddress : storageAccount.ipAddressesWithAccess()) { 588 | info.append("\n\t\t\t").append(ipAddress); 589 | } 590 | } 591 | if (storageAccount.ipAddressRangesWithAccess().size() > 0) { 592 | info.append("\n\t\tIP address-ranges with access: "); 593 | for (String ipAddressRange : storageAccount.ipAddressRangesWithAccess()) { 594 | info.append("\n\t\t\t").append(ipAddressRange); 595 | } 596 | } 597 | info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.inner().enableHttpsTrafficOnly()); 598 | 599 | info.append("\n\tEncryption status: "); 600 | for (Map.Entry eStatus : storageAccount.encryptionStatuses().entrySet()) { 601 | info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); 602 | } 603 | 604 | System.out.println(info.toString()); 605 | } 606 | 607 | /** 608 | * Print storage account keys. 609 | * 610 | * @param storageAccountKeys a list of storage account keys 611 | */ 612 | public static void print(List storageAccountKeys) { 613 | for (int i = 0; i < storageAccountKeys.size(); i++) { 614 | StorageAccountKey storageAccountKey = storageAccountKeys.get(i); 615 | System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" 616 | + storageAccountKey.value()); 617 | } 618 | } 619 | 620 | 621 | /** 622 | * Print Redis Cache. 623 | * 624 | * @param redisCache a Redis cache. 625 | */ 626 | public static void print(RedisCache redisCache) { 627 | StringBuilder redisInfo = new StringBuilder() 628 | .append("Redis Cache Name: ").append(redisCache.name()) 629 | .append("\n\tResource group: ").append(redisCache.resourceGroupName()) 630 | .append("\n\tRegion: ").append(redisCache.region()) 631 | .append("\n\tSKU Name: ").append(redisCache.sku().name()) 632 | .append("\n\tSKU Family: ").append(redisCache.sku().family()) 633 | .append("\n\tHost name: ").append(redisCache.hostName()) 634 | .append("\n\tSSL port: ").append(redisCache.sslPort()) 635 | .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); 636 | if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { 637 | redisInfo.append("\n\tRedis Configuration:"); 638 | for (Map.Entry redisConfiguration : redisCache.redisConfiguration().entrySet()) { 639 | redisInfo.append("\n\t '").append(redisConfiguration.getKey()) 640 | .append("' : '").append(redisConfiguration.getValue()).append("'"); 641 | } 642 | } 643 | if (redisCache.isPremium()) { 644 | RedisCachePremium premium = redisCache.asPremium(); 645 | List scheduleEntries = premium.listPatchSchedules(); 646 | if (scheduleEntries != null && !scheduleEntries.isEmpty()) { 647 | redisInfo.append("\n\tRedis Patch Schedule:"); 648 | for (ScheduleEntry schedule : scheduleEntries) { 649 | redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) 650 | .append("', start at: '").append(schedule.startHourUtc()) 651 | .append("', maintenance window: '").append(schedule.maintenanceWindow()) 652 | .append("'"); 653 | } 654 | } 655 | } 656 | 657 | System.out.println(redisInfo.toString()); 658 | } 659 | 660 | /** 661 | * Print Redis Cache access keys. 662 | * 663 | * @param redisAccessKeys a keys for Redis Cache 664 | */ 665 | public static void print(RedisAccessKeys redisAccessKeys) { 666 | StringBuilder redisKeys = new StringBuilder() 667 | .append("Redis Access Keys: ") 668 | .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") 669 | .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); 670 | 671 | System.out.println(redisKeys.toString()); 672 | } 673 | 674 | /** 675 | * Print management lock. 676 | * @param lock a management lock 677 | */ 678 | public static void print(ManagementLock lock) { 679 | StringBuilder info = new StringBuilder(); 680 | info.append("\nLock ID: ").append(lock.id()) 681 | .append("\nLocked resource ID: ").append(lock.lockedResourceId()) 682 | .append("\nLevel: ").append(lock.level()); 683 | System.out.println(info.toString()); 684 | } 685 | 686 | /** 687 | * Print load balancer. 688 | * 689 | * @param resource a load balancer 690 | */ 691 | public static void print(LoadBalancer resource) { 692 | StringBuilder info = new StringBuilder(); 693 | info.append("Load balancer: ").append(resource.id()) 694 | .append("Name: ").append(resource.name()) 695 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 696 | .append("\n\tRegion: ").append(resource.region()) 697 | .append("\n\tTags: ").append(resource.tags()) 698 | .append("\n\tBackends: ").append(resource.backends().keySet().toString()); 699 | 700 | // Show public IP addresses 701 | info.append("\n\tPublic IP address IDs: ") 702 | .append(resource.publicIPAddressIds().size()); 703 | for (String pipId : resource.publicIPAddressIds()) { 704 | info.append("\n\t\tPIP id: ").append(pipId); 705 | } 706 | 707 | // Show TCP probes 708 | info.append("\n\tTCP probes: ") 709 | .append(resource.tcpProbes().size()); 710 | for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { 711 | info.append("\n\t\tProbe name: ").append(probe.name()) 712 | .append("\n\t\t\tPort: ").append(probe.port()) 713 | .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) 714 | .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); 715 | 716 | // Show associated load balancing rules 717 | info.append("\n\t\t\tReferenced from load balancing rules: ") 718 | .append(probe.loadBalancingRules().size()); 719 | for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { 720 | info.append("\n\t\t\t\tName: ").append(rule.name()); 721 | } 722 | } 723 | 724 | // Show HTTP probes 725 | info.append("\n\tHTTP probes: ") 726 | .append(resource.httpProbes().size()); 727 | for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { 728 | info.append("\n\t\tProbe name: ").append(probe.name()) 729 | .append("\n\t\t\tPort: ").append(probe.port()) 730 | .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) 731 | .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) 732 | .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); 733 | 734 | // Show associated load balancing rules 735 | info.append("\n\t\t\tReferenced from load balancing rules: ") 736 | .append(probe.loadBalancingRules().size()); 737 | for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { 738 | info.append("\n\t\t\t\tName: ").append(rule.name()); 739 | } 740 | } 741 | 742 | // Show load balancing rules 743 | info.append("\n\tLoad balancing rules: ") 744 | .append(resource.loadBalancingRules().size()); 745 | for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { 746 | info.append("\n\t\tLB rule name: ").append(rule.name()) 747 | .append("\n\t\t\tProtocol: ").append(rule.protocol()) 748 | .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) 749 | .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) 750 | .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); 751 | 752 | LoadBalancerFrontend frontend = rule.frontend(); 753 | info.append("\n\t\t\tFrontend: "); 754 | if (frontend != null) { 755 | info.append(frontend.name()); 756 | } else { 757 | info.append("(None)"); 758 | } 759 | 760 | info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); 761 | 762 | LoadBalancerBackend backend = rule.backend(); 763 | info.append("\n\t\t\tBackend: "); 764 | if (backend != null) { 765 | info.append(backend.name()); 766 | } else { 767 | info.append("(None)"); 768 | } 769 | 770 | info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); 771 | 772 | LoadBalancerProbe probe = rule.probe(); 773 | info.append("\n\t\t\tProbe: "); 774 | if (probe == null) { 775 | info.append("(None)"); 776 | } else { 777 | info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); 778 | } 779 | } 780 | 781 | // Show frontends 782 | info.append("\n\tFrontends: ") 783 | .append(resource.frontends().size()); 784 | for (LoadBalancerFrontend frontend : resource.frontends().values()) { 785 | info.append("\n\t\tFrontend name: ").append(frontend.name()) 786 | .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); 787 | if (frontend.isPublic()) { 788 | info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIPAddressId()); 789 | } else { 790 | info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) 791 | .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) 792 | .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAddress()) 793 | .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAllocationMethod()); 794 | } 795 | 796 | // Inbound NAT pool references 797 | info.append("\n\t\t\tReferenced inbound NAT pools: ") 798 | .append(frontend.inboundNatPools().size()); 799 | for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { 800 | info.append("\n\t\t\t\tName: ").append(pool.name()); 801 | } 802 | 803 | // Inbound NAT rule references 804 | info.append("\n\t\t\tReferenced inbound NAT rules: ") 805 | .append(frontend.inboundNatRules().size()); 806 | for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { 807 | info.append("\n\t\t\t\tName: ").append(rule.name()); 808 | } 809 | 810 | // Load balancing rule references 811 | info.append("\n\t\t\tReferenced load balancing rules: ") 812 | .append(frontend.loadBalancingRules().size()); 813 | for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { 814 | info.append("\n\t\t\t\tName: ").append(rule.name()); 815 | } 816 | } 817 | 818 | // Show inbound NAT rules 819 | info.append("\n\tInbound NAT rules: ") 820 | .append(resource.inboundNatRules().size()); 821 | for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { 822 | info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) 823 | .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) 824 | .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) 825 | .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) 826 | .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) 827 | .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) 828 | .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIPConfigurationName()) 829 | .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) 830 | .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); 831 | } 832 | 833 | // Show inbound NAT pools 834 | info.append("\n\tInbound NAT pools: ") 835 | .append(resource.inboundNatPools().size()); 836 | for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { 837 | info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) 838 | .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) 839 | .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) 840 | .append("\n\t\t\tFrontend port range: ") 841 | .append(natPool.frontendPortRangeStart()) 842 | .append("-") 843 | .append(natPool.frontendPortRangeEnd()) 844 | .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); 845 | } 846 | 847 | // Show backends 848 | info.append("\n\tBackends: ") 849 | .append(resource.backends().size()); 850 | for (LoadBalancerBackend backend : resource.backends().values()) { 851 | info.append("\n\t\tBackend name: ").append(backend.name()); 852 | 853 | // Show assigned backend NICs 854 | info.append("\n\t\t\tReferenced NICs: ") 855 | .append(backend.backendNicIPConfigurationNames().entrySet().size()); 856 | for (Map.Entry entry : backend.backendNicIPConfigurationNames().entrySet()) { 857 | info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) 858 | .append(" - IP Config: ").append(entry.getValue()); 859 | } 860 | 861 | // Show assigned virtual machines 862 | Set vmIds = backend.getVirtualMachineIds(); 863 | info.append("\n\t\t\tReferenced virtual machine ids: ") 864 | .append(vmIds.size()); 865 | for (String vmId : vmIds) { 866 | info.append("\n\t\t\t\tVM ID: ").append(vmId); 867 | } 868 | 869 | // Show assigned load balancing rules 870 | info.append("\n\t\t\tReferenced load balancing rules: ") 871 | .append(new ArrayList(backend.loadBalancingRules().keySet())); 872 | } 873 | 874 | System.out.println(info.toString()); 875 | } 876 | 877 | /** 878 | * Prints batch account keys. 879 | * 880 | * @param batchAccountKeys a list of batch account keys 881 | */ 882 | public static void print(BatchAccountKeys batchAccountKeys) { 883 | System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" 884 | + batchAccountKeys.secondary() + ")"); 885 | } 886 | 887 | /** 888 | * Prints batch account. 889 | * 890 | * @param batchAccount a Batch Account 891 | */ 892 | public static void print(BatchAccount batchAccount) { 893 | StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); 894 | 895 | if (batchAccount.applications().size() > 0) { 896 | for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { 897 | Application application = applicationEntry.getValue(); 898 | StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); 899 | 900 | for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { 901 | ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); 902 | StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); 903 | singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); 904 | 905 | applicationPackages.append(singleApplicationPackage); 906 | singleApplicationPackage.append("\n"); 907 | } 908 | 909 | StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); 910 | singleApplication.append("\n\t\tdisplayName: " + application.displayName()); 911 | singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); 912 | singleApplication.append(applicationPackages); 913 | applicationsOutput.append(singleApplication); 914 | applicationsOutput.append("\n"); 915 | } 916 | } 917 | 918 | System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) 919 | .append("Name: ").append(batchAccount.name()) 920 | .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) 921 | .append("\n\tRegion: ").append(batchAccount.region()) 922 | .append("\n\tTags: ").append(batchAccount.tags()) 923 | .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) 924 | .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) 925 | .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) 926 | .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) 927 | .append(applicationsOutput) 928 | .toString()); 929 | } 930 | 931 | /** 932 | * Print app service domain. 933 | * 934 | * @param resource an app service domain 935 | */ 936 | public static void print(AppServiceDomain resource) { 937 | StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) 938 | .append("Name: ").append(resource.name()) 939 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 940 | .append("\n\tRegion: ").append(resource.region()) 941 | .append("\n\tCreated time: ").append(resource.createdTime()) 942 | .append("\n\tExpiration time: ").append(resource.expirationTime()) 943 | .append("\n\tContact: "); 944 | Contact contact = resource.registrantContact(); 945 | if (contact == null) { 946 | builder = builder.append("Private"); 947 | } else { 948 | builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); 949 | } 950 | builder = builder.append("\n\tName servers: "); 951 | for (String nameServer : resource.nameServers()) { 952 | builder = builder.append("\n\t\t" + nameServer); 953 | } 954 | System.out.println(builder.toString()); 955 | } 956 | 957 | /** 958 | * Print app service certificate order. 959 | * 960 | * @param resource an app service certificate order 961 | */ 962 | public static void print(AppServiceCertificateOrder resource) { 963 | StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) 964 | .append("Name: ").append(resource.name()) 965 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 966 | .append("\n\tRegion: ").append(resource.region()) 967 | .append("\n\tDistinguished name: ").append(resource.distinguishedName()) 968 | .append("\n\tProduct type: ").append(resource.productType()) 969 | .append("\n\tValid years: ").append(resource.validityInYears()) 970 | .append("\n\tStatus: ").append(resource.status()) 971 | .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) 972 | .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); 973 | System.out.println(builder.toString()); 974 | } 975 | 976 | /** 977 | * Print app service plan. 978 | * 979 | * @param resource an app service plan 980 | */ 981 | public static void print(AppServicePlan resource) { 982 | StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) 983 | .append("Name: ").append(resource.name()) 984 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 985 | .append("\n\tRegion: ").append(resource.region()) 986 | .append("\n\tPricing tier: ").append(resource.pricingTier()); 987 | System.out.println(builder.toString()); 988 | } 989 | 990 | /** 991 | * Print a web app. 992 | * 993 | * @param resource a web app 994 | */ 995 | public static void print(WebAppBase resource) { 996 | StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) 997 | .append("Name: ").append(resource.name()) 998 | .append("\n\tState: ").append(resource.state()) 999 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 1000 | .append("\n\tRegion: ").append(resource.region()) 1001 | .append("\n\tDefault hostname: ").append(resource.defaultHostName()) 1002 | .append("\n\tApp service plan: ").append(resource.appServicePlanId()) 1003 | .append("\n\tHost name bindings: "); 1004 | for (HostNameBinding binding : resource.getHostNameBindings().values()) { 1005 | builder = builder.append("\n\t\t" + binding.toString()); 1006 | } 1007 | builder = builder.append("\n\tSSL bindings: "); 1008 | for (HostNameSslState binding : resource.hostNameSslStates().values()) { 1009 | builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); 1010 | if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { 1011 | builder = builder.append(" - " + binding.thumbprint()); 1012 | } 1013 | } 1014 | builder = builder.append("\n\tApp settings: "); 1015 | for (AppSetting setting : resource.getAppSettings().values()) { 1016 | builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); 1017 | } 1018 | builder = builder.append("\n\tConnection strings: "); 1019 | for (ConnectionString conn : resource.getConnectionStrings().values()) { 1020 | builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); 1021 | } 1022 | System.out.println(builder.toString()); 1023 | } 1024 | 1025 | /** 1026 | * Print a traffic manager profile. 1027 | * 1028 | * @param profile a traffic manager profile 1029 | */ 1030 | public static void print(TrafficManagerProfile profile) { 1031 | StringBuilder info = new StringBuilder(); 1032 | info.append("Traffic Manager Profile: ").append(profile.id()) 1033 | .append("\n\tName: ").append(profile.name()) 1034 | .append("\n\tResource group: ").append(profile.resourceGroupName()) 1035 | .append("\n\tRegion: ").append(profile.regionName()) 1036 | .append("\n\tTags: ").append(profile.tags()) 1037 | .append("\n\tDNSLabel: ").append(profile.dnsLabel()) 1038 | .append("\n\tFQDN: ").append(profile.fqdn()) 1039 | .append("\n\tTTL: ").append(profile.timeToLive()) 1040 | .append("\n\tEnabled: ").append(profile.isEnabled()) 1041 | .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) 1042 | .append("\n\tMonitor status: ").append(profile.monitorStatus()) 1043 | .append("\n\tMonitoring port: ").append(profile.monitoringPort()) 1044 | .append("\n\tMonitoring path: ").append(profile.monitoringPath()); 1045 | 1046 | Map azureEndpoints = profile.azureEndpoints(); 1047 | if (!azureEndpoints.isEmpty()) { 1048 | info.append("\n\tAzure endpoints:"); 1049 | int idx = 1; 1050 | for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { 1051 | info.append("\n\t\tAzure endpoint: #").append(idx++) 1052 | .append("\n\t\t\tId: ").append(endpoint.id()) 1053 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1054 | .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) 1055 | .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) 1056 | .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) 1057 | .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) 1058 | .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) 1059 | .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); 1060 | } 1061 | } 1062 | 1063 | Map externalEndpoints = profile.externalEndpoints(); 1064 | if (!externalEndpoints.isEmpty()) { 1065 | info.append("\n\tExternal endpoints:"); 1066 | int idx = 1; 1067 | for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { 1068 | info.append("\n\t\tExternal endpoint: #").append(idx++) 1069 | .append("\n\t\t\tId: ").append(endpoint.id()) 1070 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1071 | .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) 1072 | .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) 1073 | .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) 1074 | .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) 1075 | .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) 1076 | .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); 1077 | } 1078 | } 1079 | 1080 | Map nestedProfileEndpoints = profile.nestedProfileEndpoints(); 1081 | if (!nestedProfileEndpoints.isEmpty()) { 1082 | info.append("\n\tNested profile endpoints:"); 1083 | int idx = 1; 1084 | for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { 1085 | info.append("\n\t\tNested profile endpoint: #").append(idx++) 1086 | .append("\n\t\t\tId: ").append(endpoint.id()) 1087 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1088 | .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) 1089 | .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) 1090 | .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) 1091 | .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) 1092 | .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) 1093 | .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) 1094 | .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); 1095 | } 1096 | } 1097 | System.out.println(info.toString()); 1098 | } 1099 | 1100 | /** 1101 | * Print a dns zone. 1102 | * 1103 | * @param dnsZone a dns zone 1104 | */ 1105 | public static void print(DnsZone dnsZone) { 1106 | StringBuilder info = new StringBuilder(); 1107 | info.append("DNS Zone: ").append(dnsZone.id()) 1108 | .append("\n\tName (Top level domain): ").append(dnsZone.name()) 1109 | .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) 1110 | .append("\n\tRegion: ").append(dnsZone.regionName()) 1111 | .append("\n\tTags: ").append(dnsZone.tags()) 1112 | .append("\n\tName servers:"); 1113 | for (String nameServer : dnsZone.nameServers()) { 1114 | info.append("\n\t\t").append(nameServer); 1115 | } 1116 | SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); 1117 | SoaRecord soaRecord = soaRecordSet.record(); 1118 | info.append("\n\tSOA Record:") 1119 | .append("\n\t\tHost:").append(soaRecord.host()) 1120 | .append("\n\t\tEmail:").append(soaRecord.email()) 1121 | .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) 1122 | .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) 1123 | .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) 1124 | .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) 1125 | .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); 1126 | 1127 | PagedList aRecordSets = dnsZone.aRecordSets().list(); 1128 | info.append("\n\tA Record sets:"); 1129 | for (ARecordSet aRecordSet : aRecordSets) { 1130 | info.append("\n\t\tId: ").append(aRecordSet.id()) 1131 | .append("\n\t\tName: ").append(aRecordSet.name()) 1132 | .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) 1133 | .append("\n\t\tIP v4 addresses: "); 1134 | for (String ipAddress : aRecordSet.ipv4Addresses()) { 1135 | info.append("\n\t\t\t").append(ipAddress); 1136 | } 1137 | } 1138 | 1139 | PagedList aaaaRecordSets = dnsZone.aaaaRecordSets().list(); 1140 | info.append("\n\tAAAA Record sets:"); 1141 | for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { 1142 | info.append("\n\t\tId: ").append(aaaaRecordSet.id()) 1143 | .append("\n\t\tName: ").append(aaaaRecordSet.name()) 1144 | .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) 1145 | .append("\n\t\tIP v6 addresses: "); 1146 | for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { 1147 | info.append("\n\t\t\t").append(ipAddress); 1148 | } 1149 | } 1150 | 1151 | PagedList cnameRecordSets = dnsZone.cNameRecordSets().list(); 1152 | info.append("\n\tCNAME Record sets:"); 1153 | for (CNameRecordSet cnameRecordSet : cnameRecordSets) { 1154 | info.append("\n\t\tId: ").append(cnameRecordSet.id()) 1155 | .append("\n\t\tName: ").append(cnameRecordSet.name()) 1156 | .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) 1157 | .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); 1158 | } 1159 | 1160 | PagedList mxRecordSets = dnsZone.mxRecordSets().list(); 1161 | info.append("\n\tMX Record sets:"); 1162 | for (MXRecordSet mxRecordSet : mxRecordSets) { 1163 | info.append("\n\t\tId: ").append(mxRecordSet.id()) 1164 | .append("\n\t\tName: ").append(mxRecordSet.name()) 1165 | .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) 1166 | .append("\n\t\tRecords: "); 1167 | for (MxRecord mxRecord : mxRecordSet.records()) { 1168 | info.append("\n\t\t\tExchange server, Preference: ") 1169 | .append(mxRecord.exchange()) 1170 | .append(" ") 1171 | .append(mxRecord.preference()); 1172 | } 1173 | } 1174 | 1175 | PagedList nsRecordSets = dnsZone.nsRecordSets().list(); 1176 | info.append("\n\tNS Record sets:"); 1177 | for (NSRecordSet nsRecordSet : nsRecordSets) { 1178 | info.append("\n\t\tId: ").append(nsRecordSet.id()) 1179 | .append("\n\t\tName: ").append(nsRecordSet.name()) 1180 | .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) 1181 | .append("\n\t\tName servers: "); 1182 | for (String nameServer : nsRecordSet.nameServers()) { 1183 | info.append("\n\t\t\t").append(nameServer); 1184 | } 1185 | } 1186 | 1187 | PagedList ptrRecordSets = dnsZone.ptrRecordSets().list(); 1188 | info.append("\n\tPTR Record sets:"); 1189 | for (PtrRecordSet ptrRecordSet : ptrRecordSets) { 1190 | info.append("\n\t\tId: ").append(ptrRecordSet.id()) 1191 | .append("\n\t\tName: ").append(ptrRecordSet.name()) 1192 | .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) 1193 | .append("\n\t\tTarget domain names: "); 1194 | for (String domainNames : ptrRecordSet.targetDomainNames()) { 1195 | info.append("\n\t\t\t").append(domainNames); 1196 | } 1197 | } 1198 | 1199 | PagedList srvRecordSets = dnsZone.srvRecordSets().list(); 1200 | info.append("\n\tSRV Record sets:"); 1201 | for (SrvRecordSet srvRecordSet : srvRecordSets) { 1202 | info.append("\n\t\tId: ").append(srvRecordSet.id()) 1203 | .append("\n\t\tName: ").append(srvRecordSet.name()) 1204 | .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) 1205 | .append("\n\t\tRecords: "); 1206 | for (SrvRecord srvRecord : srvRecordSet.records()) { 1207 | info.append("\n\t\t\tTarget, Port, Priority, Weight: ") 1208 | .append(srvRecord.target()) 1209 | .append(", ") 1210 | .append(srvRecord.port()) 1211 | .append(", ") 1212 | .append(srvRecord.priority()) 1213 | .append(", ") 1214 | .append(srvRecord.weight()); 1215 | } 1216 | } 1217 | 1218 | PagedList txtRecordSets = dnsZone.txtRecordSets().list(); 1219 | info.append("\n\tTXT Record sets:"); 1220 | for (TxtRecordSet txtRecordSet : txtRecordSets) { 1221 | info.append("\n\t\tId: ").append(txtRecordSet.id()) 1222 | .append("\n\t\tName: ").append(txtRecordSet.name()) 1223 | .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) 1224 | .append("\n\t\tRecords: "); 1225 | for (TxtRecord txtRecord : txtRecordSet.records()) { 1226 | if (txtRecord.value().size() > 0) { 1227 | info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); 1228 | } 1229 | } 1230 | } 1231 | System.out.println(info.toString()); 1232 | } 1233 | 1234 | /** 1235 | * Print an Azure Container Registry. 1236 | * @param azureRegistry an Azure Container Registry 1237 | */ 1238 | public static void print(Registry azureRegistry) { 1239 | StringBuilder info = new StringBuilder(); 1240 | 1241 | RegistryCredentials acrCredentials = azureRegistry.getCredentials(); 1242 | info.append("Azure Container Registry: ").append(azureRegistry.id()) 1243 | .append("\n\tName: ").append(azureRegistry.name()) 1244 | .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) 1245 | .append("\n\tUser: ").append(acrCredentials.username()) 1246 | .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) 1247 | .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); 1248 | System.out.println(info.toString()); 1249 | } 1250 | 1251 | /** 1252 | * Print an Azure Container Service. 1253 | * @param containerService an Azure Container Service 1254 | */ 1255 | public static void print(ContainerService containerService) { 1256 | StringBuilder info = new StringBuilder(); 1257 | 1258 | info.append("Azure Container Service: ").append(containerService.id()) 1259 | .append("\n\tName: ").append(containerService.name()) 1260 | .append("\n\tWith orchestration: ").append(containerService.orchestratorType().toString()) 1261 | .append("\n\tMaster FQDN: ").append(containerService.masterFqdn()) 1262 | .append("\n\tMaster node count: ").append(containerService.masterNodeCount()) 1263 | .append("\n\tMaster domain label prefix: ").append(containerService.masterDnsPrefix()) 1264 | .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(containerService.agentPools().keySet()).get(0)) 1265 | .append("\n\t\tAgent pool count: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).count()) 1266 | .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).vmSize().toString()) 1267 | .append("\n\t\tAgent pool FQDN: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).fqdn()) 1268 | .append("\n\t\tAgent pool domain label prefix: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).dnsPrefix()) 1269 | .append("\n\tLinux user name: ").append(containerService.linuxRootUsername()) 1270 | .append("\n\tSSH key: ").append(containerService.sshKey()); 1271 | if (containerService.orchestratorType() == ContainerServiceOrchestratorTypes.KUBERNETES) { 1272 | info.append("\n\tName: ").append(containerService.servicePrincipalClientId()); 1273 | } 1274 | 1275 | System.out.println(info.toString()); 1276 | } 1277 | 1278 | /** 1279 | * Print an Azure Container Service (AKS). 1280 | * @param kubernetesCluster a managed container service 1281 | */ 1282 | public static void print(KubernetesCluster kubernetesCluster) { 1283 | StringBuilder info = new StringBuilder(); 1284 | 1285 | info.append("Azure Container Service: ").append(kubernetesCluster.id()) 1286 | .append("\n\tName: ").append(kubernetesCluster.name()) 1287 | .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) 1288 | .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) 1289 | .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) 1290 | .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) 1291 | .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) 1292 | .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) 1293 | .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) 1294 | .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); 1295 | 1296 | System.out.println(info.toString()); 1297 | } 1298 | 1299 | /** 1300 | * Print an Azure Search Service. 1301 | * @param searchService an Azure Search Service 1302 | */ 1303 | public static void print(SearchService searchService) { 1304 | StringBuilder info = new StringBuilder(); 1305 | AdminKeys adminKeys = searchService.getAdminKeys(); 1306 | List queryKeys = searchService.listQueryKeys(); 1307 | 1308 | info.append("Azure Search: ").append(searchService.id()) 1309 | .append("\n\tResource group: ").append(searchService.resourceGroupName()) 1310 | .append("\n\tRegion: ").append(searchService.region()) 1311 | .append("\n\tTags: ").append(searchService.tags()) 1312 | .append("\n\tSku: ").append(searchService.sku().name()) 1313 | .append("\n\tStatus: ").append(searchService.status()) 1314 | .append("\n\tProvisioning State: ").append(searchService.provisioningState()) 1315 | .append("\n\tHosting Mode: ").append(searchService.hostingMode()) 1316 | .append("\n\tReplicas: ").append(searchService.replicaCount()) 1317 | .append("\n\tPartitions: ").append(searchService.partitionCount()) 1318 | .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) 1319 | .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) 1320 | .append("\n\tQuery keys:"); 1321 | 1322 | for (QueryKey queryKey : queryKeys) { 1323 | info.append("\n\t\tKey name: ").append(queryKey.name()); 1324 | info.append("\n\t\t Value: ").append(queryKey.key()); 1325 | } 1326 | System.out.println(info.toString()); 1327 | } 1328 | 1329 | /** 1330 | * Retrieve the secondary service principal client ID. 1331 | * @param envSecondaryServicePrincipal an Azure Container Registry 1332 | * @return a service principal client ID 1333 | * @throws Exception exception 1334 | */ 1335 | public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws Exception { 1336 | Properties authSettings = new Properties(); 1337 | FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); 1338 | authSettings.load(credentialsFileStream); 1339 | credentialsFileStream.close(); 1340 | 1341 | return authSettings.getProperty("client"); 1342 | } 1343 | 1344 | /** 1345 | * Retrieve the secondary service principal secret. 1346 | * @param envSecondaryServicePrincipal an Azure Container Registry 1347 | * @return a service principal secret 1348 | * @throws Exception exception 1349 | */ 1350 | public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws Exception { 1351 | Properties authSettings = new Properties(); 1352 | FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); 1353 | authSettings.load(credentialsFileStream); 1354 | credentialsFileStream.close(); 1355 | 1356 | return authSettings.getProperty("key"); 1357 | } 1358 | 1359 | /** 1360 | * Creates and returns a randomized name based on the prefix file for use by the sample. 1361 | * @param namePrefix The prefix string to be used in generating the name. 1362 | * @return a random name 1363 | * */ 1364 | public static String createRandomName(String namePrefix) { 1365 | return SdkContext.randomResourceName(namePrefix, 30); 1366 | } 1367 | 1368 | /** 1369 | * This method creates a certificate for given password. 1370 | * 1371 | * @param certPath location of certificate file 1372 | * @param pfxPath location of pfx file 1373 | * @param alias User alias 1374 | * @param password alias password 1375 | * @param cnName domain name 1376 | * @throws Exception exceptions from the creation 1377 | */ 1378 | public static void createCertificate(String certPath, String pfxPath, 1379 | String alias, String password, String cnName) throws Exception { 1380 | if (new File(pfxPath).exists()) { 1381 | return; 1382 | } 1383 | String validityInDays = "3650"; 1384 | String keyAlg = "RSA"; 1385 | String sigAlg = "SHA1withRSA"; 1386 | String keySize = "2048"; 1387 | String storeType = "pkcs12"; 1388 | String command = "keytool"; 1389 | String jdkPath = System.getProperty("java.home"); 1390 | if (jdkPath != null && !jdkPath.isEmpty()) { 1391 | jdkPath = jdkPath.concat("\\bin"); 1392 | if (new File(jdkPath).isDirectory()) { 1393 | command = String.format("%s%s%s", jdkPath, File.separator, command); 1394 | } 1395 | } else { 1396 | return; 1397 | } 1398 | 1399 | // Create Pfx file 1400 | String[] commandArgs = {command, "-genkey", "-alias", alias, 1401 | "-keystore", pfxPath, "-storepass", password, "-validity", 1402 | validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, 1403 | "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; 1404 | Utils.cmdInvocation(commandArgs, false); 1405 | 1406 | // Create cer file i.e. extract public key from pfx 1407 | File pfxFile = new File(pfxPath); 1408 | if (pfxFile.exists()) { 1409 | String[] certCommandArgs = {command, "-export", "-alias", alias, 1410 | "-storetype", storeType, "-keystore", pfxPath, 1411 | "-storepass", password, "-rfc", "-file", certPath}; 1412 | // output of keytool export command is going to error stream 1413 | // although command is 1414 | // executed successfully, hence ignoring error stream in this case 1415 | Utils.cmdInvocation(certCommandArgs, true); 1416 | 1417 | // Check if file got created or not 1418 | File cerFile = new File(pfxPath); 1419 | if (!cerFile.exists()) { 1420 | throw new IOException( 1421 | "Error occurred while creating certificate" 1422 | + StringUtils.join(" ", certCommandArgs)); 1423 | } 1424 | } else { 1425 | throw new IOException("Error occurred while creating certificates" 1426 | + StringUtils.join(" ", commandArgs)); 1427 | } 1428 | } 1429 | 1430 | /** 1431 | * This method is used for invoking native commands. 1432 | * 1433 | * @param command 1434 | * :- command to invoke. 1435 | * @param ignoreErrorStream 1436 | * : Boolean which controls whether to throw exception or not 1437 | * based on error stream. 1438 | * @return result :- depending on the method invocation. 1439 | * @throws Exception exceptions thrown from the execution 1440 | */ 1441 | public static String cmdInvocation(String[] command, 1442 | boolean ignoreErrorStream) throws Exception { 1443 | String result = ""; 1444 | String error = ""; 1445 | InputStream inputStream = null; 1446 | InputStream errorStream = null; 1447 | BufferedReader br = null; 1448 | BufferedReader ebr = null; 1449 | try { 1450 | Process process = new ProcessBuilder(command).start(); 1451 | inputStream = process.getInputStream(); 1452 | errorStream = process.getErrorStream(); 1453 | br = new BufferedReader(new InputStreamReader(inputStream)); 1454 | result = br.readLine(); 1455 | process.waitFor(); 1456 | ebr = new BufferedReader(new InputStreamReader(errorStream)); 1457 | error = ebr.readLine(); 1458 | if (error != null && (!error.equals(""))) { 1459 | // To do - Log error message 1460 | 1461 | if (!ignoreErrorStream) { 1462 | throw new Exception(error, null); 1463 | } 1464 | } 1465 | } catch (Exception e) { 1466 | throw new Exception("Exception occurred while invoking command", e); 1467 | } finally { 1468 | if (inputStream != null) { 1469 | inputStream.close(); 1470 | } 1471 | if (errorStream != null) { 1472 | errorStream.close(); 1473 | } 1474 | if (br != null) { 1475 | br.close(); 1476 | } 1477 | if (ebr != null) { 1478 | ebr.close(); 1479 | } 1480 | } 1481 | return result; 1482 | } 1483 | 1484 | 1485 | /** 1486 | * Prints information for passed SQL Server. 1487 | * @param sqlServer sqlServer to be printed 1488 | */ 1489 | public static void print(SqlServer sqlServer) { 1490 | StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) 1491 | .append("Name: ").append(sqlServer.name()) 1492 | .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) 1493 | .append("\n\tRegion: ").append(sqlServer.region()) 1494 | .append("\n\tSqlServer version: ").append(sqlServer.version()) 1495 | .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); 1496 | System.out.println(builder.toString()); 1497 | } 1498 | 1499 | /** 1500 | * Prints information for the passed SQL Database. 1501 | * @param database database to be printed 1502 | */ 1503 | public static void print(SqlDatabase database) { 1504 | StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) 1505 | .append("Name: ").append(database.name()) 1506 | .append("\n\tResource group: ").append(database.resourceGroupName()) 1507 | .append("\n\tRegion: ").append(database.region()) 1508 | .append("\n\tSqlServer Name: ").append(database.sqlServerName()) 1509 | .append("\n\tEdition of SQL database: ").append(database.edition()) 1510 | .append("\n\tCollation of SQL database: ").append(database.collation()) 1511 | .append("\n\tCreation date of SQL database: ").append(database.creationDate()) 1512 | .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) 1513 | .append("\n\tCurrent service objective of SQL database: ").append(database.serviceLevelObjective()) 1514 | .append("\n\tId of current service objective of SQL database: ").append(database.currentServiceObjectiveId()) 1515 | .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) 1516 | .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); 1517 | 1518 | System.out.println(builder.toString()); 1519 | } 1520 | 1521 | /** 1522 | * Prints information for the passed firewall rule. 1523 | * @param firewallRule firewall rule to be printed. 1524 | */ 1525 | public static void print(SqlFirewallRule firewallRule) { 1526 | StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) 1527 | .append("Name: ").append(firewallRule.name()) 1528 | .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) 1529 | .append("\n\tRegion: ").append(firewallRule.region()) 1530 | .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) 1531 | .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIPAddress()) 1532 | .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIPAddress()); 1533 | 1534 | System.out.println(builder.toString()); 1535 | } 1536 | 1537 | /** 1538 | * Prints information for the passed virtual network rule. 1539 | * @param virtualNetworkRule virtual network rule to be printed. 1540 | */ 1541 | public static void print(SqlVirtualNetworkRule virtualNetworkRule) { 1542 | StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) 1543 | .append("Name: ").append(virtualNetworkRule.name()) 1544 | .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) 1545 | .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) 1546 | .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) 1547 | .append("\n\tState: ").append(virtualNetworkRule.state()); 1548 | 1549 | System.out.println(builder.toString()); 1550 | } 1551 | 1552 | /** 1553 | * Prints information for the passed SQL subscription usage metric. 1554 | * @param subscriptionUsageMetric metric to be printed. 1555 | */ 1556 | public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { 1557 | StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) 1558 | .append("Name: ").append(subscriptionUsageMetric.name()) 1559 | .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) 1560 | .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) 1561 | .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) 1562 | .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) 1563 | .append("\n\tType: ").append(subscriptionUsageMetric.type()); 1564 | 1565 | System.out.println(builder.toString()); 1566 | } 1567 | 1568 | /** 1569 | * Prints information for the passed SQL database usage metric. 1570 | * @param dbUsageMetric metric to be printed. 1571 | */ 1572 | public static void print(SqlDatabaseUsageMetric dbUsageMetric) { 1573 | StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") 1574 | .append("Name: ").append(dbUsageMetric.name()) 1575 | .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) 1576 | .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) 1577 | .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) 1578 | .append("\n\tLimit: ").append(dbUsageMetric.limit()) 1579 | .append("\n\tUnit: ").append(dbUsageMetric.unit()) 1580 | .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); 1581 | 1582 | System.out.println(builder.toString()); 1583 | } 1584 | 1585 | /** 1586 | * Prints information for the passed SQL database metric. 1587 | * @param dbMetric metric to be printed. 1588 | */ 1589 | public static void print(SqlDatabaseMetric dbMetric) { 1590 | StringBuilder builder = new StringBuilder().append("SQL Database Metric") 1591 | .append("Name: ").append(dbMetric.name()) 1592 | .append("\n\tStart Time: ").append(dbMetric.startTime()) 1593 | .append("\n\tEnd Time: ").append(dbMetric.endTime()) 1594 | .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) 1595 | .append("\n\tUnit: ").append(dbMetric.unit()); 1596 | for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { 1597 | builder 1598 | .append("\n\tMetric Value: ") 1599 | .append("\n\t\tCount: ").append(metricValue.count()) 1600 | .append("\n\t\tAverage: ").append(metricValue.average()) 1601 | .append("\n\t\tMaximum: ").append(metricValue.maximum()) 1602 | .append("\n\t\tMinimum: ").append(metricValue.minimum()) 1603 | .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) 1604 | .append("\n\t\tTotal: ").append(metricValue.total()); 1605 | } 1606 | 1607 | System.out.println(builder.toString()); 1608 | } 1609 | 1610 | /** 1611 | * Prints information for the passed Failover Group. 1612 | * @param failoverGroup the SQL Failover Group to be printed. 1613 | */ 1614 | public static void print(SqlFailoverGroup failoverGroup) { 1615 | StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) 1616 | .append("Name: ").append(failoverGroup.name()) 1617 | .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) 1618 | .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) 1619 | .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) 1620 | .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) 1621 | .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) 1622 | .append("\n\tReplication state: ").append(failoverGroup.replicationState()) 1623 | .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); 1624 | builder.append("\n\tPartner Servers: "); 1625 | for (PartnerInfo item : failoverGroup.partnerServers()) { 1626 | builder 1627 | .append("\n\t\tId: ").append(item.id()) 1628 | .append("\n\t\tLocation: ").append(item.location()) 1629 | .append("\n\t\tReplication role: ").append(item.replicationRole()); 1630 | } 1631 | builder.append("\n\tDatabases: "); 1632 | for (String databaseId : failoverGroup.databases()) { 1633 | builder.append("\n\t\tID: ").append(databaseId); 1634 | } 1635 | 1636 | System.out.println(builder.toString()); 1637 | } 1638 | 1639 | /** 1640 | * Prints information for the passed SQL server key. 1641 | * @param serverKey virtual network rule to be printed. 1642 | */ 1643 | public static void print(SqlServerKey serverKey) { 1644 | StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) 1645 | .append("Name: ").append(serverKey.name()) 1646 | .append("\n\tResource group: ").append(serverKey.resourceGroupName()) 1647 | .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) 1648 | .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") 1649 | .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) 1650 | .append("\n\tServer Key URI: ").append(serverKey.uri()) 1651 | .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) 1652 | .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); 1653 | 1654 | System.out.println(builder.toString()); 1655 | } 1656 | 1657 | /** 1658 | * Prints information of the elastic pool passed in. 1659 | * @param elasticPool elastic pool to be printed 1660 | */ 1661 | public static void print(SqlElasticPool elasticPool) { 1662 | StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) 1663 | .append("Name: ").append(elasticPool.name()) 1664 | .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) 1665 | .append("\n\tRegion: ").append(elasticPool.region()) 1666 | .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) 1667 | .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) 1668 | .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) 1669 | .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) 1670 | .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) 1671 | .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) 1672 | .append("\n\tState of the elastic pool: ").append(elasticPool.state()) 1673 | .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageMB()); 1674 | 1675 | System.out.println(builder.toString()); 1676 | } 1677 | 1678 | /** 1679 | * Prints information of the elastic pool activity. 1680 | * @param elasticPoolActivity elastic pool activity to be printed 1681 | */ 1682 | public static void print(ElasticPoolActivity elasticPoolActivity) { 1683 | StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) 1684 | .append("Name: ").append(elasticPoolActivity.name()) 1685 | .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) 1686 | .append("\n\tState: ").append(elasticPoolActivity.state()) 1687 | .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) 1688 | .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) 1689 | .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) 1690 | .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) 1691 | .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) 1692 | .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) 1693 | .append("\n\tOperation: ").append(elasticPoolActivity.operation()) 1694 | .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) 1695 | .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) 1696 | .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) 1697 | .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); 1698 | 1699 | System.out.println(builder.toString()); 1700 | 1701 | } 1702 | 1703 | /** 1704 | * Prints information of the database activity. 1705 | * @param databaseActivity database activity to be printed 1706 | */ 1707 | public static void print(ElasticPoolDatabaseActivity databaseActivity) { 1708 | StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) 1709 | .append("Name: ").append(databaseActivity.name()) 1710 | .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) 1711 | .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) 1712 | .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) 1713 | .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) 1714 | .append("\n\tState: ").append(databaseActivity.state()) 1715 | .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) 1716 | .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) 1717 | .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) 1718 | .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) 1719 | .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) 1720 | .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); 1721 | 1722 | System.out.println(builder.toString()); 1723 | } 1724 | 1725 | /** 1726 | * Print an application gateway. 1727 | * @param resource an application gateway 1728 | */ 1729 | public static void print(ApplicationGateway resource) { 1730 | StringBuilder info = new StringBuilder(); 1731 | info.append("Application gateway: ").append(resource.id()) 1732 | .append("Name: ").append(resource.name()) 1733 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 1734 | .append("\n\tRegion: ").append(resource.region()) 1735 | .append("\n\tTags: ").append(resource.tags()) 1736 | .append("\n\tSKU: ").append(resource.sku().toString()) 1737 | .append("\n\tOperational state: ").append(resource.operationalState()) 1738 | .append("\n\tInternet-facing? ").append(resource.isPublic()) 1739 | .append("\n\tInternal? ").append(resource.isPrivate()) 1740 | .append("\n\tDefault private IP address: ").append(resource.privateIPAddress()) 1741 | .append("\n\tPrivate IP address allocation method: ").append(resource.privateIPAllocationMethod()) 1742 | .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); 1743 | 1744 | // Show IP configs 1745 | Map ipConfigs = resource.ipConfigurations(); 1746 | info.append("\n\tIP configurations: ").append(ipConfigs.size()); 1747 | for (ApplicationGatewayIPConfiguration ipConfig : ipConfigs.values()) { 1748 | info.append("\n\t\tName: ").append(ipConfig.name()) 1749 | .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) 1750 | .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); 1751 | } 1752 | 1753 | // Show frontends 1754 | Map frontends = resource.frontends(); 1755 | info.append("\n\tFrontends: ").append(frontends.size()); 1756 | for (ApplicationGatewayFrontend frontend : frontends.values()) { 1757 | info.append("\n\t\tName: ").append(frontend.name()) 1758 | .append("\n\t\t\tPublic? ").append(frontend.isPublic()); 1759 | 1760 | if (frontend.isPublic()) { 1761 | // Show public frontend info 1762 | info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIPAddressId()); 1763 | } 1764 | 1765 | if (frontend.isPrivate()) { 1766 | // Show private frontend info 1767 | info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIPAddress()) 1768 | .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIPAllocationMethod()) 1769 | .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) 1770 | .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); 1771 | } 1772 | } 1773 | 1774 | // Show backends 1775 | Map backends = resource.backends(); 1776 | info.append("\n\tBackends: ").append(backends.size()); 1777 | for (ApplicationGatewayBackend backend : backends.values()) { 1778 | info.append("\n\t\tName: ").append(backend.name()) 1779 | .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); 1780 | 1781 | // Show addresses 1782 | Collection addresses = backend.addresses(); 1783 | info.append("\n\t\t\tAddresses: ").append(addresses.size()); 1784 | for (ApplicationGatewayBackendAddress address : addresses) { 1785 | info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) 1786 | .append("\n\t\t\t\tIP: ").append(address.ipAddress()); 1787 | } 1788 | } 1789 | 1790 | // Show backend HTTP configurations 1791 | Map httpConfigs = resource.backendHttpConfigurations(); 1792 | info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); 1793 | for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { 1794 | info.append("\n\t\tName: ").append(httpConfig.name()) 1795 | .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) 1796 | .append("\n\t\t\tPort: ").append(httpConfig.port()) 1797 | .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) 1798 | .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) 1799 | .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) 1800 | .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) 1801 | .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) 1802 | .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) 1803 | .append("\n\t\tPath: ").append(httpConfig.path()); 1804 | ApplicationGatewayProbe probe = httpConfig.probe(); 1805 | if (probe != null) { 1806 | info.append("\n\t\tProbe: " + probe.name()); 1807 | } 1808 | info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); 1809 | } 1810 | 1811 | // Show SSL certificates 1812 | Map sslCerts = resource.sslCertificates(); 1813 | info.append("\n\tSSL certificates: ").append(sslCerts.size()); 1814 | for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { 1815 | info.append("\n\t\tName: ").append(cert.name()) 1816 | .append("\n\t\t\tCert data: ").append(cert.publicData()); 1817 | } 1818 | 1819 | // Show redirect configurations 1820 | Map redirects = resource.redirectConfigurations(); 1821 | info.append("\n\tRedirect configurations: ").append(redirects.size()); 1822 | for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { 1823 | info.append("\n\t\tName: ").append(redirect.name()) 1824 | .append("\n\t\tTarget URL: ").append(redirect.type()) 1825 | .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) 1826 | .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) 1827 | .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) 1828 | .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) 1829 | .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); 1830 | } 1831 | 1832 | // Show HTTP listeners 1833 | Map listeners = resource.listeners(); 1834 | info.append("\n\tHTTP listeners: ").append(listeners.size()); 1835 | for (ApplicationGatewayListener listener : listeners.values()) { 1836 | info.append("\n\t\tName: ").append(listener.name()) 1837 | .append("\n\t\t\tHost name: ").append(listener.hostName()) 1838 | .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) 1839 | .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) 1840 | .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) 1841 | .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) 1842 | .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); 1843 | if (listener.sslCertificate() != null) { 1844 | info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); 1845 | } 1846 | } 1847 | 1848 | // Show probes 1849 | Map probes = resource.probes(); 1850 | info.append("\n\tProbes: ").append(probes.size()); 1851 | for (ApplicationGatewayProbe probe : probes.values()) { 1852 | info.append("\n\t\tName: ").append(probe.name()) 1853 | .append("\n\t\tProtocol:").append(probe.protocol().toString()) 1854 | .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) 1855 | .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) 1856 | .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) 1857 | .append("\n\t\tHost: ").append(probe.host()) 1858 | .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) 1859 | .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); 1860 | } 1861 | 1862 | // Show request routing rules 1863 | Map rules = resource.requestRoutingRules(); 1864 | info.append("\n\tRequest routing rules: ").append(rules.size()); 1865 | for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { 1866 | info.append("\n\t\tName: ").append(rule.name()) 1867 | .append("\n\t\tType: ").append(rule.ruleType()) 1868 | .append("\n\t\tPublic IP address ID: ").append(rule.publicIPAddressId()) 1869 | .append("\n\t\tHost name: ").append(rule.hostName()) 1870 | .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) 1871 | .append("\n\t\tFrontend port: ").append(rule.frontendPort()) 1872 | .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) 1873 | .append("\n\t\tBackend port: ").append(rule.backendPort()) 1874 | .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) 1875 | .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); 1876 | 1877 | // Show backend addresses 1878 | Collection addresses = rule.backendAddresses(); 1879 | info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); 1880 | for (ApplicationGatewayBackendAddress address : addresses) { 1881 | info.append("\n\t\t\t\t") 1882 | .append(address.fqdn()) 1883 | .append(" [").append(address.ipAddress()).append("]"); 1884 | } 1885 | 1886 | // Show SSL cert 1887 | info.append("\n\t\t\tSSL certificate name: "); 1888 | ApplicationGatewaySslCertificate cert = rule.sslCertificate(); 1889 | if (cert == null) { 1890 | info.append("(None)"); 1891 | } else { 1892 | info.append(cert.name()); 1893 | } 1894 | 1895 | // Show backend 1896 | info.append("\n\t\t\tAssociated backend address pool: "); 1897 | ApplicationGatewayBackend backend = rule.backend(); 1898 | if (backend == null) { 1899 | info.append("(None)"); 1900 | } else { 1901 | info.append(backend.name()); 1902 | } 1903 | 1904 | // Show backend HTTP settings config 1905 | info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); 1906 | ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); 1907 | if (config == null) { 1908 | info.append("(None)"); 1909 | } else { 1910 | info.append(config.name()); 1911 | } 1912 | 1913 | // Show frontend listener 1914 | info.append("\n\t\t\tAssociated frontend listener: "); 1915 | ApplicationGatewayListener listener = rule.listener(); 1916 | if (listener == null) { 1917 | info.append("(None)"); 1918 | } else { 1919 | info.append(config.name()); 1920 | } 1921 | } 1922 | System.out.println(info.toString()); 1923 | } 1924 | 1925 | /** 1926 | * Prints information of a virtual machine custom image. 1927 | * 1928 | * @param image the image 1929 | */ 1930 | public static void print(VirtualMachineCustomImage image) { 1931 | StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) 1932 | .append("Name: ").append(image.name()) 1933 | .append("\n\tResource group: ").append(image.resourceGroupName()) 1934 | .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); 1935 | 1936 | builder.append("\n\tOS disk image: ") 1937 | .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) 1938 | .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) 1939 | .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) 1940 | .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); 1941 | if (image.isCreatedFromVirtualMachine()) { 1942 | builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); 1943 | } 1944 | if (image.osDiskImage().managedDisk() != null) { 1945 | builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); 1946 | } 1947 | if (image.osDiskImage().snapshot() != null) { 1948 | builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); 1949 | } 1950 | if (image.osDiskImage().blobUri() != null) { 1951 | builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); 1952 | } 1953 | if (image.dataDiskImages() != null) { 1954 | for (ImageDataDisk diskImage : image.dataDiskImages().values()) { 1955 | builder.append("\n\tDisk Image (Lun) #: ").append(diskImage.lun()) 1956 | .append("\n\t\tCaching: ").append(diskImage.caching()) 1957 | .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); 1958 | if (image.isCreatedFromVirtualMachine()) { 1959 | builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); 1960 | } 1961 | if (diskImage.managedDisk() != null) { 1962 | builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); 1963 | } 1964 | if (diskImage.snapshot() != null) { 1965 | builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); 1966 | } 1967 | if (diskImage.blobUri() != null) { 1968 | builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); 1969 | } 1970 | } 1971 | } 1972 | System.out.println(builder.toString()); 1973 | } 1974 | 1975 | /** 1976 | * Uploads a file to an Azure web app. 1977 | * @param profile the publishing profile for the web app. 1978 | * @param fileName the name of the file on server 1979 | * @param file the local file 1980 | */ 1981 | public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) { 1982 | FTPClient ftpClient = new FTPClient(); 1983 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 1984 | String server = ftpUrlSegments[0]; 1985 | String path = "./site/wwwroot/webapps"; 1986 | if (fileName.contains("/")) { 1987 | int lastslash = fileName.lastIndexOf('/'); 1988 | path = path + "/" + fileName.substring(0, lastslash); 1989 | fileName = fileName.substring(lastslash + 1); 1990 | } 1991 | try { 1992 | ftpClient.connect(server); 1993 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 1994 | ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 1995 | for (String segment : path.split("/")) { 1996 | if (!ftpClient.changeWorkingDirectory(segment)) { 1997 | ftpClient.makeDirectory(segment); 1998 | ftpClient.changeWorkingDirectory(segment); 1999 | } 2000 | } 2001 | ftpClient.storeFile(fileName, file); 2002 | ftpClient.disconnect(); 2003 | } catch (IOException e) { 2004 | e.printStackTrace(); 2005 | } 2006 | } 2007 | 2008 | /** 2009 | * Uploads a file to an Azure function app. 2010 | * @param profile the publishing profile for the web app. 2011 | * @param fileName the name of the file on server 2012 | * @param file the local file 2013 | */ 2014 | public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) { 2015 | FTPClient ftpClient = new FTPClient(); 2016 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 2017 | String server = ftpUrlSegments[0]; 2018 | String path = "site/wwwroot"; 2019 | if (fileName.contains("/")) { 2020 | int lastslash = fileName.lastIndexOf('/'); 2021 | path = path + "/" + fileName.substring(0, lastslash); 2022 | fileName = fileName.substring(lastslash + 1); 2023 | } 2024 | try { 2025 | ftpClient.connect(server); 2026 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 2027 | ftpClient.setFileType(FTP.ASCII_FILE_TYPE); 2028 | for (String segment : path.split("/")) { 2029 | if (!ftpClient.changeWorkingDirectory(segment)) { 2030 | ftpClient.makeDirectory(segment); 2031 | ftpClient.changeWorkingDirectory(segment); 2032 | } 2033 | } 2034 | ftpClient.storeFile(fileName, file); 2035 | ftpClient.disconnect(); 2036 | } catch (IOException e) { 2037 | e.printStackTrace(); 2038 | } 2039 | } 2040 | 2041 | /** 2042 | * Uploads a file to an Azure web app. 2043 | * @param profile the publishing profile for the web app. 2044 | * @param fileName the name of the file on server 2045 | * @param file the local file 2046 | */ 2047 | public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String fileName, InputStream file) { 2048 | FTPClient ftpClient = new FTPClient(); 2049 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 2050 | String server = ftpUrlSegments[0]; 2051 | String path = "./site/wwwroot"; 2052 | if (fileName.contains("/")) { 2053 | int lastslash = fileName.lastIndexOf('/'); 2054 | path = path + "/" + fileName.substring(0, lastslash); 2055 | fileName = fileName.substring(lastslash + 1); 2056 | } 2057 | try { 2058 | ftpClient.connect(server); 2059 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 2060 | ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 2061 | for (String segment : path.split("/")) { 2062 | if (!ftpClient.changeWorkingDirectory(segment)) { 2063 | ftpClient.makeDirectory(segment); 2064 | ftpClient.changeWorkingDirectory(segment); 2065 | } 2066 | } 2067 | ftpClient.storeFile(fileName, file); 2068 | ftpClient.disconnect(); 2069 | } catch (IOException e) { 2070 | e.printStackTrace(); 2071 | } 2072 | } 2073 | 2074 | private Utils() { 2075 | 2076 | } 2077 | 2078 | /** 2079 | * Print service bus namespace info. 2080 | * @param serviceBusNamespace a service bus namespace 2081 | */ 2082 | public static void print(ServiceBusNamespace serviceBusNamespace) { 2083 | StringBuilder builder = new StringBuilder() 2084 | .append("Service bus Namespace: ").append(serviceBusNamespace.id()) 2085 | .append("\n\tName: ").append(serviceBusNamespace.name()) 2086 | .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) 2087 | .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) 2088 | .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) 2089 | .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) 2090 | .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) 2091 | .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) 2092 | .append("\n\tSku: ") 2093 | .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) 2094 | .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) 2095 | .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); 2096 | 2097 | System.out.println(builder.toString()); 2098 | } 2099 | 2100 | /** 2101 | * Print service bus queue info. 2102 | * @param queue a service bus queue 2103 | */ 2104 | public static void print(Queue queue) { 2105 | StringBuilder builder = new StringBuilder() 2106 | .append("Service bus Queue: ").append(queue.id()) 2107 | .append("\n\tName: ").append(queue.name()) 2108 | .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) 2109 | .append("\n\tCreatedAt: ").append(queue.createdAt()) 2110 | .append("\n\tUpdatedAt: ").append(queue.updatedAt()) 2111 | .append("\n\tAccessedAt: ").append(queue.accessedAt()) 2112 | .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) 2113 | .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) 2114 | .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) 2115 | .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) 2116 | .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) 2117 | .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) 2118 | .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) 2119 | .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) 2120 | .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) 2121 | .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) 2122 | .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) 2123 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) 2124 | .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) 2125 | .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) 2126 | .append("\n\tMessageCount: ").append(queue.messageCount()) 2127 | .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) 2128 | .append("\n\tStatus: ").append(queue.status()) 2129 | .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) 2130 | .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) 2131 | .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); 2132 | 2133 | System.out.println(builder.toString()); 2134 | 2135 | } 2136 | 2137 | /** 2138 | * Print service bus queue authorization keys info. 2139 | * @param queueAuthorizationRule a service bus queue authorization keys 2140 | */ 2141 | public static void print(QueueAuthorizationRule queueAuthorizationRule) { 2142 | StringBuilder builder = new StringBuilder() 2143 | .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) 2144 | .append("\n\tName: ").append(queueAuthorizationRule.name()) 2145 | .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) 2146 | .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) 2147 | .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); 2148 | 2149 | List rights = queueAuthorizationRule.rights(); 2150 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2151 | for (AccessRights right: rights) { 2152 | builder.append("\n\t\tAccessRight: ") 2153 | .append("\n\t\t\tName :").append(right.name()); 2154 | } 2155 | 2156 | System.out.println(builder.toString()); 2157 | } 2158 | 2159 | /** 2160 | * Print service bus namespace authorization keys info. 2161 | * @param keys a service bus namespace authorization keys 2162 | */ 2163 | public static void print(AuthorizationKeys keys) { 2164 | StringBuilder builder = new StringBuilder() 2165 | .append("Authorization keys: ") 2166 | .append("\n\tPrimaryKey: ").append(keys.primaryKey()) 2167 | .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) 2168 | .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) 2169 | .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); 2170 | 2171 | System.out.println(builder.toString()); 2172 | } 2173 | 2174 | /** 2175 | * Print service bus namespace authorization rule info. 2176 | * @param namespaceAuthorizationRule a service bus namespace authorization rule 2177 | */ 2178 | public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { 2179 | StringBuilder builder = new StringBuilder() 2180 | .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) 2181 | .append("\n\tName: ").append(namespaceAuthorizationRule.name()) 2182 | .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) 2183 | .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); 2184 | 2185 | List rights = namespaceAuthorizationRule.rights(); 2186 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2187 | for (AccessRights right: rights) { 2188 | builder.append("\n\t\tAccessRight: ") 2189 | .append("\n\t\t\tName :").append(right.name()); 2190 | } 2191 | 2192 | System.out.println(builder.toString()); 2193 | } 2194 | 2195 | /** 2196 | * Print service bus topic info. 2197 | * @param topic a service bus topic 2198 | */ 2199 | public static void print(Topic topic) { 2200 | StringBuilder builder = new StringBuilder() 2201 | .append("Service bus topic: ").append(topic.id()) 2202 | .append("\n\tName: ").append(topic.name()) 2203 | .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) 2204 | .append("\n\tCreatedAt: ").append(topic.createdAt()) 2205 | .append("\n\tUpdatedAt: ").append(topic.updatedAt()) 2206 | .append("\n\tAccessedAt: ").append(topic.accessedAt()) 2207 | .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) 2208 | .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) 2209 | .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) 2210 | .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) 2211 | .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) 2212 | .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) 2213 | .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) 2214 | .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) 2215 | .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) 2216 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) 2217 | .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) 2218 | .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) 2219 | .append("\n\tStatus: ").append(topic.status()) 2220 | .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) 2221 | .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) 2222 | .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); 2223 | 2224 | System.out.println(builder.toString()); 2225 | } 2226 | 2227 | /** 2228 | * Print service bus subscription info. 2229 | * @param serviceBusSubscription a service bus subscription 2230 | */ 2231 | public static void print(ServiceBusSubscription serviceBusSubscription) { 2232 | StringBuilder builder = new StringBuilder() 2233 | .append("Service bus subscription: ").append(serviceBusSubscription.id()) 2234 | .append("\n\tName: ").append(serviceBusSubscription.name()) 2235 | .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) 2236 | .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) 2237 | .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) 2238 | .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) 2239 | .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) 2240 | .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) 2241 | .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) 2242 | .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) 2243 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) 2244 | .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) 2245 | .append("\n\tStatus: ").append(serviceBusSubscription.status()) 2246 | .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) 2247 | .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) 2248 | .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) 2249 | .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) 2250 | .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) 2251 | .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) 2252 | .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) 2253 | .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); 2254 | 2255 | System.out.println(builder.toString()); 2256 | } 2257 | 2258 | /** 2259 | * Print topic Authorization Rule info. 2260 | * @param topicAuthorizationRule a topic Authorization Rule 2261 | */ 2262 | public static void print(TopicAuthorizationRule topicAuthorizationRule) { 2263 | StringBuilder builder = new StringBuilder() 2264 | .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) 2265 | .append("\n\tName: ").append(topicAuthorizationRule.name()) 2266 | .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) 2267 | .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) 2268 | .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); 2269 | 2270 | List rights = topicAuthorizationRule.rights(); 2271 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2272 | for (AccessRights right: rights) { 2273 | builder.append("\n\t\tAccessRight: ") 2274 | .append("\n\t\t\tName :").append(right.name()); 2275 | } 2276 | 2277 | System.out.println(builder.toString()); 2278 | } 2279 | 2280 | /** 2281 | * Print CosmosDB info. 2282 | * @param cosmosDBAccount a CosmosDB 2283 | */ 2284 | public static void print(CosmosDBAccount cosmosDBAccount) { 2285 | StringBuilder builder = new StringBuilder() 2286 | .append("CosmosDB: ").append(cosmosDBAccount.id()) 2287 | .append("\n\tName: ").append(cosmosDBAccount.name()) 2288 | .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) 2289 | .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) 2290 | .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) 2291 | .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); 2292 | 2293 | DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); 2294 | DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); 2295 | builder 2296 | .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) 2297 | .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) 2298 | .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) 2299 | .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); 2300 | 2301 | for (com.microsoft.azure.management.cosmosdb.Location writeReplica : cosmosDBAccount.writableReplications()) { 2302 | builder.append("\n\t\tWrite replication: ") 2303 | .append("\n\t\t\tName :").append(writeReplica.locationName()); 2304 | } 2305 | 2306 | builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); 2307 | for (com.microsoft.azure.management.cosmosdb.Location readReplica : cosmosDBAccount.readableReplications()) { 2308 | builder.append("\n\t\tRead replication: ") 2309 | .append("\n\t\t\tName :").append(readReplica.locationName()); 2310 | } 2311 | 2312 | } 2313 | 2314 | /** 2315 | * Print Active Directory User info. 2316 | * @param user active directory user 2317 | */ 2318 | public static void print(ActiveDirectoryUser user) { 2319 | StringBuilder builder = new StringBuilder() 2320 | .append("Active Directory User: ").append(user.id()) 2321 | .append("\n\tName: ").append(user.name()) 2322 | .append("\n\tMail: ").append(user.mail()) 2323 | .append("\n\tMail Nickname: ").append(user.mailNickname()) 2324 | .append("\n\tSign In Name: ").append(user.signInName()) 2325 | .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); 2326 | 2327 | System.out.println(builder.toString()); 2328 | } 2329 | 2330 | /** 2331 | * Print Active Directory User info. 2332 | * @param role role definition 2333 | */ 2334 | public static void print(RoleDefinition role) { 2335 | StringBuilder builder = new StringBuilder() 2336 | .append("Role Definition: ").append(role.id()) 2337 | .append("\n\tName: ").append(role.name()) 2338 | .append("\n\tRole Name: ").append(role.roleName()) 2339 | .append("\n\tType: ").append(role.type()) 2340 | .append("\n\tDescription: ").append(role.description()) 2341 | .append("\n\tType: ").append(role.type()); 2342 | 2343 | Set permissions = role.permissions(); 2344 | builder.append("\n\tPermissions: ").append(permissions.size()); 2345 | for (Permission permission : permissions) { 2346 | builder.append("\n\t\tPermission Actions: " + permission.actions().size()); 2347 | for (String action : permission.actions()) { 2348 | builder.append("\n\t\t\tName :").append(action); 2349 | } 2350 | builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); 2351 | for (String notAction : permission.notActions()) { 2352 | builder.append("\n\t\t\tName :").append(notAction); 2353 | } 2354 | } 2355 | 2356 | Set assignableScopes = role.assignableScopes(); 2357 | builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); 2358 | for (String scope : assignableScopes) { 2359 | builder.append("\n\t\tAssignable Scope: ") 2360 | .append("\n\t\t\tName :").append(scope); 2361 | } 2362 | 2363 | System.out.println(builder.toString()); 2364 | } 2365 | 2366 | /** 2367 | * Print Role Assignment info. 2368 | * @param roleAssignment role assignment 2369 | */ 2370 | public static void print(RoleAssignment roleAssignment) { 2371 | StringBuilder builder = new StringBuilder() 2372 | .append("Role Assignment: ") 2373 | .append("\n\tScope: ").append(roleAssignment.scope()) 2374 | .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) 2375 | .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); 2376 | 2377 | System.out.println(builder.toString()); 2378 | } 2379 | 2380 | /** 2381 | * Print Active Directory Group info. 2382 | * @param group active directory group 2383 | */ 2384 | public static void print(ActiveDirectoryGroup group) { 2385 | StringBuilder builder = new StringBuilder() 2386 | .append("Active Directory Group: ").append(group.id()) 2387 | .append("\n\tName: ").append(group.name()) 2388 | .append("\n\tMail: ").append(group.mail()) 2389 | .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) 2390 | .append("\n\tGroup members:"); 2391 | 2392 | for (ActiveDirectoryObject object : group.listMembers()) { 2393 | builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) 2394 | .append("\tName: ").append(object.name()); 2395 | } 2396 | 2397 | System.out.println(builder.toString()); 2398 | } 2399 | 2400 | /** 2401 | * Print Active Directory Application info. 2402 | * @param application active directory application 2403 | */ 2404 | public static void print(ActiveDirectoryApplication application) { 2405 | StringBuilder builder = new StringBuilder() 2406 | .append("Active Directory Application: ").append(application.id()) 2407 | .append("\n\tName: ").append(application.name()) 2408 | .append("\n\tSign on URL: ").append(application.signOnUrl()) 2409 | .append("\n\tReply URLs:"); 2410 | for (String replyUrl : application.replyUrls()) { 2411 | builder.append("\n\t\t").append(replyUrl); 2412 | } 2413 | 2414 | System.out.println(builder.toString()); 2415 | } 2416 | 2417 | /** 2418 | * Print Service Principal info. 2419 | * 2420 | * @param servicePrincipal service principal 2421 | */ 2422 | public static void print(ServicePrincipal servicePrincipal) { 2423 | StringBuilder builder = new StringBuilder() 2424 | .append("Service Principal: ").append(servicePrincipal.id()) 2425 | .append("\n\tName: ").append(servicePrincipal.name()) 2426 | .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); 2427 | 2428 | List names = servicePrincipal.servicePrincipalNames(); 2429 | builder.append("\n\tNames: ").append(names.size()); 2430 | for (String name : names) { 2431 | builder.append("\n\t\tName: ").append(name); 2432 | } 2433 | System.out.println(builder.toString()); 2434 | } 2435 | 2436 | /** 2437 | * Print Network Watcher info. 2438 | * 2439 | * @param nw network watcher 2440 | */ 2441 | public static void print(NetworkWatcher nw) { 2442 | StringBuilder builder = new StringBuilder() 2443 | .append("Network Watcher: ").append(nw.id()) 2444 | .append("\n\tName: ").append(nw.name()) 2445 | .append("\n\tResource group name: ").append(nw.resourceGroupName()) 2446 | .append("\n\tRegion name: ").append(nw.regionName()); 2447 | System.out.println(builder.toString()); 2448 | } 2449 | 2450 | /** 2451 | * Print packet capture info. 2452 | * 2453 | * @param resource packet capture 2454 | */ 2455 | public static void print(PacketCapture resource) { 2456 | StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) 2457 | .append("\n\tName: ").append(resource.name()) 2458 | .append("\n\tTarget id: ").append(resource.targetId()) 2459 | .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) 2460 | .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) 2461 | .append("\n\tProvisioning state: ").append(resource.provisioningState()) 2462 | .append("\n\tStorage location:") 2463 | .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) 2464 | .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) 2465 | .append("\n\tFile path: ").append(resource.storageLocation().filePath()) 2466 | .append("\n\t Packet capture filters: ").append(resource.filters().size()); 2467 | for (PacketCaptureFilter filter : resource.filters()) { 2468 | sb.append("\n\t\tProtocol: ").append(filter.protocol()); 2469 | sb.append("\n\t\tLocal IP address: ").append(filter.localIPAddress()); 2470 | sb.append("\n\t\tRemote IP address: ").append(filter.remoteIPAddress()); 2471 | sb.append("\n\t\tLocal port: ").append(filter.localPort()); 2472 | sb.append("\n\t\tRemote port: ").append(filter.remotePort()); 2473 | } 2474 | System.out.println(sb.toString()); 2475 | } 2476 | 2477 | /** 2478 | * Print verification IP flow info. 2479 | * 2480 | * @param resource IP flow verification info 2481 | */ 2482 | public static void print(VerificationIPFlow resource) { 2483 | System.out.println(new StringBuilder("IP flow verification: ") 2484 | .append("\n\tAccess: ").append(resource.access()) 2485 | .append("\n\tRule name: ").append(resource.ruleName()) 2486 | .toString()); 2487 | } 2488 | 2489 | /** 2490 | * Print topology info. 2491 | * 2492 | * @param resource topology 2493 | */ 2494 | public static void print(Topology resource) { 2495 | StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) 2496 | .append("\n\tTopology parameters: ") 2497 | .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) 2498 | .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) 2499 | .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) 2500 | .append("\n\tCreated time: ").append(resource.createdTime()) 2501 | .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); 2502 | for (TopologyResource tr : resource.resources().values()) { 2503 | sb.append("\n\tTopology resource: ").append(tr.id()) 2504 | .append("\n\t\tName: ").append(tr.name()) 2505 | .append("\n\t\tLocation: ").append(tr.location()) 2506 | .append("\n\t\tAssociations:"); 2507 | for (TopologyAssociation association : tr.associations()) { 2508 | sb.append("\n\t\t\tName:").append(association.name()) 2509 | .append("\n\t\t\tResource id:").append(association.resourceId()) 2510 | .append("\n\t\t\tAssociation type:").append(association.associationType()); 2511 | } 2512 | } 2513 | System.out.println(sb.toString()); 2514 | } 2515 | 2516 | /** 2517 | * Print flow log settings info. 2518 | * 2519 | * @param resource flow log settings 2520 | */ 2521 | public static void print(FlowLogSettings resource) { 2522 | System.out.println(new StringBuilder().append("Flow log settings: ") 2523 | .append("Target resource id: ").append(resource.targetResourceId()) 2524 | .append("\n\tFlow log enabled: ").append(resource.enabled()) 2525 | .append("\n\tStorage account id: ").append(resource.storageId()) 2526 | .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) 2527 | .append("\n\tRetention policy days: ").append(resource.retentionDays()) 2528 | .toString()); 2529 | } 2530 | 2531 | /** 2532 | * Print availability set info. 2533 | * 2534 | * @param resource an availability set 2535 | */ 2536 | public static void print(SecurityGroupView resource) { 2537 | StringBuilder sb = new StringBuilder().append("Security group view: ") 2538 | .append("\n\tVirtual machine id: ").append(resource.vmId()); 2539 | for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { 2540 | sb.append("\n\tSecurity group network interface:").append(sgni.id()) 2541 | .append("\n\t\tSecurity group network interface:") 2542 | .append("\n\t\tEffective security rules:"); 2543 | for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { 2544 | sb.append("\n\t\t\tName: ").append(rule.name()) 2545 | .append("\n\t\t\tDirection: ").append(rule.direction()) 2546 | .append("\n\t\t\tAccess: ").append(rule.access()) 2547 | .append("\n\t\t\tPriority: ").append(rule.priority()) 2548 | .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) 2549 | .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) 2550 | .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) 2551 | .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) 2552 | .append("\n\t\t\tProtocol: ").append(rule.protocol()); 2553 | } 2554 | sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); 2555 | printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); 2556 | if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { 2557 | sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); 2558 | printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); 2559 | } 2560 | sb.append("\n\t\tDefault security rules:"); 2561 | printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); 2562 | } 2563 | System.out.println(sb.toString()); 2564 | } 2565 | 2566 | private static void printSecurityRule(StringBuilder sb, List rules) { 2567 | for (SecurityRuleInner rule : rules) { 2568 | sb.append("\n\t\t\tName: ").append(rule.name()) 2569 | .append("\n\t\t\tDirection: ").append(rule.direction()) 2570 | .append("\n\t\t\tAccess: ").append(rule.access()) 2571 | .append("\n\t\t\tPriority: ").append(rule.priority()) 2572 | .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) 2573 | .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) 2574 | .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) 2575 | .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) 2576 | .append("\n\t\t\tProtocol: ").append(rule.protocol()) 2577 | .append("\n\t\t\tDescription: ").append(rule.description()) 2578 | .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); 2579 | } 2580 | } 2581 | 2582 | /** 2583 | * Print next hop info. 2584 | * 2585 | * @param resource an availability set 2586 | */ 2587 | public static void print(NextHop resource) { 2588 | System.out.println(new StringBuilder("Next hop: ") 2589 | .append("Next hop type: ").append(resource.nextHopType()) 2590 | .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) 2591 | .append("\n\tRoute table id: ").append(resource.routeTableId()) 2592 | .toString()); 2593 | } 2594 | 2595 | /** 2596 | * Print container group info. 2597 | * 2598 | * @param resource a container group 2599 | */ 2600 | public static void print(ContainerGroup resource) { 2601 | StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) 2602 | .append("Name: ").append(resource.name()) 2603 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 2604 | .append("\n\tRegion: ").append(resource.region()) 2605 | .append("\n\tTags: ").append(resource.tags()) 2606 | .append("\n\tOS type: ").append(resource.osType()); 2607 | 2608 | if (resource.ipAddress() != null) { 2609 | info.append("\n\tPublic IP address: ").append(resource.ipAddress()); 2610 | } 2611 | if (resource.externalTcpPorts() != null) { 2612 | info.append("\n\tExternal TCP ports:"); 2613 | for (int port : resource.externalTcpPorts()) { 2614 | info.append(" ").append(port); 2615 | } 2616 | } 2617 | if (resource.externalUdpPorts() != null) { 2618 | info.append("\n\tExternal UDP ports:"); 2619 | for (int port : resource.externalUdpPorts()) { 2620 | info.append(" ").append(port); 2621 | } 2622 | } 2623 | if (resource.imageRegistryServers() != null) { 2624 | info.append("\n\tPrivate Docker image registries:"); 2625 | for (String server : resource.imageRegistryServers()) { 2626 | info.append(" ").append(server); 2627 | } 2628 | } 2629 | if (resource.volumes() != null) { 2630 | info.append("\n\tVolume mapping: "); 2631 | for (Map.Entry entry: resource.volumes().entrySet()) { 2632 | info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") 2633 | .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); 2634 | } 2635 | } 2636 | if (resource.containers() != null) { 2637 | info.append("\n\tContainer instances: "); 2638 | for (Map.Entry entry: resource.containers().entrySet()) { 2639 | Container container = entry.getValue(); 2640 | info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); 2641 | info.append("\n\t\t\tResources: "); 2642 | info.append(container.resources().requests().cpu()).append("CPUs "); 2643 | info.append(container.resources().requests().memoryInGB()).append("GB"); 2644 | info.append("\n\t\t\tPorts:"); 2645 | for (ContainerPort port : container.ports()) { 2646 | info.append(" ").append(port.port()); 2647 | } 2648 | if (container.volumeMounts() != null) { 2649 | info.append("\n\t\t\tVolume mounts:"); 2650 | for (VolumeMount volumeMount : container.volumeMounts()) { 2651 | info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); 2652 | } 2653 | } 2654 | if (container.command() != null) { 2655 | info.append("\n\t\t\tStart commands:"); 2656 | for (String command : container.command()) { 2657 | info.append("\n\t\t\t\t").append(command); 2658 | } 2659 | } 2660 | if (container.environmentVariables() != null) { 2661 | info.append("\n\t\t\tENV vars:"); 2662 | for (EnvironmentVariable envVar : container.environmentVariables()) { 2663 | info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); 2664 | } 2665 | } 2666 | } 2667 | } 2668 | 2669 | System.out.println(info.toString()); 2670 | } 2671 | 2672 | /** 2673 | * Print event hub namespace. 2674 | * 2675 | * @param resource a virtual machine 2676 | */ 2677 | public static void print(EventHubNamespace resource) { 2678 | StringBuilder info = new StringBuilder(); 2679 | info.append("Eventhub Namespace: ").append(resource.id()) 2680 | .append("\n\tName: ").append(resource.name()) 2681 | .append("\n\tRegion: ").append(resource.region()) 2682 | .append("\n\tTags: ").append(resource.tags()) 2683 | .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) 2684 | .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) 2685 | .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) 2686 | .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) 2687 | .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) 2688 | .append("\n\tCreated time: ").append(resource.createdAt()) 2689 | .append("\n\tUpdated time: ").append(resource.updatedAt()); 2690 | 2691 | System.out.println(info.toString()); 2692 | } 2693 | 2694 | /** 2695 | * Print event hub. 2696 | * 2697 | * @param resource event hub 2698 | */ 2699 | public static void print(EventHub resource) { 2700 | StringBuilder info = new StringBuilder(); 2701 | info.append("Eventhub: ").append(resource.id()) 2702 | .append("\n\tName: ").append(resource.name()) 2703 | .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) 2704 | .append("\n\tNamespace: ").append(resource.namespaceName()) 2705 | .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) 2706 | .append("\n\tPartition ids: ").append(resource.partitionIds()); 2707 | if (resource.isDataCaptureEnabled()) { 2708 | info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); 2709 | info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); 2710 | if (resource.captureDestination() != null) { 2711 | info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); 2712 | info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); 2713 | } 2714 | } 2715 | System.out.println(info.toString()); 2716 | } 2717 | 2718 | /** 2719 | * Print event hub namespace recovery pairing. 2720 | * 2721 | * @param resource event hub namespace disaster recovery pairing 2722 | */ 2723 | public static void print(EventHubDisasterRecoveryPairing resource) { 2724 | StringBuilder info = new StringBuilder(); 2725 | info.append("DisasterRecoveryPairing: ").append(resource.id()) 2726 | .append("\n\tName: ").append(resource.name()) 2727 | .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) 2728 | .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) 2729 | .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) 2730 | .append("\n\tNamespace role: ").append(resource.namespaceRole()); 2731 | System.out.println(info.toString()); 2732 | } 2733 | 2734 | /** 2735 | * Print event hub namespace recovery pairing auth rules. 2736 | * 2737 | * @param resource event hub namespace disaster recovery pairing auth rule 2738 | */ 2739 | public static void print(DisasterRecoveryPairingAuthorizationRule resource) { 2740 | StringBuilder info = new StringBuilder(); 2741 | info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); 2742 | List rightsStr = new ArrayList<>(); 2743 | for (com.microsoft.azure.management.eventhub.AccessRights rights : resource.rights()) { 2744 | rightsStr.add(rights.toString()); 2745 | } 2746 | info.append("\n\tRights: ").append(rightsStr); 2747 | System.out.println(info.toString()); 2748 | } 2749 | 2750 | /** 2751 | * Print event hub namespace recovery pairing auth rule key. 2752 | * 2753 | * @param resource event hub namespace disaster recovery pairing auth rule key 2754 | */ 2755 | public static void print(DisasterRecoveryPairingAuthorizationKey resource) { 2756 | StringBuilder info = new StringBuilder(); 2757 | info.append("DisasterRecoveryPairing auth key: ") 2758 | .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) 2759 | .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) 2760 | .append("\n\t Primary key: ").append(resource.primaryKey()) 2761 | .append("\n\t Secondary key: ").append(resource.secondaryKey()) 2762 | .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) 2763 | .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); 2764 | System.out.println(info.toString()); 2765 | } 2766 | 2767 | /** 2768 | * Print event hub consumer group. 2769 | * 2770 | * @param resource event hub consumer group 2771 | */ 2772 | public static void print(EventHubConsumerGroup resource) { 2773 | StringBuilder info = new StringBuilder(); 2774 | info.append("Event hub consumer group: ").append(resource.id()) 2775 | .append("\n\tName: ").append(resource.name()) 2776 | .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) 2777 | .append("\n\tNamespace: ").append(resource.namespaceName()) 2778 | .append("\n\tEvent hub name: ").append(resource.eventHubName()) 2779 | .append("\n\tUser metadata: ").append(resource.userMetadata()); 2780 | System.out.println(info.toString()); 2781 | } 2782 | 2783 | /** 2784 | * Print Batch AI Cluster. 2785 | * 2786 | * @param resource batch ai cluster 2787 | */ 2788 | public static void print(BatchAICluster resource) { 2789 | StringBuilder info = new StringBuilder("Batch AI cluster: ") 2790 | .append("\n\tId: ").append(resource.id()) 2791 | .append("\n\tName: ").append(resource.name()) 2792 | .append("\n\tResource group: ").append(resource.workspace().resourceGroupName()) 2793 | .append("\n\tRegion: ").append(resource.workspace().regionName()) 2794 | .append("\n\tVM Size: ").append(resource.vmSize()) 2795 | .append("\n\tVM Priority: ").append(resource.vmPriority()) 2796 | .append("\n\tSubnet: ").append(resource.subnet()) 2797 | .append("\n\tAllocation state: ").append(resource.allocationState()) 2798 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) 2799 | .append("\n\tCreation time: ").append(resource.creationTime()) 2800 | .append("\n\tCurrent node count: ").append(resource.currentNodeCount()) 2801 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) 2802 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()); 2803 | if (resource.scaleSettings().autoScale() != null) { 2804 | info.append("\n\tAuto scale settings: ") 2805 | .append("\n\t\tInitial node count: ").append(resource.scaleSettings().autoScale().initialNodeCount()) 2806 | .append("\n\t\tMinimum node count: ").append(resource.scaleSettings().autoScale().minimumNodeCount()) 2807 | .append("\n\t\tMaximum node count: ").append(resource.scaleSettings().autoScale().maximumNodeCount()); 2808 | } 2809 | if (resource.scaleSettings().manual() != null) { 2810 | info.append("\n\tManual scale settings: ") 2811 | .append("\n\t\tTarget node count: ").append(resource.scaleSettings().manual().targetNodeCount()) 2812 | .append("\n\t\tDeallocation option: ") 2813 | .append(resource.scaleSettings().manual().nodeDeallocationOption()); 2814 | } 2815 | if (resource.nodeStateCounts() != null) { 2816 | info.append("\n\tNode state counts: ") 2817 | .append("\n\t\tRunning nodes count: ").append(resource.nodeStateCounts().runningNodeCount()) 2818 | .append("\n\t\tIdle nodes count: ").append(resource.nodeStateCounts().idleNodeCount()) 2819 | .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()) 2820 | .append("\n\t\tLeaving nodes count: ").append(resource.nodeStateCounts().leavingNodeCount()) 2821 | .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()); 2822 | } 2823 | if (resource.virtualMachineConfiguration() != null && resource.virtualMachineConfiguration().imageReference() != null) { 2824 | info.append("\n\tVirtual machine configuration: ") 2825 | .append("\n\t\tPublisher: ").append(resource.virtualMachineConfiguration().imageReference().publisher()) 2826 | .append("\n\t\tOffer: ").append(resource.virtualMachineConfiguration().imageReference().offer()) 2827 | .append("\n\t\tSku: ").append(resource.virtualMachineConfiguration().imageReference().sku()) 2828 | .append("\n\t\tVersion: ").append(resource.virtualMachineConfiguration().imageReference().version()); 2829 | } 2830 | if (resource.nodeSetup() != null && resource.nodeSetup().setupTask() != null) { 2831 | info.append("\n\tSetup task: ") 2832 | .append("\n\t\tCommand line: ").append(resource.nodeSetup().setupTask().commandLine()) 2833 | .append("\n\t\tStdout/err Path Prefix: ").append(resource.nodeSetup().setupTask().stdOutErrPathPrefix()); 2834 | } 2835 | System.out.println(info.toString()); 2836 | } 2837 | 2838 | /** 2839 | * Print Batch AI Job. 2840 | * 2841 | * @param resource batch ai job 2842 | */ 2843 | public static void print(BatchAIJob resource) { 2844 | StringBuilder info = new StringBuilder("Batch AI job: ") 2845 | .append("\n\tId: ").append(resource.id()) 2846 | .append("\n\tName: ").append(resource.name()) 2847 | .append("\n\tCluster Id: ").append(resource.cluster()) 2848 | .append("\n\tCreation time: ").append(resource.creationTime()) 2849 | .append("\n\tNode count: ").append(resource.nodeCount()) 2850 | .append("\n\tPriority: ").append(resource.schedulingPriority()) 2851 | .append("\n\tExecution state: ").append(resource.executionState()) 2852 | .append("\n\tExecution state transition time: ").append(resource.executionStateTransitionTime()) 2853 | .append("\n\tTool type: ").append(resource.toolType()) 2854 | .append("\n\tExperiment name: ").append(resource.experiment().name()); 2855 | if (resource.mountVolumes() != null) { 2856 | info.append("\n\tMount volumes:"); 2857 | if (resource.mountVolumes().azureFileShares() != null) { 2858 | info.append("\n\t\tAzure fileshares:"); 2859 | for (AzureFileShareReference share : resource.mountVolumes().azureFileShares()) { 2860 | info.append("\n\t\t\tAccount name:").append(share.accountName()) 2861 | .append("\n\t\t\tFile Url:").append(share.azureFileUrl()) 2862 | .append("\n\t\t\tDirectory mode:").append(share.directoryMode()) 2863 | .append("\n\t\t\tFile mode:").append(share.fileMode()) 2864 | .append("\n\t\t\tRelative mount path:").append(share.relativeMountPath()); 2865 | } 2866 | } 2867 | } 2868 | System.out.println(info.toString()); 2869 | } 2870 | 2871 | /** 2872 | * Print Diagnostic Setting. 2873 | * 2874 | * @param resource Diagnostic Setting instance 2875 | */ 2876 | public static void print(DiagnosticSetting resource) { 2877 | StringBuilder info = new StringBuilder("Diagnostic Setting: ") 2878 | .append("\n\tId: ").append(resource.id()) 2879 | .append("\n\tAssociated resource Id: ").append(resource.resourceId()) 2880 | .append("\n\tName: ").append(resource.name()) 2881 | .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) 2882 | .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) 2883 | .append("\n\tEventHub name: ").append(resource.eventHubName()) 2884 | .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); 2885 | if (resource.logs() != null && !resource.logs().isEmpty()) { 2886 | info.append("\n\tLog Settings: "); 2887 | for (LogSettings ls : resource.logs()) { 2888 | info.append("\n\t\tCategory: ").append(ls.category()); 2889 | info.append("\n\t\tRetention policy: "); 2890 | if (ls.retentionPolicy() != null) { 2891 | info.append(ls.retentionPolicy().days() + " days"); 2892 | } else { 2893 | info.append("NONE"); 2894 | } 2895 | } 2896 | } 2897 | if (resource.metrics() != null && !resource.metrics().isEmpty()) { 2898 | info.append("\n\tMetric Settings: "); 2899 | for (MetricSettings ls : resource.metrics()) { 2900 | info.append("\n\t\tCategory: ").append(ls.category()); 2901 | info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); 2902 | info.append("\n\t\tRetention policy: "); 2903 | if (ls.retentionPolicy() != null) { 2904 | info.append(ls.retentionPolicy().days() + " days"); 2905 | } else { 2906 | info.append("NONE"); 2907 | } 2908 | } 2909 | } 2910 | System.out.println(info.toString()); 2911 | } 2912 | 2913 | /** 2914 | * Print Action group settings. 2915 | * 2916 | * @param actionGroup action group instance 2917 | */ 2918 | public static void print(ActionGroup actionGroup) { 2919 | StringBuilder info = new StringBuilder("Action Group: ") 2920 | .append("\n\tId: ").append(actionGroup.id()) 2921 | .append("\n\tName: ").append(actionGroup.name()) 2922 | .append("\n\tShort Name: ").append(actionGroup.shortName()); 2923 | 2924 | if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { 2925 | info.append("\n\tEmail receivers: "); 2926 | for (EmailReceiver er : actionGroup.emailReceivers()) { 2927 | info.append("\n\t\tName: ").append(er.name()); 2928 | info.append("\n\t\tEMail: ").append(er.emailAddress()); 2929 | info.append("\n\t\tStatus: ").append(er.status()); 2930 | info.append("\n\t\t==="); 2931 | } 2932 | } 2933 | 2934 | if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { 2935 | info.append("\n\tSMS text message receivers: "); 2936 | for (SmsReceiver er : actionGroup.smsReceivers()) { 2937 | info.append("\n\t\tName: ").append(er.name()); 2938 | info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); 2939 | info.append("\n\t\tStatus: ").append(er.status()); 2940 | info.append("\n\t\t==="); 2941 | } 2942 | } 2943 | 2944 | if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { 2945 | info.append("\n\tWebhook receivers: "); 2946 | for (WebhookReceiver er : actionGroup.webhookReceivers()) { 2947 | info.append("\n\t\tName: ").append(er.name()); 2948 | info.append("\n\t\tURI: ").append(er.serviceUri()); 2949 | info.append("\n\t\t==="); 2950 | } 2951 | } 2952 | 2953 | if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { 2954 | info.append("\n\tApp Push Notification receivers: "); 2955 | for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { 2956 | info.append("\n\t\tName: ").append(er.name()); 2957 | info.append("\n\t\tEmail: ").append(er.emailAddress()); 2958 | info.append("\n\t\t==="); 2959 | } 2960 | } 2961 | 2962 | if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { 2963 | info.append("\n\tVoice Message receivers: "); 2964 | for (VoiceReceiver er : actionGroup.voiceReceivers()) { 2965 | info.append("\n\t\tName: ").append(er.name()); 2966 | info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); 2967 | info.append("\n\t\t==="); 2968 | } 2969 | } 2970 | 2971 | if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { 2972 | info.append("\n\tAutomation Runbook receivers: "); 2973 | for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { 2974 | info.append("\n\t\tName: ").append(er.name()); 2975 | info.append("\n\t\tRunbook Name: ").append(er.runbookName()); 2976 | info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); 2977 | info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); 2978 | info.append("\n\t\tService URI: ").append(er.serviceUri()); 2979 | info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); 2980 | info.append("\n\t\t==="); 2981 | } 2982 | } 2983 | 2984 | if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { 2985 | info.append("\n\tAzure Functions receivers: "); 2986 | for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { 2987 | info.append("\n\t\tName: ").append(er.name()); 2988 | info.append("\n\t\tFunction Name: ").append(er.functionName()); 2989 | info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); 2990 | info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); 2991 | info.append("\n\t\t==="); 2992 | } 2993 | } 2994 | 2995 | if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { 2996 | info.append("\n\tLogic App receivers: "); 2997 | for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { 2998 | info.append("\n\t\tName: ").append(er.name()); 2999 | info.append("\n\t\tResource Id: ").append(er.resourceId()); 3000 | info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); 3001 | info.append("\n\t\t==="); 3002 | } 3003 | } 3004 | 3005 | if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { 3006 | info.append("\n\tITSM receivers: "); 3007 | for (ItsmReceiver er : actionGroup.itsmReceivers()) { 3008 | info.append("\n\t\tName: ").append(er.name()); 3009 | info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); 3010 | info.append("\n\t\tConnection Id: ").append(er.connectionId()); 3011 | info.append("\n\t\tRegion: ").append(er.region()); 3012 | info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); 3013 | info.append("\n\t\t==="); 3014 | } 3015 | } 3016 | System.out.println(info.toString()); 3017 | } 3018 | 3019 | /** 3020 | * Print activity log alert settings. 3021 | * 3022 | * @param activityLogAlert activity log instance 3023 | */ 3024 | public static void print(ActivityLogAlert activityLogAlert) { 3025 | 3026 | StringBuilder info = new StringBuilder("Activity Log Alert: ") 3027 | .append("\n\tId: ").append(activityLogAlert.id()) 3028 | .append("\n\tName: ").append(activityLogAlert.name()) 3029 | .append("\n\tDescription: ").append(activityLogAlert.description()) 3030 | .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); 3031 | 3032 | if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { 3033 | info.append("\n\tScopes: "); 3034 | for (String er : activityLogAlert.scopes()) { 3035 | info.append("\n\t\tId: ").append(er); 3036 | } 3037 | } 3038 | 3039 | if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { 3040 | info.append("\n\tAction Groups: "); 3041 | for (String er : activityLogAlert.actionGroupIds()) { 3042 | info.append("\n\t\tAction Group Id: ").append(er); 3043 | } 3044 | } 3045 | 3046 | if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { 3047 | info.append("\n\tAlert conditions (when all of is true): "); 3048 | for (Map.Entry er : activityLogAlert.equalsConditions().entrySet()) { 3049 | info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); 3050 | } 3051 | } 3052 | System.out.println(info.toString()); 3053 | } 3054 | 3055 | /** 3056 | * Print metric alert settings. 3057 | * 3058 | * @param metricAlert metric alert instance 3059 | */ 3060 | public static void print(MetricAlert metricAlert) { 3061 | 3062 | StringBuilder info = new StringBuilder("Metric Alert: ") 3063 | .append("\n\tId: ").append(metricAlert.id()) 3064 | .append("\n\tName: ").append(metricAlert.name()) 3065 | .append("\n\tDescription: ").append(metricAlert.description()) 3066 | .append("\n\tIs Enabled: ").append(metricAlert.enabled()) 3067 | .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) 3068 | .append("\n\tSeverity: ").append(metricAlert.severity()) 3069 | .append("\n\tWindow Size: ").append(metricAlert.windowSize()) 3070 | .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); 3071 | 3072 | if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { 3073 | info.append("\n\tScopes: "); 3074 | for (String er : metricAlert.scopes()) { 3075 | info.append("\n\t\tId: ").append(er); 3076 | } 3077 | } 3078 | 3079 | if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { 3080 | info.append("\n\tAction Groups: "); 3081 | for (String er : metricAlert.actionGroupIds()) { 3082 | info.append("\n\t\tAction Group Id: ").append(er); 3083 | } 3084 | } 3085 | 3086 | if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { 3087 | info.append("\n\tAlert conditions (when all of is true): "); 3088 | for (Map.Entry er : metricAlert.alertCriterias().entrySet()) { 3089 | MetricAlertCondition alertCondition = er.getValue(); 3090 | info.append("\n\t\tCondition name: ").append(er.getKey()) 3091 | .append("\n\t\tSignal name: ").append(alertCondition.metricName()) 3092 | .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) 3093 | .append("\n\t\tOperator: ").append(alertCondition.condition()) 3094 | .append("\n\t\tThreshold: ").append(alertCondition.threshold()) 3095 | .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); 3096 | if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { 3097 | for (MetricDimension dimon : alertCondition.dimensions()) { 3098 | info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); 3099 | for (String vals : dimon.values()) { 3100 | info.append(vals).append(", "); 3101 | } 3102 | info.append("]"); 3103 | } 3104 | } 3105 | } 3106 | } 3107 | System.out.println(info.toString()); 3108 | } 3109 | private static OkHttpClient httpClient; 3110 | 3111 | /** 3112 | * Ensure the HTTP client is valid. 3113 | * 3114 | */ 3115 | private static OkHttpClient ensureValidHttpClient() { 3116 | if (httpClient == null) { 3117 | httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build(); 3118 | } 3119 | 3120 | return httpClient; 3121 | } 3122 | 3123 | /** 3124 | * Connect to a specified URL using "curl" like HTTP GET client. 3125 | * 3126 | * @param url URL to be tested 3127 | * @return the HTTP GET response content 3128 | */ 3129 | public static String curl(String url) { 3130 | Request request = new Request.Builder().url(url).get().build(); 3131 | try { 3132 | return ensureValidHttpClient().newCall(request).execute().body().string(); 3133 | } catch (IOException e) { 3134 | return null; 3135 | } 3136 | } 3137 | } --------------------------------------------------------------------------------