Search in sources :

Example 6 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project gitblit by gitblit.

the class JGitUtils method repairFetchSpecs.

/**
	 * Automatic repair of (some) invalid refspecs.  These are the result of a
	 * bug in JGit cloning where a double forward-slash was injected.  :(
	 *
	 * @param repository
	 * @return true, if the refspecs were repaired
	 */
public static boolean repairFetchSpecs(Repository repository) {
    StoredConfig rc = repository.getConfig();
    // auto-repair broken fetch ref specs
    for (String name : rc.getSubsections("remote")) {
        int invalidSpecs = 0;
        int repairedSpecs = 0;
        List<String> specs = new ArrayList<String>();
        for (String spec : rc.getStringList("remote", name, "fetch")) {
            try {
                RefSpec rs = new RefSpec(spec);
                // valid spec
                specs.add(spec);
            } catch (IllegalArgumentException e) {
                // invalid spec
                invalidSpecs++;
                if (spec.contains("//")) {
                    // auto-repair this known spec bug
                    spec = spec.replace("//", "/");
                    specs.add(spec);
                    repairedSpecs++;
                }
            }
        }
        if (invalidSpecs == repairedSpecs && repairedSpecs > 0) {
            // the fetch specs were automatically repaired
            rc.setStringList("remote", name, "fetch", specs);
            try {
                rc.save();
                rc.load();
                LOGGER.debug("repaired {} invalid fetch refspecs for {}", repairedSpecs, repository.getDirectory());
                return true;
            } catch (Exception e) {
                LOGGER.error(null, e);
            }
        } else if (invalidSpecs > 0) {
            LOGGER.error("mirror executor found {} invalid fetch refspecs for {}", invalidSpecs, repository.getDirectory());
        }
    }
    return false;
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) RefSpec(org.eclipse.jgit.transport.RefSpec) ArrayList(java.util.ArrayList) RevisionSyntaxException(org.eclipse.jgit.errors.RevisionSyntaxException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) GitBlitException(com.gitblit.GitBlitException) AmbiguousObjectException(org.eclipse.jgit.errors.AmbiguousObjectException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) IOException(java.io.IOException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) StopWalkException(org.eclipse.jgit.errors.StopWalkException)

Example 7 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project gitblit by gitblit.

the class GitServletTest method testRefChange.

private void testRefChange(AccessPermission permission, Status expectedCreate, Status expectedDelete, Status expectedRewind) throws Exception {
    final String originName = "ticgit.git";
    final String forkName = "refchecks/ticgit.git";
    final String workingCopy = "refchecks/ticgit-wc";
    // lower access restriction on origin repository
    RepositoryModel origin = repositories().getRepositoryModel(originName);
    origin.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(origin.name, origin, false);
    UserModel user = getUser();
    delete(user);
    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);
    // fork from original to a temporary bare repo
    File refChecks = new File(GitBlitSuite.REPOSITORIES, forkName);
    if (refChecks.exists()) {
        FileUtils.delete(refChecks, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(url + "/" + originName);
    clone.setDirectory(refChecks);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());
    // elevate repository to clone permission
    RepositoryModel model = repositories().getRepositoryModel(forkName);
    switch(permission) {
        case VIEW:
            model.accessRestriction = AccessRestrictionType.CLONE;
            break;
        case CLONE:
            model.accessRestriction = AccessRestrictionType.CLONE;
            break;
        default:
            model.accessRestriction = AccessRestrictionType.PUSH;
    }
    model.authorizationControl = AuthorizationControl.NAMED;
    // grant user specified
    user.setRepositoryPermission(model.name, permission);
    gitblit().addUser(user);
    repositories().updateRepositoryModel(model.name, model, false);
    // clone temp bare repo to working copy
    File local = new File(GitBlitSuite.REPOSITORIES, workingCopy);
    if (local.exists()) {
        FileUtils.delete(local, FileUtils.RECURSIVE);
    }
    clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, model.name));
    clone.setDirectory(local);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    try {
        GitBlitSuite.close(clone.call());
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.CLONE)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);
            // user does not have clone permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            return;
        }
    }
    Git git = Git.open(local);
    // commit a file and push it
    File file = new File(local, "PUSHCHK");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("push test").call();
    Iterable<PushResult> results = null;
    try {
        results = git.push().setCredentialsProvider(cp).setRemote("origin").call();
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.PUSH)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);
            // user does not have push permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            GitBlitSuite.close(git);
            return;
        }
    }
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (permission.atLeast(AccessPermission.PUSH)) {
            assertTrue("User failed to push commit?! " + status.name(), Status.OK.equals(status));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);
            assertTrue("User was able to push commit! " + status.name(), Status.REJECTED_OTHER_REASON.equals(status));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }
    // create a local branch and push the new branch back to the origin
    git.branchCreate().setName("protectme").call();
    RefSpec refSpec = new RefSpec("refs/heads/protectme:refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedCreate)) {
            assertTrue("User failed to push creation?! " + status.name(), status.equals(expectedCreate));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);
            assertTrue("User was able to push ref creation! " + status.name(), status.equals(expectedCreate));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }
    // delete the branch locally
    git.branchDelete().setBranchNames("protectme").call();
    // push a delete ref command
    refSpec = new RefSpec(":refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedDelete)) {
            assertTrue("User failed to push ref deletion?! " + status.name(), status.equals(Status.OK));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);
            assertTrue("User was able to push ref deletion?! " + status.name(), status.equals(expectedDelete));
            GitBlitSuite.close(git);
            // skip rewind test
            return;
        }
    }
    // rewind master by two commits
    git.reset().setRef("HEAD~2").setMode(ResetType.HARD).call();
    // commit a change on this detached HEAD
    file = new File(local, "REWINDCHK");
    os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    RevCommit commit = git.commit().setMessage("rewind master and new commit").call();
    // Reset master to our new commit now we our local branch tip is no longer
    // upstream of the remote branch tip.  It is an alternate tip of the branch.
    JGitUtils.setBranchRef(git.getRepository(), "refs/heads/master", commit.getName());
    // Try pushing our new tip to the origin.
    // This requires the server to "rewind" it's master branch and update it
    // to point to our alternate tip.  This leaves the original master tip
    // unreferenced.
    results = git.push().setCredentialsProvider(cp).setRemote("origin").setForce(true).call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedRewind)) {
            assertTrue("User failed to rewind master?! " + status.name(), status.equals(expectedRewind));
        } else {
            assertTrue("User was able to rewind master?! " + status.name(), status.equals(expectedRewind));
        }
    }
    GitBlitSuite.close(git);
    // close serving repository
    GitBlitSuite.close(refChecks);
    delete(user);
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) Status(org.eclipse.jgit.transport.RemoteRefUpdate.Status) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) RepositoryModel(com.gitblit.models.RepositoryModel) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) PushResult(org.eclipse.jgit.transport.PushResult) Date(java.util.Date) BufferedWriter(java.io.BufferedWriter) UserModel(com.gitblit.models.UserModel) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 8 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project azure-sdk-for-java by Azure.

