jenkins.scm.api.SCMEvent Java Examples

The following examples show how to use jenkins.scm.api.SCMEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FreeStyleMultiBranchProjectTest.java    From multi-branch-project-plugin with MIT License 6 votes vote down vote up
@Test
@Ignore("Currently failing to honour contract of multi-branch projects with respect to dead branches")
public void given_multibranchWithSources_when_accessingDeadBranch_then_branchCannotBeBuilt() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        FreeStyleMultiBranchProject prj = r.jenkins.createProject(FreeStyleMultiBranchProject.class, "foo");
        prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false)));
        prj.scheduleBuild2(0).getFuture().get();
        r.waitUntilNoActivity();
        assertThat("We now have branches",
                prj.getItems(), not(is((Collection<FreeStyleProject>) Collections.<FreeStyleProject>emptyList())));
        FreeStyleProject master = prj.getItem("master");
        assertThat("We now have the master branch", master, notNullValue());
        r.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assumeThat(master.isBuildable(), is(true));
        c.deleteBranch("foo", "master");
        fire(new MockSCMHeadEvent(
                "given_multibranchWithSources_when_branchRemoved_then_branchProjectIsNotBuildable",
                SCMEvent.Type.REMOVED, c, "foo", "master", "junkHash"));
        r.waitUntilNoActivity();
        assertThat(master.isBuildable(), is(false));
    }
}
 
Example #2
Source File: SkipInitialBuildOnFirstBranchIndexingTest.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
@Test
public void if__first__branch__indexing__isAutomaticBuild__then__returns__true() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        BasicMultiBranchProject prj = j.jenkins.createProject(BasicMultiBranchProject.class, "project");
        prj.setCriteria(null);
        BranchSource source = new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches()));
        source.setBuildStrategies(Collections.<BranchBuildStrategy>singletonList(new SkipInitialBuildOnFirstBranchIndexing()));
        prj.getSourcesList().add(source);
        fire(new MockSCMHeadEvent(SCMEvent.Type.CREATED, c, "foo", "master", c.getRevision("foo", "master")));
        FreeStyleProject master = prj.getItem("master");
        j.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), nullValue());
        c.addFile("foo", "master", "adding file", "file", new byte[0]);
        fire(new MockSCMHeadEvent(SCMEvent.Type.UPDATED, c, "foo", "master", c.getRevision("foo", "master")));
        j.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1));
        c.addFile("foo", "master", "adding file", "file", new byte[0]);
        fire(new MockSCMHeadEvent(SCMEvent.Type.UPDATED, c, "foo", "master", c.getRevision("foo", "master")));
        j.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assertThat("The master branch was built", master.getLastBuild().getNumber(), is(2));
    }
}
 
Example #3
Source File: SkipInitialBuildOnFirstBranchIndexingTest.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
@Test
public void if__skipInitialBuildOnFirstBranchIndexing__is__disabled__first__branch__indexing__triggers__the__build() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        BasicMultiBranchProject prj = j.jenkins.createProject(BasicMultiBranchProject.class, "my-project");
        prj.setCriteria(null);
        prj.getSourcesList().add(new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches())));
        fire(new MockSCMHeadEvent(SCMEvent.Type.CREATED, c, "foo", "master", c.getRevision("foo", "master")));
        FreeStyleProject master = prj.getItem("master");
        j.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1));
        c.addFile("foo", "master", "adding file", "file", new byte[0]);
        fire(new MockSCMHeadEvent(SCMEvent.Type.UPDATED, c, "foo", "master", c.getRevision("foo", "master")));
        j.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assertThat("The master branch was built", master.getLastBuild().getNumber(), is(2));
    }
}
 
