Search in sources :

Example 26 with WebApp

use of com.microsoft.azure.management.appservice.WebApp in project azure-sdk-for-java by Azure.

the class ManageDns method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final String customDomainName = "THE CUSTOM DOMAIN THAT YOU OWN (e.g. contoso.com)";
    final String rgName = SdkContext.randomResourceName("rgNEMV_", 24);
    final String appServicePlanName = SdkContext.randomResourceName("jplan1_", 15);
    final String webAppName = SdkContext.randomResourceName("webapp1-", 20);
    try {
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
        //============================================================
        // Creates root DNS Zone
        System.out.println("Creating root DNS zone " + customDomainName + "...");
        DnsZone rootDnsZone = azure.dnsZones().define(customDomainName).withExistingResourceGroup(resourceGroup).create();
        System.out.println("Created root DNS zone " + rootDnsZone.name());
        Utils.print(rootDnsZone);
        //============================================================
        // Sets NS records in the parent zone (hosting custom domain) to make Azure DNS the authoritative
        // source for name resolution for the zone
        System.out.println("Go to your registrar portal and configure your domain " + customDomainName + " with following name server addresses");
        for (String nameServer : rootDnsZone.nameServers()) {
            System.out.println(" " + nameServer);
        }
        System.out.println("Press a key after finishing above step");
        System.in.read();
        //============================================================
        // Creates a web App
        System.out.println("Creating Web App " + webAppName + "...");
        WebApp webApp = azure.webApps().define(webAppName).withRegion(Region.US_EAST2).withExistingResourceGroup(rgName).withNewWindowsPlan(PricingTier.BASIC_B1).defineSourceControl().withPublicGitRepository("https://github.com/jianghaolu/azure-site-test").withBranch("master").attach().create();
        System.out.println("Created web app " + webAppName);
        Utils.print(webApp);
        //============================================================
        // Creates a CName record and bind it with the web app
        // Step 1: Adds CName Dns record to root DNS zone that specify web app host domain as an
        // alias for www.[customDomainName]
        System.out.println("Updating DNS zone by adding a CName record...");
        rootDnsZone = rootDnsZone.update().withCNameRecordSet("www", webApp.defaultHostName()).apply();
        System.out.println("DNS zone updated");
        Utils.print(rootDnsZone);
        // Waiting for a minute for DNS CName entry to propagate
        System.out.println("Waiting a minute for CName record entry to propagate...");
        Thread.sleep(60 * 1000);
        // Step 2: Adds a web app host name binding for www.[customDomainName]
        //         This binding action will fail if the CName record propagation is not yet completed
        System.out.println("Updating Web app with host name binding...");
        webApp.update().defineHostnameBinding().withThirdPartyDomain(customDomainName).withSubDomain("www").withDnsRecordType(CustomHostNameDnsRecordType.CNAME).attach().apply();
        System.out.println("Web app updated");
        Utils.print(webApp);
        //============================================================
        // Creates a virtual machine with public IP
        System.out.println("Creating a virtual machine with public IP...");
        VirtualMachine virtualMachine1 = azure.virtualMachines().define(SdkContext.randomResourceName("employeesvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("empip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
        System.out.println("Virtual machine created");
        //============================================================
        // Update DNS zone by adding a A record in root DNS zone pointing to virtual machine IPv4 address
        PublicIPAddress vm1PublicIPAddress = virtualMachine1.getPrimaryPublicIPAddress();
        System.out.println("Updating root DNS zone " + customDomainName + "...");
        rootDnsZone = rootDnsZone.update().defineARecordSet("employees").withIPv4Address(vm1PublicIPAddress.ipAddress()).attach().apply();
        System.out.println("Updated root DNS zone " + rootDnsZone.name());
        Utils.print(rootDnsZone);
        // Prints the CName and A Records in the root DNS zone
        //
        System.out.println("Getting CName record set in the root DNS zone " + customDomainName + "...");
        PagedList<CNameRecordSet> cnameRecordSets = rootDnsZone.cNameRecordSets().list();
        for (CNameRecordSet cnameRecordSet : cnameRecordSets) {
            System.out.println("Name: " + cnameRecordSet.name() + " Canonical Name: " + cnameRecordSet.canonicalName());
        }
        System.out.println("Getting ARecord record set in the root DNS zone " + customDomainName + "...");
        PagedList<ARecordSet> aRecordSets = rootDnsZone.aRecordSets().list();
        for (ARecordSet aRecordSet : aRecordSets) {
            System.out.println("Name: " + aRecordSet.name());
            for (String ipv4Address : aRecordSet.ipv4Addresses()) {
                System.out.println("  " + ipv4Address);
            }
        }
        //============================================================
        // Creates a child DNS zone
        String partnerSubDomainName = "partners." + customDomainName;
        System.out.println("Creating child DNS zone " + partnerSubDomainName + "...");
        DnsZone partnersDnsZone = azure.dnsZones().define(partnerSubDomainName).withExistingResourceGroup(resourceGroup).create();
        System.out.println("Created child DNS zone " + partnersDnsZone.name());
        Utils.print(partnersDnsZone);
        //============================================================
        // Adds NS records in the root dns zone to delegate partners.[customDomainName] to child dns zone
        System.out.println("Updating root DNS zone " + rootDnsZone + "...");
        DnsRecordSet.UpdateDefinitionStages.WithNSRecordNameServerOrAttachable<DnsZone.Update> nsRecordStage = rootDnsZone.update().defineNSRecordSet("partners").withNameServer(partnersDnsZone.nameServers().get(0));
        for (int i = 1; i < partnersDnsZone.nameServers().size(); i++) {
            nsRecordStage = nsRecordStage.withNameServer(partnersDnsZone.nameServers().get(i));
        }
        nsRecordStage.attach().apply();
        System.out.println("Root DNS zone updated");
        Utils.print(rootDnsZone);
        //============================================================
        // Creates a virtual machine with public IP
        System.out.println("Creating a virtual machine with public IP...");
        VirtualMachine virtualMachine2 = azure.virtualMachines().define(SdkContext.randomResourceName("partnersvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("ptnerpip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
        System.out.println("Virtual machine created");
        //============================================================
        // Update child DNS zone by adding a A record pointing to virtual machine IPv4 address
        PublicIPAddress vm2PublicIPAddress = virtualMachine2.getPrimaryPublicIPAddress();
        System.out.println("Updating child DNS zone " + partnerSubDomainName + "...");
        partnersDnsZone = partnersDnsZone.update().defineARecordSet("@").withIPv4Address(vm2PublicIPAddress.ipAddress()).attach().apply();
        System.out.println("Updated child DNS zone " + partnersDnsZone.name());
        Utils.print(partnersDnsZone);
        //============================================================
        // Removes A record entry from the root DNS zone
        System.out.println("Removing A Record from root DNS zone " + rootDnsZone.name() + "...");
        rootDnsZone = rootDnsZone.update().withoutARecordSet("employees").apply();
        System.out.println("Removed A Record from root DNS zone");
        Utils.print(rootDnsZone);
        //============================================================
        // Deletes the DNS zone
        System.out.println("Deleting child DNS zone " + partnersDnsZone.name() + "...");
        azure.dnsZones().deleteById(partnersDnsZone.id());
        System.out.println("Deleted child DNS zone " + partnersDnsZone.name());
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : ARecordSet(com.microsoft.azure.management.dns.ARecordSet) CNameRecordSet(com.microsoft.azure.management.dns.CNameRecordSet) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) DnsZone(com.microsoft.azure.management.dns.DnsZone) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) WebApp(com.microsoft.azure.management.appservice.WebApp) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 27 with WebApp

use of com.microsoft.azure.management.appservice.WebApp in project azure-tools-for-java by Microsoft.

the class OpenWebappAction method actionPerformed.

@Override
public void actionPerformed(NodeActionEvent e) {
    try {
        WebApp webApp = webappNode.getWebApp();
        String appServiceLink = "https://" + webApp.defaultHostName();
        PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(appServiceLink));
    } catch (Exception ex) {
        DefaultLoader.getUIHelper().logError(ex.getMessage(), ex);
    }
}
Also used : URL(java.net.URL) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 28 with WebApp

use of com.microsoft.azure.management.appservice.WebApp in project azure-tools-for-java by Microsoft.

the class WebAppDeployDialog method deploy.

private void deploy(String artifactName, String artifactPath) {
    int selectedRow = table.getSelectionIndex();
    String appServiceName = table.getItems()[selectedRow].getText(0);
    WebAppDetails wad = webAppDetailsMap.get(appServiceName);
    WebApp webApp = wad.webApp;
    boolean isDeployToRoot = btnDeployToRoot.getSelection();
    String errTitle = "Deploy Web App Error";
    String sitePath = buildSiteLink(wad.webApp, isDeployToRoot ? null : artifactName);
    //Map<String, String> threadParams = new HashMap<>();
    //threadParams.put("sitePath", sitePath);
    String jobDescription = String.format("Web App '%s' deployment", webApp.name());
    String deploymentName = UUID.randomUUID().toString();
    AzureDeploymentProgressNotification.createAzureDeploymentProgressNotification(deploymentName, jobDescription);
    Job job = new Job(jobDescription) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            String message = "Deploying Web App...";
            String cancelMessage = "Interrupted by user";
            String successMessage = "";
            String errorMessage = "Error";
            Map<String, String> postEventProperties = new HashMap<String, String>();
            postEventProperties.put("Java App Name", project.getName());
            monitor.beginTask(message, IProgressMonitor.UNKNOWN);
            try {
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 5, message);
                PublishingProfile pp = webApp.getPublishingProfile();
                WebAppUtils.deployArtifact(artifactName, artifactPath, pp, isDeployToRoot, new UpdateProgressIndicator(monitor));
                if (monitor.isCanceled()) {
                    AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, null, -1, cancelMessage);
                    return Status.CANCEL_STATUS;
                }
                message = "Checking Web App availability...";
                monitor.setTaskName(message);
                //monitor.subTask("Link: " + sitePath);
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 75, message);
                // to make warn up cancelable
                int stepLimit = 5;
                int sleepMs = 1000;
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            for (int step = 0; step < stepLimit; ++step) {
                                if (WebAppUtils.isUrlAccessible(sitePath)) {
                                    // warm up
                                    break;
                                }
                                Thread.sleep(sleepMs);
                            }
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@Thread@run@ProgressDialog@deploy@AppServiceCreateDialog@SingInDialog", ex));
                        } catch (InterruptedException ex) {
                            System.out.println("The thread is interupted");
                        }
                    }
                });
                thread.start();
                while (thread.isAlive()) {
                    if (monitor.isCanceled()) {
                        // it's published but not warmed up yet - consider as success
                        AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 100, successMessage);
                        return Status.CANCEL_STATUS;
                    } else
                        Thread.sleep(sleepMs);
                }
                monitor.done();
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 100, successMessage);
            } catch (IOException | InterruptedException ex) {
                //threadParams.put("sitePath", null);
                postEventProperties.put("PublishError", ex.getMessage());
                ex.printStackTrace();
                LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@ProgressDialog@deploy@AppServiceCreateDialog", ex));
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, null, -1, errorMessage);
                Display.getDefault().asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        ErrorWindow.go(parentShell, ex.getMessage(), errTitle);
                        ;
                    }
                });
            }
            AppInsightsClient.create("Deploy as WebApp", "", postEventProperties);
            return Status.OK_STATUS;
        }
    };
    job.schedule();
