Example usage for org.eclipse.jgit.api PushCommand setRefSpecs

List of usage examples for org.eclipse.jgit.api PushCommand setRefSpecs

Introduction

In this page you can find the example usage for org.eclipse.jgit.api PushCommand setRefSpecs.

Prototype

public PushCommand setRefSpecs(List<RefSpec> specs) 

Source Link

Document

The ref specs to be used in the push operation

Usage

From source file:com.microsoft.azure.management.appservice.samples.ManageWebAppSourceControl.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  w  w .  j a v a2  s .  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 app5Name = SdkContext.randomResourceName("webapp5-", 20);
    final String app6Name = SdkContext.randomResourceName("webapp5-", 20);
    final String app7Name = SdkContext.randomResourceName("webapp7-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String app3Url = app3Name + suffix;
    final String app4Url = app4Name + suffix;
    final String app5Url = app5Name + suffix;
    final String app6Url = app6Name + suffix;
    final String app7Url = app7Name + suffix;
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    final String rg7Name = SdkContext.randomResourceName("rg7NEMV_", 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.uploadFileToWebApp(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");
        SdkContext.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");
        SdkContext.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);
        SdkContext.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)
                // 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 web app " + app4.name());
        Utils.print(app4);

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

        //============================================================
        // Create a 5th web app with the existing app service plan

        System.out.println("Creating web app " + app5Name + " in resource group " + rgName + "...");

        WebApp app5 = azure.webApps().define(app5Name).withExistingWindowsPlan(plan)
                .withExistingResourceGroup(rgName).withJavaVersion(JavaVersion.JAVA_8_NEWEST)
                .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).create();

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

        //============================================================
        // Deploy to the 5th web app through web deploy

        System.out.println("Deploying helloworld.war to " + app5Name + " through web deploy...");

        app5.deploy().withPackageUri(
                "https://github.com/Azure/azure-libraries-for-java/raw/master/azure-samples/src/main/resources/helloworld.zip")
                .withExistingDeploymentsDeleted(true).execute();

        System.out.println("Deploying coffeeshop.war to " + app5Name + " through web deploy...");

        app5.deploy().withPackageUri(
                "https://github.com/Azure/azure-libraries-for-java/raw/master/azure-samples/src/main/resources/coffeeshop.zip")
                .withExistingDeploymentsDeleted(false).execute();

        System.out.println("Deployments to web app " + app5.name() + " completed");
        Utils.print(app5);

        // warm up
        System.out.println("Warming up " + app5Url + "/helloworld...");
        curl("http://" + app5Url + "/helloworld");
        SdkContext.sleep(5000);
        System.out.println("CURLing " + app5Url + "/helloworld...");
        System.out.println(curl("http://" + app5Url + "/helloworld"));
        System.out.println("CURLing " + app5Url + "/coffeeshop...");
        System.out.println(curl("http://" + app5Url + "/coffeeshop"));

        //============================================================
        // Create a 6th web app with the existing app service plan

        System.out.println("Creating web app " + app6Name + " in resource group " + rgName + "...");

        WebApp app6 = azure.webApps().define(app6Name).withExistingWindowsPlan(plan)
                .withExistingResourceGroup(rgName).withJavaVersion(JavaVersion.JAVA_8_NEWEST)
                .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).create();

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

        //============================================================
        // Deploy to the 6th web app through WAR deploy

        System.out.println("Deploying helloworld.war to " + app6Name + " through WAR deploy...");

        app6.update().withAppSetting("SCM_TARGET_PATH", "webapps/helloworld").apply();
        app6.warDeploy(new File(ManageWebAppSourceControl.class.getResource("/helloworld.war").getPath()));

        System.out.println("Deploying coffeeshop.war to " + app6Name + " through WAR deploy...");

        app6.update().withAppSetting("SCM_TARGET_PATH", "webapps/coffeeshop").apply();
        app6.restart();
        app6.warDeploy(new File(ManageWebAppSourceControl.class.getResource("/coffeeshop.war").getPath()));

        System.out.println("Deployments to web app " + app6.name() + " completed");
        Utils.print(app6);

        // warm up
        System.out.println("Warming up " + app6Url + "/helloworld...");
        curl("http://" + app6Url + "/helloworld");
        SdkContext.sleep(5000);
        System.out.println("CURLing " + app6Url + "/helloworld...");
        System.out.println(curl("http://" + app6Url + "/helloworld"));
        System.out.println("CURLing " + app6Url + "/coffeeshop...");
        System.out.println(curl("http://" + app6Url + "/coffeeshop"));

        //============================================================
        // Create a 7th web app with the existing app service plan

        System.out.println("Creating web app " + app7Name + " in resource group " + rgName + "...");

        WebApp app7 = azure.webApps().define(app7Name).withRegion(Region.US_WEST).withNewResourceGroup(rg7Name)
                .withNewLinuxPlan(PricingTier.STANDARD_S2).withBuiltInImage(RuntimeStack.JAVA_8_JRE8)
                .withAppSetting("JAVA_OPTS", "-Djava.security.egd=file:/dev/./urandom").create();

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

        //============================================================
        // Deploy to the 7th web app through ZIP deploy

        System.out.println("Deploying app.zip to " + app7Name + " through ZIP deploy...");

        for (int i = 0; i < 5; i++) {
            try {
                app7.zipDeploy(new File(ManageWebAppSourceControl.class.getResource("/app.zip").getPath()));
                break;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Deployments to web app " + app7.name() + " completed");
        Utils.print(app7);

        // warm up
        System.out.println("Warming up " + app7Url);
        curl("http://" + app7Url);
        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);
            azure.resourceGroups().beginDeleteByName(rg7Name);
            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.ManageWebAppSourceControlAsync.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 av  a 2 s  .c  o  m*/
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.uploadFileToWebApp(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)
                                        // Uncomment the following lines to turn on 4th scenario
                                        //.defineSourceControl()
                                        //    .withContinuouslyIntegratedGitHubRepository("username", "reponame")
                                        //    .withBranch("master")
                                        //    .withGitHubAccessToken("YOUR GITHUB PERSONAL TOKEN")
                                        //    .attach()
                                        .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;
}

