public void execute(StaplerResponse response) { if (build != null) { try { response.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getUrl()); } catch (IOException e) { try { response.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl()); } catch (IOException e1) { throw HttpResponses.error(500, "Failed to redirect to build page"); } } } } }
@RequirePOST public HttpResponse doDelete() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); file.delete(); owner.files.remove(this); return HttpResponses.redirectTo("../.."); } }
@RequirePOST public HttpResponse doRename(@AncestorInPath User u, @QueryParameter String tokenUuid, @QueryParameter String newName) throws IOException { // only current user + administrator can rename token u.checkPermission(Jenkins.ADMINISTER); if (StringUtils.isBlank(newName)) { return HttpResponses.errorJSON("The name cannot be empty"); } if(StringUtils.isBlank(tokenUuid)){ // using the web UI this should not occur return HttpResponses.errorWithoutStack(400, "The tokenUuid cannot be empty"); } ApiTokenProperty p = u.getProperty(ApiTokenProperty.class); if (p == null) { return HttpResponses.errorWithoutStack(400, "The user does not have any ApiToken yet, try generating one before."); } boolean renameOk = p.tokenStore.renameToken(tokenUuid, newName); if(!renameOk){ // that could potentially happen if the token is removed from another page // between your page loaded and your action return HttpResponses.errorJSON("No token found, try refreshing the page"); } u.save(); return HttpResponses.ok(); }
/** * Called to determine if there was an incomplete installation, what the statuses of the plugins are */ @Restricted(DoNotUse.class) // WebOnly public HttpResponse doIncompleteInstallStatus() { try { Map<String,String> jobs = InstallUtil.getPersistedInstallStatus(); if(jobs == null) { jobs = Collections.emptyMap(); } return HttpResponses.okJSON(jobs); } catch (Exception e) { return HttpResponses.errorJSON(String.format("ERROR: %s", e.getMessage())); } }
@RequirePOST public HttpResponse doScan(StaplerRequest req) throws IOException, GeneralSecurityException { if(req.hasParameter("background")) { start(false); } else if(req.hasParameter("schedule")) { scanOnBoot.on(); } else if(req.hasParameter("dismiss")) { disable(true); } else throw HttpResponses.error(400,"Invalid request submission: " + req.getParameterMap()); return HttpResponses.redirectViaContextPath("/manage"); }
void execute() { if (!(project instanceof Job<?, ?>)) { throw HttpResponses.errorWithoutStack(409, "Pipeline Hook is not supported for this project"); } ACL.impersonate(ACL.SYSTEM, new TriggerNotifier(project, secretToken, Jenkins.getAuthentication()) { @Override protected void performOnPost(GitLabPushTrigger trigger) { trigger.onPost(pipelineBuildHook); } }); throw HttpResponses.ok(); }
@SuppressWarnings("unused") @RequirePOST public HttpResponse doValidateJenkinsfile(StaplerRequest req) { Jenkins.getInstance().checkPermission(Jenkins.READ); JSONObject result = new JSONObject(); String groovyAsString = req.getParameter("jenkinsfile"); if (!StringUtils.isEmpty(groovyAsString)) { try { ModelASTPipelineDef pipelineDef = Converter.scriptToPipelineDef(groovyAsString); if (pipelineDef != null) { result.accumulate("result", "success"); } else { reportFailure(result, "Jenkinsfile content '" + groovyAsString + "' did not contain the 'pipeline' step"); } } catch (Exception e) { reportFailure(result, e); } } else { reportFailure(result, "No content found for 'jenkinsfile' parameter"); } return HttpResponses.okJSON(result); }
/** * Updates the credentials. * * @param req the request. * @return the response. * @throws ServletException if something goes wrong. * @throws IOException if something goes wrong. */ @RequirePOST @Restricted(NoExternalUse.class) @SuppressWarnings("unused") // stapler web method public HttpResponse doUpdateSubmit(StaplerRequest req) throws ServletException, IOException { getStore().checkPermission(UPDATE); JSONObject data = req.getSubmittedForm(); Credentials credentials = req.bindJSON(Credentials.class, data); if (!getStore().updateCredentials(this.domain.domain, this.credentials, credentials)) { return HttpResponses.redirectTo("concurrentModification"); } return HttpResponses.redirectToDot(); }
/** * Approves specific callables by their names. */ @RequirePOST public HttpResponse doApprove(@QueryParameter String value) throws IOException { whitelisted.append(value); return HttpResponses.ok(); }
@Restricted(DoNotUse.class) public HttpResponse doInstallStatus(StaplerRequest request) { try { String correlationId = request.getParameter("correlationId"); Map<String,Object> response = new HashMap<>(); response.put("state", Jenkins.getInstance().getInstallState().name()); List<Map<String, String>> installStates = new ArrayList<>(); response.put("jobs", installStates); return HttpResponses.okJSON(JSONObject.fromObject(response)); } catch (Exception e) { return HttpResponses.errorJSON(String.format("ERROR: %s", e.getMessage()));
/** * Installs a list of plugins from a JSON POST. * @param req The request object. * @return A JSON response that includes a "correlationId" in the "data" element. * That "correlationId" can then be used in calls to * {@link UpdateCenter#doInstallStatus(org.kohsuke.stapler.StaplerRequest)}. * @throws IOException Error reading JSON payload fro request. */ @RequirePOST @Restricted(DoNotUse.class) // WebOnly public HttpResponse doInstallPlugins(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String payload = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); JSONObject request = JSONObject.fromObject(payload); JSONArray pluginListJSON = request.getJSONArray("plugins"); List<String> plugins = new ArrayList<>(); for (int i = 0; i < pluginListJSON.size(); i++) { plugins.add(pluginListJSON.getString(i)); } UUID correlationId = UUID.randomUUID(); try { boolean dynamicLoad = request.getBoolean("dynamicLoad"); install(plugins, dynamicLoad, correlationId); JSONObject responseData = new JSONObject(); responseData.put("correlationId", correlationId.toString()); return hudson.util.HttpResponses.okJSON(responseData); } catch (Exception e) { return hudson.util.HttpResponses.errorJSON(e.getMessage()); } }
@RequirePOST @Restricted(NoExternalUse.class) public HttpResponse doCreateAdminUser(StaplerRequest req, StaplerResponse rsp) throws IOException { Jenkins j = Jenkins.getInstance(); j.checkPermission(Jenkins.ADMINISTER); HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) j.getSecurityRealm(); Authentication auth = new UsernamePasswordAuthenticationToken(newUser.getId(), req.getParameter("password1")); auth = securityRealm.getSecurityComponents().manager.authenticate(auth); SecurityContextHolder.getContext().setAuthentication(auth); HttpSession session = req.getSession(false); if (session != null) { HttpSession newSession = req.getSession(true); data.accumulate("crumbRequestField", crumbIssuer.getCrumbRequestField()).accumulate("crumb", crumbIssuer.getCrumb(req)); return HttpResponses.okJSON(data); } catch (AccountCreationFailedException e) { return HttpResponses.forwardToView(securityRealm, "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly"); } finally { if (admin != null) {
/** * Redirects the user to the plugin manager or security configuration */ @RequirePOST public HttpResponse doForward(@QueryParameter String fix, @QueryParameter String configure) { if (fix != null) { return HttpResponses.redirectViaContextPath("pluginManager"); } if (configure != null) { return HttpResponses.redirectViaContextPath("configureSecurity"); } // shouldn't happen return HttpResponses.redirectViaContextPath("/"); }
@RequirePOST @Restricted(NoExternalUse.class) public HttpResponse doConfigureInstance(StaplerRequest req, @QueryParameter String rootUrl) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); Map<String, String> errors = new HashMap<>(); // pre-check data checkRootUrl(errors, rootUrl); if(!errors.isEmpty()){ return HttpResponses.errorJSON(Messages.SetupWizard_ConfigureInstance_ValidationErrors(), errors); } // use the parameters to configure the instance useRootUrl(errors, rootUrl); if(!errors.isEmpty()){ return HttpResponses.errorJSON(Messages.SetupWizard_ConfigureInstance_ValidationErrors(), errors); } InstallUtil.proceedToNextStateFrom(InstallState.CONFIGURE_INSTANCE); CrumbIssuer crumbIssuer = Jenkins.get().getCrumbIssuer(); JSONObject data = new JSONObject(); if (crumbIssuer != null) { data.accumulate("crumbRequestField", crumbIssuer.getCrumbRequestField()).accumulate("crumb", crumbIssuer.getCrumb(req)); } return HttpResponses.okJSON(data); }
/** * Invalidates the cached data and force retrieval. * * @since 1.432 */ @RequirePOST public HttpResponse doInvalidateData() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); dataTimestamp = 0; data = null; return HttpResponses.ok(); }
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException { checkPermission(PROVISION); if (template == null) { throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing"); } SlaveTemplate t = getTemplate(template); if (t == null) { throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template); } try { List<EC2AbstractSlave> nodes = getNewOrExistingAvailableSlave(t, 1, true); if (nodes == null || nodes.isEmpty()) throw HttpResponses.error(SC_BAD_REQUEST, "Cloud or AMI instance cap would be exceeded for: " + template); //Reconnect a stopped instance, the ADD is invoking the connect only for the node creation Computer c = nodes.get(0).toComputer(); if (nodes.get(0).getStopOnTerminate() && c != null) { c.connect(false); } Jenkins.getInstance().addNode(nodes.get(0)); return HttpResponses.redirectViaContextPath("/computer/" + nodes.get(0).getNodeName()); } catch (AmazonClientException e) { throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e); } }
@Restricted(DoNotUse.class) // WebOnly public HttpResponse doPlugins() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray response = new JSONArray(); Map<String,JSONObject> allPlugins = new HashMap<>(); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { for (UpdateSite.Plugin plugin: site.getAvailables()) { JSONObject pluginInfo = allPlugins.get(plugin.name); return hudson.util.HttpResponses.okJSON(response);
@RequirePOST public HttpResponse doCreateAdminUser(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins j = Jenkins.getInstance(); j.checkPermission(Jenkins.ADMINISTER); HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm)j.getSecurityRealm(); Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = securityRealm.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); data.accumulate("crumbRequestField", crumbIssuer.getCrumbRequestField()).accumulate("crumb", crumbIssuer.getCrumb(req)); return HttpResponses.okJSON(data); } else { return HttpResponses.okJSON();
@SuppressWarnings("unused") @RequirePOST public HttpResponse doValidate(StaplerRequest req) { Jenkins.getInstance().checkPermission(Jenkins.READ); List<String> output = new ArrayList<>(); String groovyAsString = req.getParameter("jenkinsfile"); if (groovyAsString != null) { try { if (Converter.scriptToPipelineDef(groovyAsString) != null) { output.add("Jenkinsfile successfully validated."); } else { output.add("Jenkinsfile content '" + groovyAsString + "' did not contain the 'pipeline' step"); } } catch (Exception e) { output.add("Errors encountered validating Jenkinsfile:"); output.addAll(ModelConverterAction.errorToStrings(e)); } } else { output.add("No Jenkinsfile specified"); } return HttpResponses.plainText(StringUtils.join(output, "\n")); }
/** * Deletes a domain. * * @param req the request. * @return the response. * @throws IOException if something goes wrong. */ @RequirePOST @Restricted(NoExternalUse.class) @SuppressWarnings("unused") // stapler web method public HttpResponse doDoDelete(StaplerRequest req) throws IOException { if (!getStore().isDomainsModifiable()) { return HttpResponses.status(400); } getStore().checkPermission(MANAGE_DOMAINS); if (getStore().removeDomain(domain)) { return HttpResponses.redirectTo("../.."); } return HttpResponses.redirectToDot(); }