//        try {
//            ProgressDialog.get(this.getShell(), "Deploy Web App Progress").run(true, true, new IRunnableWithProgress() {
//                @Override
//                public void run(IProgressMonitor monitor) {
//                    monitor.beginTask("Deploying Web App...", IProgressMonitor.UNKNOWN);
//                    try {
//                        PublishingProfile pp = webApp.getPublishingProfile();
//                        WebAppUtils.deployArtifact(artifactName, artifactPath,
//                                pp, isDeployToRoot, new UpdateProgressIndicator(monitor));
//                        monitor.setTaskName("Checking Web App availability...");
//                        monitor.subTask("Link: " + sitePath);
//                        
//                        // to make warn up cancelable
//                        int stepLimit = 5;
//                        int sleepMs = 2000;
//                        Thread thread = new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    for (int step = 0; step < stepLimit; ++step) {
//                                        if (WebAppUtils.isUrlAccessible(sitePath))  { // warm up
//                                            break;
//                                        }
//                                        Thread.sleep(sleepMs);
//                                    }
//                                } catch (IOException | InterruptedException ex) {
//                                    ex.printStackTrace();
//                                    LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@Thread@run@ProgressDialog@deploy@AppServiceCreateDialog@SingInDialog", ex));
//                                }
//                            }
//                        });
//                        thread.run();
//                        while (thread.isAlive()) {
//                            if (monitor.isCanceled()) return;
//                            else Thread.sleep(sleepMs);
//                        }
//                        
//                        monitor.done();
//                    } catch (IOException | InterruptedException ex) {
//                        threadParams.put("sitePath", null);
//                        ex.printStackTrace();
//                        LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@ProgressDialog@deploy@AppServiceCreateDialog", ex));
//                        Display.getDefault().asyncExec(new Runnable() {
//                            @Override
//                            public void run() {
//                                ErrorWindow.go(parentShell, ex.getMessage(), errTitle);;
//                            }
//                        });
//                    }
//                }
//            });
//        } catch (InvocationTargetException | InterruptedException ex) {
//            threadParams.put("sitePath", null);
//            ex.printStackTrace();
//            LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "deploy@AppServiceCreateDialog", ex));
//            ErrorWindow.go(getShell(), ex.getMessage(), errTitle);;
//        }
//return threadParams.get("sitePath");
}
Also used : WebAppDetails(com.microsoft.azuretools.utils.WebAppUtils.WebAppDetails) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) HashMap(java.util.HashMap) IOException(java.io.IOException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) UpdateProgressIndicator(com.microsoft.azuretools.core.utils.UpdateProgressIndicator) Job(org.eclipse.core.runtime.jobs.Job) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 29 with WebApp