From source file:com.mortardata.project.TestEmbeddedMortarProject.java

License:Apache License

@Test
public void testSetupGitMirror() throws IOException, GitAPIException {
    Git gitSpy = spy(this.git);

    PushCommand pushMock = mock(PushCommand.class);
    when(gitSpy.push()).thenReturn(pushMock);
    when(pushMock.setRemote(anyString())).thenReturn(pushMock);
    when(pushMock.setCredentialsProvider(any(CredentialsProvider.class))).thenReturn(pushMock);
    when(pushMock.setRefSpecs(any(RefSpec.class))).thenReturn(pushMock);

    String commiter = "fake_committer";
    EmbeddedMortarProject e = new EmbeddedMortarProject(this.rootPath, this.remoteURLHttps);
    e.setupGitMirror(gitSpy, this.fakeCP, commiter);

    // ensure that we pushed to the remote URL
    verify(pushMock).setRemote(this.remoteURLHttps);
    verify(pushMock).call();//from w  w w . j a va  2 s  .c  o  m

    // ensure that the mirror exists with a .gitkeep
    Assert.assertTrue(new File(this.mirrorPath, ".gitkeep").exists());

    // ensure that the mirror is at master
    Assert.assertEquals("master", this.git.getRepository().getBranch());
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

@Override
public boolean push(String sourceBranch, String destinationBranch) {

    PushCommand command = _git.push();
    boolean ret = true;
    RefSpec refSpec = new RefSpec().setSourceDestination(sourceBranch, destinationBranch);
    command.setRefSpecs(refSpec);
    try {//from w w  w  .  j  a va 2  s .com
        List<Ref> remoteBranches = _git.branchList().setListMode(ListMode.REMOTE).call();
        Iterable<PushResult> results = command.call();
        for (PushResult pushResult : results) {
            Collection<RemoteRefUpdate> resultsCollection = pushResult.getRemoteUpdates();
            Map<PushResult, RemoteRefUpdate> resultsMap = new HashMap<>();
            for (RemoteRefUpdate remoteRefUpdate : resultsCollection) {
                resultsMap.put(pushResult, remoteRefUpdate);
            }

            RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate(destinationBranch);
            if (remoteUpdate != null) {
                org.eclipse.jgit.transport.RemoteRefUpdate.Status status = remoteUpdate.getStatus();
                ret = status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
                        || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE);
            }

            if (remoteUpdate == null && !remoteBranches.toString().contains(destinationBranch)) {

                for (RemoteRefUpdate resultValue : resultsMap.values()) {
                    if (resultValue.toString().contains("REJECTED_OTHER_REASON")) {
                        ret = false;
                    }
                }
            }
        }
    } catch (Throwable e) {
        throw new RuntimeException(
                String.format("Failed to push [%s] into [%s]", sourceBranch, destinationBranch), e);
    }

    return ret;
}