Example #4
Source File: GiteaWebhookHandler.java    From gitea-plugin with MIT License 6 votes vote down vote up
protected GiteaWebhookHandler(String eventName) {
    this.eventName = eventName;
    Type bt = Types.getBaseClass(getClass(), GiteaWebhookHandler.class);
    if (bt instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) bt;
        // this 'p' is the closest approximation of P of GiteadSCMEventHandler
        Class e = Types.erasure(pt.getActualTypeArguments()[0]);
        if (!SCMEvent.class.isAssignableFrom(e)) {
            throw new AssertionError(
                    "Could not determine the " + SCMEvent.class + " event class generic parameter of "
                            + getClass() + " best guess was " + e);
        }
        Class p = Types.erasure(pt.getActualTypeArguments()[1]);
        if (!GiteaEvent.class.isAssignableFrom(p)) {
            throw new AssertionError(
                    "Could not determine the " + GiteaEvent.class + " payload class generic parameter of "
                            + getClass() + " best guess was " + p);
        }
        this.eventClass = e;
        this.payloadClass = p;
    } else {
        throw new AssertionError("Type inferrence failure for subclass " + getClass()
                + " of parameterized type " + GiteaWebhookHandler.class
                + ". Use the constructor that takes the Class objects explicitly.");
    }
}
 
Example #5
Source File: FreeStyleMultiBranchProjectTest.java    From multi-branch-project-plugin with MIT License 6 votes vote down vote up
@Test
public void given_multibranchWithSources_when_accessingDeadBranch_then_branchCanBeDeleted() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        FreeStyleMultiBranchProject prj = r.jenkins.createProject(FreeStyleMultiBranchProject.class, "foo");
        prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false)));
        prj.scheduleBuild2(0).getFuture().get();
        r.waitUntilNoActivity();
        assertThat("We now have branches",
                prj.getItems(), not(is((Collection<FreeStyleProject>) Collections.<FreeStyleProject>emptyList())));
        FreeStyleProject master = prj.getItem("master");
        assertThat("We now have the master branch", master, notNullValue());
        r.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assumeThat(master.getACL().hasPermission(ACL.SYSTEM, Item.DELETE), is(false));
        c.deleteBranch("foo", "master");
        fire(new MockSCMHeadEvent(
                "given_multibranchWithSources_when_branchRemoved_then_branchProjectIsNotBuildable",
                SCMEvent.Type.REMOVED, c, "foo", "master", "junkHash"));
        r.waitUntilNoActivity();
        assertThat(master.getACL().hasPermission(ACL.SYSTEM, Item.DELETE), is(true));
    }
}
 
Example #6
Source File: FreeStyleMultiBranchProjectTest.java    From multi-branch-project-plugin with MIT License 6 votes vote down vote up
@Test
public void given_multibranchWithSources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        FreeStyleMultiBranchProject prj = r.jenkins.createProject(FreeStyleMultiBranchProject.class, "foo");
        prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false)));
        fire(new MockSCMHeadEvent("given_multibranchWithSources_when_matchingEvent_then_branchesAreFoundAndBuilt", SCMEvent.Type.UPDATED, c, "foo", "master", "junkHash"));
        assertThat("We now have branches",
                prj.getItems(), not(is((Collection<FreeStyleProject>) Collections.<FreeStyleProject>emptyList())));
        FreeStyleProject master = prj.getItem("master");
        assertThat("We now have the master branch", master, notNullValue());
        r.waitUntilNoActivity();
        assertThat("The master branch was built", master.getLastBuild(), notNullValue());
        assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1));
    }
}
 
Example #7
Source File: GHMultiBranchSubscriber.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
protected void onEvent(GHSubscriberEvent event) {
    try {
        BranchInfo ref = extractRefInfo(event.getGHEvent(), event.getPayload(), true);

        if (ref.isTag()) {
            SCMHeadEvent.fireNow(new GitHubTagSCMHeadEvent(
                    SCMEvent.Type.UPDATED,
                    event.getTimestamp(),
                    ref,
                    ref.getRepo())
            );
        } else {
            SCMHeadEvent.fireNow(new GitHubBranchSCMHeadEvent(
                    SCMEvent.Type.UPDATED,
                    event.getTimestamp(),
                    ref,
                    ref.getRepo())
            );
        }

    } catch (Exception e) {
        LOGGER.error("Can't process {} hook", event, e);
    }
}
 
