Search in sources :

Example 26 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class GithubScmTest method validateAndCreate.

protected void validateAndCreate(String accessToken) throws Exception {
    Mailer.UserProperty userProperty = mock(Mailer.UserProperty.class);
    when(userProperty.getAddress()).thenReturn("joe@example.com");
    JSONObject req = new JSONObject().element("accessToken", accessToken);
    GithubScm githubScm = new GithubScm(() -> new Link("/blue/organizations/jenkins/scm/"));
    mockCredentials("joe", accessToken, githubScm.getId(), GithubScm.DOMAIN_NAME);
    mockStatic(HttpRequest.class);
    HttpRequest httpRequestMock = mock(HttpRequest.class);
    ArgumentCaptor<String> urlStringCaptor = ArgumentCaptor.forClass(String.class);
    when(HttpRequest.get(urlStringCaptor.capture())).thenReturn(httpRequestMock);
    ArgumentCaptor<String> tokenCaptor = ArgumentCaptor.forClass(String.class);
    when(httpRequestMock.withAuthorizationToken(tokenCaptor.capture())).thenReturn(httpRequestMock);
    HttpURLConnection httpURLConnectionMock = mock(HttpURLConnection.class);
    doNothing().when(httpURLConnectionMock).connect();
    when(httpRequestMock.connect()).thenReturn(httpURLConnectionMock);
    when(httpURLConnectionMock.getHeaderField("X-OAuth-Scopes")).thenReturn("user:email,repo");
    when(httpURLConnectionMock.getResponseCode()).thenReturn(200);
    String guser = "{\n  \"login\": \"joe\",\n  \"id\": 1, \"email\": \"joe@example.com\", \"created_at\": \"2008-01-14T04:33:35Z\"}";
    mockStatic(Stapler.class);
    StaplerRequest request = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(request);
    when(HttpRequest.getInputStream(httpURLConnectionMock)).thenReturn(new ByteArrayInputStream(guser.getBytes(StandardCharsets.UTF_8)));
    githubScm.validateAndCreate(req);
    String id = githubScm.getCredentialId();
    Assert.assertEquals(githubScm.getId(), id);
    Assert.assertEquals("constructed url", "https://api.github.com/user", urlStringCaptor.getValue());
    Assert.assertEquals("access token passed to github", accessToken.trim(), tokenCaptor.getValue());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) JSONObject(net.sf.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Mailer(hudson.tasks.Mailer) Link(io.jenkins.blueocean.rest.hal.Link)

Example 27 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class GithubOrganizationFolderTest method testGithubOrgFolderCreation.

@Test
public void testGithubOrgFolderCreation() throws IOException {
    OrganizationFolder organizationFolder = j.jenkins.createProject(OrganizationFolder.class, "orgFolder1");
    BlueOrganization blueOrganization = mock(BlueOrganization.class);
    GithubOrganizationFolder githubOrganizationFolder = new GithubOrganizationFolder(blueOrganization, organizationFolder, new Link("abc"));
    githubOrganizationFolder.addRepo("repo1", new GithubOrganizationFolder.BlueRepositoryProperty() {

        @Override
        public boolean meetsIndexingCriteria() {
            return false;
        }
    });
    assertEquals("orgFolder1", githubOrganizationFolder.getName());
    assertEquals(1, githubOrganizationFolder.repos().size());
}
Also used : OrganizationFolder(jenkins.branch.OrganizationFolder) BlueOrganization(io.jenkins.blueocean.rest.model.BlueOrganization) Link(io.jenkins.blueocean.rest.hal.Link) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 28 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class DownstreamJobListener method onStarted.

@Override
public void onStarted(Run<?, ?> run, TaskListener listener) {
    for (Cause cause : run.getCauses()) {
        if (cause instanceof BuildUpstreamCause) {
            BuildUpstreamCause buildUpstreamCause = (BuildUpstreamCause) cause;
            Run triggerRun = buildUpstreamCause.getUpstreamRun();
            if (triggerRun instanceof WorkflowRun) {
                FlowExecution execution = ((WorkflowRun) triggerRun).getExecution();
                FlowNode node;
                if (execution == null) {
                    LOGGER.warning("Could not retrieve upstream FlowExecution");
                    continue;
                }
                try {
                    node = execution.getNode(buildUpstreamCause.getNodeId());
                } catch (IOException e) {
                    LOGGER.warning("Could not retrieve upstream node: " + e);
                    continue;
                }
                if (node == null) {
                    LOGGER.warning("Could not retrieve upstream node (null)");
                    continue;
                }
                // Add an action on the triggerRun node pointing to the currently executing run
                String description = run.getDescription();
                if (description == null) {
                    description = run.getFullDisplayName();
                }
                Link link = LinkResolver.resolveLink(run);
                if (link != null) {
                    try {
                        // Also add to the actual trigger node so we can find it later by step
                        node.addAction(new NodeDownstreamBuildAction(link, description));
                        node.save();
                    } catch (IOException e) {
                        LOGGER.severe("Could not persist node: " + e);
                    }
                }
            }
        }
    }
}
Also used : Cause(hudson.model.Cause) BuildUpstreamCause(org.jenkinsci.plugins.workflow.support.steps.build.BuildUpstreamCause) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) Run(hudson.model.Run) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) IOException(java.io.IOException) BuildUpstreamCause(org.jenkinsci.plugins.workflow.support.steps.build.BuildUpstreamCause) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode)

