Example usage for org.eclipse.jgit.api Git commit

List of usage examples for org.eclipse.jgit.api Git commit

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git commit.

Prototype

public CommitCommand commit() 

Source Link

Document

Return a command object to execute a Commit command

Usage

From source file:com.google.gerrit.acceptance.git.GitUtil.java

License:Apache License

private static Commit createCommit(Git git, PersonIdent i, String msg, String changeId)
        throws GitAPIException, IOException {

    final CommitCommand commitCmd = git.commit();
    commitCmd.setAmend(changeId != null);
    commitCmd.setAuthor(i);//from   w w w .  j  av a2s .c  o  m
    commitCmd.setCommitter(i);

    if (changeId == null) {
        ObjectId id = computeChangeId(git, i, msg);
        changeId = "I" + id.getName();
    }
    msg = ChangeIdUtil.insertId(msg, ObjectId.fromString(changeId.substring(1)));
    commitCmd.setMessage(msg);

    RevCommit c = commitCmd.call();
    return new Commit(c, changeId);
}

From source file:com.google.gerrit.acceptance.git.ssh.GitUtil.java

License:Apache License

public static String createCommit(Git git, PersonIdent i, String msg, boolean insertChangeId)
        throws GitAPIException, IOException {
    ObjectId changeId = null;/*from  w ww  .java 2  s .  c  o  m*/
    if (insertChangeId) {
        changeId = computeChangeId(git, i, msg);
        msg = ChangeIdUtil.insertId(msg, changeId);
    }

    final CommitCommand commitCmd = git.commit();
    commitCmd.setAuthor(i);
    commitCmd.setCommitter(i);
    commitCmd.setMessage(msg);
    commitCmd.call();

    return changeId != null ? "I" + changeId.getName() : null;
}

From source file:com.google.gerrit.server.change.IncludedInResolverTest.java

License:Apache License