Example #8
Source File: GHPRMultiBranchSubscriber.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
protected void onEvent(GHSubscriberEvent event) {
    try {
        GitHub gh = GitHub.offline();

        PullRequestInfo ref = extractPullRequestInfo(event.getGHEvent(), event.getPayload(), gh);
        SCMHeadEvent.fireNow(new GitHubPullRequestScmHeadEvent(
                SCMEvent.Type.UPDATED,
                event.getTimestamp(),
                ref,
                ref.getRepo())
        );

    } catch (Exception e) {
        LOG.error("Can't process {} hook", event, e);
    }
}
 
Example #9
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPushEventUpdated_then_updatedHeadEventFired() throws Exception {
    PushGHEventSubscriber subscriber = new PushGHEventSubscriber();

    firedEventType = SCMEvent.Type.UPDATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pushEventUpdated.json");
    waitAndAssertReceived(true);
}
 
Example #10
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghRepositoryEventCreatedFromFork_then_createdSourceEventFired() throws Exception {
    GitHubRepositoryEventSubscriber subscriber = new GitHubRepositoryEventSubscriber();

    firedEventType = SCMEvent.Type.CREATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/repositoryEventCreated.json");
    waitAndAssertReceived(true);
}
 
Example #11
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPullRequestEventSync_then_updatedHeadEventFired() throws Exception {
    PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber();

    firedEventType = SCMEvent.Type.UPDATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pullRequestEventUpdatedSync.json");
    waitAndAssertReceived(true);
}
 
Example #12
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPullRequestEventReopened_then_updatedHeadEventFired() throws Exception {
    PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber();

    firedEventType = SCMEvent.Type.UPDATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pullRequestEventUpdated.json");
    waitAndAssertReceived(true);
}
 
Example #13
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPullRequestEventClosed_then_removedHeadEventFired() throws Exception {
    PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber();

    firedEventType = SCMEvent.Type.REMOVED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pullRequestEventRemoved.json");
    waitAndAssertReceived(true);
}
 
Example #14
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPullRequestEventOpened_then_createdHeadEventFired() throws Exception {
    PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber();

    firedEventType = SCMEvent.Type.CREATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pullRequestEventCreated.json");
    waitAndAssertReceived(true);
}
 
Example #15
Source File: GitLabWebHookAction.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
public HttpResponse doPost(StaplerRequest request) throws IOException, GitLabApiException {
    if (!request.getMethod().equals("POST")) {
        return HttpResponses
            .error(HttpServletResponse.SC_BAD_REQUEST,
                "Only POST requests are supported, this was a " + request.getMethod()
                    + " request");
    }
    if (!"application/json".equals(request.getContentType())) {
        return HttpResponses
            .error(HttpServletResponse.SC_BAD_REQUEST,
                "Only application/json content is supported, this was " + request
                    .getContentType());
    }
    String type = request.getHeader("X-Gitlab-Event");
    if (StringUtils.isBlank(type)) {
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
            "Expecting a GitLab event, missing expected X-Gitlab-Event header");
    }
    String secretToken = request.getHeader("X-Gitlab-Token");
    if(!isValidToken(secretToken)) {
        return HttpResponses.error(HttpServletResponse.SC_UNAUTHORIZED,
            "Expecting a valid secret token");
    }
    String origin = SCMEvent.originOf(request);
    WebHookManager webHookManager = new WebHookManager();
    webHookManager.addListener(new GitLabWebHookListener(origin));
    webHookManager.handleEvent(request);
    return HttpResponses.ok(); // TODO find a better response
}
 
Example #16
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPushEventDeleted_then_removedHeadEventFired() throws Exception {
    PushGHEventSubscriber subscriber = new PushGHEventSubscriber();

    firedEventType = SCMEvent.Type.REMOVED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pushEventRemoved.json");
    waitAndAssertReceived(true);
}
 
