Search in sources :

Example 71 with StaplerRequest

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

the class ApiHead method getDynamic.

/**
 * Exposes all {@link ApiRoutable}s to URL space.
 *
 * @param route current URL route handled by ApiHead
 * @return {@link ApiRoutable} object
 */
public ApiRoutable getDynamic(String route) {
    setApis();
    StaplerRequest request = Stapler.getCurrentRequest();
    String m = request.getMethod();
    if (m.equalsIgnoreCase("POST") || m.equalsIgnoreCase("PUT") || m.equalsIgnoreCase("PATCH")) {
        String header = request.getHeader("Content-Type");
        if (header == null || !header.contains("application/json")) {
            throw new ServiceException(415, "Content-Type: application/json required");
        }
    }
    ApiRoutable apiRoutable = apis.get(route);
    // JENKINS-46025 - Avoid caching REST API responses for IE
    StaplerResponse response = Stapler.getCurrentResponse();
    if (response != null && !response.containsHeader("Cache-Control")) {
        response.setHeader("Cache-Control", "no-cache, no-store, no-transform");
    }
    return apiRoutable;
}
Also used : ServiceException(io.jenkins.blueocean.commons.ServiceException) StaplerRequest(org.kohsuke.stapler.StaplerRequest) StaplerResponse(org.kohsuke.stapler.StaplerResponse)

Example 72 with StaplerRequest

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

the class GithubScmContentProviderTest method saveContentToMbpGHE.

@Test
public void saveContentToMbpGHE() throws UnirestException, IOException {
    String credentialId = createGithubEnterpriseCredential();
    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);
    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n").branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();
    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));
    MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME);
    String request = "{\n" + "  \"content\" : {\n" + "    \"message\" : \"first commit\",\n" + "    \"path\" : \"Jenkinsfile\",\n" + "    \"branch\" : \"test1\",\n" + "    \"repo\" : \"PR-demo\",\n" + "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" + "    \"base64Data\" : " + "\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\"" + "  }\n" + "}";
    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    GithubFile file = (GithubFile) new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", file.getContent().getName());
    assertEquals("e23b8ef5c2c4244889bf94db6c05cc08ea138aef", file.getContent().getSha());
    assertEquals("PR-demo", file.getContent().getRepo());
    assertEquals("cloudbeers", file.getContent().getOwner());
}
Also used : JSONObject(net.sf.json.JSONObject) StaplerRequest(org.kohsuke.stapler.StaplerRequest) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) MultiBranchProject(jenkins.branch.MultiBranchProject) GitContent(io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent) Test(org.junit.Test)

Example 73 with StaplerRequest

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

the class GithubScmContentProviderTest method unauthorizedAccessToContentForOrgFolderShouldFail.