@Override
@Before/*from  www . ja  v  a  2  s  .  c o  m*/
public void setUp() throws Exception {
    super.setUp();

    /*- The following graph will be created.
            
      o   tag 2.5, 2.5_annotated, 2.5_annotated_twice
      |\
      | o tag 2.0.1
      | o tag 2.0
      o | tag 1.3
      |/
      o   c3
            
      | o tag 1.0.1
      |/
      o   tag 1.0
      o   c2
      o   c1
            
     */

    // TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
    @SuppressWarnings("resource")
    Git git = new Git(db);
    revWalk = new RevWalk(db);
    // Version 1.0
    commit_initial = git.commit().setMessage("c1").call();
    git.commit().setMessage("c2").call();
    RevCommit commit_v1_0 = git.commit().setMessage("version 1.0").call();
    git.tag().setName(TAG_1_0).setObjectId(commit_v1_0).call();
    RevCommit c3 = git.commit().setMessage("c3").call();
    // Version 1.01
    createAndCheckoutBranch(commit_v1_0, BRANCH_1_0);
    RevCommit commit_v1_0_1 = git.commit().setMessage("verREFS_HEADS_RELsion 1.0.1").call();
    git.tag().setName(TAG_1_0_1).setObjectId(commit_v1_0_1).call();
    // Version 1.3
    createAndCheckoutBranch(c3, BRANCH_1_3);
    commit_v1_3 = git.commit().setMessage("version 1.3").call();
    git.tag().setName(TAG_1_3).setObjectId(commit_v1_3).call();
    // Version 2.0
    createAndCheckoutBranch(c3, BRANCH_2_0);
    RevCommit commit_v2_0 = git.commit().setMessage("version 2.0").call();
    git.tag().setName(TAG_2_0).setObjectId(commit_v2_0).call();
    RevCommit commit_v2_0_1 = git.commit().setMessage("version 2.0.1").call();
    git.tag().setName(TAG_2_0_1).setObjectId(commit_v2_0_1).call();

    // Version 2.5
    createAndCheckoutBranch(commit_v1_3, BRANCH_2_5);
    git.merge().include(commit_v2_0_1).setCommit(false).setFastForward(FastForwardMode.NO_FF).call();
    commit_v2_5 = git.commit().setMessage("version 2.5").call();
    git.tag().setName(TAG_2_5).setObjectId(commit_v2_5).setAnnotated(false).call();
    Ref ref_tag_2_5_annotated = git.tag().setName(TAG_2_5_ANNOTATED).setObjectId(commit_v2_5).setAnnotated(true)
            .call();
    RevTag tag_2_5_annotated = revWalk.parseTag(ref_tag_2_5_annotated.getObjectId());
    git.tag().setName(TAG_2_5_ANNOTATED_TWICE).setObjectId(tag_2_5_annotated).setAnnotated(true).call();
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It tests Submodule.update in the scenario a merged commit is an empty one
 * (it does not have a .gitmodules file) and the project the commit was merged
 * is not a submodule of other project./*  w  ww  .j  a v  a  2  s . c  om*/
 *
 * @throws Exception If an exception occurs.
 */
@Test
public void testEmptyCommit() throws Exception {
    expect(schemaFactory.open()).andReturn(schema);

    final Repository realDb = createWorkRepository();
    final Git git = new Git(realDb);

    final RevCommit mergeTip = git.commit().setMessage("test").call();

    final Branch.NameKey branchNameKey = new Branch.NameKey(new Project.NameKey("test-project"), "test-branch");

    expect(urlProvider.get()).andReturn("http://localhost:8080");

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    final ResultSet<SubmoduleSubscription> emptySubscriptions = new ListResultSet<>(
            new ArrayList<SubmoduleSubscription>());
    expect(subscriptions.bySubmodule(branchNameKey)).andReturn(emptySubscriptions);

    schema.close();

    doReplay();

    final SubmoduleOp submoduleOp = new SubmoduleOp(branchNameKey, mergeTip, new RevWalk(realDb), urlProvider,
            schemaFactory, realDb, null, new ArrayList<Change>(), null, null, null, null, null, null);

    submoduleOp.update();

    doVerify();
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It tests SubmoduleOp.update in a scenario considering no .gitmodules file
 * in a merged commit to a destination project/branch that is a source one to
 * one called "target-project"./*from w  w w .  jav a2s.com*/
 * <p>
 * It expects to update the git link called "source-project" to be in target
 * repository.
 * </p>
 *
 * @throws Exception If an exception occurs.
 */
@Test
public void testOneSubscriberToUpdate() throws Exception {
    expect(schemaFactory.open()).andReturn(schema);

    final Repository sourceRepository = createWorkRepository();
    final Git sourceGit = new Git(sourceRepository);

    addRegularFileToIndex("file.txt", "test content", sourceRepository);

    final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call();

    final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"),
            "refs/heads/master");

    final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId());
    final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()),
            new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs());

    final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>();
    mergedCommits.put(submittedChange.getId(), codeReviewCommit);

    final List<Change> submitted = new ArrayList<>();
    submitted.add(submittedChange);

    final Repository targetRepository = createWorkRepository();
    final Git targetGit = new Git(targetRepository);

    addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);

    targetGit.commit().setMessage("test").call();

    final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"),
            sourceBranchNameKey.get());

    expect(urlProvider.get()).andReturn("http://localhost:8080");

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList(
            new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project")));
    expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers);

    expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository)
            .anyTimes();

    Capture<RefUpdate> ruCapture = new Capture<>();
    gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture));
    changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class),
            EasyMock.<Account>isNull());

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    final ResultSet<SubmoduleSubscription> emptySubscriptions = new ListResultSet<>(
            new ArrayList<SubmoduleSubscription>());
    expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(emptySubscriptions);

    schema.close();

    final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com");

    doReplay();

    final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip,
            new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository,
            new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager,
            gitRefUpdated, null, changeHooks);

    submoduleOp.update();

    doVerify();
    RefUpdate ru = ruCapture.getValue();
    assertEquals(ru.getName(), targetBranchNameKey.get());
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It tests SubmoduleOp.update in a scenario considering established circular
 * reference in submodule_subscriptions table.
 * <p>/*from w  w w . j a v  a  2  s  .com*/
 * In the tested scenario there is no .gitmodules file in a merged commit to a
 * destination project/branch that is a source one to one called
 * "target-project".
 * <p>
 * submodule_subscriptions table will be incorrect due source appearing as a
 * subscriber or target-project: according to database target-project has as
 * source the source-project, and source-project has as source the
 * target-project.
 * <p>
 * It expects to update the git link called "source-project" to be in target
 * repository and ignoring the incorrect row in database establishing the
 * circular reference.
 * </p>
 *
 * @throws Exception If an exception occurs.
 */
