Search in sources :

Example 16 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gocd by gocd.

the class ConfigRepository method getMergedConfig.

String getMergedConfig(String branchName, RevCommit newCommit) throws GitAPIException, IOException {
    MergeResult result = null;
    try {
        checkout(branchName);
        result = git.merge().include(newCommit).call();
    } catch (GitAPIException e) {
        LOGGER.info("[CONFIG_MERGE] Merging commit {} by user {} to branch {} at revision {} failed", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName());
        throw e;
    }
    if (!result.getMergeStatus().isSuccessful()) {
        LOGGER.info("[CONFIG_MERGE] Merging commit {} by user {} to branch {} at revision {} failed as config file has changed", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName());
        throw new ConfigFileHasChangedException();
    }
    LOGGER.info("[CONFIG_MERGE] Successfully merged commit {} by user {} to branch {}. Merge commit revision is {}", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName());
    return FileUtils.readFileToString(new File(workingDir, CRUISE_CONFIG_XML));
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ConfigFileHasChangedException(com.thoughtworks.go.config.exceptions.ConfigFileHasChangedException) File(java.io.File)

Example 17 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gocd by gocd.

the class PipelineConfigServiceIntegrationTest method shouldShowThePipelineConfigErrorMessageWhenPipelineBeingCreatedFromTemplateHasErrors.

@Test
public void shouldShowThePipelineConfigErrorMessageWhenPipelineBeingCreatedFromTemplateHasErrors() throws GitAPIException {
    JobConfigs jobConfigs = new JobConfigs();
    jobConfigs.add(new JobConfig(new CaseInsensitiveString("Job")));
    StageConfig stage = new StageConfig(new CaseInsensitiveString("Stage-1"), jobConfigs);
    final PipelineTemplateConfig templateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("foo"), stage);
    goConfigDao.updateConfig(new UpdateConfigCommand() {

        @Override
        public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception {
            cruiseConfig.addTemplate(templateConfig);
            return cruiseConfig;
        }
    });
    PipelineConfig pipeline = GoConfigMother.createPipelineConfigWithMaterialConfig();
    pipeline.templatize(templateConfig.name());
    DependencyMaterialConfig material = new DependencyMaterialConfig(new CaseInsensitiveString("Invalid-pipeline"), new CaseInsensitiveString("Stage"));
    pipeline.addMaterialConfig(material);
    pipelineConfigService.createPipelineConfig(user, pipeline, result, groupName);
    assertThat(result.toString(), result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(422));
    assertThat(material.errors().firstError(), is(String.format("Pipeline with name 'Invalid-pipeline' does not exist, it is defined as a dependency for pipeline 'pipeline' (cruise-config.xml)", pipeline.name())));
}
Also used : DependencyMaterialConfig(com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig) ExpectedException(org.junit.rules.ExpectedException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException)

Example 18 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException 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 19 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gerrit by GerritCodeReview.

the class GetArchive method apply.

@Override
public BinaryResult apply(RevisionResource rsrc) throws BadRequestException, IOException, MethodNotAllowedException {
    if (Strings.isNullOrEmpty(format)) {
        throw new BadRequestException("format is not specified");
    }
    final ArchiveFormat f = allowedFormats.extensions.get("." + format);
    if (f == null) {
        throw new BadRequestException("unknown archive format");
    }
    if (f == ArchiveFormat.ZIP) {
        throw new MethodNotAllowedException("zip format is disabled");
    }
    boolean close = true;
    final Repository repo = repoManager.openRepository(rsrc.getControl().getProject().getNameKey());
    try {
        final RevCommit commit;
        String name;
        try (RevWalk rw = new RevWalk(repo)) {
            commit = rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
            name = name(f, rw, commit);
        }
        BinaryResult bin = new BinaryResult() {

            @Override
            public void writeTo(OutputStream out) throws IOException {
                try {
                    new ArchiveCommand(repo).setFormat(f.name()).setTree(commit.getTree()).setOutputStream(out).call();
                } catch (GitAPIException e) {
                    throw new IOException(e);
                }
            }

            @Override
            public void close() throws IOException {
                repo.close();
            }
        };
        bin.disableGzip().setContentType(f.getMimeType()).setAttachmentName(name);
        close = false;
        return bin;
    } finally {
        if (close) {
            repo.close();
        }
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ArchiveCommand(org.eclipse.jgit.api.ArchiveCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Repository(org.eclipse.jgit.lib.Repository) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult)

Example 20 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gerrit by GerritCodeReview.

the class CreateTag method apply.

@Override
public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException, PermissionBackendException {
    if (input == null) {
        input = new TagInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    ref = RefUtil.normalizeTagRef(ref);
    RefControl refControl = resource.getControl().controlForRef(ref);
    PermissionBackend.ForRef perm = permissionBackend.user(identifiedUser).project(resource.getNameKey()).ref(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated && !refControl.canPerform(Permission.CREATE_TAG)) {
            throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
        } else {
            perm.check(RefPermission.CREATE);
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }
        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())).setAnnotated(isAnnotated).setSigned(isSigned);
            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
            }
            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), identifiedUser.get().getAccount());
            try (RevWalk w = new RevWalk(repo)) {
                return ListTags.createTagInfo(perm, result, w);
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision");
    } catch (GitAPIException e) {
        log.error("Cannot create tag \"" + ref + "\"", e);
        throw new IOException(e);
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) TagInput(com.google.gerrit.extensions.api.projects.TagInput) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidRevisionException(com.google.gerrit.server.project.RefUtil.InvalidRevisionException)

Aggregations

GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)49 IOException (java.io.IOException)23 GitException (org.eclipse.che.api.git.exception.GitException)18 Git (org.eclipse.jgit.api.Git)18 File (java.io.File)14 RevCommit (org.eclipse.jgit.revwalk.RevCommit)12 ArrayList (java.util.ArrayList)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 Ref (org.eclipse.jgit.lib.Ref)10 Repository (org.eclipse.jgit.lib.Repository)9 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)8 RevWalk (org.eclipse.jgit.revwalk.RevWalk)7 RefSpec (org.eclipse.jgit.transport.RefSpec)7 PushResult (org.eclipse.jgit.transport.PushResult)6 HashMap (java.util.HashMap)5 DiffCommitFile (org.eclipse.che.api.git.shared.DiffCommitFile)5 CheckoutConflictException (org.eclipse.jgit.api.errors.CheckoutConflictException)5 GitUser (org.eclipse.che.api.git.shared.GitUser)4 AddCommand (org.eclipse.jgit.api.AddCommand)4 CloneCommand (org.eclipse.jgit.api.CloneCommand)4