Skip to content

Commit

Permalink
Add source control sample
Browse files Browse the repository at this point in the history
  • Loading branch information
jianghaolu committed Dec 9, 2016
1 parent dfda01a commit fcbaf63
Show file tree
Hide file tree
Showing 5 changed files with 331 additions and 73 deletions.
5 changes: 5 additions & 0 deletions azure-samples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public static void main(String[] args) {
final String app2Name = ResourceNamer.randomResourceName("webapp2-", 20);
final String app3Name = ResourceNamer.randomResourceName("webapp3-", 20);
final String planName = ResourceNamer.randomResourceName("jplan_", 15);
final String rg1Name = ResourceNamer.randomResourceName("rg1NEMV_", 24);
final String rg2Name = ResourceNamer.randomResourceName("rg2NEMV_", 24);
final String rg1Name = ResourceNamer.randomResourceName("rg1NEMV_", 24);
final String rg2Name = ResourceNamer.randomResourceName("rg2NEMV_", 24);

try {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/

package com.microsoft.azure.management.appservice.samples;

import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.appservice.AppServicePlan;
import com.microsoft.azure.management.appservice.AppServicePricingTier;
import com.microsoft.azure.management.appservice.JavaVersion;
import com.microsoft.azure.management.appservice.PublishingProfile;
import com.microsoft.azure.management.appservice.WebApp;
import com.microsoft.azure.management.appservice.WebContainer;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.resources.fluentcore.utils.ResourceNamer;
import com.microsoft.azure.management.samples.Utils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
* Azure App Service basic sample for managing web apps.
* - Create 2 web apps under the same new app service plan:
* - Deploy to 1 using FTP
* - Deploy to 2 using Git
* - Deploy to 3 using
* - List web apps
* - Delete a web app
*/
public final class ManageWebAppSourceControl {

private static OkHttpClient httpClient;

/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
// New resources
final String app1Name = ResourceNamer.randomResourceName("webapp1-", 20);
final String app2Name = ResourceNamer.randomResourceName("webapp2-", 20);
final String app3Name = ResourceNamer.randomResourceName("webapp3-", 20);
final String planName = ResourceNamer.randomResourceName("jplan_", 15);
final String rg1Name = ResourceNamer.randomResourceName("rg1NEMV_", 24);
final String rg2Name = ResourceNamer.randomResourceName("rg2NEMV_", 24);

try {

//=============================================================
// Authenticate

final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

Azure azure = Azure
.configure()
.withLogLevel(HttpLoggingInterceptor.Level.BODY)
.authenticate(credFile)
.withDefaultSubscription();

// Print selected subscription
System.out.println("Selected subscription: " + azure.subscriptionId());
try {


//============================================================
// Create a web app with a new app service plan

System.out.println("Creating web app " + app1Name + " in resource group " + rg1Name + "...");

WebApp app1 = azure.webApps()
.define(app1Name)
.withNewResourceGroup(rg1Name)
.withNewAppServicePlan(planName)
.withRegion(Region.US_WEST)
.withPricingTier(AppServicePricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.create();

System.out.println("Created web app " + app1.name());
Utils.print(app1);

//============================================================
// Deploy to app 1 through FTP

System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");

uploadFileToFtp(app1.getPublishingProfile(), "helloworld.war", ManageWebAppSourceControl.class.getResourceAsStream("/helloworld.war"));

System.out.println("Deployment helloworld.war to web app " + app1.name() + " completed");
Utils.print(app1);

System.out.println("CURLing " + app1Name + ".azurewebsites.net/helloworld");
System.out.println(curl("http://" + app1Name + ".azurewebsites.net/helloworld"));

//============================================================
// Create a second web app with the same app service plan

System.out.println("Creating another web app " + app2Name + " in resource group " + rg1Name + "...");
AppServicePlan plan = azure.appServices().appServicePlans().getByGroup(rg1Name, planName);
WebApp app2 = azure.webApps()
.define(app2Name)
.withExistingResourceGroup(rg1Name)
.withExistingAppServicePlan(plan)
.create();

System.out.println("Created web app " + app2.name());
Utils.print(app2);

//============================================================
// Deploy to app 2 through Github

System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");

uploadFileToFtp(app1.getPublishingProfile(), "helloworld.war", ManageWebAppSourceControl.class.getResourceAsStream("/helloworld.war"));

System.out.println("Deployment helloworld.war to web app " + app1.name() + " completed");
Utils.print(app1);

System.out.println("CURLing " + app1Name + ".azurewebsites.net/helloworld");
System.out.println(curl("http://" + app1Name + ".azurewebsites.net/helloworld"));

//============================================================
// Create a third web app with the same app service plan, but
// in a different resource group

System.out.println("Creating another web app " + app3Name + " in resource group " + rg2Name + "...");
WebApp app3 = azure.webApps()
.define(app3Name)
.withNewResourceGroup(rg2Name)
.withExistingAppServicePlan(plan)
.create();

System.out.println("Created web app " + app3.name());
Utils.print(app3);

//============================================================
// stop and start app1, restart app 2
System.out.println("Stopping web app " + app1.name());
app1.stop();
System.out.println("Stopped web app " + app1.name());
Utils.print(app1);
System.out.println("Starting web app " + app1.name());
app1.start();
System.out.println("Started web app " + app1.name());
Utils.print(app1);
System.out.println("Restarting web app " + app2.name());
app2.restart();
System.out.println("Restarted web app " + app2.name());
Utils.print(app2);

//============================================================
// Configure app 3 to have Java 8 enabled
System.out.println("Adding Java support to web app " + app3Name + "...");
app3.update()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.apply();
System.out.println("Java supported on web app " + app3Name + "...");

//=============================================================
// List web apps

System.out.println("Printing list of web apps in resource group " + rg1Name + "...");

for (WebApp webApp : azure.webApps().listByGroup(rg1Name)) {
Utils.print(webApp);
}

System.out.println("Printing list of web apps in resource group " + rg2Name + "...");

for (WebApp webApp : azure.webApps().listByGroup(rg2Name)) {
Utils.print(webApp);
}

//=============================================================
// Delete a web app

System.out.println("Deleting web app " + app1Name + "...");
azure.webApps().deleteByGroup(rg1Name, app1Name);
System.out.println("Deleted web app " + app1Name + "...");

System.out.println("Printing list of web apps in resource group " + rg1Name + " again...");
for (WebApp webApp : azure.webApps().listByGroup(rg1Name)) {
Utils.print(webApp);
}

} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rg1Name);
azure.resourceGroups().beginDeleteByName(rg1Name);
System.out.println("Deleted Resource Group: " + rg1Name);
System.out.println("Deleting Resource Group: " + rg2Name);
azure.resourceGroups().beginDeleteByName(rg2Name);
System.out.println("Deleted Resource Group: " + rg2Name);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}

} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}

private static String curl(String url) {
Request request = new Request.Builder().url(url).get().build();
try {
return httpClient.newCall(request).execute().body().string();
} catch (IOException e) {
return null;
}
}

static {
httpClient = new OkHttpClient.Builder().build();
}

private static void uploadFileToFtp(PublishingProfile profile, String fileName, InputStream file) throws Exception {
FTPClient ftpClient = new FTPClient();
String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
String server = ftpUrlSegments[0];
String path = "./site/wwwroot/webapps";
ftpClient.connect(server);
ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(path);
ftpClient.storeFile(fileName, file);
ftpClient.disconnect();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
Expand All @@ -35,18 +34,8 @@
* - domain
* - Create a domain
* - certificate
* - Create a Wildcard SSL certificate for the domain
* - update 1st web app to use the domain and a new standard SSL certificate
* - update 2nd web app to use the domain and the created wildcard SSL certificate
* - slots
* - create 2 slots under 2nd web app and bind to the domain and the wildcard SSL certificate
* - turn on auto-swap for 2nd slot
* - set connection strings to a storage account on production slot and make them sticky
* - source control
* - bind a simple web app in a public GitHub repo to 2nd slot and have it auto-swapped to production
* - Verify the web app has access to the storage account
* - Delete a slot
* - Delete a web app
* - Upload a self-signed wildcard certificate
* - update both web apps to use the domain and the created wildcard SSL certificate
*/
public final class ManageWebAppWithDomainSsl {

Expand Down Expand Up @@ -165,12 +154,26 @@ public static void main(String[] args) {

System.out.println("Creating a self-signed certificate " + pfxPath + "...");

createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName);
Utils.createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName);

System.out.println("Created self-signed certificate " + pfxPath);

//============================================================
// Bind domain to web app 2 and turn on wild card SSL
// Bind domain to web app 2 and turn on wild card SSL for both

System.out.println("Binding https://" + app1Name + "." + domainName + " to web app " + app1Name + "...");

app1 = app1.update()
.withManagedHostnameBindings(domain, app1Name)
.defineSslBinding()
.forHostname(app1Name + "." + domainName)
.withPfxCertificateToUpload(new File(pfxPath), certPassword)
.withSniBasedSsl()
.attach()
.apply();

System.out.println("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name);
Utils.print(app1);

System.out.println("Binding https://" + app2Name + "." + domainName + " to web app " + app2Name + "...");

Expand Down Expand Up @@ -217,61 +220,5 @@ private static Response curl(String url) throws IOException {
httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build();
}

/**
* This method creates a certificate for given password.
*
* @param certPath location of certificate file
* @param pfxPath location of pfx file
* @param alias User alias
* @param password alias password
* @param cnName domain name
* @throws Exception exceptions from the creation
*/
public static void createCertificate(String certPath, String pfxPath,
String alias, String password, String cnName) throws Exception {

String validityInDays = "3650";
String keyAlg = "RSA";
String sigAlg = "SHA1withRSA";
String keySize = "2048";
String storeType = "pkcs12";
String command = "keytool";
String jdkPath = System.getProperty("java.home");
if (jdkPath != null && !jdkPath.isEmpty()) {
jdkPath = jdkPath.concat("\\bin");
}
if (new File(jdkPath).isDirectory()) {
command = String.format("%s%s%s", jdkPath, File.separator, command);
}

// Create Pfx file
String[] commandArgs = {command, "-genkey", "-alias", alias,
"-keystore", pfxPath, "-storepass", password, "-validity",
validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize,
"-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1" };
Utils.cmdInvocation(commandArgs, false);

// Create cer file i.e. extract public key from pfx
File pfxFile = new File(pfxPath);
if (pfxFile.exists()) {
String[] certCommandArgs = {command, "-export", "-alias", alias,
"-storetype", storeType, "-keystore", pfxPath,
"-storepass", password, "-rfc", "-file", certPath };
// output of keytool export command is going to error stream
// although command is
// executed successfully, hence ignoring error stream in this case
Utils.cmdInvocation(certCommandArgs, true);

// Check if file got created or not
File cerFile = new File(pfxPath);
if (!cerFile.exists()) {
throw new IOException(
"Error occurred while creating certificate"
+ StringUtils.join(" ", certCommandArgs));
}
} else {
throw new IOException("Error occurred while creating certificates"
+ StringUtils.join(" ", commandArgs));
}
}
}
Loading

0 comments on commit fcbaf63

Please sign in to comment.