Java Code Examples for org.kohsuke.stapler.StaplerResponse#sendError()

The following examples show how to use org.kohsuke.stapler.StaplerResponse#sendError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TokenReloadAction.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
    String token = getReloadTokenProperty();

    if (Strings.isNullOrEmpty(token)) {
        response.sendError(404);
        LOGGER.warning("Configuration reload via token is not enabled");
    } else {
        String requestToken = getRequestToken(request);

        if (token.equals(requestToken)) {
            LOGGER.info("Configuration reload triggered via token");

            try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
                ConfigurationAsCode.get().configure();
            }
        } else {
            response.sendError(401);
            LOGGER.warning("Invalid token received, not reloading configuration");
        }
    }
}
 
Example 2
Source File: LockableResourcesRootAction.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
public void doReset(StaplerRequest req, StaplerResponse rsp)
	throws IOException, ServletException {
	Jenkins.get().checkPermission(UNLOCK);

	String name = req.getParameter("resource");
	LockableResource r = LockableResourcesManager.get().fromName(name);
	if (r == null) {
		rsp.sendError(404, "Resource not found " + name);
		return;
	}

	List<LockableResource> resources = new ArrayList<>();
	resources.add(r);
	LockableResourcesManager.get().reset(resources);

	rsp.forwardToPreviousPage(req);
}
 
Example 3
Source File: LockableResourcesRootAction.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
public void doUnreserve(StaplerRequest req, StaplerResponse rsp)
	throws IOException, ServletException {
	Jenkins.get().checkPermission(RESERVE);

	String name = req.getParameter("resource");
	LockableResource r = LockableResourcesManager.get().fromName(name);
	if (r == null) {
		rsp.sendError(404, "Resource not found " + name);
		return;
	}

	String userName = getUserName();
	if ((userName == null || !userName.equals(r.getReservedBy()))
			&& !Jenkins.get().hasPermission(Jenkins.ADMINISTER))
		throw new AccessDeniedException2(Jenkins.getAuthentication(),
				RESERVE);

	List<LockableResource> resources = new ArrayList<>();
	resources.add(r);
	LockableResourcesManager.get().unreserve(resources);

	rsp.forwardToPreviousPage(req);
}
 
Example 4
Source File: LockableResourcesRootAction.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
public void doReserve(StaplerRequest req, StaplerResponse rsp)
	throws IOException, ServletException {
	Jenkins.get().checkPermission(RESERVE);

	String name = req.getParameter("resource");
	LockableResource r = LockableResourcesManager.get().fromName(name);
	if (r == null) {
		rsp.sendError(404, "Resource not found " + name);
		return;
	}

	List<LockableResource> resources = new ArrayList<>();
	resources.add(r);
	String userName = getUserName();
	if (userName != null)
		LockableResourcesManager.get().reserve(resources, userName);

	rsp.forwardToPreviousPage(req);
}
 
Example 5
Source File: LockableResourcesRootAction.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
public void doUnlock(StaplerRequest req, StaplerResponse rsp)
		throws IOException, ServletException {
	Jenkins.get().checkPermission(UNLOCK);

	String name = req.getParameter("resource");
	LockableResource r = LockableResourcesManager.get().fromName(name);
	if (r == null) {
		rsp.sendError(404, "Resource not found " + name);
		return;
	}

	List<LockableResource> resources = new ArrayList<>();
	resources.add(r);
	LockableResourcesManager.get().unlock(resources, null);

	rsp.forwardToPreviousPage(req);
}
 
Example 6
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final Map<Source, String> issues = checkWith(YamlSource.of(req));
    res.setContentType("application/json");
    final JSONArray warnings = new JSONArray();
    issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue()))
            .forEach(warnings::add);
    warnings.write(res.getWriter());
}
 
Example 7
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Export JSONSchema to URL
 * @throws Exception
 */
@Restricted(NoExternalUse.class)
public void doSchema(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    res.setContentType("application/json; charset=utf-8");
    res.getWriter().print(writeJSONSchema());
}
 
Example 8
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    export(out);

    req.setAttribute("export", out.toString(StandardCharsets.UTF_8.name()));
    req.getView(this, "viewExport.jelly").forward(req, res);
}
 