Example 29 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class BlueMessageEnricher method maybeEnrichMessage.

private void maybeEnrichMessage(@Nonnull Message message) {
    String channelName = message.getChannelName();
    if (channelName.equals(Events.JobChannel.NAME) && message instanceof JobChannelMessage) {
        JobChannelMessage jobChannelMessage = (JobChannelMessage) message;
        Item jobChannelItem = jobChannelMessage.getJobChannelItem();
        if (jobChannelItem == null) {
            return;
        }
        Link jobUrl = LinkResolver.resolveLink(jobChannelItem);
        if (jobUrl == null) {
            return;
        }
        BlueOrganization org = OrganizationFactory.getInstance().getContainingOrg(jobChannelItem);
        if (org != null) {
            message.set(EventProps.Jenkins.jenkins_org, org.getName());
        }
        jobChannelMessage.set(BlueEventProps.blueocean_job_rest_url, jobUrl.getHref());
        jobChannelMessage.set(BlueEventProps.blueocean_job_pipeline_name, AbstractPipelineImpl.getFullName(org, jobChannelItem));
        if (jobChannelItem instanceof WorkflowJob) {
            ItemGroup<? extends Item> parent = jobChannelItem.getParent();
            if (parent instanceof WorkflowMultiBranchProject) {
                String multiBranchProjectName = AbstractPipelineImpl.getFullName(org, (WorkflowMultiBranchProject) parent);
                jobChannelMessage.set(BlueEventProps.blueocean_job_pipeline_name, multiBranchProjectName);
                jobChannelMessage.set(BlueEventProps.blueocean_job_branch_name, jobChannelItem.getName());
            }
        }
        if (message.containsKey("job_run_queueId") && jobChannelItem instanceof hudson.model.Job) {
            String queueIdStr = message.get("job_run_queueId");
            if (queueIdStr == null) {
                return;
            }
            final long queueId = Long.parseLong(queueIdStr);
            Queue.Item queueItem = Jenkins.get().getQueue().getItem(queueId);
            if (queueItem == null) {
                return;
            }
            hudson.model.Job job = (hudson.model.Job) jobChannelItem;
            BlueQueueItem blueQueueItem = QueueUtil.getQueuedItem(null, queueItem, job);
            if (blueQueueItem != null) {
                jobChannelMessage.set(BlueEventProps.blueocean_queue_item_expected_build_number, Integer.toString(blueQueueItem.getExpectedBuildNumber()));
            } else {
                // If build is already running, we simply take the run id and pass it on
                if (message.get("job_run_status") != null) {
                    String buildNumberStr = message.get("jenkins_object_id");
                    if (StringUtils.isNotBlank(buildNumberStr)) {
                        jobChannelMessage.set(BlueEventProps.blueocean_queue_item_expected_build_number, message.get("jenkins_object_id"));
                    }
                }
            }
        }
    }
}
Also used : JobChannelMessage(org.jenkinsci.plugins.pubsub.JobChannelMessage) BlueOrganization(io.jenkins.blueocean.rest.model.BlueOrganization) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Item(hudson.model.Item) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) Link(io.jenkins.blueocean.rest.hal.Link)

