org.kohsuke.stapler.StaplerResponse Java Examples

The following examples show how to use org.kohsuke.stapler.StaplerResponse. 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: AWSDeviceFarmTestResult.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Create the graph image for the number of device minutes used in a test run, for the previous three Jenkins runs.
 *
 * @param request
 * @param response
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doDurationGraph(StaplerRequest request, StaplerResponse response) throws IOException {
    // Abort if having Java AWT issues.
    if (ChartUtil.awtProblemCause != null) {
        response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
        return;
    }

    // Check the "If-Modified-Since" header and abort if we don't need re-create the graph.
    if (isCompleted()) {
        Calendar timestamp = getOwner().getTimestamp();
        if (request.checkIfModified(timestamp, response)) {
            return;
        }
    }

    // Create new duration graph for this AWS Device Farm result.
    Graph graph = AWSDeviceFarmGraph.createDurationTrendGraph(build, isCompleted(), getPreviousResults(DefaultTrendGraphSize));
    graph.doPng(request, response);
}
 
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: EzScrumRoot.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void doRemovePlugin(StaplerRequest request, StaplerResponse response) throws Exception {
	String pluginName = request.getParameter("pluginName");// it is unique

	PluginModifier pluginModifier = new PluginModifier();
	try {
		// remove import.jsp which in plugin to host
		pluginModifier.removePluginImportPath(FilenameUtils.removeExtension(pluginName));
	} catch (Exception e) {
		throw e;
	}
	final String pluginPath = "./WebContent/pluginWorkspace/" + pluginName;

	PluginManager pluginManager = new PluginManager();
	// uninstall plugin 
	pluginManager.removePlugin(pluginPath);
}
 
Example #4
Source File: GitLabAvatarCache.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
    throws IOException, ServletException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", bos);
    } finally {
        if (flushImage) {
            image.flush();
        }
    }
    final byte[] bytes = bos.toByteArray();
    if (lastModified > 0) {
        rsp.addDateHeader("Last-Modified", lastModified);
    }
    rsp.addHeader("Cache-control", cacheControl);
    rsp.setContentType("image/png");
    rsp.setContentLength(bytes.length);
    rsp.getOutputStream().write(bytes);
}
 
Example #5
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 #6
Source File: StatusImage.java    From jenkins-status-badges-plugin with MIT License 6 votes vote down vote up
@Override
public void generateResponse( StaplerRequest req, StaplerResponse rsp, Object node )
    throws IOException, ServletException
{
    String v = req.getHeader( "If-None-Match" );
    if ( etag.equals( v ) )
    {
        rsp.setStatus( SC_NOT_MODIFIED );
        return;
    }

    rsp.setHeader( "ETag", etag );
    rsp.setHeader( "Expires", "Fri, 01 Jan 1984 00:00:00 GMT" );
    rsp.setHeader( "Cache-Control", "no-cache, private" );
    rsp.setHeader( "Content-Type", "image/svg+xml;charset=utf-8" );
    rsp.setHeader( "Content-Length", length );
    rsp.getOutputStream().write( payload.getBytes() );
}
 