Example #17
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void given_ghPushEventCreated_then_createdHeadEventFired() throws Exception {
    PushGHEventSubscriber subscriber = new PushGHEventSubscriber();

    firedEventType = SCMEvent.Type.CREATED;
    ghEvent = callOnEvent(subscriber, "EventsTest/pushEventCreated.json");
    waitAndAssertReceived(true);
}
 
Example #18
Source File: GiteaWebhookHandler.java    From gitea-plugin with MIT License 5 votes vote down vote up
public GiteaWebhookHandler() {
    Type bt = Types.getBaseClass(getClass(), GiteaWebhookHandler.class);
    if (bt instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) bt;
        // this 'p' is the closest approximation of P of GiteadSCMEventHandler
        Class e = Types.erasure(pt.getActualTypeArguments()[0]);
        if (!SCMEvent.class.isAssignableFrom(e)) {
            throw new AssertionError(
                    "Could not determine the " + SCMEvent.class + " event class generic parameter of "
                            + getClass() + " best guess was " + e);
        }
        Class p = Types.erasure(pt.getActualTypeArguments()[1]);
        if (!GiteaEvent.class.isAssignableFrom(p)) {
            throw new AssertionError(
                    "Could not determine the " + GiteaEvent.class + " payload class generic parameter of "
                            + getClass() + " best guess was " + p);
        }
        this.eventClass = e;
        this.payloadClass = p;
    } else {
        throw new AssertionError("Type inferrence failure for subclass " + getClass()
                + " of parameterized type " + GiteaWebhookHandler.class
                + ". Use the constructor that takes the Class objects explicitly.");
    }
    Matcher eventNameMatcher =
            Pattern.compile("^\\QGitea\\E([A-Z][a-z_]*)\\QSCM\\E(Head|Source|Navigator)?\\QEvent\\E$")
                    .matcher(eventClass.getSimpleName());
    if (eventNameMatcher.matches()) {
        this.eventName = eventNameMatcher.group(1).toLowerCase(Locale.ENGLISH);
    } else {
        throw new AssertionError("Could not infer event name from " + eventClass
                + " as it does not follow the convention Gitea[Name]SCMEvent. Use the constructor that specifies "
                + "the event name explicitly");
    }
}
 
Example #19
Source File: GitLabSystemHookAction.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
public HttpResponse doPost(StaplerRequest request) throws GitLabApiException {
    if (!request.getMethod().equals("POST")) {
        return HttpResponses
            .error(HttpServletResponse.SC_BAD_REQUEST,
                "Only POST requests are supported, this was a " + request.getMethod()
                    + " request");
    }
    if (!"application/json".equals(request.getContentType())) {
        return HttpResponses
            .error(HttpServletResponse.SC_BAD_REQUEST,
                "Only application/json content is supported, this was " + request
                    .getContentType());
    }
    String type = request.getHeader("X-Gitlab-Event");
    if (StringUtils.isBlank(type)) {
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
            "Expecting a GitLab event, missing expected X-Gitlab-Event header");
    }
    String secretToken = request.getHeader("X-Gitlab-Token");
    if(!isValidToken(secretToken)) {
        return HttpResponses.error(HttpServletResponse.SC_UNAUTHORIZED,
            "Expecting a valid secret token");
    }
    String origin = SCMEvent.originOf(request);
    SystemHookManager systemHookManager = new SystemHookManager();
    systemHookManager.addListener(new GitLabSystemHookListener(origin));
    systemHookManager.handleEvent(request);
    return HttpResponses.ok(); // TODO find a better response
}
 
Example #20
Source File: EventsTest.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
private void receiveEvent(SCMEvent.Type type, String origin) {
    eventReceived = true;

    assertEquals("Event type should be the same", type, firedEventType);
    assertEquals("Event origin should be the same", origin, ghEvent.getOrigin());
}
 