@Test
public void testAvoidingCircularReference() throws Exception {
    expect(schemaFactory.open()).andReturn(schema);

    final Repository sourceRepository = createWorkRepository();
    final Git sourceGit = new Git(sourceRepository);

    addRegularFileToIndex("file.txt", "test content", sourceRepository);

    final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call();

    final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"),
            "refs/heads/master");

    final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId());
    final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()),
            new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs());

    final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>();
    mergedCommits.put(submittedChange.getId(), codeReviewCommit);

    final List<Change> submitted = new ArrayList<>();
    submitted.add(submittedChange);

    final Repository targetRepository = createWorkRepository();
    final Git targetGit = new Git(targetRepository);

    addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);

    targetGit.commit().setMessage("test").call();

    final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"),
            sourceBranchNameKey.get());

    expect(urlProvider.get()).andReturn("http://localhost:8080");

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList(
            new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project")));
    expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers);

    expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository)
            .anyTimes();

    Capture<RefUpdate> ruCapture = new Capture<>();
    gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture));
    changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class),
            EasyMock.<Account>isNull());

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    final ResultSet<SubmoduleSubscription> incorrectSubscriptions = new ListResultSet<>(
            Collections.singletonList(
                    new SubmoduleSubscription(sourceBranchNameKey, targetBranchNameKey, "target-project")));
    expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(incorrectSubscriptions);

    schema.close();

    final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com");

    doReplay();

    final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip,
            new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository,
            new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager,
            gitRefUpdated, null, changeHooks);

    submoduleOp.update();

    doVerify();
    RefUpdate ru = ruCapture.getValue();
    assertEquals(ru.getName(), targetBranchNameKey.get());
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It calls SubmoduleOp.update method considering scenario only updating
 * Subscriptions table./*  w  w w .java2 s  . co  m*/
 * <p>
 * In this test a commit is created and considered merged to
 * {@code mergedBranch} branch.
 * </p>
 * <p>
 * The destination project the commit was merged is not considered to be a
 * source of another project (no subscribers found to this project).
 * </p>
 *
 * @param gitModulesFileContent The .gitmodules file content.
 * @param mergedBranch The {@code Branch.NameKey} instance representing the
 *        project/branch the commit was merged.
 * @param extractedSubscriptions The subscription rows extracted from
 *        gitmodules file.
 * @param previousSubscriptions The subscription rows to be considering as
 *        existing and pointing as target to the {@code mergedBranch}
 *        before updating the table.
 * @throws Exception If an exception occurs.
 */