From source file:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

void gitPush(String o, String d) throws MojoExecutionException {
    try {/*from  w w  w.  jav  a 2s .  c  o  m*/
        RefSpec spec = new RefSpec(d + ":" + d);
        PushCommand ff = git.push();
        ff.setRemote(o);
        ff.setRefSpecs(spec);
        ff.setPushTags();
        Iterable<PushResult> f = ff.call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PushResponse push(PushRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
            ConfigConstants.CONFIG_KEY_URL);
    PushResponse pushResponseDto = newDto(PushResponse.class);
    try {//from   ww  w.j av  a2 s .c  o m
        PushCommand pushCommand = getGit().push();

        if (request.getRemote() != null) {
            pushCommand.setRemote(remoteName);
        }
        List<String> refSpec = request.getRefSpec();
        if (!refSpec.isEmpty()) {
            List<RefSpec> refSpecInst = new ArrayList<>(refSpec.size());
            refSpecInst.addAll(refSpec.stream().map(RefSpec::new).collect(Collectors.toList()));
            pushCommand.setRefSpecs(refSpecInst);
        }

        pushCommand.setForce(request.isForce());

        int timeout = request.getTimeout();
        if (timeout > 0) {
            pushCommand.setTimeout(timeout);
        }

        @SuppressWarnings("unchecked")
        Iterable<PushResult> pushResults = (Iterable<PushResult>) executeRemoteCommand(remoteUri, pushCommand);
        PushResult pushResult = pushResults.iterator().next();
        return addCommandOutputUpdates(pushResponseDto, request, pushResult);
    } catch (GitAPIException exception) {
        if ("origin: not found.".equals(exception.getMessage())) {
            throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
        } else {
            throw new GitException(exception.getMessage(), exception);
        }
    }
}

From source file:org.eclipse.orion.server.filesystem.git.GitFileStore.java

License:Open Source License

private void push() throws CoreException {
    try {/*from   w ww  .ja v  a  2s  .com*/
        Repository local = getLocalRepo();
        Git git = new Git(local);

        PushCommand push = git.push();
        push.setRefSpecs(new RefSpec("refs/heads/*:refs/heads/*"));
        push.setCredentialsProvider(getCredentialsProvider());

        Iterable<PushResult> pushResults = push.call();

        for (PushResult pushResult : pushResults) {
            Collection<RemoteRefUpdate> updates = pushResult.getRemoteUpdates();
            for (RemoteRefUpdate update : updates) {
                org.eclipse.jgit.transport.RemoteRefUpdate.Status status = update.getStatus();
                if (status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
                        || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE)) {
                    LogHelper.log(new Status(IStatus.INFO, Activator.PI_GIT, 1, "Push succeed: " + this, null));
                } else {
                    throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR,
                            status.toString(), null));
                }
            }
        }
    } catch (Exception e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, e.getMessage(), e));
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public void commit(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException {
    try {/*from  w w w  . j av a 2 s  .co  m*/
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Commit", 100);
        Git git = new Git(repository);
        // AddCommand addCommand = git.add();
        List<String> changedFiles = addNewFiles(git, subMon.newChild(30));
        if (!changedFiles.isEmpty()) {
            checkCanceled(subMon);
            CommitCommand commit = git.commit();
            Preferences node = PreferencesUtil.scopeFor(project.getParent());
            String username = node.get(GitConstants.KEY_USERNAME, "Jabylon");
            String email = node.get(GitConstants.KEY_EMAIL, "jabylon@example.org");
            String message = node.get(GitConstants.KEY_MESSAGE, "Auto Sync-up by Jabylon");
            boolean insertChangeId = node.getBoolean(GitConstants.KEY_INSERT_CHANGE_ID, false);
            commit.setAuthor(username, email);
            commit.setCommitter(username, email);
            commit.setInsertChangeId(insertChangeId);
            commit.setMessage(message);
            for (String path : changedFiles) {
                checkCanceled(subMon);
                commit.setOnly(path);

            }
            commit.call();
            subMon.worked(10);
        } else {
            LOGGER.info("No changed files, skipping commit phase");
        }
        checkCanceled(subMon);
        PushCommand push = git.push();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            push.setRemote(stripUserInfo(uri).toString());
        push.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(60)));
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            push.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        push.setCredentialsProvider(createCredentialsProvider(project.getParent()));

        RefSpec spec = createRefSpec(project);
        push.setRefSpecs(spec);

        Iterable<PushResult> result = push.call();
        for (PushResult r : result) {
            for (RemoteRefUpdate rru : r.getRemoteUpdates()) {
                if (rru.getStatus() != RemoteRefUpdate.Status.OK
                        && rru.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE) {
                    String error = "Push failed: " + rru.getStatus();
                    LOGGER.error(error);
                    throw new TeamProviderException(error);
                }
            }
        }

        Ref ref = repository.getRef(project.getName());
        if (ref != null) {
            LOGGER.info("Successfully pushed {} to {}", ref.getObjectId(),
                    project.getParent().getRepositoryURI());
        }
    } catch (NoHeadException e) {
        throw new TeamProviderException(e);
    } catch (NoMessageException e) {
        throw new TeamProviderException(e);
    } catch (ConcurrentRefUpdateException e) {
        throw new TeamProviderException(e);
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (WrongRepositoryStateException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

From source file:org.ms123.common.git.GitServiceImpl.java

License:Open Source License

public void push(@PName("name") String name) throws RpcException {
    try {/*from w  w  w.java2s.  com*/
        String gitSpace = System.getProperty("git.repos");
        File dir = new File(gitSpace, name);
        if (!dir.exists()) {
            throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.push:Repo(" + name + ") not exists");
        }
        Git git = Git.open(dir);
        PushCommand push = git.push();
        push.setRefSpecs(new RefSpec(REF_PREFIX + "master")).setRemote("origin");
        //ic.setPushAll(true);
        Iterable<PushResult> result = null;
        try {
            result = push.call();
        } catch (org.eclipse.jgit.api.errors.TransportException e) {
            if (e.getCause() instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
                info("Push:" + e.getCause().getMessage());
                return;
            } else {
                throw e;
            }
        }
        for (PushResult pushResult : result) {
            if (StringUtils.isNotBlank(pushResult.getMessages())) {
                debug(pushResult.getMessages());
            }
        }
        return;
    } catch (Exception e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.push:", e);
    } finally {
    }
}