Example #21
Source File: PullRequestGHEventSubscriber.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
@Override
protected void onEvent(GHSubscriberEvent event) {
    try {
        final GHEventPayload.PullRequest p = GitHub.offline()
                .parseEventPayload(new StringReader(event.getPayload()), GHEventPayload.PullRequest.class);
        String action = p.getAction();
        String repoUrl = p.getRepository().getHtmlUrl().toExternalForm();
        LOGGER.log(Level.FINE, "Received {0} for {1} from {2}",
                new Object[]{event.getGHEvent(), repoUrl, event.getOrigin()}
        );
        Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl);
        if (matcher.matches()) {
            final GitHubRepositoryName changedRepository = GitHubRepositoryName.create(repoUrl);
            if (changedRepository == null) {
                LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl);
                return;
            }

            if ("opened".equals(action)) {
                fireAfterDelay(new SCMHeadEventImpl(
                        SCMEvent.Type.CREATED,
                        event.getTimestamp(),
                        p,
                        changedRepository,
                        event.getOrigin()
                ));
            } else if ("reopened".equals(action) || "synchronize".equals(action) || "edited".equals(action)) {
                fireAfterDelay(new SCMHeadEventImpl(
                        SCMEvent.Type.UPDATED,
                        event.getTimestamp(),
                        p,
                        changedRepository,
                        event.getOrigin()
                ));
            } else if ("closed".equals(action)) {
                fireAfterDelay(new SCMHeadEventImpl(
                        SCMEvent.Type.REMOVED,
                        event.getTimestamp(),
                        p,
                        changedRepository,
                        event.getOrigin()
                ));
            }
        }

    } catch (IOException e) {
        LogRecord lr = new LogRecord(Level.WARNING, "Could not parse {0} event from {1} with payload: {2}");
        lr.setParameters(new Object[]{event.getGHEvent(), event.getOrigin(), event.getPayload()});
        lr.setThrown(e);
        LOGGER.log(lr);
    }
}
 
Example #22
Source File: AbstractScmSourceEvent.java    From blueocean-plugin with MIT License 4 votes vote down vote up
public AbstractScmSourceEvent(String repoName, String origin) {
    super(SCMEvent.Type.CREATED, new Object(), origin);
    this.repoName = repoName;
}
 
Example #23
Source File: GiteaWebhookAction.java    From gitea-plugin with MIT License 4 votes vote down vote up
public HttpResponse doPost(StaplerRequest request) throws IOException {
    String origin = SCMEvent.originOf(request);
    if (!request.getMethod().equals("POST")) {
        LOGGER.log(Level.FINE, "Received {0} request (expecting POST) from {1}",
                new Object[]{request.getMethod(), origin});
        return HttpResponses
                .error(HttpServletResponse.SC_BAD_REQUEST,
                        "Only POST requests are supported, this was a " + request.getMethod() + " request");
    }
    if (!"application/json".equals(request.getContentType())) {
        LOGGER.log(Level.FINE, "Received {0} body (expecting application/json) from {1}",
                new Object[]{request.getContentType(), origin});
        return HttpResponses
                .error(HttpServletResponse.SC_BAD_REQUEST,
                        "Only application/json content is supported, this was " + request.getContentType());
    }
    String type = request.getHeader("X-Gitea-Event");
    if (StringUtils.isBlank(type)) {
        LOGGER.log(Level.FINE, "Received request without X-Gitea-Event header from {1}",
                new Object[]{request.getContentType(), origin});
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
                "Expecting a Gitea event, missing expected X-Gitea-Event header");
    }
    LOGGER.log(Level.FINER, "Received {0} event from {1}", new Object[]{
            request.getContentType(), origin
    });
    boolean processed = false;
    for (GiteaWebhookHandler<?, ?> h : ExtensionList.lookup(GiteaWebhookHandler.class)) {
        if (h.matches(type)) {
            LOGGER.log(Level.FINER, "Processing {0} event from {1} with {2}",
                    new Object[]{type, origin, h});
            h.process(request.getInputStream(), origin);
            processed = true;
        }
    }
    if (!processed) {
        LOGGER.log(Level.INFO, "Received hook payload with unknown type: {0} from {1}",
                new Object[]{type, origin});
    }
    return HttpResponses.text(processed ? "Processed" : "Ignored");
}