private void doOnlySubscriptionTableOperations(final String gitModulesFileContent,
        final Branch.NameKey mergedBranch, final List<SubmoduleSubscription> extractedSubscriptions,
        final List<SubmoduleSubscription> previousSubscriptions) throws Exception {
    expect(schemaFactory.open()).andReturn(schema);

    final Repository realDb = createWorkRepository();
    final Git git = new Git(realDb);

    addRegularFileToIndex(".gitmodules", gitModulesFileContent, realDb);

    final RevCommit mergeTip = git.commit().setMessage("test").call();

    expect(urlProvider.get()).andReturn("http://localhost:8080").times(2);

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    expect(subscriptions.bySuperProject(mergedBranch)).andReturn(new ListResultSet<>(previousSubscriptions));

    SortedSet<Project.NameKey> existingProjects = new TreeSet<>();

    for (SubmoduleSubscription extracted : extractedSubscriptions) {
        existingProjects.add(extracted.getSubmodule().getParentKey());
    }

    for (int index = 0; index < extractedSubscriptions.size(); index++) {
        expect(repoManager.list()).andReturn(existingProjects);
    }

    final Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<>();
    for (SubmoduleSubscription s : extractedSubscriptions) {
        if (previousSubscriptions.contains(s)) {
            alreadySubscribeds.add(s);
        }
    }

    final Set<SubmoduleSubscription> subscriptionsToRemove = new HashSet<>(previousSubscriptions);
    final List<SubmoduleSubscription> subscriptionsToInsert = new ArrayList<>(extractedSubscriptions);

    subscriptionsToRemove.removeAll(subscriptionsToInsert);
    subscriptionsToInsert.removeAll(alreadySubscribeds);

    if (!subscriptionsToRemove.isEmpty()) {
        expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
        subscriptions.delete(subscriptionsToRemove);
    }

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    subscriptions.insert(subscriptionsToInsert);

    expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
    expect(subscriptions.bySubmodule(mergedBranch))
            .andReturn(new ListResultSet<>(new ArrayList<SubmoduleSubscription>()));

    schema.close();

    doReplay();

    final SubmoduleOp submoduleOp = new SubmoduleOp(mergedBranch, mergeTip, new RevWalk(realDb), urlProvider,
            schemaFactory, realDb, new Project(mergedBranch.getParentKey()), new ArrayList<Change>(), null,
            null, repoManager, null, null, null);

    submoduleOp.update();
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public static GitService init(String site, String dir) throws Exception {
    String repoPath = dir + "/" + site;
    log.debug("Repository Path :" + repoPath);
    Repository repo = new FileRepository(repoPath + "/.git");
    Git git = null;
    try {/*  w  w w.  j a  v a 2 s. c om*/
        repo.create();
        git = new Git(repo);

        File localGitRepo = new File(repoPath);
        localGitRepo.mkdirs();
        new File(localGitRepo, "delete.me").createNewFile();

        git.add().addFilepattern("delete.me").call();
        git.commit().setMessage("initial commit").call();
        return new GitService(git);
    } catch (IllegalStateException e) {
        log.debug("Repo Already exists locally");
        if (repo != null) {
            repo.close();
        }
    }
    return null;
}

From source file:com.microsoft.azure.management.appservice.samples.ManageFunctionAppSourceControl.java

License:Open Source License

/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 *///from w ww  . j  a  va 2s  .c  om
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name = SdkContext.randomResourceName("webapp2-", 20);
    final String app3Name = SdkContext.randomResourceName("webapp3-", 20);
    final String app4Name = SdkContext.randomResourceName("webapp4-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String app3Url = app3Name + suffix;
    final String app4Url = app4Name + suffix;
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);

    try {

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

        System.out.println("Creating function app " + app1Name + " in resource group " + rgName + "...");

        FunctionApp app1 = azure.appServices().functionApps().define(app1Name).withRegion(Region.US_WEST)
                .withNewResourceGroup(rgName).create();

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

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

        System.out.println("Deploying a function app to " + app1Name + " through FTP...");

        Utils.uploadFileToFunctionApp(app1.getPublishingProfile(), "host.json",
                ManageFunctionAppSourceControl.class.getResourceAsStream("/square-function-app/host.json"));
        Utils.uploadFileToFunctionApp(app1.getPublishingProfile(), "square/function.json",
                ManageFunctionAppSourceControl.class
                        .getResourceAsStream("/square-function-app/square/function.json"));
        Utils.uploadFileToFunctionApp(app1.getPublishingProfile(), "square/index.js",
                ManageFunctionAppSourceControl.class
                        .getResourceAsStream("/square-function-app/square/index.js"));

        // sync triggers
        app1.syncTriggers();

        System.out.println("Deployment square app to function app " + app1.name() + " completed");
        Utils.print(app1);

        // warm up
        System.out.println("Warming up " + app1Url + "/api/square...");
        post("http://" + app1Url + "/api/square", "625");
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/api/square...");
        System.out.println("Square of 625 is " + post("http://" + app1Url + "/api/square", "625"));

        //============================================================
        // Create a second function app with local git source control

        System.out
                .println("Creating another function app " + app2Name + " in resource group " + rgName + "...");
        AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId());
        FunctionApp app2 = azure.appServices().functionApps().define(app2Name).withExistingAppServicePlan(plan)
                .withExistingResourceGroup(rgName).withExistingStorageAccount(app1.storageAccount())
                .withLocalGitSourceControl().create();

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

        //============================================================
        // Deploy to app 2 through local Git

        System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");

        PublishingProfile profile = app2.getPublishingProfile();
        Git git = Git.init()
                .setDirectory(new File(
                        ManageFunctionAppSourceControl.class.getResource("/square-function-app/").getPath()))
                .call();
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Initial commit").call();
        PushCommand command = git.push();
        command.setRemote(profile.gitUrl());
        command.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
        command.setRefSpecs(new RefSpec("master:master"));
        command.setForce(true);
        command.call();

        System.out.println("Deployment to function app " + app2.name() + " completed");
        Utils.print(app2);

        // warm up
        System.out.println("Warming up " + app2Url + "/api/square...");
        post("http://" + app2Url + "/api/square", "725");
        Thread.sleep(5000);
        System.out.println("CURLing " + app2Url + "/api/square...");
        System.out.println("Square of 725 is " + post("http://" + app2Url + "/api/square", "725"));

        //============================================================
        // Create a 3rd function app with a public GitHub repo in Azure-Samples

        System.out.println("Creating another function app " + app3Name + "...");
        FunctionApp app3 = azure.appServices().functionApps().define(app3Name).withExistingAppServicePlan(plan)
                .withNewResourceGroup(rgName).withExistingStorageAccount(app2.storageAccount())
                .defineSourceControl()
                .withPublicGitRepository("https://github.com/jianghaolu/square-function-app-sample")
                .withBranch("master").attach().create();

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

        // warm up
        System.out.println("Warming up " + app3Url + "/api/square...");
        post("http://" + app3Url + "/api/square", "825");
        Thread.sleep(5000);
        System.out.println("CURLing " + app3Url + "/api/square...");
        System.out.println("Square of 825 is " + post("http://" + app3Url + "/api/square", "825"));

        //============================================================
        // Create a 4th function app with a personal GitHub repo and turn on continuous integration

        System.out.println("Creating another function app " + app4Name + "...");
        FunctionApp app4 = azure.appServices().functionApps().define(app4Name).withExistingAppServicePlan(plan)
                .withExistingResourceGroup(rgName).withExistingStorageAccount(app3.storageAccount())
                // Uncomment the following lines to turn on 4th scenario
                //.defineSourceControl()
                //    .withContinuouslyIntegratedGitHubRepository("username", "reponame")
                //    .withBranch("master")
                //    .withGitHubAccessToken("YOUR GITHUB PERSONAL TOKEN")
                //    .attach()
                .create();

        System.out.println("Created function app " + app4.name());
        Utils.print(app4);

        // warm up
        System.out.println("Warming up " + app4Url + "...");
        curl("http://" + app4Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app4Url + "...");
        System.out.println(curl("http://" + app4Url));

        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;
}