the class ManageWebAppSourceControl 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) {
    // 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 web app with a new app service plan
        System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
        WebApp app1 = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withNewWindowsPlan(PricingTier.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...");
        Utils.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);
        // warm up
        System.out.println("Warming up " + app1Url + "/helloworld...");
        curl("http://" + app1Url + "/helloworld");
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/helloworld...");
        System.out.println(curl("http://" + app1Url + "/helloworld"));
        //============================================================
        // Create a second web app with local git source control
        System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
        AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId());
        WebApp app2 = azure.webApps().define(app2Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).withLocalGitSourceControl().withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).create();
        System.out.println("Created web 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(ManageWebAppSourceControl.class.getResource("/azure-samples-appservice-helloworld/").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 web app " + app2.name() + " completed");
        Utils.print(app2);
        // warm up
        System.out.println("Warming up " + app2Url + "/helloworld...");
        curl("http://" + app2Url + "/helloworld");
        Thread.sleep(5000);
        System.out.println("CURLing " + app2Url + "/helloworld...");
        System.out.println(curl("http://" + app2Url + "/helloworld"));
        //============================================================
        // Create a 3rd web app with a public GitHub repo in Azure-Samples
        System.out.println("Creating another web app " + app3Name + "...");
        WebApp app3 = azure.webApps().define(app3Name).withExistingWindowsPlan(plan).withNewResourceGroup(rgName).defineSourceControl().withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started").withBranch("master").attach().create();
        System.out.println("Created web app " + app3.name());
        Utils.print(app3);
        // warm up
        System.out.println("Warming up " + app3Url + "...");
        curl("http://" + app3Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app3Url + "...");
        System.out.println(curl("http://" + app3Url));
        //============================================================
        // Create a 4th web app with a personal GitHub repo and turn on continuous integration
        System.out.println("Creating another web app " + app4Name + "...");
        WebApp app4 = azure.webApps().define(app4Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).create();
        System.out.println("Created web 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;
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) File(java.io.File) PushCommand(org.eclipse.jgit.api.PushCommand) IOException(java.io.IOException) WebApp(com.microsoft.azure.management.appservice.WebApp) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan)

Example 9 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project azure-sdk-for-java by Azure.