use of com.microsoft.azure.management.appservice.WebApp in project azure-tools-for-java by Microsoft.

the class WebAppDeployDialog method createAppService.

private void createAppService() {
    AppServiceCreateDialog d = AppServiceCreateDialog.go(getShell());
    if (d == null) {
        // something went wrong - report an error!
        return;
    }
    WebApp wa = d.getWebApp();
    doFillTable();
    selectTableRowWithWebAppName(wa.name());
    fillAppServiceDetails();
}
Also used : WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 30 with WebApp

use of com.microsoft.azure.management.appservice.WebApp in project azure-tools-for-java by Microsoft.

the class WebAppDeployDialog method createAppService.

private void createAppService() {
    AppInsightsClient.createByType(AppInsightsClient.EventType.WebApp, "", "Create");
    AppServiceCreateDialog d = AppServiceCreateDialog.go(project);
    if (d == null) {
        // something went wrong - report an error!
        return;
    }
    WebApp wa = d.getWebApp();
    doFillTable();
    selectTableRowWithWebAppName(wa.name());
//fillAppServiceDetails();
}
Also used : WebApp(com.microsoft.azure.management.appservice.WebApp)

Aggregations

WebApp (com.microsoft.azure.management.appservice.WebApp)32 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)15 IOException (java.io.IOException)12 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)6 File (java.io.File)6 PublishingProfile (com.microsoft.azure.management.appservice.PublishingProfile)5 SubscriptionDetail (com.microsoft.azuretools.authmanage.models.SubscriptionDetail)5 WebAppDetails (com.microsoft.azuretools.utils.WebAppUtils.WebAppDetails)5 AppServiceDomain (com.microsoft.azure.management.appservice.AppServiceDomain)3 TrafficManagerProfile (com.microsoft.azure.management.trafficmanager.TrafficManagerProfile)3 HashMap (java.util.HashMap)3 List (java.util.List)3 DefaultTableModel (javax.swing.table.DefaultTableModel)3 Git (org.eclipse.jgit.api.Git)3 SqlDatabase (com.microsoft.azure.management.sql.SqlDatabase)2 SqlServer (com.microsoft.azure.management.sql.SqlServer)2 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)2 CloudStorageAccount (com.microsoft.azure.storage.CloudStorageAccount)2 StorageException (com.microsoft.azure.storage.StorageException)2 CloudBlobContainer (com.microsoft.azure.storage.blob.CloudBlobContainer)2