From source file:com.microsoft.azure.management.appservice.samples.ManageFunctionAppWithAuthentication.java

License:Open Source License

/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 *///from   ww  w .j  a va  2 s  .co m
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name = SdkContext.randomResourceName("webapp2-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);

    try {

        //============================================================
        // Create a function app with admin level auth

        System.out.println("Creating function app " + app1Name + " in resource group " + rgName
                + " with admin level auth...");

        FunctionApp app1 = azure.appServices().functionApps().define(app1Name).withRegion(Region.US_WEST)
                .withNewResourceGroup(rgName).withLocalGitSourceControl().create();

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

        //============================================================
        // Create a second function app with function level auth

        System.out.println("Creating another function app " + app2Name + " in resource group " + rgName
                + " with function level auth...");
        AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId());
        FunctionApp app2 = azure.appServices().functionApps().define(app2Name).withExistingAppServicePlan(plan)
                .withExistingResourceGroup(rgName).withExistingStorageAccount(app1.storageAccount())
                .withLocalGitSourceControl().create();

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

        //============================================================
        // Deploy to app 1 through Git

        System.out.println("Deploying a local function app to " + app1Name + " through Git...");

        PublishingProfile profile = app1.getPublishingProfile();
        Git git = Git.init().setDirectory(new File(ManageFunctionAppWithAuthentication.class
                .getResource("/square-function-app-admin-auth/").getPath())).call();
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Initial commit").call();
        PushCommand command = git.push();
        command.setRemote(profile.gitUrl());
        command.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
        command.setRefSpecs(new RefSpec("master:master"));
        command.setForce(true);
        command.call();

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

        // warm up
        System.out.println("Warming up " + app1Url + "/api/square...");
        post("http://" + app1Url + "/api/square", "625");
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/api/square...");
        System.out.println("Square of 625 is "
                + post("http://" + app1Url + "/api/square?code=" + app1.getMasterKey(), "625"));

        //============================================================
        // Deploy to app 2 through Git

        System.out.println("Deploying a local function app to " + app2Name + " through Git...");

        profile = app2.getPublishingProfile();
        git = Git.init().setDirectory(new File(ManageFunctionAppWithAuthentication.class
                .getResource("/square-function-app-function-auth/").getPath())).call();
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Initial commit").call();
        command = git.push();
        command.setRemote(profile.gitUrl());
        command.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
        command.setRefSpecs(new RefSpec("master:master"));
        command.setForce(true);
        command.call();

        System.out.println("Deployment to function app " + app2.name() + " completed");
        Utils.print(app2);

        String masterKey = app2.getMasterKey();
        Map<String, String> functionsHeader = new HashMap<>();
        functionsHeader.put("x-functions-key", masterKey);
        String response = curl("http://" + app2Url + "/admin/functions/square/keys", functionsHeader);
        Pattern pattern = Pattern.compile("\"name\":\"default\",\"value\":\"([\\w=/]+)\"");
        Matcher matcher = pattern.matcher(response);
        matcher.find();
        String functionKey = matcher.group(1);

        // warm up
        System.out.println("Warming up " + app2Url + "/api/square...");
        post("http://" + app2Url + "/api/square", "725");
        Thread.sleep(5000);
        System.out.println("CURLing " + app2Url + "/api/square...");
        System.out.println(
                "Square of 725 is " + post("http://" + app2Url + "/api/square?code=" + functionKey, "725"));

        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;
}