Search in sources :

Example 61 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project blueocean-plugin by jenkinsci.

the class AbstractBitbucketScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    User authenticatedUser = getAuthenticatedUser();
    StaplerRequest request = Stapler.getCurrentRequest();
    Objects.requireNonNull(request, "This request must be made in HTTP context");
    String credentialId = BitbucketCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());
    List<ErrorMessage.Error> errors = new ArrayList<>();
    StandardUsernamePasswordCredentials credential = null;
    if (credentialId == null) {
        errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "Missing credential id. It must be provided either as HTTP header: " + X_CREDENTIAL_ID + " or as query parameter 'credentialId'"));
    } else {
        credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        if (credential == null) {
            errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), String.format("credentialId: %s not found in user %s's credential store", credentialId, authenticatedUser.getId())));
        }
    }
    String apiUrl = request.getParameter("apiUrl");
    if (StringUtils.isBlank(apiUrl)) {
        errors.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "apiUrl is required parameter"));
    }
    if (!errors.isEmpty()) {
        throw new ServiceException.BadRequestException(new ErrorMessage(400, "Failed to return Bitbucket organizations").addAll(errors));
    } else {
        apiUrl = normalizeApiUrl(apiUrl);
        BitbucketApiFactory apiFactory = BitbucketApiFactory.resolve(this.getId());
        if (apiFactory == null) {
            throw new ServiceException.UnexpectedErrorException("BitbucketApiFactory to handle apiUrl " + apiUrl + " not found");
        }
        Objects.requireNonNull(credential);
        final BitbucketApi api = apiFactory.create(apiUrl, credential);
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                return new BitbucketOrg(api.getOrg(name), api, getLink());
            }

            @Override
            public Link getLink() {
                return AbstractBitbucketScm.this.getLink().rel("organizations");
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return iterator(0, 100);
            }

            @Override
            public Iterator<ScmOrganization> iterator(int start, int limit) {
                if (limit <= 0) {
                    limit = PagedResponse.DEFAULT_LIMIT;
                }
                if (start < 0) {
                    start = 0;
                }
                int page = (start / limit) + 1;
                return api.getOrgs(page, limit).getValues().stream().map(input -> {
                    if (input != null) {
                        return (ScmOrganization) new BitbucketOrg(input, api, getLink());
                    }
                    return null;
                }).iterator();
            }
        };
    }
}
Also used : BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) StringUtils(org.apache.commons.lang.StringUtils) URL(java.net.URL) PagedResponse(io.jenkins.blueocean.rest.pageable.PagedResponse) StaplerRequest(org.kohsuke.stapler.StaplerRequest) ArrayList(java.util.ArrayList) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Container(io.jenkins.blueocean.rest.model.Container) User(hudson.model.User) CredentialsScope(com.cloudbees.plugins.credentials.CredentialsScope) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) Nonnull(javax.annotation.Nonnull) Restricted(org.kohsuke.accmod.Restricted) Iterator(java.util.Iterator) HttpResponse(org.kohsuke.stapler.HttpResponse) MalformedURLException(java.net.MalformedURLException) Reachable(io.jenkins.blueocean.rest.Reachable) NoExternalUse(org.kohsuke.accmod.restrictions.NoExternalUse) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JsonBody(io.jenkins.blueocean.commons.stapler.JsonBody) Objects(java.util.Objects) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) List(java.util.List) Stapler(org.kohsuke.stapler.Stapler) BitbucketEndpointConfiguration(com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration) JSONObject(net.sf.json.JSONObject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) AbstractScm(io.jenkins.blueocean.rest.impl.pipeline.scm.AbstractScm) Collections(java.util.Collections) Link(io.jenkins.blueocean.rest.hal.Link) User(hudson.model.User) StaplerRequest(org.kohsuke.stapler.StaplerRequest) ArrayList(java.util.ArrayList) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) Container(io.jenkins.blueocean.rest.model.Container) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage)

Example 62 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project blueocean-plugin by jenkinsci.