@Test
public void unauthorizedAccessToContentForOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    String aliceCredentialId = createGithubCredential(alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);
    try {
        // Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
Also used : User(hudson.model.User) ServiceException(io.jenkins.blueocean.commons.ServiceException) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Mailer(hudson.tasks.Mailer) MultiBranchProject(jenkins.branch.MultiBranchProject) Test(org.junit.Test)

Example 74 with StaplerRequest

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

the class BlueUrlTokenizer method parseCurrentRequest.

/**
 * Parse the {@link Stapler#getCurrentRequest() current Stapler request} and return a {@link BlueUrlTokenizer} instance
 * iff the URL is a Blue Ocean UI URL.
 *
 * @return A {@link BlueUrlTokenizer} instance iff the URL is a Blue Ocean UI URL, otherwise {@code null}.
 * @throws IllegalStateException Called outside the scope of an active {@link StaplerRequest}.
 */
@CheckForNull
public static BlueUrlTokenizer parseCurrentRequest() throws IllegalStateException {
    StaplerRequest currentRequest = Stapler.getCurrentRequest();
    if (currentRequest == null) {
        throw new IllegalStateException("Illegal call to BlueoceanUrl.parseCurrentRequest outside the scope of an active StaplerRequest.");
    }
    String path = currentRequest.getOriginalRequestURI();
    String contextPath = currentRequest.getContextPath();
    path = path.substring(contextPath.length());
    return parse(path);
}
Also used : StaplerRequest(org.kohsuke.stapler.StaplerRequest) CheckForNull(javax.annotation.CheckForNull)

Example 75 with StaplerRequest

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

the class PipelineNodeImpl method restart.

public HttpResponse restart(StaplerRequest request) {
    try {
        JSONObject body = JSONObject.fromObject(IOUtils.toString(request.getReader()));
        boolean restart = body.getBoolean("restart");
        if (restart && isRestartable()) {
            LOGGER.debug("submitInputStep, restart: {}, step: {}", restart, this.getDisplayName());
            RestartDeclarativePipelineAction restartDeclarativePipelineAction = this.run.getAction(RestartDeclarativePipelineAction.class);
            Queue.Item item = restartDeclarativePipelineAction.run(this.getDisplayName());
            BluePipeline bluePipeline = BluePipelineFactory.getPipelineInstance(this.run.getParent(), this.parent);
            BlueQueueItem queueItem = QueueUtil.getQueuedItem(bluePipeline.getOrganization(), item, run.getParent());
            if (queueItem != null) {
                // If the item is still queued
                return (req, rsp, node1) -> {
                    rsp.setStatus(HttpServletResponse.SC_OK);
                    rsp.getOutputStream().print(Export.toJson(queueItem.toRun()));
                };
            }
            final WorkflowRun restartRun = getRun(run.getParent(), item.getId());
            if (restartRun != null) {
                return (req, rsp, node1) -> {
                    rsp.setStatus(HttpServletResponse.SC_OK);
                    rsp.getOutputStream().print(Export.toJson(new PipelineRunImpl(restartRun, parent, bluePipeline.getOrganization())));
                };
            } else {
                // For some reason could not be added to the queue
                throw new ServiceException.UnexpectedErrorException("Run was not added to queue.");
            }
        }
    // ISE cant happen if stage not restartable or anything else :)
    } catch (Exception e) {
        LOGGER.warn("error restarting stage: " + e.getMessage(), e);
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
    return null;
}
Also used : ActionProxiesImpl(io.jenkins.blueocean.service.embedded.rest.ActionProxiesImpl) Date(java.util.Date) RestartDeclarativePipelineAction(org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction) StaplerRequest(org.kohsuke.stapler.StaplerRequest) LoggerFactory(org.slf4j.LoggerFactory) Exported(org.kohsuke.stapler.export.Exported) Export(io.jenkins.blueocean.commons.stapler.Export) HashSet(java.util.HashSet) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) AbstractRunImpl(io.jenkins.blueocean.service.embedded.rest.AbstractRunImpl) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) LogAction(org.jenkinsci.plugins.workflow.actions.LogAction) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Action(hudson.model.Action) Logger(org.slf4j.Logger) HttpResponse(org.kohsuke.stapler.HttpResponse) Collection(java.util.Collection) Reachable(io.jenkins.blueocean.rest.Reachable) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) HttpServletResponse(javax.servlet.http.HttpServletResponse) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) ServiceException(io.jenkins.blueocean.commons.ServiceException) QueueUtil(io.jenkins.blueocean.service.embedded.rest.QueueUtil) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) JSONObject(net.sf.json.JSONObject) BlueActionProxy(io.jenkins.blueocean.rest.model.BlueActionProxy) BlueInputStep(io.jenkins.blueocean.rest.model.BlueInputStep) BluePipelineStepContainer(io.jenkins.blueocean.rest.model.BluePipelineStepContainer) BluePipelineFactory(io.jenkins.blueocean.rest.factory.BluePipelineFactory) CheckForNull(javax.annotation.CheckForNull) Collections(java.util.Collections) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) ServiceException(io.jenkins.blueocean.commons.ServiceException) RestartDeclarativePipelineAction(org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction) JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem)

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