Example #7
Source File: Project.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void doGetProjectPluginConfig(StaplerRequest request, StaplerResponse response) {
	PluginConfigManager pluginConfigModifier = new PluginConfigManager(this.mProjectName);
	if (!pluginConfigModifier.readFileContent().equals("")) {
		JsonParser parser = new JsonParser();
		JsonArray pluginJsonArray = parser.parse(pluginConfigModifier.readFileContent()).getAsJsonArray();
		Gson gson = new Gson();
		StringBuilder sb = new StringBuilder();
		sb.append("{success: true, data: { pluginConfigArray: [");
		for (int i = 0; i < pluginJsonArray.size(); i++) {
			PluginConfig pluginConfig = gson.fromJson(pluginJsonArray.get(i), PluginConfig.class);
			if (i != 0) {
				sb.append(",");
			}
			sb.append(gson.toJson(pluginConfig));
		}
		sb.append("]} }");
		try {
			response.getWriter().write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example #8
Source File: BitbucketServerEndpoint.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Validates this server endpoint. Checks availability and version requirement.
 * @return If valid HttpStatus 200, if unsupported version then 428 and if unreachable then 400 error code is returned.
 */
@GET
@WebMethod(name="validate")
public HttpResponse validate(){
    String version = BitbucketServerApi.getVersion(apiUrl);
    if(!BitbucketServerApi.isSupportedVersion(version)){
        throw new ServiceException.PreconditionRequired(
                Messages.bbserver_version_validation_error(
                        version, BitbucketServerApi.MINIMUM_SUPPORTED_VERSION));
    }
    return new HttpResponse(){
        @Override
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
            rsp.setStatus(200);
        }
    };
}
 
Example #9
Source File: EzScrumRoot.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void doGetInstalledPluginList(StaplerRequest request, StaplerResponse response) throws IOException {
	// write projects to XML formatoikk
	StringBuilder sb = new StringBuilder();

	PluginManager pluginManager = new PluginManager();
	List<PluginWrapper> pluginWrapperList = pluginManager.getPluginWrapperList();
	sb.append("<Plugins>");
	for (PluginWrapper pluginWrapper : pluginWrapperList) {
		String pluginName = pluginWrapper.getPluginName();
		sb.append("<Plugin>");
		sb.append("<Name>" + pluginName + "</Name>");
		sb.append("<Enable>" + pluginManager.getPluginEnable(pluginName) + "</Enable>");
		sb.append("</Plugin>");
	}
	sb.append("</Plugins>");
	try {
		response.getWriter().write(sb.toString());
		response.getWriter().close();
	} catch (IOException e) {
		throw e;
	}
}
 
Example #10
Source File: LogResource.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private void writeLog(StaplerRequest req, StaplerResponse rsp) {
    try {
        String download = req.getParameter("download");

        if("true".equalsIgnoreCase(download)) {
            rsp.setHeader("Content-Disposition", "attachment; filename=log.txt");
        }

        rsp.setContentType("text/plain;charset=UTF-8");
        rsp.setStatus(HttpServletResponse.SC_OK);

        writeLogs(req, rsp);
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Failed to get logText: " + e.getMessage(), e);
    }
}
 
Example #11
Source File: ApiHead.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: CukedoctorBuildAction.java    From cucumber-living-documentation-plugin with MIT License 6 votes vote down vote up
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {

        File docsPath = getDocsPath();

        if (docsPath.getName().endsWith("all.html")) {
            createAllDocsPage(docsPath);
            DirectoryBrowserSupport dbs = new DirectoryBrowserSupport(this, new FilePath(getDocsPath()), getTitle(), getUrlName(),
                false);

            dbs.generateResponse(req, rsp, this);
        } else if (docsPath.getName().endsWith("html")) {
            rsp.sendRedirect2(req.getContextPath()+"/"+build.getUrl() + BASE_URL + "/docsHtml");
        } else {
            rsp.sendRedirect2(req.getContextPath()+"/"+build.getUrl() +BASE_URL + "/docsPdf");
        }

    }
 
Example #13
Source File: GogsWebHookTest.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
@Test
public void whenQueryStringIsNullMustThrowException() throws Exception {
    //Prepare the SUT
    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn(null);
    GogsWebHook gogsWebHook = new GogsWebHook();


    try {
        gogsWebHook.doIndex(staplerRequest, staplerResponse);
    } catch (NullPointerException e) {
        String expectedErrMsg = "The queryString in the request is null";
        assertEquals("Not the expected error message.", expectedErrMsg, e.getMessage());
        log.info("call failed as expected.");
        return;
    }
    fail("The call should have failed.");
}
 
Example #14
Source File: IssuesDetail.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Returns a new sub page for the selected link.
 *
 * @param link
 *         the link to identify the sub page to show
 * @param request
 *         Stapler request
 * @param response
 *         Stapler response
 *
 * @return the new sub page
 */
@SuppressWarnings("unused") // Called by jelly view
public Object getDynamic(final String link, final StaplerRequest request, final StaplerResponse response) {
    try {
        return new DetailFactory().createTrendDetails(link, owner, result,
                report, newIssues, outstandingIssues, fixedIssues,
                sourceEncoding, this);
    }
    catch (NoSuchElementException ignored) {
        try {
            response.sendRedirect2("../");
        }
        catch (IOException ignore) {
            // ignore
        }
        return this; // fallback on broken URLs
    }
}
 
Example #15
Source File: Project.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public Object getDynamic(String token, StaplerRequest request, StaplerResponse response) {
	HttpSession session = request.getSession();

	ProjectObject project = SessionManager.getProjectObject(request);
	if (session == null || project == null) {
		return this;
	}

	String projectName = project.getName();

	if (token.equals("productBacklog")) { // when user enter to project
		return new ProductBacklog(projectName);
	} else if (token.equals("taskBoard")) {
		return new TaskBoard(projectName);
	}

	return this;
}
 
Example #16
Source File: AWSDeviceFarmProjectAction.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Return trend graph of all AWS Device Farm results for this project.
 *
 * @param request  The request object.
 * @param response The response object.
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doGraph(StaplerRequest request, StaplerResponse response) throws IOException {
    // Abort if having Java AWT issues.
    if (ChartUtil.awtProblemCause != null) {
        response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
        return;
    }

    // Get previous AWS Device Farm build and results.
    AWSDeviceFarmTestResultAction prev = getLastBuildAction();
    if (prev == null) {
        return;
    }
    AWSDeviceFarmTestResult result = prev.getResult();
    if (result == null) {
        return;
    }

    // Create new graph for the AWS Device Farm results of all runs in this project.
    Graph graph = AWSDeviceFarmGraph.createResultTrendGraph(prev.getOwner(), false, result.getPreviousResults());
    graph.doPng(request, response);
}
 
Example #17
Source File: DynamicBuild.java    From DotCi with MIT License 6 votes vote down vote up
@Override
public Object getDynamic(final String token, final StaplerRequest req, final StaplerResponse rsp) {
    try {
        final Build item = getRun(Combination.fromString(token));
        if (item != null) {
            if (item.getNumber() == this.getNumber()) {
                return item;
            } else {
                // redirect the user to the correct URL
                String url = Functions.joinPath(item.getUrl(), req.getRestOfPath());
                final String qs = req.getQueryString();
                if (qs != null) {
                    url += '?' + qs;
                }
                throw HttpResponses.redirectViaContextPath(url);
            }
        }
    } catch (final IllegalArgumentException e) {
        // failed to parse the token as Combination. Must be something else
    }
    return super.getDynamic(token, req, rsp);
}
 
Example #18
Source File: KubernetesComputer.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
public void doContainerLog(@QueryParameter String containerId,
                           StaplerRequest req, StaplerResponse rsp) throws KubernetesAuthException, IOException {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);

    ByteBuffer outputStream = new ByteBuffer();
    KubernetesSlave slave = getNode();
    if(slave != null) {
        KubernetesCloud cloud = slave.getKubernetesCloud();
        KubernetesClient client = cloud.connect();

        String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace());

        client.pods().inNamespace(namespace).withName(getName())
                .inContainer(containerId).tailingLines(20).watchLog(outputStream);
    }

    new LargeText(outputStream, false).doProgressText(req, rsp);
}
 