the class AbstractBitbucketScm method getStaplerRequest.

protected StaplerRequest getStaplerRequest() {
    StaplerRequest request = Stapler.getCurrentRequest();
    Objects.requireNonNull(request, "Must be called in HTTP request context");
    return request;
}
Also used : StaplerRequest(org.kohsuke.stapler.StaplerRequest)

Example 63 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest 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 64 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project blueocean-plugin by jenkinsci.

the class MultibranchPipelineRunContainer method iterator.

/**
 * Fetches maximum up to  MAX_MBP_RUNS_ROWS rows from each branch and does pagination on that.
 *
 * JVM property MAX_MBP_RUNS_ROWS can be used to tune this value to optimize performance for given setup
 */
@Override
public Iterator<BlueRun> iterator(int start, int limit) {
    List<BlueRun> c = new ArrayList<>();
    List<BluePipeline> branches;
    // Check for branch filter
    StaplerRequest req = Stapler.getCurrentRequest();
    String branchFilter = null;
    if (req != null) {
        branchFilter = req.getParameter("branch");
    }
    if (!StringUtils.isEmpty(branchFilter)) {
        BluePipeline pipeline = blueMbPipeline.getBranches().get(branchFilter);
        if (pipeline != null) {
            branches = Collections.singletonList(pipeline);
        } else {
            branches = Collections.emptyList();
        }
    } else {
        branches = StreamSupport.stream(blueMbPipeline.getBranches().spliterator(), false).collect(Collectors.toList());
        sortBranchesByLatestRun(branches);
    }
    for (final BluePipeline b : branches) {
        BlueRunContainer blueRunContainer = b.getRuns();
        if (blueRunContainer == null) {
            continue;
        }
        Iterator<BlueRun> it = blueRunContainer.iterator(0, MAX_MBP_RUNS_ROWS);
        int count = 0;
        Utils.skip(it, start);
        while (it.hasNext() && count++ < limit) {
            c.add(it.next());
        }
    }
    c.sort(LATEST_RUN_START_TIME_COMPARATOR);
    return c.stream().limit(limit).iterator();
}
Also used : BlueRun(io.jenkins.blueocean.rest.model.BlueRun) ArrayList(java.util.ArrayList) StaplerRequest(org.kohsuke.stapler.StaplerRequest) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) BlueRunContainer(io.jenkins.blueocean.rest.model.BlueRunContainer)

Example 65 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project blueocean-plugin by jenkinsci.

the class GithubMockBase method mockStapler.

protected StaplerRequest mockStapler() {
    mockStatic(Stapler.class);
    StaplerRequest staplerRequest = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(staplerRequest);
    when(staplerRequest.getRequestURI()).thenReturn("http://localhost:8080/jenkins/blue/rest/");
    when(staplerRequest.getParameter("path")).thenReturn("Jenkinsfile");
    when(staplerRequest.getParameter("repo")).thenReturn("PR-demo");
    return staplerRequest;
}
Also used : StaplerRequest(org.kohsuke.stapler.StaplerRequest)

Aggregations

StaplerRequest (org.kohsuke.stapler.StaplerRequest)79 Test (org.junit.Test)45 MultiBranchProject (jenkins.branch.MultiBranchProject)28 JSONObject (net.sf.json.JSONObject)20 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)18 ServiceException (io.jenkins.blueocean.commons.ServiceException)17 BufferedReader (java.io.BufferedReader)16 StringReader (java.io.StringReader)16 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 User (hudson.model.User)14 Mailer (hudson.tasks.Mailer)13 StaplerResponse (org.kohsuke.stapler.StaplerResponse)8 File (java.io.File)7 BitbucketScmSaveFileRequest (io.jenkins.blueocean.blueocean_bitbucket_pipeline.BitbucketScmSaveFileRequest)6 ScmFile (io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFile)5 HashMap (java.util.HashMap)5 List (java.util.List)5 Nonnull (javax.annotation.Nonnull)5 Item (hudson.model.Item)4 ArrayList (java.util.ArrayList)4