Example 30 with Link

use of io.jenkins.blueocean.rest.hal.Link in project blueocean-plugin by jenkinsci.

the class GithubScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    StandardUsernamePasswordCredentials credential = getCredential();
    String accessToken = credential.getPassword().getPlainText();
    try {
        GitHub github = GitHubFactory.connect(accessToken, getUri());
        final Link link = getLink().rel("organizations");
        // preserve the same order that github org api returns
        Map<String, ScmOrganization> orgMap = new LinkedHashMap<>();
        for (Map.Entry<String, GHOrganization> entry : github.getMyOrganizations().entrySet()) {
            orgMap.put(entry.getKey(), new GithubOrganization(GithubScm.this, entry.getValue(), credential, link));
        }
        GHMyself user = github.getMyself();
        if (orgMap.get(user.getLogin()) == null) {
            // this is to take care of case if/when github starts reporting user login as org later on
            orgMap = new HashMap<>(orgMap);
            orgMap.put(user.getLogin(), new GithubUserOrganization(user, credential, this));
        }
        final Map<String, ScmOrganization> orgs = orgMap;
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                ScmOrganization org = orgs.get(name);
                if (org == null) {
                    throw new ServiceException.NotFoundException(String.format("GitHub organization %s not found", name));
                }
                return org;
            }

            @Override
            public Link getLink() {
                return link;
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return orgs.values().iterator();
            }
        };
    } catch (IOException e) {
        if (e instanceof HttpException) {
            HttpException ex = (HttpException) e;
            if (ex.getResponseCode() == 401) {
                throw new ServiceException.PreconditionRequired("Invalid GitHub accessToken", ex);
            } else if (ex.getResponseCode() == 403) {
                throw new ServiceException.PreconditionRequired("GitHub accessToken does not have required scopes. Expected scopes 'user:email, repo'", ex);
            }
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
    }
}
Also used : GHMyself(org.kohsuke.github.GHMyself) GitHub(org.kohsuke.github.GitHub) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) ScmServerEndpointContainer(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpointContainer) Container(io.jenkins.blueocean.rest.model.Container) ServiceException(io.jenkins.blueocean.commons.ServiceException) GHOrganization(org.kohsuke.github.GHOrganization) HttpException(org.kohsuke.github.HttpException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Link(io.jenkins.blueocean.rest.hal.Link)

Aggregations

Link (io.jenkins.blueocean.rest.hal.Link)30 Test (org.junit.Test)12 BlueRun (io.jenkins.blueocean.rest.model.BlueRun)8 Run (hudson.model.Run)7 WorkflowJob (org.jenkinsci.plugins.workflow.job.WorkflowJob)7 Reachable (io.jenkins.blueocean.rest.Reachable)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 List (java.util.List)6 BlueOrganization (io.jenkins.blueocean.rest.model.BlueOrganization)5 BluePipelineNode (io.jenkins.blueocean.rest.model.BluePipelineNode)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Optional (java.util.Optional)4 Collectors (java.util.stream.Collectors)4 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)4 Job (hudson.model.Job)3 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 BluePipelineStep (io.jenkins.blueocean.rest.model.BluePipelineStep)3 BlueQueueItem (io.jenkins.blueocean.rest.model.BlueQueueItem)3