Search in sources :

Example 1 with HttpResponse

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

the class GitScm method validateAndCreate.

@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    boolean requirePush = request.has("requirePush");
    // --[ Grab repo url and SCMSource ]----------------------------------------------------------
    final String repositoryUrl;
    final AbstractGitSCMSource scmSource;
    if (request.has("repositoryUrl")) {
        repositoryUrl = request.getString("repositoryUrl");
        scmSource = new GitSCMSource(repositoryUrl);
    } else {
        try {
            String fullName = request.getJSONObject("pipeline").getString("fullName");
            SCMSourceOwner item = Jenkins.get().getItemByFullName(fullName, SCMSourceOwner.class);
            if (item != null) {
                scmSource = (AbstractGitSCMSource) item.getSCMSources().iterator().next();
                repositoryUrl = scmSource.getRemote();
            } else {
                return HttpResponses.errorJSON("No repository found for: " + fullName);
            }
        } catch (JSONException e) {
            return HttpResponses.errorJSON("No repositoryUrl or pipeline.fullName specified in request.");
        } catch (RuntimeException e) {
            return HttpResponses.errorWithoutStack(ServiceException.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    // --[ Grab user ]-------------------------------------------------------------------------------------
    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }
    // --[ Get credential id from request or create from repo url ]----------------------------------------
    String credentialId = null;
    if (request.has("credentialId")) {
        credentialId = request.getString("credentialId");
    }
    if (credentialId == null) {
        credentialId = makeCredentialId(repositoryUrl);
    }
    if (credentialId == null) {
        // Still null? Must be a bad repoURL
        throw new ServiceException.BadRequestException("Invalid URL \"" + repositoryUrl + "\"");
    }
    // Create new is only for username + password
    if (request.has("userName") || request.has("password")) {
        createPWCredentials(credentialId, user, request, repositoryUrl);
    }
    final StandardCredentials creds = CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.get(), Jenkins.getAuthentication(), (List<DomainRequirement>) null), CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId)));
    if (creds == null) {
        throw new ServiceException.NotFoundException("No credentials found for: " + credentialId);
    }
    try {
        if (requirePush) {
            String branch = request.getString("branch");
            if (repositoryUrl != null) {
                ((GitSCMSource) scmSource).setCredentialsId(credentialId);
            }
            new GitBareRepoReadSaveRequest(scmSource, branch, null, branch, null, null).invokeOnScm((GitSCMFileSystem.FSFunction<Void>) repository -> {
                GitUtils.validatePushAccess(repository, repositoryUrl, creds);
                return null;
            });
        } else {
            List<ErrorMessage.Error> errors = GitUtils.validateCredentials(repositoryUrl, creds);
            if (!errors.isEmpty()) {
                throw new ServiceException.UnauthorizedException(errors.get(0).getMessage());
            }
        }
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null && message.contains("TransportException")) {
            throw new ServiceException.PreconditionRequired("Repository URL unreachable: " + repositoryUrl);
        }
        return HttpResponses.errorWithoutStack(ServiceException.PRECONDITION_REQUIRED, message);
    }
    return HttpResponses.okJSON();
}
Also used : BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) StaplerRequest(org.kohsuke.stapler.StaplerRequest) URISyntaxException(java.net.URISyntaxException) JsonBody(org.kohsuke.stapler.json.JsonBody) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) CredentialsMatchers(com.cloudbees.plugins.credentials.CredentialsMatchers) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Locale(java.util.Locale) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Extension(hudson.Extension) Container(io.jenkins.blueocean.rest.model.Container) User(hudson.model.User) URI(java.net.URI) CredentialsScope(com.cloudbees.plugins.credentials.CredentialsScope) DomainRequirement(com.cloudbees.plugins.credentials.domains.DomainRequirement) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) JSONException(net.sf.json.JSONException) GitSCMFileSystem(jenkins.plugins.git.GitSCMFileSystem) ScmServerEndpointContainer(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpointContainer) HttpResponse(org.kohsuke.stapler.HttpResponse) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) Jenkins(jenkins.model.Jenkins) Reachable(io.jenkins.blueocean.rest.Reachable) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) IOException(java.io.IOException) Scm(io.jenkins.blueocean.rest.impl.pipeline.scm.Scm) ServiceException(io.jenkins.blueocean.commons.ServiceException) HttpResponses(hudson.util.HttpResponses) ScmFactory(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFactory) Objects(java.util.Objects) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) List(java.util.List) Stapler(org.kohsuke.stapler.Stapler) CredentialsProvider(com.cloudbees.plugins.credentials.CredentialsProvider) DigestUtils(io.jenkins.blueocean.commons.DigestUtils) 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) GitSCMSource(jenkins.plugins.git.GitSCMSource) User(hudson.model.User) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) GitSCMFileSystem(jenkins.plugins.git.GitSCMFileSystem) JSONException(net.sf.json.JSONException) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) GitSCMSource(jenkins.plugins.git.GitSCMSource) URISyntaxException(java.net.URISyntaxException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) ServiceException(io.jenkins.blueocean.commons.ServiceException) List(java.util.List) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials)

