├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── pom.xml └── src └── main └── java └── com └── microsoft └── azure └── management ├── containerservice └── samples │ └── ManageContainerServiceWithKubernetesOrchestrator.java └── samples ├── SSHShell.java └── 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/acs-java-manage-azure-container-service-with-kubernetes-orchestrator/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/acs-java-manage-azure-container-service-with-kubernetes-orchestrator/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 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - java 5 | products: 6 | - azure 7 | extensions: 8 | services: Containerservice 9 | platforms: java 10 | --- 11 | 12 | **Please use [azure-resourcemanager](https://aka.ms/azsdk/java/mgmt), see [sample](https://github.com/azure-samples/aks-java-deploy-image-from-acr-to-kubernetes/).** 13 | 14 | # Getting Started with Containerservice - Manage Container Service With Kubernetes Orchestrator - in Java # 15 | 16 | 17 | Azure Container Service sample for managing container service with Kubernetes orchestration. 18 | - Create an Azure Container Service with Kubernetes orchestration 19 | - Create a SSH private/public key 20 | - Update the number of agent virtual machines in an Azure Container Service 21 | 22 | 23 | ## Running this Sample ## 24 | 25 | To run this sample: 26 | 27 | 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). 28 | 29 | git clone https://github.com/Azure-Samples/acs-java-manage-azure-container-service-with-kubernetes-orchestrator.git 30 | 31 | cd acs-java-manage-azure-container-service-with-kubernetes-orchestrator 32 | 33 | mvn clean compile exec:java 34 | 35 | ## More information ## 36 | 37 | [http://azure.com/java](http://azure.com/java) 38 | 39 | If you don't have a Microsoft Azure subscription you can get a FREE trial account [here](http://go.microsoft.com/fwlink/?LinkId=330212) 40 | 41 | --- 42 | 43 | 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. 44 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.microsoft.azure 6 | acs-java-manage-azure-container-service-with-kubernetes-orchestrator 7 | 0.0.1-SNAPSHOT 8 | ManageContainerServiceWithKubernetesOrchestrator.java 9 | 10 | https://github.com/Azure/acs-java-manage-azure-container-service-with-kubernetes-orchestrator 11 | 12 | 13 | 14 | org.codehaus.mojo 15 | exec-maven-plugin 16 | 1.4.0 17 | 18 | com.microsoft.azure.management.containerservice.samples.ManageContainerServiceWithKubernetesOrchestrator 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.containerservice.samples.ManageContainerServiceWithKubernetesOrchestrator.java 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | com.microsoft.azure 55 | azure 56 | 1.36.3 57 | 58 | 59 | commons-net 60 | commons-net 61 | 3.3 62 | 63 | 64 | commons-lang 65 | commons-lang 66 | 2.6 67 | 68 | 69 | org.apache.commons 70 | commons-lang3 71 | 3.7 72 | 73 | 74 | com.jcraft 75 | jsch 76 | 0.1.55 77 | 78 | 79 | com.github.cverges.expect4j 80 | expect4j 81 | 1.6 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /src/main/java/com/microsoft/azure/management/containerservice/samples/ManageContainerServiceWithKubernetesOrchestrator.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.containerservice.samples; 8 | 9 | import com.microsoft.azure.management.Azure; 10 | import com.microsoft.azure.management.containerservice.ContainerService; 11 | import com.microsoft.azure.management.containerservice.ContainerServiceMasterProfileCount; 12 | import com.microsoft.azure.management.containerservice.ContainerServiceVMSizeTypes; 13 | import com.microsoft.azure.management.resources.fluentcore.arm.Region; 14 | import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; 15 | import com.microsoft.azure.management.samples.SSHShell; 16 | import com.microsoft.azure.management.samples.Utils; 17 | import com.microsoft.rest.LogLevel; 18 | 19 | import java.io.File; 20 | import java.nio.file.Files; 21 | import java.nio.file.Paths; 22 | import java.util.Date; 23 | 24 | /** 25 | * Azure Container Service sample for managing container service with Kubernetes orchestration. 26 | * - Create an Azure Container Service with Kubernetes orchestration 27 | * - Create a SSH private/public key 28 | * - Update the number of agent virtual machines in an Azure Container Service 29 | */ 30 | public class ManageContainerServiceWithKubernetesOrchestrator { 31 | 32 | /** 33 | * Main function which runs the actual sample. 34 | * 35 | * @param azure instance of the azure client 36 | * @param clientId secondary service principal client ID 37 | * @param secret secondary service principal secret 38 | * @return true if sample runs successfully 39 | */ 40 | public static boolean runSample(Azure azure, String clientId, String secret) { 41 | final String rgName = SdkContext.randomResourceName("rgACS", 15); 42 | final String acsName = SdkContext.randomResourceName("acssample", 30); 43 | final Region region = Region.US_EAST; 44 | String servicePrincipalClientId = clientId; // replace with a real service principal client id 45 | String servicePrincipalSecret = secret; // and corresponding secret 46 | final String rootUserName = "acsuser"; 47 | 48 | try { 49 | 50 | //============================================================= 51 | // If service principal client id and secret are not set via the local variables, attempt to read the service 52 | // principal client id and secret from a secondary ".azureauth" file set through an environment variable. 53 | // 54 | // If the environment variable was not set then reuse the main service principal set for running this sample. 55 | 56 | if (servicePrincipalClientId.isEmpty() || servicePrincipalSecret.isEmpty()) { 57 | servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); 58 | servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); 59 | if (servicePrincipalClientId.isEmpty() || servicePrincipalSecret.isEmpty()) { 60 | String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); 61 | 62 | if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { 63 | envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); 64 | } 65 | 66 | servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); 67 | servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); 68 | } 69 | } 70 | 71 | 72 | //============================================================= 73 | // Create an SSH private/public key pair to be used when creating the container service 74 | 75 | System.out.println("Creating an SSH private and public key pair"); 76 | 77 | SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); 78 | System.out.println("SSH private key value: " + sshKeys.getSshPrivateKey()); 79 | System.out.println("SSH public key value: " + sshKeys.getSshPublicKey()); 80 | 81 | 82 | //============================================================= 83 | // Create an Azure Container Service with Kubernetes orchestration 84 | 85 | System.out.println("Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); 86 | 87 | Date t1 = new Date(); 88 | 89 | ContainerService azureContainerService = azure.containerServices().define(acsName) 90 | .withRegion(region) 91 | .withNewResourceGroup(rgName) 92 | .withKubernetesOrchestration() 93 | .withServicePrincipal(servicePrincipalClientId, servicePrincipalSecret) 94 | .withLinux() 95 | .withRootUsername(rootUserName) 96 | .withSshKey(sshKeys.getSshPublicKey()) 97 | .withMasterNodeCount(ContainerServiceMasterProfileCount.MIN) 98 | .defineAgentPool("agentpool") 99 | .withVirtualMachineCount(1) 100 | .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D1_V2) 101 | .withDnsPrefix("dns-ap-" + acsName) 102 | .attach() 103 | .withMasterDnsPrefix("dns-" + acsName) 104 | .create(); 105 | 106 | Date t2 = new Date(); 107 | System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureContainerService.id()); 108 | Utils.print(azureContainerService); 109 | 110 | //============================================================= 111 | // Update a Kubernetes Azure Container Service with two agents (virtual machines) 112 | 113 | System.out.println("Updating a Kubernetes Azure Container Service with two agents (virtual machines)"); 114 | 115 | t1 = new Date(); 116 | 117 | azureContainerService.update() 118 | .withAgentVirtualMachineCount(2) 119 | .apply(); 120 | 121 | t2 = new Date(); 122 | System.out.println("Updated Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureContainerService.id()); 123 | Utils.print(azureContainerService); 124 | 125 | return true; 126 | } catch (Exception f) { 127 | System.out.println(f.getMessage()); 128 | f.printStackTrace(); 129 | } finally { 130 | try { 131 | System.out.println("Deleting Resource Group: " + rgName); 132 | azure.resourceGroups().beginDeleteByName(rgName); 133 | System.out.println("Deleted Resource Group: " + rgName); 134 | } catch (NullPointerException npe) { 135 | System.out.println("Did not create any resources in Azure. No clean up is necessary"); 136 | } catch (Exception g) { 137 | g.printStackTrace(); 138 | } 139 | } 140 | return false; 141 | } 142 | 143 | /** 144 | * Main entry point. 145 | * 146 | * @param args the parameters 147 | */ 148 | public static void main(String[] args) { 149 | try { 150 | //============================================================= 151 | // Authenticate 152 | 153 | final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); 154 | 155 | Azure azure = Azure.configure() 156 | .withLogLevel(LogLevel.BODY) 157 | .authenticate(credFile) 158 | .withDefaultSubscription(); 159 | 160 | // Print selected subscription 161 | System.out.println("Selected subscription: " + azure.subscriptionId()); 162 | 163 | runSample(azure, "", ""); 164 | } catch (Exception e) { 165 | System.out.println(e.getMessage()); 166 | e.printStackTrace(); 167 | } 168 | } 169 | } -------------------------------------------------------------------------------- /src/main/java/com/microsoft/azure/management/samples/SSHShell.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.jcraft.jsch.Channel; 10 | import com.jcraft.jsch.ChannelExec; 11 | import com.jcraft.jsch.ChannelSftp; 12 | import com.jcraft.jsch.ChannelShell; 13 | import com.jcraft.jsch.JSch; 14 | import com.jcraft.jsch.JSchException; 15 | import com.jcraft.jsch.KeyPair; 16 | import com.jcraft.jsch.Session; 17 | import expect4j.Closure; 18 | import expect4j.Expect4j; 19 | import expect4j.ExpectState; 20 | import expect4j.matches.Match; 21 | import expect4j.matches.RegExpMatch; 22 | import org.apache.oro.text.regex.MalformedPatternException; 23 | 24 | import java.io.BufferedOutputStream; 25 | import java.io.ByteArrayOutputStream; 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.util.ArrayList; 29 | import java.util.Hashtable; 30 | import java.util.List; 31 | 32 | /** 33 | * Utility class to run commands on Linux VM via SSH. 34 | */ 35 | public final class SSHShell { 36 | private final Session session; 37 | private final ChannelShell channel; 38 | private final Expect4j expect; 39 | private final StringBuilder shellBuffer = new StringBuilder(); 40 | private List linuxPromptMatches = new ArrayList<>(); 41 | 42 | /** 43 | * Creates SSHShell. 44 | * 45 | * @param host the host name 46 | * @param port the ssh port 47 | * @param userName the ssh user name 48 | * @param password the ssh password 49 | * @return the shell 50 | * @throws JSchException 51 | * @throws IOException 52 | */ 53 | private SSHShell(String host, int port, String userName, String password) 54 | throws JSchException, IOException { 55 | Closure expectClosure = getExpectClosure(); 56 | for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) { 57 | try { 58 | Match match = new RegExpMatch(linuxPromptPattern, expectClosure); 59 | linuxPromptMatches.add(match); 60 | } catch (MalformedPatternException malformedEx) { 61 | throw new RuntimeException(malformedEx); 62 | } 63 | } 64 | JSch jsch = new JSch(); 65 | this.session = jsch.getSession(userName, host, port); 66 | session.setPassword(password); 67 | Hashtable config = new Hashtable<>(); 68 | config.put("StrictHostKeyChecking", "no"); 69 | session.setConfig(config); 70 | session.connect(60000); 71 | this.channel = (ChannelShell) session.openChannel("shell"); 72 | this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); 73 | channel.connect(); 74 | } 75 | 76 | /** 77 | * Creates SSHShell. 78 | * 79 | * @param host the host name 80 | * @param port the ssh port 81 | * @param userName the ssh user name 82 | * @param sshPrivateKey the ssh password 83 | * @return the shell 84 | * @throws JSchException 85 | * @throws IOException 86 | */ 87 | private SSHShell(String host, int port, String userName, byte[] sshPrivateKey) 88 | throws JSchException, IOException { 89 | Closure expectClosure = getExpectClosure(); 90 | for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) { 91 | try { 92 | Match match = new RegExpMatch(linuxPromptPattern, expectClosure); 93 | linuxPromptMatches.add(match); 94 | } catch (MalformedPatternException malformedEx) { 95 | throw new RuntimeException(malformedEx); 96 | } 97 | } 98 | JSch jsch = new JSch(); 99 | jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts"); 100 | jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null); 101 | this.session = jsch.getSession(userName, host, port); 102 | this.session.setConfig("StrictHostKeyChecking", "no"); 103 | this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); 104 | session.connect(60000); 105 | this.channel = (ChannelShell) session.openChannel("shell"); 106 | this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); 107 | channel.connect(); 108 | } 109 | 110 | /** 111 | * Opens a SSH shell. 112 | * 113 | * @param host the host name 114 | * @param port the ssh port 115 | * @param userName the ssh user name 116 | * @param password the ssh password 117 | * @return the shell 118 | * @throws JSchException exception thrown 119 | * @throws IOException IO exception thrown 120 | */ 121 | public static SSHShell open(String host, int port, String userName, String password) 122 | throws JSchException, IOException { 123 | return new SSHShell(host, port, userName, password); 124 | } 125 | 126 | /** 127 | * Opens a SSH shell. 128 | * 129 | * @param host the host name 130 | * @param port the ssh port 131 | * @param userName the ssh user name 132 | * @param sshPrivateKey the ssh private key 133 | * @return the shell 134 | * @throws JSchException exception thrown 135 | * @throws IOException IO exception thrown 136 | */ 137 | public static SSHShell open(String host, int port, String userName, byte[] sshPrivateKey) 138 | throws JSchException, IOException { 139 | return new SSHShell(host, port, userName, sshPrivateKey); 140 | } 141 | 142 | /** 143 | * Runs a given list of commands in the shell. 144 | * 145 | * @param commands the commands 146 | * @return the result 147 | * @throws Exception exception thrown 148 | */ 149 | public String runCommands(List commands) throws Exception { 150 | String output = null; 151 | try { 152 | for (String command : commands) { 153 | expect.expect(this.linuxPromptMatches); 154 | expect.send(command); 155 | expect.send("\r"); 156 | expect.expect(this.linuxPromptMatches); 157 | } 158 | output = shellBuffer.toString(); 159 | } finally { 160 | shellBuffer.setLength(0); 161 | } 162 | return output; 163 | } 164 | 165 | /** 166 | * Executes a command on the remote host. 167 | * 168 | * @param command the command to be executed 169 | * @param getExitStatus return the exit status captured in the stdout 170 | * @param withErr capture the stderr as part of the output 171 | * @return the content of the remote output from executing the command 172 | * @throws Exception exception thrown 173 | */ 174 | public String executeCommand(String command, Boolean getExitStatus, Boolean withErr) throws Exception { 175 | String result = ""; 176 | String resultErr = ""; 177 | 178 | Channel channel = this.session.openChannel("exec"); 179 | ((ChannelExec) channel).setCommand(command); 180 | InputStream commandOutput = channel.getInputStream(); 181 | InputStream commandErr = ((ChannelExec) channel).getErrStream(); 182 | channel.connect(); 183 | byte[] tmp = new byte[4096]; 184 | while (true) { 185 | while (commandOutput.available() > 0) { 186 | int i = commandOutput.read(tmp, 0, 4096); 187 | if (i < 0) { 188 | break; 189 | } 190 | result += new String(tmp, 0, i); 191 | } 192 | while (commandErr.available() > 0) { 193 | int i = commandErr.read(tmp, 0, 4096); 194 | if (i < 0) { 195 | break; 196 | } 197 | resultErr += new String(tmp, 0, i); 198 | } 199 | if (channel.isClosed()) { 200 | if (commandOutput.available() > 0) { 201 | continue; 202 | } 203 | if (getExitStatus) { 204 | result += "exit-status: " + channel.getExitStatus(); 205 | if (withErr) { 206 | result += "\n With error:\n" + resultErr; 207 | } 208 | } 209 | break; 210 | } 211 | try { 212 | Thread.sleep(100); 213 | } catch (Exception ee) { } 214 | } 215 | channel.disconnect(); 216 | 217 | return result; 218 | } 219 | 220 | /** 221 | * Downloads the content of a file from the remote host as a String. 222 | * 223 | * @param fileName the name of the file for which the content will be downloaded 224 | * @param fromPath the path of the file for which the content will be downloaded 225 | * @param isUserHomeBased true if the path of the file is relative to the user's home directory 226 | * @return the content of the file 227 | * @throws Exception exception thrown 228 | */ 229 | public String download(String fileName, String fromPath, boolean isUserHomeBased) throws Exception { 230 | ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp"); 231 | channel.connect(); 232 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 233 | BufferedOutputStream buff = new BufferedOutputStream(outputStream); 234 | String absolutePath = isUserHomeBased ? channel.getHome() + "/" + fromPath : fromPath; 235 | channel.cd(absolutePath); 236 | channel.get(fileName, buff); 237 | 238 | channel.disconnect(); 239 | 240 | return outputStream.toString(); 241 | } 242 | 243 | /** 244 | * Creates a new file on the remote host using the input content. 245 | * 246 | * @param from the byte array content to be uploaded 247 | * @param fileName the name of the file for which the content will be saved into 248 | * @param toPath the path of the file for which the content will be saved into 249 | * @param isUserHomeBased true if the path of the file is relative to the user's home directory 250 | * @param filePerm file permissions to be set 251 | * @throws Exception exception thrown 252 | */ 253 | public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) throws Exception { 254 | ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp"); 255 | channel.connect(); 256 | String absolutePath = isUserHomeBased ? channel.getHome() + "/" + toPath : toPath; 257 | 258 | String path = ""; 259 | for (String dir : absolutePath.split("/")) { 260 | path = path + "/" + dir; 261 | try { 262 | channel.mkdir(path); 263 | } catch (Exception ee) { 264 | } 265 | } 266 | channel.cd(absolutePath); 267 | channel.put(from, fileName); 268 | if (filePerm != null) { 269 | channel.chmod(Integer.parseInt(filePerm), absolutePath + "/" + fileName); 270 | } 271 | 272 | channel.disconnect(); 273 | } 274 | 275 | /** 276 | * Closes shell. 277 | */ 278 | public void close() { 279 | if (expect != null) { 280 | expect.close(); 281 | } 282 | if (channel != null) { 283 | channel.disconnect(); 284 | } 285 | if (session != null) { 286 | session.disconnect(); 287 | } 288 | } 289 | 290 | private Closure getExpectClosure() { 291 | return new Closure() { 292 | public void run(ExpectState expectState) throws Exception { 293 | String outputBuffer = expectState.getBuffer(); 294 | System.out.println(outputBuffer); 295 | shellBuffer.append(outputBuffer); 296 | expectState.exp_continue(); 297 | } 298 | }; 299 | } 300 | 301 | /** 302 | * Automatically generate SSH keys. 303 | * @param passPhrase the byte array content to be uploaded 304 | * @param comment the name of the file for which the content will be saved into 305 | * @return SSH public and private key 306 | * @throws Exception exception thrown 307 | */ 308 | public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception { 309 | JSch jsch = new JSch(); 310 | KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA); 311 | ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048); 312 | ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048); 313 | 314 | keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts"); 315 | 316 | if (passPhrase == null || passPhrase.isEmpty()) { 317 | keyPair.writePrivateKey(privateKeyBuff); 318 | } else { 319 | keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes()); 320 | } 321 | 322 | return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString()); 323 | } 324 | 325 | /** 326 | * Internal class to retain the generate SSH keys. 327 | */ 328 | public static class SshPublicPrivateKey { 329 | private String sshPublicKey; 330 | private String sshPrivateKey; 331 | 332 | /** 333 | * Constructor. 334 | * @param sshPrivateKey SSH private key 335 | * @param sshPublicKey SSH public key 336 | */ 337 | public SshPublicPrivateKey(String sshPrivateKey, String sshPublicKey) { 338 | this.sshPrivateKey = sshPrivateKey; 339 | this.sshPublicKey = sshPublicKey; 340 | } 341 | 342 | /** 343 | * Get SSH public key. 344 | * @return public key 345 | */ 346 | public String getSshPublicKey() { 347 | return sshPublicKey; 348 | } 349 | 350 | /** 351 | * Get SSH private key. 352 | * @return private key 353 | */ 354 | public String getSshPrivateKey() { 355 | return sshPrivateKey; 356 | } 357 | 358 | /** 359 | * Set SSH public key. 360 | * @param sshPublicKey public key 361 | */ 362 | public void setSshPublicKey(String sshPublicKey) { 363 | this.sshPublicKey = sshPublicKey; 364 | } 365 | 366 | /** 367 | * Set SSH private key. 368 | * @param sshPrivateKey private key 369 | */ 370 | public void setSshPrivateKey(String sshPrivateKey) { 371 | this.sshPrivateKey = sshPrivateKey; 372 | } 373 | } 374 | } 375 | -------------------------------------------------------------------------------- /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 HTTPS probes 743 | info.append("\n\tHTTPS probes: ") 744 | .append(resource.httpsProbes().size()); 745 | for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { 746 | info.append("\n\t\tProbe name: ").append(probe.name()) 747 | .append("\n\t\t\tPort: ").append(probe.port()) 748 | .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) 749 | .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) 750 | .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); 751 | 752 | // Show associated load balancing rules 753 | info.append("\n\t\t\tReferenced from load balancing rules: ") 754 | .append(probe.loadBalancingRules().size()); 755 | for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { 756 | info.append("\n\t\t\t\tName: ").append(rule.name()); 757 | } 758 | } 759 | 760 | // Show load balancing rules 761 | info.append("\n\tLoad balancing rules: ") 762 | .append(resource.loadBalancingRules().size()); 763 | for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { 764 | info.append("\n\t\tLB rule name: ").append(rule.name()) 765 | .append("\n\t\t\tProtocol: ").append(rule.protocol()) 766 | .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) 767 | .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) 768 | .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); 769 | 770 | LoadBalancerFrontend frontend = rule.frontend(); 771 | info.append("\n\t\t\tFrontend: "); 772 | if (frontend != null) { 773 | info.append(frontend.name()); 774 | } else { 775 | info.append("(None)"); 776 | } 777 | 778 | info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); 779 | 780 | LoadBalancerBackend backend = rule.backend(); 781 | info.append("\n\t\t\tBackend: "); 782 | if (backend != null) { 783 | info.append(backend.name()); 784 | } else { 785 | info.append("(None)"); 786 | } 787 | 788 | info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); 789 | 790 | LoadBalancerProbe probe = rule.probe(); 791 | info.append("\n\t\t\tProbe: "); 792 | if (probe == null) { 793 | info.append("(None)"); 794 | } else { 795 | info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); 796 | } 797 | } 798 | 799 | // Show frontends 800 | info.append("\n\tFrontends: ") 801 | .append(resource.frontends().size()); 802 | for (LoadBalancerFrontend frontend : resource.frontends().values()) { 803 | info.append("\n\t\tFrontend name: ").append(frontend.name()) 804 | .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); 805 | if (frontend.isPublic()) { 806 | info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIPAddressId()); 807 | } else { 808 | info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) 809 | .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) 810 | .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAddress()) 811 | .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAllocationMethod()); 812 | } 813 | 814 | // Inbound NAT pool references 815 | info.append("\n\t\t\tReferenced inbound NAT pools: ") 816 | .append(frontend.inboundNatPools().size()); 817 | for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { 818 | info.append("\n\t\t\t\tName: ").append(pool.name()); 819 | } 820 | 821 | // Inbound NAT rule references 822 | info.append("\n\t\t\tReferenced inbound NAT rules: ") 823 | .append(frontend.inboundNatRules().size()); 824 | for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { 825 | info.append("\n\t\t\t\tName: ").append(rule.name()); 826 | } 827 | 828 | // Load balancing rule references 829 | info.append("\n\t\t\tReferenced load balancing rules: ") 830 | .append(frontend.loadBalancingRules().size()); 831 | for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { 832 | info.append("\n\t\t\t\tName: ").append(rule.name()); 833 | } 834 | } 835 | 836 | // Show inbound NAT rules 837 | info.append("\n\tInbound NAT rules: ") 838 | .append(resource.inboundNatRules().size()); 839 | for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { 840 | info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) 841 | .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) 842 | .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) 843 | .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) 844 | .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) 845 | .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) 846 | .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIPConfigurationName()) 847 | .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) 848 | .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); 849 | } 850 | 851 | // Show inbound NAT pools 852 | info.append("\n\tInbound NAT pools: ") 853 | .append(resource.inboundNatPools().size()); 854 | for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { 855 | info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) 856 | .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) 857 | .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) 858 | .append("\n\t\t\tFrontend port range: ") 859 | .append(natPool.frontendPortRangeStart()) 860 | .append("-") 861 | .append(natPool.frontendPortRangeEnd()) 862 | .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); 863 | } 864 | 865 | // Show backends 866 | info.append("\n\tBackends: ") 867 | .append(resource.backends().size()); 868 | for (LoadBalancerBackend backend : resource.backends().values()) { 869 | info.append("\n\t\tBackend name: ").append(backend.name()); 870 | 871 | // Show assigned backend NICs 872 | info.append("\n\t\t\tReferenced NICs: ") 873 | .append(backend.backendNicIPConfigurationNames().entrySet().size()); 874 | for (Map.Entry entry : backend.backendNicIPConfigurationNames().entrySet()) { 875 | info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) 876 | .append(" - IP Config: ").append(entry.getValue()); 877 | } 878 | 879 | // Show assigned virtual machines 880 | Set vmIds = backend.getVirtualMachineIds(); 881 | info.append("\n\t\t\tReferenced virtual machine ids: ") 882 | .append(vmIds.size()); 883 | for (String vmId : vmIds) { 884 | info.append("\n\t\t\t\tVM ID: ").append(vmId); 885 | } 886 | 887 | // Show assigned load balancing rules 888 | info.append("\n\t\t\tReferenced load balancing rules: ") 889 | .append(new ArrayList(backend.loadBalancingRules().keySet())); 890 | } 891 | 892 | System.out.println(info.toString()); 893 | } 894 | 895 | /** 896 | * Prints batch account keys. 897 | * 898 | * @param batchAccountKeys a list of batch account keys 899 | */ 900 | public static void print(BatchAccountKeys batchAccountKeys) { 901 | System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" 902 | + batchAccountKeys.secondary() + ")"); 903 | } 904 | 905 | /** 906 | * Prints batch account. 907 | * 908 | * @param batchAccount a Batch Account 909 | */ 910 | public static void print(BatchAccount batchAccount) { 911 | StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); 912 | 913 | if (batchAccount.applications().size() > 0) { 914 | for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { 915 | Application application = applicationEntry.getValue(); 916 | StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); 917 | 918 | for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { 919 | ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); 920 | StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); 921 | singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); 922 | 923 | applicationPackages.append(singleApplicationPackage); 924 | singleApplicationPackage.append("\n"); 925 | } 926 | 927 | StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); 928 | singleApplication.append("\n\t\tdisplayName: " + application.displayName()); 929 | singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); 930 | singleApplication.append(applicationPackages); 931 | applicationsOutput.append(singleApplication); 932 | applicationsOutput.append("\n"); 933 | } 934 | } 935 | 936 | System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) 937 | .append("Name: ").append(batchAccount.name()) 938 | .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) 939 | .append("\n\tRegion: ").append(batchAccount.region()) 940 | .append("\n\tTags: ").append(batchAccount.tags()) 941 | .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) 942 | .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) 943 | .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) 944 | .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) 945 | .append(applicationsOutput) 946 | .toString()); 947 | } 948 | 949 | /** 950 | * Print app service domain. 951 | * 952 | * @param resource an app service domain 953 | */ 954 | public static void print(AppServiceDomain resource) { 955 | StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) 956 | .append("Name: ").append(resource.name()) 957 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 958 | .append("\n\tRegion: ").append(resource.region()) 959 | .append("\n\tCreated time: ").append(resource.createdTime()) 960 | .append("\n\tExpiration time: ").append(resource.expirationTime()) 961 | .append("\n\tContact: "); 962 | Contact contact = resource.registrantContact(); 963 | if (contact == null) { 964 | builder = builder.append("Private"); 965 | } else { 966 | builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); 967 | } 968 | builder = builder.append("\n\tName servers: "); 969 | for (String nameServer : resource.nameServers()) { 970 | builder = builder.append("\n\t\t" + nameServer); 971 | } 972 | System.out.println(builder.toString()); 973 | } 974 | 975 | /** 976 | * Print app service certificate order. 977 | * 978 | * @param resource an app service certificate order 979 | */ 980 | public static void print(AppServiceCertificateOrder resource) { 981 | StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) 982 | .append("Name: ").append(resource.name()) 983 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 984 | .append("\n\tRegion: ").append(resource.region()) 985 | .append("\n\tDistinguished name: ").append(resource.distinguishedName()) 986 | .append("\n\tProduct type: ").append(resource.productType()) 987 | .append("\n\tValid years: ").append(resource.validityInYears()) 988 | .append("\n\tStatus: ").append(resource.status()) 989 | .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) 990 | .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); 991 | System.out.println(builder.toString()); 992 | } 993 | 994 | /** 995 | * Print app service plan. 996 | * 997 | * @param resource an app service plan 998 | */ 999 | public static void print(AppServicePlan resource) { 1000 | StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) 1001 | .append("Name: ").append(resource.name()) 1002 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 1003 | .append("\n\tRegion: ").append(resource.region()) 1004 | .append("\n\tPricing tier: ").append(resource.pricingTier()); 1005 | System.out.println(builder.toString()); 1006 | } 1007 | 1008 | /** 1009 | * Print a web app. 1010 | * 1011 | * @param resource a web app 1012 | */ 1013 | public static void print(WebAppBase resource) { 1014 | StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) 1015 | .append("\n\tName: ").append(resource.name()) 1016 | .append("\n\tState: ").append(resource.state()) 1017 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 1018 | .append("\n\tRegion: ").append(resource.region()) 1019 | .append("\n\tDefault hostname: ").append(resource.defaultHostName()) 1020 | .append("\n\tApp service plan: ").append(resource.appServicePlanId()) 1021 | .append("\n\tHost name bindings: "); 1022 | for (HostNameBinding binding : resource.getHostNameBindings().values()) { 1023 | builder = builder.append("\n\t\t" + binding.toString()); 1024 | } 1025 | builder = builder.append("\n\tSSL bindings: "); 1026 | for (HostNameSslState binding : resource.hostNameSslStates().values()) { 1027 | builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); 1028 | if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { 1029 | builder = builder.append(" - " + binding.thumbprint()); 1030 | } 1031 | } 1032 | builder = builder.append("\n\tApp settings: "); 1033 | for (AppSetting setting : resource.getAppSettings().values()) { 1034 | builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); 1035 | } 1036 | builder = builder.append("\n\tConnection strings: "); 1037 | for (ConnectionString conn : resource.getConnectionStrings().values()) { 1038 | builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); 1039 | } 1040 | System.out.println(builder.toString()); 1041 | } 1042 | 1043 | /** 1044 | * Print a traffic manager profile. 1045 | * 1046 | * @param profile a traffic manager profile 1047 | */ 1048 | public static void print(TrafficManagerProfile profile) { 1049 | StringBuilder info = new StringBuilder(); 1050 | info.append("Traffic Manager Profile: ").append(profile.id()) 1051 | .append("\n\tName: ").append(profile.name()) 1052 | .append("\n\tResource group: ").append(profile.resourceGroupName()) 1053 | .append("\n\tRegion: ").append(profile.regionName()) 1054 | .append("\n\tTags: ").append(profile.tags()) 1055 | .append("\n\tDNSLabel: ").append(profile.dnsLabel()) 1056 | .append("\n\tFQDN: ").append(profile.fqdn()) 1057 | .append("\n\tTTL: ").append(profile.timeToLive()) 1058 | .append("\n\tEnabled: ").append(profile.isEnabled()) 1059 | .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) 1060 | .append("\n\tMonitor status: ").append(profile.monitorStatus()) 1061 | .append("\n\tMonitoring port: ").append(profile.monitoringPort()) 1062 | .append("\n\tMonitoring path: ").append(profile.monitoringPath()); 1063 | 1064 | Map azureEndpoints = profile.azureEndpoints(); 1065 | if (!azureEndpoints.isEmpty()) { 1066 | info.append("\n\tAzure endpoints:"); 1067 | int idx = 1; 1068 | for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { 1069 | info.append("\n\t\tAzure endpoint: #").append(idx++) 1070 | .append("\n\t\t\tId: ").append(endpoint.id()) 1071 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1072 | .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) 1073 | .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) 1074 | .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) 1075 | .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) 1076 | .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) 1077 | .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); 1078 | } 1079 | } 1080 | 1081 | Map externalEndpoints = profile.externalEndpoints(); 1082 | if (!externalEndpoints.isEmpty()) { 1083 | info.append("\n\tExternal endpoints:"); 1084 | int idx = 1; 1085 | for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { 1086 | info.append("\n\t\tExternal endpoint: #").append(idx++) 1087 | .append("\n\t\t\tId: ").append(endpoint.id()) 1088 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1089 | .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) 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 | 1098 | Map nestedProfileEndpoints = profile.nestedProfileEndpoints(); 1099 | if (!nestedProfileEndpoints.isEmpty()) { 1100 | info.append("\n\tNested profile endpoints:"); 1101 | int idx = 1; 1102 | for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { 1103 | info.append("\n\t\tNested profile endpoint: #").append(idx++) 1104 | .append("\n\t\t\tId: ").append(endpoint.id()) 1105 | .append("\n\t\t\tType: ").append(endpoint.endpointType()) 1106 | .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) 1107 | .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) 1108 | .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) 1109 | .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) 1110 | .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) 1111 | .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) 1112 | .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); 1113 | } 1114 | } 1115 | System.out.println(info.toString()); 1116 | } 1117 | 1118 | /** 1119 | * Print a dns zone. 1120 | * 1121 | * @param dnsZone a dns zone 1122 | */ 1123 | public static void print(DnsZone dnsZone) { 1124 | StringBuilder info = new StringBuilder(); 1125 | info.append("DNS Zone: ").append(dnsZone.id()) 1126 | .append("\n\tName (Top level domain): ").append(dnsZone.name()) 1127 | .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) 1128 | .append("\n\tRegion: ").append(dnsZone.regionName()) 1129 | .append("\n\tTags: ").append(dnsZone.tags()) 1130 | .append("\n\tName servers:"); 1131 | for (String nameServer : dnsZone.nameServers()) { 1132 | info.append("\n\t\t").append(nameServer); 1133 | } 1134 | SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); 1135 | SoaRecord soaRecord = soaRecordSet.record(); 1136 | info.append("\n\tSOA Record:") 1137 | .append("\n\t\tHost:").append(soaRecord.host()) 1138 | .append("\n\t\tEmail:").append(soaRecord.email()) 1139 | .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) 1140 | .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) 1141 | .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) 1142 | .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) 1143 | .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); 1144 | 1145 | PagedList aRecordSets = dnsZone.aRecordSets().list(); 1146 | info.append("\n\tA Record sets:"); 1147 | for (ARecordSet aRecordSet : aRecordSets) { 1148 | info.append("\n\t\tId: ").append(aRecordSet.id()) 1149 | .append("\n\t\tName: ").append(aRecordSet.name()) 1150 | .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) 1151 | .append("\n\t\tIP v4 addresses: "); 1152 | for (String ipAddress : aRecordSet.ipv4Addresses()) { 1153 | info.append("\n\t\t\t").append(ipAddress); 1154 | } 1155 | } 1156 | 1157 | PagedList aaaaRecordSets = dnsZone.aaaaRecordSets().list(); 1158 | info.append("\n\tAAAA Record sets:"); 1159 | for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { 1160 | info.append("\n\t\tId: ").append(aaaaRecordSet.id()) 1161 | .append("\n\t\tName: ").append(aaaaRecordSet.name()) 1162 | .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) 1163 | .append("\n\t\tIP v6 addresses: "); 1164 | for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { 1165 | info.append("\n\t\t\t").append(ipAddress); 1166 | } 1167 | } 1168 | 1169 | PagedList cnameRecordSets = dnsZone.cNameRecordSets().list(); 1170 | info.append("\n\tCNAME Record sets:"); 1171 | for (CNameRecordSet cnameRecordSet : cnameRecordSets) { 1172 | info.append("\n\t\tId: ").append(cnameRecordSet.id()) 1173 | .append("\n\t\tName: ").append(cnameRecordSet.name()) 1174 | .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) 1175 | .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); 1176 | } 1177 | 1178 | PagedList mxRecordSets = dnsZone.mxRecordSets().list(); 1179 | info.append("\n\tMX Record sets:"); 1180 | for (MXRecordSet mxRecordSet : mxRecordSets) { 1181 | info.append("\n\t\tId: ").append(mxRecordSet.id()) 1182 | .append("\n\t\tName: ").append(mxRecordSet.name()) 1183 | .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) 1184 | .append("\n\t\tRecords: "); 1185 | for (MxRecord mxRecord : mxRecordSet.records()) { 1186 | info.append("\n\t\t\tExchange server, Preference: ") 1187 | .append(mxRecord.exchange()) 1188 | .append(" ") 1189 | .append(mxRecord.preference()); 1190 | } 1191 | } 1192 | 1193 | PagedList nsRecordSets = dnsZone.nsRecordSets().list(); 1194 | info.append("\n\tNS Record sets:"); 1195 | for (NSRecordSet nsRecordSet : nsRecordSets) { 1196 | info.append("\n\t\tId: ").append(nsRecordSet.id()) 1197 | .append("\n\t\tName: ").append(nsRecordSet.name()) 1198 | .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) 1199 | .append("\n\t\tName servers: "); 1200 | for (String nameServer : nsRecordSet.nameServers()) { 1201 | info.append("\n\t\t\t").append(nameServer); 1202 | } 1203 | } 1204 | 1205 | PagedList ptrRecordSets = dnsZone.ptrRecordSets().list(); 1206 | info.append("\n\tPTR Record sets:"); 1207 | for (PtrRecordSet ptrRecordSet : ptrRecordSets) { 1208 | info.append("\n\t\tId: ").append(ptrRecordSet.id()) 1209 | .append("\n\t\tName: ").append(ptrRecordSet.name()) 1210 | .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) 1211 | .append("\n\t\tTarget domain names: "); 1212 | for (String domainNames : ptrRecordSet.targetDomainNames()) { 1213 | info.append("\n\t\t\t").append(domainNames); 1214 | } 1215 | } 1216 | 1217 | PagedList srvRecordSets = dnsZone.srvRecordSets().list(); 1218 | info.append("\n\tSRV Record sets:"); 1219 | for (SrvRecordSet srvRecordSet : srvRecordSets) { 1220 | info.append("\n\t\tId: ").append(srvRecordSet.id()) 1221 | .append("\n\t\tName: ").append(srvRecordSet.name()) 1222 | .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) 1223 | .append("\n\t\tRecords: "); 1224 | for (SrvRecord srvRecord : srvRecordSet.records()) { 1225 | info.append("\n\t\t\tTarget, Port, Priority, Weight: ") 1226 | .append(srvRecord.target()) 1227 | .append(", ") 1228 | .append(srvRecord.port()) 1229 | .append(", ") 1230 | .append(srvRecord.priority()) 1231 | .append(", ") 1232 | .append(srvRecord.weight()); 1233 | } 1234 | } 1235 | 1236 | PagedList txtRecordSets = dnsZone.txtRecordSets().list(); 1237 | info.append("\n\tTXT Record sets:"); 1238 | for (TxtRecordSet txtRecordSet : txtRecordSets) { 1239 | info.append("\n\t\tId: ").append(txtRecordSet.id()) 1240 | .append("\n\t\tName: ").append(txtRecordSet.name()) 1241 | .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) 1242 | .append("\n\t\tRecords: "); 1243 | for (TxtRecord txtRecord : txtRecordSet.records()) { 1244 | if (txtRecord.value().size() > 0) { 1245 | info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); 1246 | } 1247 | } 1248 | } 1249 | System.out.println(info.toString()); 1250 | } 1251 | 1252 | /** 1253 | * Print an Azure Container Registry. 1254 | * @param azureRegistry an Azure Container Registry 1255 | */ 1256 | public static void print(Registry azureRegistry) { 1257 | StringBuilder info = new StringBuilder(); 1258 | 1259 | RegistryCredentials acrCredentials = azureRegistry.getCredentials(); 1260 | info.append("Azure Container Registry: ").append(azureRegistry.id()) 1261 | .append("\n\tName: ").append(azureRegistry.name()) 1262 | .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) 1263 | .append("\n\tUser: ").append(acrCredentials.username()) 1264 | .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) 1265 | .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); 1266 | System.out.println(info.toString()); 1267 | } 1268 | 1269 | /** 1270 | * Print an Azure Container Service. 1271 | * @param containerService an Azure Container Service 1272 | */ 1273 | public static void print(ContainerService containerService) { 1274 | StringBuilder info = new StringBuilder(); 1275 | 1276 | info.append("Azure Container Service: ").append(containerService.id()) 1277 | .append("\n\tName: ").append(containerService.name()) 1278 | .append("\n\tWith orchestration: ").append(containerService.orchestratorType().toString()) 1279 | .append("\n\tMaster FQDN: ").append(containerService.masterFqdn()) 1280 | .append("\n\tMaster node count: ").append(containerService.masterNodeCount()) 1281 | .append("\n\tMaster domain label prefix: ").append(containerService.masterDnsPrefix()) 1282 | .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(containerService.agentPools().keySet()).get(0)) 1283 | .append("\n\t\tAgent pool count: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).count()) 1284 | .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).vmSize().toString()) 1285 | .append("\n\t\tAgent pool FQDN: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).fqdn()) 1286 | .append("\n\t\tAgent pool domain label prefix: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).dnsPrefix()) 1287 | .append("\n\tLinux user name: ").append(containerService.linuxRootUsername()) 1288 | .append("\n\tSSH key: ").append(containerService.sshKey()); 1289 | if (containerService.orchestratorType() == ContainerServiceOrchestratorTypes.KUBERNETES) { 1290 | info.append("\n\tName: ").append(containerService.servicePrincipalClientId()); 1291 | } 1292 | 1293 | System.out.println(info.toString()); 1294 | } 1295 | 1296 | /** 1297 | * Print an Azure Container Service (AKS). 1298 | * @param kubernetesCluster a managed container service 1299 | */ 1300 | public static void print(KubernetesCluster kubernetesCluster) { 1301 | StringBuilder info = new StringBuilder(); 1302 | 1303 | info.append("Azure Container Service: ").append(kubernetesCluster.id()) 1304 | .append("\n\tName: ").append(kubernetesCluster.name()) 1305 | .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) 1306 | .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) 1307 | .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) 1308 | .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) 1309 | .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) 1310 | .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) 1311 | .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) 1312 | .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); 1313 | 1314 | System.out.println(info.toString()); 1315 | } 1316 | 1317 | /** 1318 | * Print an Azure Search Service. 1319 | * @param searchService an Azure Search Service 1320 | */ 1321 | public static void print(SearchService searchService) { 1322 | StringBuilder info = new StringBuilder(); 1323 | AdminKeys adminKeys = searchService.getAdminKeys(); 1324 | List queryKeys = searchService.listQueryKeys(); 1325 | 1326 | info.append("Azure Search: ").append(searchService.id()) 1327 | .append("\n\tResource group: ").append(searchService.resourceGroupName()) 1328 | .append("\n\tRegion: ").append(searchService.region()) 1329 | .append("\n\tTags: ").append(searchService.tags()) 1330 | .append("\n\tSku: ").append(searchService.sku().name()) 1331 | .append("\n\tStatus: ").append(searchService.status()) 1332 | .append("\n\tProvisioning State: ").append(searchService.provisioningState()) 1333 | .append("\n\tHosting Mode: ").append(searchService.hostingMode()) 1334 | .append("\n\tReplicas: ").append(searchService.replicaCount()) 1335 | .append("\n\tPartitions: ").append(searchService.partitionCount()) 1336 | .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) 1337 | .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) 1338 | .append("\n\tQuery keys:"); 1339 | 1340 | for (QueryKey queryKey : queryKeys) { 1341 | info.append("\n\t\tKey name: ").append(queryKey.name()); 1342 | info.append("\n\t\t Value: ").append(queryKey.key()); 1343 | } 1344 | System.out.println(info.toString()); 1345 | } 1346 | 1347 | /** 1348 | * Retrieve the secondary service principal client ID. 1349 | * @param envSecondaryServicePrincipal an Azure Container Registry 1350 | * @return a service principal client ID 1351 | * @throws Exception exception 1352 | */ 1353 | public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws Exception { 1354 | Properties authSettings = new Properties(); 1355 | FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); 1356 | authSettings.load(credentialsFileStream); 1357 | credentialsFileStream.close(); 1358 | 1359 | return authSettings.getProperty("client"); 1360 | } 1361 | 1362 | /** 1363 | * Retrieve the secondary service principal secret. 1364 | * @param envSecondaryServicePrincipal an Azure Container Registry 1365 | * @return a service principal secret 1366 | * @throws Exception exception 1367 | */ 1368 | public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws Exception { 1369 | Properties authSettings = new Properties(); 1370 | FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); 1371 | authSettings.load(credentialsFileStream); 1372 | credentialsFileStream.close(); 1373 | 1374 | return authSettings.getProperty("key"); 1375 | } 1376 | 1377 | /** 1378 | * Creates and returns a randomized name based on the prefix file for use by the sample. 1379 | * @param namePrefix The prefix string to be used in generating the name. 1380 | * @return a random name 1381 | * */ 1382 | public static String createRandomName(String namePrefix) { 1383 | return SdkContext.randomResourceName(namePrefix, 30); 1384 | } 1385 | 1386 | /** 1387 | * This method creates a certificate for given password. 1388 | * 1389 | * @param certPath location of certificate file 1390 | * @param pfxPath location of pfx file 1391 | * @param alias User alias 1392 | * @param password alias password 1393 | * @param cnName domain name 1394 | * @throws Exception exceptions from the creation 1395 | */ 1396 | public static void createCertificate(String certPath, String pfxPath, 1397 | String alias, String password, String cnName) throws Exception { 1398 | SdkContext.prepareFileLocation(new File(pfxPath), new File(certPath)); 1399 | if (new File(pfxPath).exists()) { 1400 | return; 1401 | } 1402 | String validityInDays = "3650"; 1403 | String keyAlg = "RSA"; 1404 | String sigAlg = "SHA1withRSA"; 1405 | String keySize = "2048"; 1406 | String storeType = "pkcs12"; 1407 | String command = "keytool"; 1408 | String jdkPath = System.getProperty("java.home"); 1409 | if (jdkPath != null && !jdkPath.isEmpty()) { 1410 | jdkPath = jdkPath.concat("\\bin"); 1411 | if (new File(jdkPath).isDirectory()) { 1412 | command = String.format("%s%s%s", jdkPath, File.separator, command); 1413 | } 1414 | } else { 1415 | return; 1416 | } 1417 | 1418 | // Create Pfx file 1419 | String[] commandArgs = {command, "-genkey", "-alias", alias, 1420 | "-keystore", pfxPath, "-storepass", password, "-validity", 1421 | validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, 1422 | "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; 1423 | Utils.cmdInvocation(commandArgs, true); 1424 | 1425 | // Create cer file i.e. extract public key from pfx 1426 | File pfxFile = new File(pfxPath); 1427 | if (pfxFile.exists()) { 1428 | String[] certCommandArgs = {command, "-export", "-alias", alias, 1429 | "-storetype", storeType, "-keystore", pfxPath, 1430 | "-storepass", password, "-rfc", "-file", certPath}; 1431 | // output of keytool export command is going to error stream 1432 | // although command is 1433 | // executed successfully, hence ignoring error stream in this case 1434 | Utils.cmdInvocation(certCommandArgs, true); 1435 | 1436 | // Check if file got created or not 1437 | File cerFile = new File(pfxPath); 1438 | if (!cerFile.exists()) { 1439 | throw new IOException( 1440 | "Error occurred while creating certificate" 1441 | + StringUtils.join(" ", certCommandArgs)); 1442 | } 1443 | } else { 1444 | throw new IOException("Error occurred while creating certificates" 1445 | + StringUtils.join(" ", commandArgs)); 1446 | } 1447 | } 1448 | 1449 | /** 1450 | * This method is used for invoking native commands. 1451 | * 1452 | * @param command 1453 | * :- command to invoke. 1454 | * @param ignoreErrorStream 1455 | * : Boolean which controls whether to throw exception or not 1456 | * based on error stream. 1457 | * @return result :- depending on the method invocation. 1458 | * @throws Exception exceptions thrown from the execution 1459 | */ 1460 | public static String cmdInvocation(String[] command, 1461 | boolean ignoreErrorStream) throws Exception { 1462 | String result = ""; 1463 | String error = ""; 1464 | InputStream inputStream = null; 1465 | InputStream errorStream = null; 1466 | BufferedReader br = null; 1467 | BufferedReader ebr = null; 1468 | try { 1469 | Process process = new ProcessBuilder(command).start(); 1470 | inputStream = process.getInputStream(); 1471 | errorStream = process.getErrorStream(); 1472 | br = new BufferedReader(new InputStreamReader(inputStream)); 1473 | result = br.readLine(); 1474 | process.waitFor(); 1475 | ebr = new BufferedReader(new InputStreamReader(errorStream)); 1476 | error = ebr.readLine(); 1477 | if (error != null && (!error.equals(""))) { 1478 | // To do - Log error message 1479 | 1480 | if (!ignoreErrorStream) { 1481 | throw new Exception(error, null); 1482 | } 1483 | } 1484 | } catch (Exception e) { 1485 | throw new Exception("Exception occurred while invoking command", e); 1486 | } finally { 1487 | if (inputStream != null) { 1488 | inputStream.close(); 1489 | } 1490 | if (errorStream != null) { 1491 | errorStream.close(); 1492 | } 1493 | if (br != null) { 1494 | br.close(); 1495 | } 1496 | if (ebr != null) { 1497 | ebr.close(); 1498 | } 1499 | } 1500 | return result; 1501 | } 1502 | 1503 | 1504 | /** 1505 | * Prints information for passed SQL Server. 1506 | * @param sqlServer sqlServer to be printed 1507 | */ 1508 | public static void print(SqlServer sqlServer) { 1509 | StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) 1510 | .append("Name: ").append(sqlServer.name()) 1511 | .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) 1512 | .append("\n\tRegion: ").append(sqlServer.region()) 1513 | .append("\n\tSqlServer version: ").append(sqlServer.version()) 1514 | .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); 1515 | System.out.println(builder.toString()); 1516 | } 1517 | 1518 | /** 1519 | * Prints information for the passed SQL Database. 1520 | * @param database database to be printed 1521 | */ 1522 | public static void print(SqlDatabase database) { 1523 | StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) 1524 | .append("Name: ").append(database.name()) 1525 | .append("\n\tResource group: ").append(database.resourceGroupName()) 1526 | .append("\n\tRegion: ").append(database.region()) 1527 | .append("\n\tSqlServer Name: ").append(database.sqlServerName()) 1528 | .append("\n\tEdition of SQL database: ").append(database.edition()) 1529 | .append("\n\tCollation of SQL database: ").append(database.collation()) 1530 | .append("\n\tCreation date of SQL database: ").append(database.creationDate()) 1531 | .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) 1532 | .append("\n\tCurrent service objective of SQL database: ").append(database.serviceLevelObjective()) 1533 | .append("\n\tId of current service objective of SQL database: ").append(database.currentServiceObjectiveId()) 1534 | .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) 1535 | .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); 1536 | 1537 | System.out.println(builder.toString()); 1538 | } 1539 | 1540 | /** 1541 | * Prints information for the passed firewall rule. 1542 | * @param firewallRule firewall rule to be printed. 1543 | */ 1544 | public static void print(SqlFirewallRule firewallRule) { 1545 | StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) 1546 | .append("Name: ").append(firewallRule.name()) 1547 | .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) 1548 | .append("\n\tRegion: ").append(firewallRule.region()) 1549 | .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) 1550 | .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIPAddress()) 1551 | .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIPAddress()); 1552 | 1553 | System.out.println(builder.toString()); 1554 | } 1555 | 1556 | /** 1557 | * Prints information for the passed virtual network rule. 1558 | * @param virtualNetworkRule virtual network rule to be printed. 1559 | */ 1560 | public static void print(SqlVirtualNetworkRule virtualNetworkRule) { 1561 | StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) 1562 | .append("Name: ").append(virtualNetworkRule.name()) 1563 | .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) 1564 | .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) 1565 | .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) 1566 | .append("\n\tState: ").append(virtualNetworkRule.state()); 1567 | 1568 | System.out.println(builder.toString()); 1569 | } 1570 | 1571 | /** 1572 | * Prints information for the passed SQL subscription usage metric. 1573 | * @param subscriptionUsageMetric metric to be printed. 1574 | */ 1575 | public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { 1576 | StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) 1577 | .append("Name: ").append(subscriptionUsageMetric.name()) 1578 | .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) 1579 | .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) 1580 | .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) 1581 | .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) 1582 | .append("\n\tType: ").append(subscriptionUsageMetric.type()); 1583 | 1584 | System.out.println(builder.toString()); 1585 | } 1586 | 1587 | /** 1588 | * Prints information for the passed SQL database usage metric. 1589 | * @param dbUsageMetric metric to be printed. 1590 | */ 1591 | public static void print(SqlDatabaseUsageMetric dbUsageMetric) { 1592 | StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") 1593 | .append("Name: ").append(dbUsageMetric.name()) 1594 | .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) 1595 | .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) 1596 | .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) 1597 | .append("\n\tLimit: ").append(dbUsageMetric.limit()) 1598 | .append("\n\tUnit: ").append(dbUsageMetric.unit()) 1599 | .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); 1600 | 1601 | System.out.println(builder.toString()); 1602 | } 1603 | 1604 | /** 1605 | * Prints information for the passed SQL database metric. 1606 | * @param dbMetric metric to be printed. 1607 | */ 1608 | public static void print(SqlDatabaseMetric dbMetric) { 1609 | StringBuilder builder = new StringBuilder().append("SQL Database Metric") 1610 | .append("Name: ").append(dbMetric.name()) 1611 | .append("\n\tStart Time: ").append(dbMetric.startTime()) 1612 | .append("\n\tEnd Time: ").append(dbMetric.endTime()) 1613 | .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) 1614 | .append("\n\tUnit: ").append(dbMetric.unit()); 1615 | for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { 1616 | builder 1617 | .append("\n\tMetric Value: ") 1618 | .append("\n\t\tCount: ").append(metricValue.count()) 1619 | .append("\n\t\tAverage: ").append(metricValue.average()) 1620 | .append("\n\t\tMaximum: ").append(metricValue.maximum()) 1621 | .append("\n\t\tMinimum: ").append(metricValue.minimum()) 1622 | .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) 1623 | .append("\n\t\tTotal: ").append(metricValue.total()); 1624 | } 1625 | 1626 | System.out.println(builder.toString()); 1627 | } 1628 | 1629 | /** 1630 | * Prints information for the passed Failover Group. 1631 | * @param failoverGroup the SQL Failover Group to be printed. 1632 | */ 1633 | public static void print(SqlFailoverGroup failoverGroup) { 1634 | StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) 1635 | .append("Name: ").append(failoverGroup.name()) 1636 | .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) 1637 | .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) 1638 | .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) 1639 | .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) 1640 | .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) 1641 | .append("\n\tReplication state: ").append(failoverGroup.replicationState()) 1642 | .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); 1643 | builder.append("\n\tPartner Servers: "); 1644 | for (PartnerInfo item : failoverGroup.partnerServers()) { 1645 | builder 1646 | .append("\n\t\tId: ").append(item.id()) 1647 | .append("\n\t\tLocation: ").append(item.location()) 1648 | .append("\n\t\tReplication role: ").append(item.replicationRole()); 1649 | } 1650 | builder.append("\n\tDatabases: "); 1651 | for (String databaseId : failoverGroup.databases()) { 1652 | builder.append("\n\t\tID: ").append(databaseId); 1653 | } 1654 | 1655 | System.out.println(builder.toString()); 1656 | } 1657 | 1658 | /** 1659 | * Prints information for the passed SQL server key. 1660 | * @param serverKey virtual network rule to be printed. 1661 | */ 1662 | public static void print(SqlServerKey serverKey) { 1663 | StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) 1664 | .append("Name: ").append(serverKey.name()) 1665 | .append("\n\tResource group: ").append(serverKey.resourceGroupName()) 1666 | .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) 1667 | .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") 1668 | .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) 1669 | .append("\n\tServer Key URI: ").append(serverKey.uri()) 1670 | .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) 1671 | .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); 1672 | 1673 | System.out.println(builder.toString()); 1674 | } 1675 | 1676 | /** 1677 | * Prints information of the elastic pool passed in. 1678 | * @param elasticPool elastic pool to be printed 1679 | */ 1680 | public static void print(SqlElasticPool elasticPool) { 1681 | StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) 1682 | .append("Name: ").append(elasticPool.name()) 1683 | .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) 1684 | .append("\n\tRegion: ").append(elasticPool.region()) 1685 | .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) 1686 | .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) 1687 | .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) 1688 | .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) 1689 | .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) 1690 | .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) 1691 | .append("\n\tState of the elastic pool: ").append(elasticPool.state()) 1692 | .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageMB()); 1693 | 1694 | System.out.println(builder.toString()); 1695 | } 1696 | 1697 | /** 1698 | * Prints information of the elastic pool activity. 1699 | * @param elasticPoolActivity elastic pool activity to be printed 1700 | */ 1701 | public static void print(ElasticPoolActivity elasticPoolActivity) { 1702 | StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) 1703 | .append("Name: ").append(elasticPoolActivity.name()) 1704 | .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) 1705 | .append("\n\tState: ").append(elasticPoolActivity.state()) 1706 | .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) 1707 | .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) 1708 | .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) 1709 | .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) 1710 | .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) 1711 | .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) 1712 | .append("\n\tOperation: ").append(elasticPoolActivity.operation()) 1713 | .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) 1714 | .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) 1715 | .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) 1716 | .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); 1717 | 1718 | System.out.println(builder.toString()); 1719 | 1720 | } 1721 | 1722 | /** 1723 | * Prints information of the database activity. 1724 | * @param databaseActivity database activity to be printed 1725 | */ 1726 | public static void print(ElasticPoolDatabaseActivity databaseActivity) { 1727 | StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) 1728 | .append("Name: ").append(databaseActivity.name()) 1729 | .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) 1730 | .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) 1731 | .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) 1732 | .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) 1733 | .append("\n\tState: ").append(databaseActivity.state()) 1734 | .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) 1735 | .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) 1736 | .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) 1737 | .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) 1738 | .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) 1739 | .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); 1740 | 1741 | System.out.println(builder.toString()); 1742 | } 1743 | 1744 | /** 1745 | * Print an application gateway. 1746 | * @param resource an application gateway 1747 | */ 1748 | public static void print(ApplicationGateway resource) { 1749 | StringBuilder info = new StringBuilder(); 1750 | info.append("Application gateway: ").append(resource.id()) 1751 | .append("Name: ").append(resource.name()) 1752 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 1753 | .append("\n\tRegion: ").append(resource.region()) 1754 | .append("\n\tTags: ").append(resource.tags()) 1755 | .append("\n\tSKU: ").append(resource.sku().toString()) 1756 | .append("\n\tOperational state: ").append(resource.operationalState()) 1757 | .append("\n\tInternet-facing? ").append(resource.isPublic()) 1758 | .append("\n\tInternal? ").append(resource.isPrivate()) 1759 | .append("\n\tDefault private IP address: ").append(resource.privateIPAddress()) 1760 | .append("\n\tPrivate IP address allocation method: ").append(resource.privateIPAllocationMethod()) 1761 | .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); 1762 | 1763 | // Show IP configs 1764 | Map ipConfigs = resource.ipConfigurations(); 1765 | info.append("\n\tIP configurations: ").append(ipConfigs.size()); 1766 | for (ApplicationGatewayIPConfiguration ipConfig : ipConfigs.values()) { 1767 | info.append("\n\t\tName: ").append(ipConfig.name()) 1768 | .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) 1769 | .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); 1770 | } 1771 | 1772 | // Show frontends 1773 | Map frontends = resource.frontends(); 1774 | info.append("\n\tFrontends: ").append(frontends.size()); 1775 | for (ApplicationGatewayFrontend frontend : frontends.values()) { 1776 | info.append("\n\t\tName: ").append(frontend.name()) 1777 | .append("\n\t\t\tPublic? ").append(frontend.isPublic()); 1778 | 1779 | if (frontend.isPublic()) { 1780 | // Show public frontend info 1781 | info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIPAddressId()); 1782 | } 1783 | 1784 | if (frontend.isPrivate()) { 1785 | // Show private frontend info 1786 | info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIPAddress()) 1787 | .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIPAllocationMethod()) 1788 | .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) 1789 | .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); 1790 | } 1791 | } 1792 | 1793 | // Show backends 1794 | Map backends = resource.backends(); 1795 | info.append("\n\tBackends: ").append(backends.size()); 1796 | for (ApplicationGatewayBackend backend : backends.values()) { 1797 | info.append("\n\t\tName: ").append(backend.name()) 1798 | .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); 1799 | 1800 | // Show addresses 1801 | Collection addresses = backend.addresses(); 1802 | info.append("\n\t\t\tAddresses: ").append(addresses.size()); 1803 | for (ApplicationGatewayBackendAddress address : addresses) { 1804 | info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) 1805 | .append("\n\t\t\t\tIP: ").append(address.ipAddress()); 1806 | } 1807 | } 1808 | 1809 | // Show backend HTTP configurations 1810 | Map httpConfigs = resource.backendHttpConfigurations(); 1811 | info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); 1812 | for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { 1813 | info.append("\n\t\tName: ").append(httpConfig.name()) 1814 | .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) 1815 | .append("\n\t\t\tPort: ").append(httpConfig.port()) 1816 | .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) 1817 | .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) 1818 | .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) 1819 | .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) 1820 | .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) 1821 | .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) 1822 | .append("\n\t\tPath: ").append(httpConfig.path()); 1823 | ApplicationGatewayProbe probe = httpConfig.probe(); 1824 | if (probe != null) { 1825 | info.append("\n\t\tProbe: " + probe.name()); 1826 | } 1827 | info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); 1828 | } 1829 | 1830 | // Show SSL certificates 1831 | Map sslCerts = resource.sslCertificates(); 1832 | info.append("\n\tSSL certificates: ").append(sslCerts.size()); 1833 | for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { 1834 | info.append("\n\t\tName: ").append(cert.name()) 1835 | .append("\n\t\t\tCert data: ").append(cert.publicData()); 1836 | } 1837 | 1838 | // Show redirect configurations 1839 | Map redirects = resource.redirectConfigurations(); 1840 | info.append("\n\tRedirect configurations: ").append(redirects.size()); 1841 | for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { 1842 | info.append("\n\t\tName: ").append(redirect.name()) 1843 | .append("\n\t\tTarget URL: ").append(redirect.type()) 1844 | .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) 1845 | .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) 1846 | .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) 1847 | .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) 1848 | .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); 1849 | } 1850 | 1851 | // Show HTTP listeners 1852 | Map listeners = resource.listeners(); 1853 | info.append("\n\tHTTP listeners: ").append(listeners.size()); 1854 | for (ApplicationGatewayListener listener : listeners.values()) { 1855 | info.append("\n\t\tName: ").append(listener.name()) 1856 | .append("\n\t\t\tHost name: ").append(listener.hostName()) 1857 | .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) 1858 | .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) 1859 | .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) 1860 | .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) 1861 | .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); 1862 | if (listener.sslCertificate() != null) { 1863 | info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); 1864 | } 1865 | } 1866 | 1867 | // Show probes 1868 | Map probes = resource.probes(); 1869 | info.append("\n\tProbes: ").append(probes.size()); 1870 | for (ApplicationGatewayProbe probe : probes.values()) { 1871 | info.append("\n\t\tName: ").append(probe.name()) 1872 | .append("\n\t\tProtocol:").append(probe.protocol().toString()) 1873 | .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) 1874 | .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) 1875 | .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) 1876 | .append("\n\t\tHost: ").append(probe.host()) 1877 | .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) 1878 | .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); 1879 | } 1880 | 1881 | // Show request routing rules 1882 | Map rules = resource.requestRoutingRules(); 1883 | info.append("\n\tRequest routing rules: ").append(rules.size()); 1884 | for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { 1885 | info.append("\n\t\tName: ").append(rule.name()) 1886 | .append("\n\t\tType: ").append(rule.ruleType()) 1887 | .append("\n\t\tPublic IP address ID: ").append(rule.publicIPAddressId()) 1888 | .append("\n\t\tHost name: ").append(rule.hostName()) 1889 | .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) 1890 | .append("\n\t\tFrontend port: ").append(rule.frontendPort()) 1891 | .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) 1892 | .append("\n\t\tBackend port: ").append(rule.backendPort()) 1893 | .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) 1894 | .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); 1895 | 1896 | // Show backend addresses 1897 | Collection addresses = rule.backendAddresses(); 1898 | info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); 1899 | for (ApplicationGatewayBackendAddress address : addresses) { 1900 | info.append("\n\t\t\t\t") 1901 | .append(address.fqdn()) 1902 | .append(" [").append(address.ipAddress()).append("]"); 1903 | } 1904 | 1905 | // Show SSL cert 1906 | info.append("\n\t\t\tSSL certificate name: "); 1907 | ApplicationGatewaySslCertificate cert = rule.sslCertificate(); 1908 | if (cert == null) { 1909 | info.append("(None)"); 1910 | } else { 1911 | info.append(cert.name()); 1912 | } 1913 | 1914 | // Show backend 1915 | info.append("\n\t\t\tAssociated backend address pool: "); 1916 | ApplicationGatewayBackend backend = rule.backend(); 1917 | if (backend == null) { 1918 | info.append("(None)"); 1919 | } else { 1920 | info.append(backend.name()); 1921 | } 1922 | 1923 | // Show backend HTTP settings config 1924 | info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); 1925 | ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); 1926 | if (config == null) { 1927 | info.append("(None)"); 1928 | } else { 1929 | info.append(config.name()); 1930 | } 1931 | 1932 | // Show frontend listener 1933 | info.append("\n\t\t\tAssociated frontend listener: "); 1934 | ApplicationGatewayListener listener = rule.listener(); 1935 | if (listener == null) { 1936 | info.append("(None)"); 1937 | } else { 1938 | info.append(config.name()); 1939 | } 1940 | } 1941 | System.out.println(info.toString()); 1942 | } 1943 | 1944 | /** 1945 | * Prints information of a virtual machine custom image. 1946 | * 1947 | * @param image the image 1948 | */ 1949 | public static void print(VirtualMachineCustomImage image) { 1950 | StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) 1951 | .append("Name: ").append(image.name()) 1952 | .append("\n\tResource group: ").append(image.resourceGroupName()) 1953 | .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); 1954 | 1955 | builder.append("\n\tOS disk image: ") 1956 | .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) 1957 | .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) 1958 | .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) 1959 | .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); 1960 | if (image.isCreatedFromVirtualMachine()) { 1961 | builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); 1962 | } 1963 | if (image.osDiskImage().managedDisk() != null) { 1964 | builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); 1965 | } 1966 | if (image.osDiskImage().snapshot() != null) { 1967 | builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); 1968 | } 1969 | if (image.osDiskImage().blobUri() != null) { 1970 | builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); 1971 | } 1972 | if (image.dataDiskImages() != null) { 1973 | for (ImageDataDisk diskImage : image.dataDiskImages().values()) { 1974 | builder.append("\n\tDisk Image (Lun) #: ").append(diskImage.lun()) 1975 | .append("\n\t\tCaching: ").append(diskImage.caching()) 1976 | .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); 1977 | if (image.isCreatedFromVirtualMachine()) { 1978 | builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); 1979 | } 1980 | if (diskImage.managedDisk() != null) { 1981 | builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); 1982 | } 1983 | if (diskImage.snapshot() != null) { 1984 | builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); 1985 | } 1986 | if (diskImage.blobUri() != null) { 1987 | builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); 1988 | } 1989 | } 1990 | } 1991 | System.out.println(builder.toString()); 1992 | } 1993 | 1994 | /** 1995 | * Uploads a file to an Azure web app. 1996 | * @param profile the publishing profile for the web app. 1997 | * @param fileName the name of the file on server 1998 | * @param file the local file 1999 | */ 2000 | public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) { 2001 | FTPClient ftpClient = new FTPClient(); 2002 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 2003 | String server = ftpUrlSegments[0]; 2004 | String path = "./site/wwwroot/webapps"; 2005 | if (fileName.contains("/")) { 2006 | int lastslash = fileName.lastIndexOf('/'); 2007 | path = path + "/" + fileName.substring(0, lastslash); 2008 | fileName = fileName.substring(lastslash + 1); 2009 | } 2010 | try { 2011 | ftpClient.connect(server); 2012 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 2013 | ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 2014 | for (String segment : path.split("/")) { 2015 | if (!ftpClient.changeWorkingDirectory(segment)) { 2016 | ftpClient.makeDirectory(segment); 2017 | ftpClient.changeWorkingDirectory(segment); 2018 | } 2019 | } 2020 | ftpClient.storeFile(fileName, file); 2021 | ftpClient.disconnect(); 2022 | } catch (IOException e) { 2023 | e.printStackTrace(); 2024 | } 2025 | } 2026 | 2027 | /** 2028 | * Uploads a file to an Azure function app. 2029 | * @param profile the publishing profile for the web app. 2030 | * @param fileName the name of the file on server 2031 | * @param file the local file 2032 | */ 2033 | public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) { 2034 | FTPClient ftpClient = new FTPClient(); 2035 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 2036 | String server = ftpUrlSegments[0]; 2037 | String path = "site/wwwroot"; 2038 | if (fileName.contains("/")) { 2039 | int lastslash = fileName.lastIndexOf('/'); 2040 | path = path + "/" + fileName.substring(0, lastslash); 2041 | fileName = fileName.substring(lastslash + 1); 2042 | } 2043 | try { 2044 | ftpClient.connect(server); 2045 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 2046 | ftpClient.setFileType(FTP.ASCII_FILE_TYPE); 2047 | for (String segment : path.split("/")) { 2048 | if (!ftpClient.changeWorkingDirectory(segment)) { 2049 | ftpClient.makeDirectory(segment); 2050 | ftpClient.changeWorkingDirectory(segment); 2051 | } 2052 | } 2053 | ftpClient.storeFile(fileName, file); 2054 | ftpClient.disconnect(); 2055 | } catch (IOException e) { 2056 | e.printStackTrace(); 2057 | } 2058 | } 2059 | 2060 | /** 2061 | * Uploads a file to an Azure web app. 2062 | * @param profile the publishing profile for the web app. 2063 | * @param fileName the name of the file on server 2064 | * @param file the local file 2065 | */ 2066 | public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String fileName, InputStream file) { 2067 | FTPClient ftpClient = new FTPClient(); 2068 | String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); 2069 | String server = ftpUrlSegments[0]; 2070 | String path = "./site/wwwroot"; 2071 | if (fileName.contains("/")) { 2072 | int lastslash = fileName.lastIndexOf('/'); 2073 | path = path + "/" + fileName.substring(0, lastslash); 2074 | fileName = fileName.substring(lastslash + 1); 2075 | } 2076 | try { 2077 | ftpClient.connect(server); 2078 | ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); 2079 | ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 2080 | for (String segment : path.split("/")) { 2081 | if (!ftpClient.changeWorkingDirectory(segment)) { 2082 | ftpClient.makeDirectory(segment); 2083 | ftpClient.changeWorkingDirectory(segment); 2084 | } 2085 | } 2086 | ftpClient.storeFile(fileName, file); 2087 | ftpClient.disconnect(); 2088 | } catch (IOException e) { 2089 | e.printStackTrace(); 2090 | } 2091 | } 2092 | 2093 | private Utils() { 2094 | 2095 | } 2096 | 2097 | /** 2098 | * Print service bus namespace info. 2099 | * @param serviceBusNamespace a service bus namespace 2100 | */ 2101 | public static void print(ServiceBusNamespace serviceBusNamespace) { 2102 | StringBuilder builder = new StringBuilder() 2103 | .append("Service bus Namespace: ").append(serviceBusNamespace.id()) 2104 | .append("\n\tName: ").append(serviceBusNamespace.name()) 2105 | .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) 2106 | .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) 2107 | .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) 2108 | .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) 2109 | .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) 2110 | .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) 2111 | .append("\n\tSku: ") 2112 | .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) 2113 | .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) 2114 | .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); 2115 | 2116 | System.out.println(builder.toString()); 2117 | } 2118 | 2119 | /** 2120 | * Print service bus queue info. 2121 | * @param queue a service bus queue 2122 | */ 2123 | public static void print(Queue queue) { 2124 | StringBuilder builder = new StringBuilder() 2125 | .append("Service bus Queue: ").append(queue.id()) 2126 | .append("\n\tName: ").append(queue.name()) 2127 | .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) 2128 | .append("\n\tCreatedAt: ").append(queue.createdAt()) 2129 | .append("\n\tUpdatedAt: ").append(queue.updatedAt()) 2130 | .append("\n\tAccessedAt: ").append(queue.accessedAt()) 2131 | .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) 2132 | .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) 2133 | .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) 2134 | .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) 2135 | .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) 2136 | .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) 2137 | .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) 2138 | .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) 2139 | .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) 2140 | .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) 2141 | .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) 2142 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) 2143 | .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) 2144 | .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) 2145 | .append("\n\tMessageCount: ").append(queue.messageCount()) 2146 | .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) 2147 | .append("\n\tStatus: ").append(queue.status()) 2148 | .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) 2149 | .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) 2150 | .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); 2151 | 2152 | System.out.println(builder.toString()); 2153 | 2154 | } 2155 | 2156 | /** 2157 | * Print service bus queue authorization keys info. 2158 | * @param queueAuthorizationRule a service bus queue authorization keys 2159 | */ 2160 | public static void print(QueueAuthorizationRule queueAuthorizationRule) { 2161 | StringBuilder builder = new StringBuilder() 2162 | .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) 2163 | .append("\n\tName: ").append(queueAuthorizationRule.name()) 2164 | .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) 2165 | .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) 2166 | .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); 2167 | 2168 | List rights = queueAuthorizationRule.rights(); 2169 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2170 | for (AccessRights right: rights) { 2171 | builder.append("\n\t\tAccessRight: ") 2172 | .append("\n\t\t\tName :").append(right.name()); 2173 | } 2174 | 2175 | System.out.println(builder.toString()); 2176 | } 2177 | 2178 | /** 2179 | * Print service bus namespace authorization keys info. 2180 | * @param keys a service bus namespace authorization keys 2181 | */ 2182 | public static void print(AuthorizationKeys keys) { 2183 | StringBuilder builder = new StringBuilder() 2184 | .append("Authorization keys: ") 2185 | .append("\n\tPrimaryKey: ").append(keys.primaryKey()) 2186 | .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) 2187 | .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) 2188 | .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); 2189 | 2190 | System.out.println(builder.toString()); 2191 | } 2192 | 2193 | /** 2194 | * Print service bus namespace authorization rule info. 2195 | * @param namespaceAuthorizationRule a service bus namespace authorization rule 2196 | */ 2197 | public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { 2198 | StringBuilder builder = new StringBuilder() 2199 | .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) 2200 | .append("\n\tName: ").append(namespaceAuthorizationRule.name()) 2201 | .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) 2202 | .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); 2203 | 2204 | List rights = namespaceAuthorizationRule.rights(); 2205 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2206 | for (AccessRights right: rights) { 2207 | builder.append("\n\t\tAccessRight: ") 2208 | .append("\n\t\t\tName :").append(right.name()); 2209 | } 2210 | 2211 | System.out.println(builder.toString()); 2212 | } 2213 | 2214 | /** 2215 | * Print service bus topic info. 2216 | * @param topic a service bus topic 2217 | */ 2218 | public static void print(Topic topic) { 2219 | StringBuilder builder = new StringBuilder() 2220 | .append("Service bus topic: ").append(topic.id()) 2221 | .append("\n\tName: ").append(topic.name()) 2222 | .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) 2223 | .append("\n\tCreatedAt: ").append(topic.createdAt()) 2224 | .append("\n\tUpdatedAt: ").append(topic.updatedAt()) 2225 | .append("\n\tAccessedAt: ").append(topic.accessedAt()) 2226 | .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) 2227 | .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) 2228 | .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) 2229 | .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) 2230 | .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) 2231 | .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) 2232 | .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) 2233 | .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) 2234 | .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) 2235 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) 2236 | .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) 2237 | .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) 2238 | .append("\n\tStatus: ").append(topic.status()) 2239 | .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) 2240 | .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) 2241 | .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); 2242 | 2243 | System.out.println(builder.toString()); 2244 | } 2245 | 2246 | /** 2247 | * Print service bus subscription info. 2248 | * @param serviceBusSubscription a service bus subscription 2249 | */ 2250 | public static void print(ServiceBusSubscription serviceBusSubscription) { 2251 | StringBuilder builder = new StringBuilder() 2252 | .append("Service bus subscription: ").append(serviceBusSubscription.id()) 2253 | .append("\n\tName: ").append(serviceBusSubscription.name()) 2254 | .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) 2255 | .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) 2256 | .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) 2257 | .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) 2258 | .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) 2259 | .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) 2260 | .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) 2261 | .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) 2262 | .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) 2263 | .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) 2264 | .append("\n\tStatus: ").append(serviceBusSubscription.status()) 2265 | .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) 2266 | .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) 2267 | .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) 2268 | .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) 2269 | .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) 2270 | .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) 2271 | .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) 2272 | .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); 2273 | 2274 | System.out.println(builder.toString()); 2275 | } 2276 | 2277 | /** 2278 | * Print topic Authorization Rule info. 2279 | * @param topicAuthorizationRule a topic Authorization Rule 2280 | */ 2281 | public static void print(TopicAuthorizationRule topicAuthorizationRule) { 2282 | StringBuilder builder = new StringBuilder() 2283 | .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) 2284 | .append("\n\tName: ").append(topicAuthorizationRule.name()) 2285 | .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) 2286 | .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) 2287 | .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); 2288 | 2289 | List rights = topicAuthorizationRule.rights(); 2290 | builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); 2291 | for (AccessRights right: rights) { 2292 | builder.append("\n\t\tAccessRight: ") 2293 | .append("\n\t\t\tName :").append(right.name()); 2294 | } 2295 | 2296 | System.out.println(builder.toString()); 2297 | } 2298 | 2299 | /** 2300 | * Print CosmosDB info. 2301 | * @param cosmosDBAccount a CosmosDB 2302 | */ 2303 | public static void print(CosmosDBAccount cosmosDBAccount) { 2304 | StringBuilder builder = new StringBuilder() 2305 | .append("CosmosDB: ").append(cosmosDBAccount.id()) 2306 | .append("\n\tName: ").append(cosmosDBAccount.name()) 2307 | .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) 2308 | .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) 2309 | .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) 2310 | .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); 2311 | 2312 | DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); 2313 | DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); 2314 | builder 2315 | .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) 2316 | .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) 2317 | .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) 2318 | .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); 2319 | 2320 | for (com.microsoft.azure.management.cosmosdb.Location writeReplica : cosmosDBAccount.writableReplications()) { 2321 | builder.append("\n\t\tWrite replication: ") 2322 | .append("\n\t\t\tName :").append(writeReplica.locationName()); 2323 | } 2324 | 2325 | builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); 2326 | for (com.microsoft.azure.management.cosmosdb.Location readReplica : cosmosDBAccount.readableReplications()) { 2327 | builder.append("\n\t\tRead replication: ") 2328 | .append("\n\t\t\tName :").append(readReplica.locationName()); 2329 | } 2330 | 2331 | } 2332 | 2333 | /** 2334 | * Print Active Directory User info. 2335 | * @param user active directory user 2336 | */ 2337 | public static void print(ActiveDirectoryUser user) { 2338 | StringBuilder builder = new StringBuilder() 2339 | .append("Active Directory User: ").append(user.id()) 2340 | .append("\n\tName: ").append(user.name()) 2341 | .append("\n\tMail: ").append(user.mail()) 2342 | .append("\n\tMail Nickname: ").append(user.mailNickname()) 2343 | .append("\n\tSign In Name: ").append(user.signInName()) 2344 | .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); 2345 | 2346 | System.out.println(builder.toString()); 2347 | } 2348 | 2349 | /** 2350 | * Print Active Directory User info. 2351 | * @param role role definition 2352 | */ 2353 | public static void print(RoleDefinition role) { 2354 | StringBuilder builder = new StringBuilder() 2355 | .append("Role Definition: ").append(role.id()) 2356 | .append("\n\tName: ").append(role.name()) 2357 | .append("\n\tRole Name: ").append(role.roleName()) 2358 | .append("\n\tType: ").append(role.type()) 2359 | .append("\n\tDescription: ").append(role.description()) 2360 | .append("\n\tType: ").append(role.type()); 2361 | 2362 | Set permissions = role.permissions(); 2363 | builder.append("\n\tPermissions: ").append(permissions.size()); 2364 | for (Permission permission : permissions) { 2365 | builder.append("\n\t\tPermission Actions: " + permission.actions().size()); 2366 | for (String action : permission.actions()) { 2367 | builder.append("\n\t\t\tName :").append(action); 2368 | } 2369 | builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); 2370 | for (String notAction : permission.notActions()) { 2371 | builder.append("\n\t\t\tName :").append(notAction); 2372 | } 2373 | } 2374 | 2375 | Set assignableScopes = role.assignableScopes(); 2376 | builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); 2377 | for (String scope : assignableScopes) { 2378 | builder.append("\n\t\tAssignable Scope: ") 2379 | .append("\n\t\t\tName :").append(scope); 2380 | } 2381 | 2382 | System.out.println(builder.toString()); 2383 | } 2384 | 2385 | /** 2386 | * Print Role Assignment info. 2387 | * @param roleAssignment role assignment 2388 | */ 2389 | public static void print(RoleAssignment roleAssignment) { 2390 | StringBuilder builder = new StringBuilder() 2391 | .append("Role Assignment: ") 2392 | .append("\n\tScope: ").append(roleAssignment.scope()) 2393 | .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) 2394 | .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); 2395 | 2396 | System.out.println(builder.toString()); 2397 | } 2398 | 2399 | /** 2400 | * Print Active Directory Group info. 2401 | * @param group active directory group 2402 | */ 2403 | public static void print(ActiveDirectoryGroup group) { 2404 | StringBuilder builder = new StringBuilder() 2405 | .append("Active Directory Group: ").append(group.id()) 2406 | .append("\n\tName: ").append(group.name()) 2407 | .append("\n\tMail: ").append(group.mail()) 2408 | .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) 2409 | .append("\n\tGroup members:"); 2410 | 2411 | for (ActiveDirectoryObject object : group.listMembers()) { 2412 | builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) 2413 | .append("\tName: ").append(object.name()); 2414 | } 2415 | 2416 | System.out.println(builder.toString()); 2417 | } 2418 | 2419 | /** 2420 | * Print Active Directory Application info. 2421 | * @param application active directory application 2422 | */ 2423 | public static void print(ActiveDirectoryApplication application) { 2424 | StringBuilder builder = new StringBuilder() 2425 | .append("Active Directory Application: ").append(application.id()) 2426 | .append("\n\tName: ").append(application.name()) 2427 | .append("\n\tSign on URL: ").append(application.signOnUrl()) 2428 | .append("\n\tReply URLs:"); 2429 | for (String replyUrl : application.replyUrls()) { 2430 | builder.append("\n\t\t").append(replyUrl); 2431 | } 2432 | 2433 | System.out.println(builder.toString()); 2434 | } 2435 | 2436 | /** 2437 | * Print Service Principal info. 2438 | * 2439 | * @param servicePrincipal service principal 2440 | */ 2441 | public static void print(ServicePrincipal servicePrincipal) { 2442 | StringBuilder builder = new StringBuilder() 2443 | .append("Service Principal: ").append(servicePrincipal.id()) 2444 | .append("\n\tName: ").append(servicePrincipal.name()) 2445 | .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); 2446 | 2447 | List names = servicePrincipal.servicePrincipalNames(); 2448 | builder.append("\n\tNames: ").append(names.size()); 2449 | for (String name : names) { 2450 | builder.append("\n\t\tName: ").append(name); 2451 | } 2452 | System.out.println(builder.toString()); 2453 | } 2454 | 2455 | /** 2456 | * Print Network Watcher info. 2457 | * 2458 | * @param nw network watcher 2459 | */ 2460 | public static void print(NetworkWatcher nw) { 2461 | StringBuilder builder = new StringBuilder() 2462 | .append("Network Watcher: ").append(nw.id()) 2463 | .append("\n\tName: ").append(nw.name()) 2464 | .append("\n\tResource group name: ").append(nw.resourceGroupName()) 2465 | .append("\n\tRegion name: ").append(nw.regionName()); 2466 | System.out.println(builder.toString()); 2467 | } 2468 | 2469 | /** 2470 | * Print packet capture info. 2471 | * 2472 | * @param resource packet capture 2473 | */ 2474 | public static void print(PacketCapture resource) { 2475 | StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) 2476 | .append("\n\tName: ").append(resource.name()) 2477 | .append("\n\tTarget id: ").append(resource.targetId()) 2478 | .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) 2479 | .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) 2480 | .append("\n\tProvisioning state: ").append(resource.provisioningState()) 2481 | .append("\n\tStorage location:") 2482 | .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) 2483 | .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) 2484 | .append("\n\tFile path: ").append(resource.storageLocation().filePath()) 2485 | .append("\n\t Packet capture filters: ").append(resource.filters().size()); 2486 | for (PacketCaptureFilter filter : resource.filters()) { 2487 | sb.append("\n\t\tProtocol: ").append(filter.protocol()); 2488 | sb.append("\n\t\tLocal IP address: ").append(filter.localIPAddress()); 2489 | sb.append("\n\t\tRemote IP address: ").append(filter.remoteIPAddress()); 2490 | sb.append("\n\t\tLocal port: ").append(filter.localPort()); 2491 | sb.append("\n\t\tRemote port: ").append(filter.remotePort()); 2492 | } 2493 | System.out.println(sb.toString()); 2494 | } 2495 | 2496 | /** 2497 | * Print verification IP flow info. 2498 | * 2499 | * @param resource IP flow verification info 2500 | */ 2501 | public static void print(VerificationIPFlow resource) { 2502 | System.out.println(new StringBuilder("IP flow verification: ") 2503 | .append("\n\tAccess: ").append(resource.access()) 2504 | .append("\n\tRule name: ").append(resource.ruleName()) 2505 | .toString()); 2506 | } 2507 | 2508 | /** 2509 | * Print topology info. 2510 | * 2511 | * @param resource topology 2512 | */ 2513 | public static void print(Topology resource) { 2514 | StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) 2515 | .append("\n\tTopology parameters: ") 2516 | .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) 2517 | .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) 2518 | .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) 2519 | .append("\n\tCreated time: ").append(resource.createdTime()) 2520 | .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); 2521 | for (TopologyResource tr : resource.resources().values()) { 2522 | sb.append("\n\tTopology resource: ").append(tr.id()) 2523 | .append("\n\t\tName: ").append(tr.name()) 2524 | .append("\n\t\tLocation: ").append(tr.location()) 2525 | .append("\n\t\tAssociations:"); 2526 | for (TopologyAssociation association : tr.associations()) { 2527 | sb.append("\n\t\t\tName:").append(association.name()) 2528 | .append("\n\t\t\tResource id:").append(association.resourceId()) 2529 | .append("\n\t\t\tAssociation type:").append(association.associationType()); 2530 | } 2531 | } 2532 | System.out.println(sb.toString()); 2533 | } 2534 | 2535 | /** 2536 | * Print flow log settings info. 2537 | * 2538 | * @param resource flow log settings 2539 | */ 2540 | public static void print(FlowLogSettings resource) { 2541 | System.out.println(new StringBuilder().append("Flow log settings: ") 2542 | .append("Target resource id: ").append(resource.targetResourceId()) 2543 | .append("\n\tFlow log enabled: ").append(resource.enabled()) 2544 | .append("\n\tStorage account id: ").append(resource.storageId()) 2545 | .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) 2546 | .append("\n\tRetention policy days: ").append(resource.retentionDays()) 2547 | .toString()); 2548 | } 2549 | 2550 | /** 2551 | * Print availability set info. 2552 | * 2553 | * @param resource an availability set 2554 | */ 2555 | public static void print(SecurityGroupView resource) { 2556 | StringBuilder sb = new StringBuilder().append("Security group view: ") 2557 | .append("\n\tVirtual machine id: ").append(resource.vmId()); 2558 | for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { 2559 | sb.append("\n\tSecurity group network interface:").append(sgni.id()) 2560 | .append("\n\t\tSecurity group network interface:") 2561 | .append("\n\t\tEffective security rules:"); 2562 | for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { 2563 | sb.append("\n\t\t\tName: ").append(rule.name()) 2564 | .append("\n\t\t\tDirection: ").append(rule.direction()) 2565 | .append("\n\t\t\tAccess: ").append(rule.access()) 2566 | .append("\n\t\t\tPriority: ").append(rule.priority()) 2567 | .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) 2568 | .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) 2569 | .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) 2570 | .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) 2571 | .append("\n\t\t\tProtocol: ").append(rule.protocol()); 2572 | } 2573 | sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); 2574 | printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); 2575 | if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { 2576 | sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); 2577 | printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); 2578 | } 2579 | sb.append("\n\t\tDefault security rules:"); 2580 | printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); 2581 | } 2582 | System.out.println(sb.toString()); 2583 | } 2584 | 2585 | private static void printSecurityRule(StringBuilder sb, List rules) { 2586 | for (SecurityRuleInner rule : rules) { 2587 | sb.append("\n\t\t\tName: ").append(rule.name()) 2588 | .append("\n\t\t\tDirection: ").append(rule.direction()) 2589 | .append("\n\t\t\tAccess: ").append(rule.access()) 2590 | .append("\n\t\t\tPriority: ").append(rule.priority()) 2591 | .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) 2592 | .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) 2593 | .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) 2594 | .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) 2595 | .append("\n\t\t\tProtocol: ").append(rule.protocol()) 2596 | .append("\n\t\t\tDescription: ").append(rule.description()) 2597 | .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); 2598 | } 2599 | } 2600 | 2601 | /** 2602 | * Print next hop info. 2603 | * 2604 | * @param resource an availability set 2605 | */ 2606 | public static void print(NextHop resource) { 2607 | System.out.println(new StringBuilder("Next hop: ") 2608 | .append("Next hop type: ").append(resource.nextHopType()) 2609 | .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) 2610 | .append("\n\tRoute table id: ").append(resource.routeTableId()) 2611 | .toString()); 2612 | } 2613 | 2614 | /** 2615 | * Print container group info. 2616 | * 2617 | * @param resource a container group 2618 | */ 2619 | public static void print(ContainerGroup resource) { 2620 | StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) 2621 | .append("Name: ").append(resource.name()) 2622 | .append("\n\tResource group: ").append(resource.resourceGroupName()) 2623 | .append("\n\tRegion: ").append(resource.region()) 2624 | .append("\n\tTags: ").append(resource.tags()) 2625 | .append("\n\tOS type: ").append(resource.osType()); 2626 | 2627 | if (resource.ipAddress() != null) { 2628 | info.append("\n\tPublic IP address: ").append(resource.ipAddress()); 2629 | } 2630 | if (resource.externalTcpPorts() != null) { 2631 | info.append("\n\tExternal TCP ports:"); 2632 | for (int port : resource.externalTcpPorts()) { 2633 | info.append(" ").append(port); 2634 | } 2635 | } 2636 | if (resource.externalUdpPorts() != null) { 2637 | info.append("\n\tExternal UDP ports:"); 2638 | for (int port : resource.externalUdpPorts()) { 2639 | info.append(" ").append(port); 2640 | } 2641 | } 2642 | if (resource.imageRegistryServers() != null) { 2643 | info.append("\n\tPrivate Docker image registries:"); 2644 | for (String server : resource.imageRegistryServers()) { 2645 | info.append(" ").append(server); 2646 | } 2647 | } 2648 | if (resource.volumes() != null) { 2649 | info.append("\n\tVolume mapping: "); 2650 | for (Map.Entry entry: resource.volumes().entrySet()) { 2651 | info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") 2652 | .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); 2653 | } 2654 | } 2655 | if (resource.containers() != null) { 2656 | info.append("\n\tContainer instances: "); 2657 | for (Map.Entry entry: resource.containers().entrySet()) { 2658 | Container container = entry.getValue(); 2659 | info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); 2660 | info.append("\n\t\t\tResources: "); 2661 | info.append(container.resources().requests().cpu()).append("CPUs "); 2662 | info.append(container.resources().requests().memoryInGB()).append("GB"); 2663 | info.append("\n\t\t\tPorts:"); 2664 | for (ContainerPort port : container.ports()) { 2665 | info.append(" ").append(port.port()); 2666 | } 2667 | if (container.volumeMounts() != null) { 2668 | info.append("\n\t\t\tVolume mounts:"); 2669 | for (VolumeMount volumeMount : container.volumeMounts()) { 2670 | info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); 2671 | } 2672 | } 2673 | if (container.command() != null) { 2674 | info.append("\n\t\t\tStart commands:"); 2675 | for (String command : container.command()) { 2676 | info.append("\n\t\t\t\t").append(command); 2677 | } 2678 | } 2679 | if (container.environmentVariables() != null) { 2680 | info.append("\n\t\t\tENV vars:"); 2681 | for (EnvironmentVariable envVar : container.environmentVariables()) { 2682 | info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); 2683 | } 2684 | } 2685 | } 2686 | } 2687 | 2688 | System.out.println(info.toString()); 2689 | } 2690 | 2691 | /** 2692 | * Print event hub namespace. 2693 | * 2694 | * @param resource a virtual machine 2695 | */ 2696 | public static void print(EventHubNamespace resource) { 2697 | StringBuilder info = new StringBuilder(); 2698 | info.append("Eventhub Namespace: ").append(resource.id()) 2699 | .append("\n\tName: ").append(resource.name()) 2700 | .append("\n\tRegion: ").append(resource.region()) 2701 | .append("\n\tTags: ").append(resource.tags()) 2702 | .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) 2703 | .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) 2704 | .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) 2705 | .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) 2706 | .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) 2707 | .append("\n\tCreated time: ").append(resource.createdAt()) 2708 | .append("\n\tUpdated time: ").append(resource.updatedAt()); 2709 | 2710 | System.out.println(info.toString()); 2711 | } 2712 | 2713 | /** 2714 | * Print event hub. 2715 | * 2716 | * @param resource event hub 2717 | */ 2718 | public static void print(EventHub resource) { 2719 | StringBuilder info = new StringBuilder(); 2720 | info.append("Eventhub: ").append(resource.id()) 2721 | .append("\n\tName: ").append(resource.name()) 2722 | .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) 2723 | .append("\n\tNamespace: ").append(resource.namespaceName()) 2724 | .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) 2725 | .append("\n\tPartition ids: ").append(resource.partitionIds()); 2726 | if (resource.isDataCaptureEnabled()) { 2727 | info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); 2728 | info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); 2729 | if (resource.captureDestination() != null) { 2730 | info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); 2731 | info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); 2732 | } 2733 | } 2734 | System.out.println(info.toString()); 2735 | } 2736 | 2737 | /** 2738 | * Print event hub namespace recovery pairing. 2739 | * 2740 | * @param resource event hub namespace disaster recovery pairing 2741 | */ 2742 | public static void print(EventHubDisasterRecoveryPairing resource) { 2743 | StringBuilder info = new StringBuilder(); 2744 | info.append("DisasterRecoveryPairing: ").append(resource.id()) 2745 | .append("\n\tName: ").append(resource.name()) 2746 | .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) 2747 | .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) 2748 | .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) 2749 | .append("\n\tNamespace role: ").append(resource.namespaceRole()); 2750 | System.out.println(info.toString()); 2751 | } 2752 | 2753 | /** 2754 | * Print event hub namespace recovery pairing auth rules. 2755 | * 2756 | * @param resource event hub namespace disaster recovery pairing auth rule 2757 | */ 2758 | public static void print(DisasterRecoveryPairingAuthorizationRule resource) { 2759 | StringBuilder info = new StringBuilder(); 2760 | info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); 2761 | List rightsStr = new ArrayList<>(); 2762 | for (com.microsoft.azure.management.eventhub.AccessRights rights : resource.rights()) { 2763 | rightsStr.add(rights.toString()); 2764 | } 2765 | info.append("\n\tRights: ").append(rightsStr); 2766 | System.out.println(info.toString()); 2767 | } 2768 | 2769 | /** 2770 | * Print event hub namespace recovery pairing auth rule key. 2771 | * 2772 | * @param resource event hub namespace disaster recovery pairing auth rule key 2773 | */ 2774 | public static void print(DisasterRecoveryPairingAuthorizationKey resource) { 2775 | StringBuilder info = new StringBuilder(); 2776 | info.append("DisasterRecoveryPairing auth key: ") 2777 | .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) 2778 | .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) 2779 | .append("\n\t Primary key: ").append(resource.primaryKey()) 2780 | .append("\n\t Secondary key: ").append(resource.secondaryKey()) 2781 | .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) 2782 | .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); 2783 | System.out.println(info.toString()); 2784 | } 2785 | 2786 | /** 2787 | * Print event hub consumer group. 2788 | * 2789 | * @param resource event hub consumer group 2790 | */ 2791 | public static void print(EventHubConsumerGroup resource) { 2792 | StringBuilder info = new StringBuilder(); 2793 | info.append("Event hub consumer group: ").append(resource.id()) 2794 | .append("\n\tName: ").append(resource.name()) 2795 | .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) 2796 | .append("\n\tNamespace: ").append(resource.namespaceName()) 2797 | .append("\n\tEvent hub name: ").append(resource.eventHubName()) 2798 | .append("\n\tUser metadata: ").append(resource.userMetadata()); 2799 | System.out.println(info.toString()); 2800 | } 2801 | 2802 | /** 2803 | * Print Batch AI Cluster. 2804 | * 2805 | * @param resource batch ai cluster 2806 | */ 2807 | public static void print(BatchAICluster resource) { 2808 | StringBuilder info = new StringBuilder("Batch AI cluster: ") 2809 | .append("\n\tId: ").append(resource.id()) 2810 | .append("\n\tName: ").append(resource.name()) 2811 | .append("\n\tResource group: ").append(resource.workspace().resourceGroupName()) 2812 | .append("\n\tRegion: ").append(resource.workspace().regionName()) 2813 | .append("\n\tVM Size: ").append(resource.vmSize()) 2814 | .append("\n\tVM Priority: ").append(resource.vmPriority()) 2815 | .append("\n\tSubnet: ").append(resource.subnet()) 2816 | .append("\n\tAllocation state: ").append(resource.allocationState()) 2817 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) 2818 | .append("\n\tCreation time: ").append(resource.creationTime()) 2819 | .append("\n\tCurrent node count: ").append(resource.currentNodeCount()) 2820 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) 2821 | .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()); 2822 | if (resource.scaleSettings().autoScale() != null) { 2823 | info.append("\n\tAuto scale settings: ") 2824 | .append("\n\t\tInitial node count: ").append(resource.scaleSettings().autoScale().initialNodeCount()) 2825 | .append("\n\t\tMinimum node count: ").append(resource.scaleSettings().autoScale().minimumNodeCount()) 2826 | .append("\n\t\tMaximum node count: ").append(resource.scaleSettings().autoScale().maximumNodeCount()); 2827 | } 2828 | if (resource.scaleSettings().manual() != null) { 2829 | info.append("\n\tManual scale settings: ") 2830 | .append("\n\t\tTarget node count: ").append(resource.scaleSettings().manual().targetNodeCount()) 2831 | .append("\n\t\tDeallocation option: ") 2832 | .append(resource.scaleSettings().manual().nodeDeallocationOption()); 2833 | } 2834 | if (resource.nodeStateCounts() != null) { 2835 | info.append("\n\tNode state counts: ") 2836 | .append("\n\t\tRunning nodes count: ").append(resource.nodeStateCounts().runningNodeCount()) 2837 | .append("\n\t\tIdle nodes count: ").append(resource.nodeStateCounts().idleNodeCount()) 2838 | .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()) 2839 | .append("\n\t\tLeaving nodes count: ").append(resource.nodeStateCounts().leavingNodeCount()) 2840 | .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()); 2841 | } 2842 | if (resource.virtualMachineConfiguration() != null && resource.virtualMachineConfiguration().imageReference() != null) { 2843 | info.append("\n\tVirtual machine configuration: ") 2844 | .append("\n\t\tPublisher: ").append(resource.virtualMachineConfiguration().imageReference().publisher()) 2845 | .append("\n\t\tOffer: ").append(resource.virtualMachineConfiguration().imageReference().offer()) 2846 | .append("\n\t\tSku: ").append(resource.virtualMachineConfiguration().imageReference().sku()) 2847 | .append("\n\t\tVersion: ").append(resource.virtualMachineConfiguration().imageReference().version()); 2848 | } 2849 | if (resource.nodeSetup() != null && resource.nodeSetup().setupTask() != null) { 2850 | info.append("\n\tSetup task: ") 2851 | .append("\n\t\tCommand line: ").append(resource.nodeSetup().setupTask().commandLine()) 2852 | .append("\n\t\tStdout/err Path Prefix: ").append(resource.nodeSetup().setupTask().stdOutErrPathPrefix()); 2853 | } 2854 | System.out.println(info.toString()); 2855 | } 2856 | 2857 | /** 2858 | * Print Batch AI Job. 2859 | * 2860 | * @param resource batch ai job 2861 | */ 2862 | public static void print(BatchAIJob resource) { 2863 | StringBuilder info = new StringBuilder("Batch AI job: ") 2864 | .append("\n\tId: ").append(resource.id()) 2865 | .append("\n\tName: ").append(resource.name()) 2866 | .append("\n\tCluster Id: ").append(resource.cluster()) 2867 | .append("\n\tCreation time: ").append(resource.creationTime()) 2868 | .append("\n\tNode count: ").append(resource.nodeCount()) 2869 | .append("\n\tPriority: ").append(resource.schedulingPriority()) 2870 | .append("\n\tExecution state: ").append(resource.executionState()) 2871 | .append("\n\tExecution state transition time: ").append(resource.executionStateTransitionTime()) 2872 | .append("\n\tTool type: ").append(resource.toolType()) 2873 | .append("\n\tExperiment name: ").append(resource.experiment().name()); 2874 | if (resource.mountVolumes() != null) { 2875 | info.append("\n\tMount volumes:"); 2876 | if (resource.mountVolumes().azureFileShares() != null) { 2877 | info.append("\n\t\tAzure fileshares:"); 2878 | for (AzureFileShareReference share : resource.mountVolumes().azureFileShares()) { 2879 | info.append("\n\t\t\tAccount name:").append(share.accountName()) 2880 | .append("\n\t\t\tFile Url:").append(share.azureFileUrl()) 2881 | .append("\n\t\t\tDirectory mode:").append(share.directoryMode()) 2882 | .append("\n\t\t\tFile mode:").append(share.fileMode()) 2883 | .append("\n\t\t\tRelative mount path:").append(share.relativeMountPath()); 2884 | } 2885 | } 2886 | } 2887 | System.out.println(info.toString()); 2888 | } 2889 | 2890 | /** 2891 | * Print Diagnostic Setting. 2892 | * 2893 | * @param resource Diagnostic Setting instance 2894 | */ 2895 | public static void print(DiagnosticSetting resource) { 2896 | StringBuilder info = new StringBuilder("Diagnostic Setting: ") 2897 | .append("\n\tId: ").append(resource.id()) 2898 | .append("\n\tAssociated resource Id: ").append(resource.resourceId()) 2899 | .append("\n\tName: ").append(resource.name()) 2900 | .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) 2901 | .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) 2902 | .append("\n\tEventHub name: ").append(resource.eventHubName()) 2903 | .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); 2904 | if (resource.logs() != null && !resource.logs().isEmpty()) { 2905 | info.append("\n\tLog Settings: "); 2906 | for (LogSettings ls : resource.logs()) { 2907 | info.append("\n\t\tCategory: ").append(ls.category()); 2908 | info.append("\n\t\tRetention policy: "); 2909 | if (ls.retentionPolicy() != null) { 2910 | info.append(ls.retentionPolicy().days() + " days"); 2911 | } else { 2912 | info.append("NONE"); 2913 | } 2914 | } 2915 | } 2916 | if (resource.metrics() != null && !resource.metrics().isEmpty()) { 2917 | info.append("\n\tMetric Settings: "); 2918 | for (MetricSettings ls : resource.metrics()) { 2919 | info.append("\n\t\tCategory: ").append(ls.category()); 2920 | info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); 2921 | info.append("\n\t\tRetention policy: "); 2922 | if (ls.retentionPolicy() != null) { 2923 | info.append(ls.retentionPolicy().days() + " days"); 2924 | } else { 2925 | info.append("NONE"); 2926 | } 2927 | } 2928 | } 2929 | System.out.println(info.toString()); 2930 | } 2931 | 2932 | /** 2933 | * Print Action group settings. 2934 | * 2935 | * @param actionGroup action group instance 2936 | */ 2937 | public static void print(ActionGroup actionGroup) { 2938 | StringBuilder info = new StringBuilder("Action Group: ") 2939 | .append("\n\tId: ").append(actionGroup.id()) 2940 | .append("\n\tName: ").append(actionGroup.name()) 2941 | .append("\n\tShort Name: ").append(actionGroup.shortName()); 2942 | 2943 | if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { 2944 | info.append("\n\tEmail receivers: "); 2945 | for (EmailReceiver er : actionGroup.emailReceivers()) { 2946 | info.append("\n\t\tName: ").append(er.name()); 2947 | info.append("\n\t\tEMail: ").append(er.emailAddress()); 2948 | info.append("\n\t\tStatus: ").append(er.status()); 2949 | info.append("\n\t\t==="); 2950 | } 2951 | } 2952 | 2953 | if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { 2954 | info.append("\n\tSMS text message receivers: "); 2955 | for (SmsReceiver er : actionGroup.smsReceivers()) { 2956 | info.append("\n\t\tName: ").append(er.name()); 2957 | info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); 2958 | info.append("\n\t\tStatus: ").append(er.status()); 2959 | info.append("\n\t\t==="); 2960 | } 2961 | } 2962 | 2963 | if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { 2964 | info.append("\n\tWebhook receivers: "); 2965 | for (WebhookReceiver er : actionGroup.webhookReceivers()) { 2966 | info.append("\n\t\tName: ").append(er.name()); 2967 | info.append("\n\t\tURI: ").append(er.serviceUri()); 2968 | info.append("\n\t\t==="); 2969 | } 2970 | } 2971 | 2972 | if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { 2973 | info.append("\n\tApp Push Notification receivers: "); 2974 | for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { 2975 | info.append("\n\t\tName: ").append(er.name()); 2976 | info.append("\n\t\tEmail: ").append(er.emailAddress()); 2977 | info.append("\n\t\t==="); 2978 | } 2979 | } 2980 | 2981 | if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { 2982 | info.append("\n\tVoice Message receivers: "); 2983 | for (VoiceReceiver er : actionGroup.voiceReceivers()) { 2984 | info.append("\n\t\tName: ").append(er.name()); 2985 | info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); 2986 | info.append("\n\t\t==="); 2987 | } 2988 | } 2989 | 2990 | if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { 2991 | info.append("\n\tAutomation Runbook receivers: "); 2992 | for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { 2993 | info.append("\n\t\tName: ").append(er.name()); 2994 | info.append("\n\t\tRunbook Name: ").append(er.runbookName()); 2995 | info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); 2996 | info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); 2997 | info.append("\n\t\tService URI: ").append(er.serviceUri()); 2998 | info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); 2999 | info.append("\n\t\t==="); 3000 | } 3001 | } 3002 | 3003 | if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { 3004 | info.append("\n\tAzure Functions receivers: "); 3005 | for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { 3006 | info.append("\n\t\tName: ").append(er.name()); 3007 | info.append("\n\t\tFunction Name: ").append(er.functionName()); 3008 | info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); 3009 | info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); 3010 | info.append("\n\t\t==="); 3011 | } 3012 | } 3013 | 3014 | if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { 3015 | info.append("\n\tLogic App receivers: "); 3016 | for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { 3017 | info.append("\n\t\tName: ").append(er.name()); 3018 | info.append("\n\t\tResource Id: ").append(er.resourceId()); 3019 | info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); 3020 | info.append("\n\t\t==="); 3021 | } 3022 | } 3023 | 3024 | if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { 3025 | info.append("\n\tITSM receivers: "); 3026 | for (ItsmReceiver er : actionGroup.itsmReceivers()) { 3027 | info.append("\n\t\tName: ").append(er.name()); 3028 | info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); 3029 | info.append("\n\t\tConnection Id: ").append(er.connectionId()); 3030 | info.append("\n\t\tRegion: ").append(er.region()); 3031 | info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); 3032 | info.append("\n\t\t==="); 3033 | } 3034 | } 3035 | System.out.println(info.toString()); 3036 | } 3037 | 3038 | /** 3039 | * Print activity log alert settings. 3040 | * 3041 | * @param activityLogAlert activity log instance 3042 | */ 3043 | public static void print(ActivityLogAlert activityLogAlert) { 3044 | 3045 | StringBuilder info = new StringBuilder("Activity Log Alert: ") 3046 | .append("\n\tId: ").append(activityLogAlert.id()) 3047 | .append("\n\tName: ").append(activityLogAlert.name()) 3048 | .append("\n\tDescription: ").append(activityLogAlert.description()) 3049 | .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); 3050 | 3051 | if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { 3052 | info.append("\n\tScopes: "); 3053 | for (String er : activityLogAlert.scopes()) { 3054 | info.append("\n\t\tId: ").append(er); 3055 | } 3056 | } 3057 | 3058 | if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { 3059 | info.append("\n\tAction Groups: "); 3060 | for (String er : activityLogAlert.actionGroupIds()) { 3061 | info.append("\n\t\tAction Group Id: ").append(er); 3062 | } 3063 | } 3064 | 3065 | if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { 3066 | info.append("\n\tAlert conditions (when all of is true): "); 3067 | for (Map.Entry er : activityLogAlert.equalsConditions().entrySet()) { 3068 | info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); 3069 | } 3070 | } 3071 | System.out.println(info.toString()); 3072 | } 3073 | 3074 | /** 3075 | * Print metric alert settings. 3076 | * 3077 | * @param metricAlert metric alert instance 3078 | */ 3079 | public static void print(MetricAlert metricAlert) { 3080 | 3081 | StringBuilder info = new StringBuilder("Metric Alert: ") 3082 | .append("\n\tId: ").append(metricAlert.id()) 3083 | .append("\n\tName: ").append(metricAlert.name()) 3084 | .append("\n\tDescription: ").append(metricAlert.description()) 3085 | .append("\n\tIs Enabled: ").append(metricAlert.enabled()) 3086 | .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) 3087 | .append("\n\tSeverity: ").append(metricAlert.severity()) 3088 | .append("\n\tWindow Size: ").append(metricAlert.windowSize()) 3089 | .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); 3090 | 3091 | if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { 3092 | info.append("\n\tScopes: "); 3093 | for (String er : metricAlert.scopes()) { 3094 | info.append("\n\t\tId: ").append(er); 3095 | } 3096 | } 3097 | 3098 | if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { 3099 | info.append("\n\tAction Groups: "); 3100 | for (String er : metricAlert.actionGroupIds()) { 3101 | info.append("\n\t\tAction Group Id: ").append(er); 3102 | } 3103 | } 3104 | 3105 | if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { 3106 | info.append("\n\tAlert conditions (when all of is true): "); 3107 | for (Map.Entry er : metricAlert.alertCriterias().entrySet()) { 3108 | MetricAlertCondition alertCondition = er.getValue(); 3109 | info.append("\n\t\tCondition name: ").append(er.getKey()) 3110 | .append("\n\t\tSignal name: ").append(alertCondition.metricName()) 3111 | .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) 3112 | .append("\n\t\tOperator: ").append(alertCondition.condition()) 3113 | .append("\n\t\tThreshold: ").append(alertCondition.threshold()) 3114 | .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); 3115 | if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { 3116 | for (MetricDimension dimon : alertCondition.dimensions()) { 3117 | info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); 3118 | for (String vals : dimon.values()) { 3119 | info.append(vals).append(", "); 3120 | } 3121 | info.append("]"); 3122 | } 3123 | } 3124 | } 3125 | } 3126 | System.out.println(info.toString()); 3127 | } 3128 | private static OkHttpClient httpClient; 3129 | 3130 | /** 3131 | * Ensure the HTTP client is valid. 3132 | * 3133 | */ 3134 | private static OkHttpClient ensureValidHttpClient() { 3135 | if (httpClient == null) { 3136 | httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build(); 3137 | } 3138 | 3139 | return httpClient; 3140 | } 3141 | 3142 | /** 3143 | * Connect to a specified URL using "curl" like HTTP GET client. 3144 | * 3145 | * @param url URL to be tested 3146 | * @return the HTTP GET response content 3147 | */ 3148 | public static String curl(String url) { 3149 | Request request = new Request.Builder().url(url).get().build(); 3150 | try { 3151 | return ensureValidHttpClient().newCall(request).execute().body().string(); 3152 | } catch (IOException e) { 3153 | return null; 3154 | } 3155 | } 3156 | } 3157 | --------------------------------------------------------------------------------