Example 9
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public void doReference(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    req.getView(this, "reference.jelly").forward(req, res);
}
 
Example 10
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReload(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configure();
    response.sendRedirect("");
}
 
Example 11
Source File: Export.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * @param req request
 * @param rsp response
 * @param bean to serve
 * @throws IOException if cannot be written
 * @throws ServletException if something goes wrong processing the request
 */
public static void doJson(StaplerRequest req, StaplerResponse rsp, Object bean) throws IOException, ServletException {
    if (req.getParameter("jsonp") == null || permit(req, bean)) {
        rsp.setHeader("X-Jenkins", Jenkins.VERSION);
        rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH);
        ExportConfig exportConfig = createExportConfig()
                .withFlavor(req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP)
                .withPrettyPrint(req.hasParameter("pretty")).withSkipIfFail(true);
        serveExposedBean(req, rsp, bean, exportConfig);
    } else {
        rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester");
    }
}
 
Example 12
Source File: ClosureExecuterAction.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public void doIndex(StaplerResponse rsp, @QueryParameter("uuid") String uuid) throws IOException {
    Runnable r = runnables.remove(UUID.fromString(uuid));
    if (r!=null) {
        r.run();
    } else {
        rsp.sendError(404);
    }
}
 
Example 13
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Gets a container {@link Fingerprint} page.
 * @param req Stapler request
 * @param rsp Stapler response
 * @param id Container ID. Method supports full 64-char IDs only.
 * @throws IOException Request processing error
 * @throws ServletException Servlet error
 */
public void doContainer(StaplerRequest req, StaplerResponse rsp, 
        @QueryParameter(required = true) String id) 
        throws IOException, ServletException {  
    checkPermission(Jenkins.READ);
    Jenkins j = Jenkins.getInstance();
    if (j == null) {
        rsp.sendError(500, "Jenkins is not ready");
        return;
    }
    
    String fingerPrintHash = DockerTraceabilityHelper.getContainerHash(id);
    rsp.sendRedirect2(j.getRootUrl()+"fingerprint/"+fingerPrintHash);
}
 
Example 14
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Gets an image {@link Fingerprint} page.
 * @param req Stapler request
 * @param rsp Stapler response
 * @param id Image ID. Method supports full 64-char IDs only.
 * @throws IOException  Request processing error
 * @throws ServletException Servlet error
 */
public void doImage(StaplerRequest req, StaplerResponse rsp, 
        @QueryParameter(required = true) String id) 
        throws IOException, ServletException {  
    checkPermission(Jenkins.READ);
    Jenkins j = Jenkins.getInstance();
    if (j == null) {
        rsp.sendError(500, "Jenkins is not ready");
        return;
    }
    
    String fingerPrintHash = DockerTraceabilityHelper.getImageHash(id);
    rsp.sendRedirect2(j.getRootUrl()+"fingerprint/"+fingerPrintHash);
}
 
Example 15
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Export live jenkins instance configuration as Yaml
 * @throws Exception
 */
@RequirePOST
@Restricted(NoExternalUse.class)
public void doExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    res.setContentType("application/x-yaml; charset=utf-8");
    res.addHeader("Content-Disposition", "attachment; filename=jenkins.yaml");
    export(res.getOutputStream());
}
 
Example 16
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doApply(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configureWith(YamlSource.of(req));
}
 
Example 17
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String newSource = request.getParameter("_.newSource");
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        List<String> candidatePaths = Collections.singletonList(normalizedSource);
        List<YamlSource> candidates = getConfigFromSources(candidatePaths);
        if (canApplyFrom(candidates)) {
            sources = candidatePaths;
            configureWith(getConfigFromSources(getSources()));
            CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
            if (config != null) {
                config.setConfigurationPath(normalizedSource);
                config.save();
            }
            LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
        } else {
            LOGGER.log(Level.WARNING, "Provided sources could not be applied");
            // todo: show message in UI
        }
    } else {
        LOGGER.log(Level.FINE, "No such source exists, applying default");
        // May be do nothing instead?
        configure();
    }
    response.sendRedirect("");
}