Example 2 with HttpResponse

use of org.kohsuke.stapler.HttpResponse 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)

Example 3 with HttpResponse

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

the class PipelineStepImpl method submitInputStep.

@Override
public HttpResponse submitInputStep(StaplerRequest request) {
    JSONObject body;
    try {
        body = JSONObject.fromObject(IOUtils.toString(request.getReader()));
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
    String id = body.getString(ID_ELEMENT);
    if (id == null) {
        throw new ServiceException.BadRequestException("id is required");
    }
    if (body.get(PARAMETERS_ELEMENT) == null && body.get(ABORT_ELEMENT) == null) {
        throw new ServiceException.BadRequestException("parameters is required");
    }
    WorkflowRun run = node.getRun();
    InputAction inputAction = run.getAction(InputAction.class);
    if (inputAction == null) {
        throw new ServiceException.BadRequestException("Error processing Input Submit request. This Run instance does not" + " have an InputAction.");
    }
    try {
        InputStepExecution execution = inputAction.getExecution(id);
        if (execution == null) {
            throw new ServiceException.BadRequestException(String.format("Error processing Input Submit request. This Run instance does not" + " have an Input with an id of '%s'.", id));
        }
        // if abort, abort and return
        if (body.get(ABORT_ELEMENT) != null && body.getBoolean(ABORT_ELEMENT)) {
            return execution.doAbort();
        }
        try {
            execution.preSubmissionCheck();
        } catch (Failure f) {
            throw new ServiceException.BadRequestException(f.getMessage());
        }
        Object o = parseValue(execution, JSONArray.fromObject(body.get(PARAMETERS_ELEMENT)), request);
        HttpResponse response = execution.proceed(o);
        for (PipelineInputStepListener listener : ExtensionList.lookup(PipelineInputStepListener.class)) {
            listener.onStepContinue(execution.getInput(), run);
        }
        return response;
    } catch (IOException | InterruptedException | TimeoutException e) {
        throw new ServiceException.UnexpectedErrorException("Error processing Input Submit request." + e.getMessage());
    }
}
Also used : InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) HttpResponse(org.kohsuke.stapler.HttpResponse) IOException(java.io.IOException) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) InputStepExecution(org.jenkinsci.plugins.workflow.support.steps.input.InputStepExecution) JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) JSONObject(net.sf.json.JSONObject) Failure(hudson.model.Failure) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

ServiceException (io.jenkins.blueocean.commons.ServiceException)3 JSONObject (net.sf.json.JSONObject)3 HttpResponse (org.kohsuke.stapler.HttpResponse)3 Reachable (io.jenkins.blueocean.rest.Reachable)2 Link (io.jenkins.blueocean.rest.hal.Link)2 IOException (java.io.IOException)2 Collections (java.util.Collections)2 List (java.util.List)2 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)2 StaplerRequest (org.kohsuke.stapler.StaplerRequest)2 CredentialsMatchers (com.cloudbees.plugins.credentials.CredentialsMatchers)1 CredentialsProvider (com.cloudbees.plugins.credentials.CredentialsProvider)1 CredentialsScope (com.cloudbees.plugins.credentials.CredentialsScope)1 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)1 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)1 DomainRequirement (com.cloudbees.plugins.credentials.domains.DomainRequirement)1 UsernamePasswordCredentialsImpl (com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl)1 NonNull (edu.umd.cs.findbugs.annotations.NonNull)1 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 Extension (hudson.Extension)1