Example #19
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 #20
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 #21
Source File: DbBackedBuild.java    From DotCi with MIT License 6 votes vote down vote up
public void doLogTail(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException {
    rsp.setContentType("text/plain;charset=UTF-8");
    final Joiner joiner = Joiner.on("\n");
    final PlainTextConsoleOutputStream out = new PlainTextConsoleOutputStream(new FlushProofOutputStream(rsp.getCompressedOutputStream(req)));
    try {
        out.write(joiner.join(getLog(5000)).getBytes());
    } catch (final IOException e) {
        // see comment in writeLogTo() method
        final InputStream input = getLogInputStream();
        try {
            IOUtils.copy(input, out);
        } finally {
            IOUtils.closeQuietly(input);
        }
    } finally {
        IOUtils.closeQuietly(out);
    }
}
 
Example #22
Source File: GogsWebHookTest.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
@Test
public void whenEmptyJob2InQueryStringMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job=&foo=bar");

    //perform the testÃŽ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No value assigned to parameter 'job'";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example #23
Source File: GogsWebHookTest.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
@Test
public void whenEmptyHeaderTypeMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);

    //perform the test
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(403);

    String expectedOutput = "Only push event can be accepted.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example #24
Source File: GithubReposController.java    From DotCi with MIT License 5 votes vote down vote up
public void doRepoAction(final StaplerRequest req, final StaplerResponse rsp) throws InvocationTargetException, IllegalAccessException {
    final String[] tokens = StringUtils.split(req.getRestOfPath(), "/");
    final GithubRepoAction repoAction = getRepoAction(tokens[0]);
    if (repoAction != null) {
        final String methodToken = tokens.length > 1 ? tokens[1] : "index";
        final String methodName = "do" + StringUtils.capitalize(methodToken);
        final Method method = ReflectionUtils.getPublicMethodNamed(repoAction.getClass(), methodName);
        method.invoke(repoAction, req, rsp);
    }
}
 
Example #25
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 #26
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 #27
Source File: AuthenticatedView.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public TopLevelItem doCreateItem(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException {
    final ItemGroup<? extends TopLevelItem> ig = getOwnerItemGroup();
    if (ig instanceof ModifiableItemGroup) {
        return ((ModifiableItemGroup<? extends TopLevelItem>) ig).doCreateItem(req, rsp);
    }
    return null;
}
 
Example #28
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 #29
Source File: Plugin.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
/**
 * todo record project<-->urlName(it must be unique) mapping into db, in order to identify disabled and enable plugin action
 * */
public Object getDynamic(String token, StaplerRequest request, StaplerResponse response) {
	PluginManager pluginManager = new PluginManager();
	List<Action> actionList = pluginManager.getActionList();
	for (Action a : actionList) {
		if (a.getUrlName().equals(token)) {
			return a;
		}
	}

	return this;
}
 
Example #30
Source File: StatusJsonActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void assertUnstableBuild(FreeStyleBuild build, ByteArrayOutputStream out, StaplerResponse response) throws IOException {
    JSONObject object = JSONObject.fromObject(new String(out.toByteArray()));
    assertThat(object.getString("sha"), is(commitSha1));
    assertThat(object.getInt("id"), is(build.getNumber()));
    assertThat(object.getString("status"), is("failed"));
}