the class ManageWebAppSourceControlAsync 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(final 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 planName = SdkContext.randomResourceName("jplan_", 15);
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    try {
        //============================================================
        // Create a web app with a new app service plan
        System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
        Observable<?> app1Observable = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withNewWindowsPlan(PricingTier.STANDARD_S1).withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).createAsync().flatMap(new Func1<Indexable, Observable<?>>() {

            @Override
            public Observable<?> call(Indexable indexable) {
                if (indexable instanceof WebApp) {
                    WebApp app = (WebApp) indexable;
                    System.out.println("Created web app " + app.name());
                    return Observable.merge(Observable.just(indexable), app.getPublishingProfileAsync().map(new Func1<PublishingProfile, PublishingProfile>() {

                        @Override
                        public PublishingProfile call(PublishingProfile publishingProfile) {
                            System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
                            Utils.uploadFileToFtp(publishingProfile, "helloworld.war", ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
                            System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
                            return publishingProfile;
                        }
                    }));
                }
                return Observable.just(indexable);
            }
        });
        System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
        System.out.println("Creating another web app " + app3Name + "...");
        System.out.println("Creating another web app " + app4Name + "...");
        Observable<?> app234Observable = azure.appServices().appServicePlans().getByResourceGroupAsync(rgName, planName).flatMap(new Func1<AppServicePlan, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(AppServicePlan plan) {
                return Observable.merge(azure.webApps().define(app2Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).withLocalGitSourceControl().withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).createAsync(), azure.webApps().define(app3Name).withExistingWindowsPlan(plan).withNewResourceGroup(rgName).defineSourceControl().withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started").withBranch("master").attach().createAsync(), azure.webApps().define(app4Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).createAsync());
            }
        }).flatMap(new Func1<Indexable, Observable<?>>() {

            @Override
            public Observable<?> call(Indexable indexable) {
                if (indexable instanceof WebApp) {
                    WebApp app = (WebApp) indexable;
                    System.out.println("Created web app " + app.name());
                    if (!app.name().equals(app2Name)) {
                        return Observable.just(indexable);
                    }
                    // for the second web app Deploy a local Tomcat
                    return app.getPublishingProfileAsync().map(new Func1<PublishingProfile, PublishingProfile>() {

                        @Override
                        public PublishingProfile call(PublishingProfile profile) {
                            System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
                            Git git = null;
                            try {
                                git = Git.init().setDirectory(new File(ManageWebAppSourceControlAsync.class.getResource("/azure-samples-appservice-helloworld/").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();
                            } catch (GitAPIException e) {
                                e.printStackTrace();
                            }
                            System.out.println("Deployment to web app " + app2Name + " completed");
                            return profile;
                        }
                    });
                }
                return Observable.just(indexable);
            }
        });
        Observable.merge(app1Observable, app234Observable).toBlocking().subscribe();
        // warm up
        System.out.println("Warming up " + app1Url + "/helloworld...");
        curl("http://" + app1Url + "/helloworld");
        System.out.println("Warming up " + app2Url + "/helloworld...");
        curl("http://" + app2Url + "/helloworld");
        System.out.println("Warming up " + app3Url + "...");
        curl("http://" + app3Url);
        System.out.println("Warming up " + app4Url + "...");
        curl("http://" + app4Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/helloworld...");
        System.out.println(curl("http://" + app1Url + "/helloworld"));
        System.out.println("CURLing " + app2Url + "/helloworld...");
        System.out.println(curl("http://" + app2Url + "/helloworld"));
        System.out.println("CURLing " + app3Url + "...");
        System.out.println(curl("http://" + app3Url));
        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().beginDeleteByNameAsync(rgName).toBlocking().subscribe();
            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 : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Observable(rx.Observable) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) Func1(rx.functions.Func1) File(java.io.File) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 10 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project azure-sdk-for-java by Azure.

the class ManageFunctionAppWithAuthentication 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) {
    // 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;
}
Also used : Pattern(java.util.regex.Pattern) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) FunctionApp(com.microsoft.azure.management.appservice.FunctionApp) PushCommand(org.eclipse.jgit.api.PushCommand) IOException(java.io.IOException) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) File(java.io.File)

Aggregations

RefSpec (org.eclipse.jgit.transport.RefSpec)46 Test (org.junit.Test)17 RevCommit (org.eclipse.jgit.revwalk.RevCommit)15 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)12 IOException (java.io.IOException)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)9 Git (org.eclipse.jgit.api.Git)8 PushCommand (org.eclipse.jgit.api.PushCommand)8 File (java.io.File)7 PushResult (org.eclipse.jgit.transport.PushResult)7 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)6 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)5 PublishingProfile (com.microsoft.azure.management.appservice.PublishingProfile)5 ArrayList (java.util.ArrayList)5 FetchCommand (org.eclipse.jgit.api.FetchCommand)5 ChangeApi (com.google.gerrit.extensions.api.changes.ChangeApi)4 CherryPickInput (com.google.gerrit.extensions.api.changes.CherryPickInput)4 GitException (org.eclipse.che.api.git.exception.GitException)4