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

The following examples show how to use org.kohsuke.stapler.StaplerResponse#setHeader() . 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: 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 2
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 3
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 4
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 5
Source File: BlueI18n.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
    rsp.setStatus(statusCode);
    rsp.setContentType("application/json; charset=UTF-8");
    if (bundleCacheEntry != null) {
        // Set pugin version info that can be used by the browser to
        // determine if it wants to use the resource bundle, or not.
        // The versions may not match (in theory - should never happen),
        // in which case the browser might not want to use the bundle data.
        jsonObject.put("plugin-version-requested", bundleCacheEntry.bundleParams.pluginVersion);
        PluginWrapper pluginWrapper = bundleCacheEntry.bundleParams.getPlugin();
        if(pluginWrapper != null) {
            jsonObject.put("plugin-version-actual", pluginWrapper.getVersion());
        }

        if (bundleCacheEntry.bundleParams.isBrowserCacheable()) {
            // Set the expiry to one year.
            rsp.setHeader("Cache-Control", "public, max-age=31536000");
        } else if (!bundleCacheEntry.bundleParams.isMatchingPluginVersionInstalled()) {
            // This should never really happen if things are installed properly
            // and the UI is coded up properly, with proper access to the installed
            // plugin version.
            LOGGER.log(Level.WARNING, String.format("Unexpected request for Blue Ocean i18n resource bundle '%s'. Installed plugin version '%s' does not match.",
                bundleCacheEntry.bundleParams, pluginWrapper!= null ? pluginWrapper.getVersion() : "unknown"));
        }
    }

    byte[] bytes = jsonObject.toString().getBytes(UTF8);
    rsp.setContentLength(bytes.length);
    rsp.getOutputStream().write(bytes);
}
 
Example 6
Source File: APIHeadTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Iterator<String> iterator() {
    StaplerResponse response = Stapler.getCurrentResponse();
    response.setHeader("Cache-Control", "max-age=10");
    return new ArrayList<String>().iterator();
}
 
Example 7
Source File: OrganizationFolderPipelineImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void getUrl() {
    StaplerRequest req = Stapler.getCurrentRequest();
    String s = req.getParameter("s");
    if (s == null) {
        s = Integer.toString(DEFAULT_ICON_SIZE);
    }
    StaplerResponse resp = Stapler.getCurrentResponse();
    try {
        resp.setHeader("Cache-Control", "max-age=" + TimeUnit.DAYS.toDays(7));
        resp.sendRedirect(action.getAvatarImageOf(s));
    } catch (IOException e) {
        throw new UnexpectedErrorException("Could not provide icon", e);
    }
}
 
Example 8
Source File: FillErrorResponse.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
        throws IOException, ServletException {
    rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    rsp.setContentType("text/html;charset=UTF-8");
    rsp.setHeader("X-Jenkins-Select-Error", clearList ? "clear" : "retain");
    rsp.getWriter().print(
            "<div class='error'><img src='" + req.getContextPath()
                    + Jenkins.RESOURCE_PATH + "/images/none.gif' height=16 width=1>" + Util.escape(getMessage()) +
                    "</div>");

}
 
Example 9
Source File: StatusPngAction.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void writeStatusBody(StaplerResponse response, Run<?, ?> build, BuildStatus status) {
    try {
        response.setHeader("Expires", "Fri, 01 Jan 1984 00:00:00 GMT");
        response.setHeader("Cache-Control", "no-cache, private");
        response.setHeader("Content-Type", "image/png");
        IOUtils.copy(getStatusImage(status), response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        throw HttpResponses.error(500, "Could not generate response.");
    }
}
 
Example 10
Source File: GitLabPushTrigger.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
public void doGenerateSecretToken(@AncestorInPath final Job<?, ?> project, StaplerResponse response) {
    byte[] random = new byte[16];   // 16x8=128bit worth of randomness, since we use md5 digest as the API token
    RANDOM.nextBytes(random);
    String secretToken = Util.toHexString(random);
    response.setHeader("script", "document.getElementById('secretToken').value='" + secretToken + "'");
}
 
Example 11
Source File: GitLabPushTrigger.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
public void doClearSecretToken(@AncestorInPath final Job<?, ?> project, StaplerResponse response) {;
    response.setHeader("script", "document.getElementById('secretToken').value=''");
}
 
Example 12
Source File: BranchHistoryWidget.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public void doAjax(final StaplerRequest req, final StaplerResponse rsp, @Header("n") final String n) throws IOException, ServletException {

    if (n == null) {
        throw HttpResponses.error(SC_BAD_REQUEST, new IllegalArgumentException("Missing the 'n' HTTP header"));
    }

    rsp.setContentType("text/html;charset=UTF-8");

    final List<T> items = new LinkedList<>();

    String nn = null;

    // TODO refactor getBuildsAfter and database query to be getBuildsAfterAndEqual
    final Iterable<T> builds = this.model.getBuildsAfter(Integer.parseInt(n) - 1);
    for (final T t : builds) {
        if (this.adapter.compare(t, n) >= 0) {
            items.add(t);
            if (this.adapter.isBuilding(t)) {
                nn = this.adapter.getKey(t);
            }
        } else {
            break;
        }
    }

    if (nn == null) {
        if (items.isEmpty()) {
            nn = n;
        } else {
            nn = this.adapter.getNextKey(this.adapter.getKey(items.get(0)));
        }
    }

    this.baseList = items;
    GReflectionUtils.setField(HistoryWidget.class, "firstTransientBuildKey", this, nn);

    rsp.setHeader("n", nn);

    req.getView(this, "ajaxBuildHistory.jelly").forward(req, rsp);
}