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

The following examples show how to use org.kohsuke.stapler.StaplerResponse#setContentType() . 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: 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 2
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 3
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 4
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 5
Source File: BuildFlowAction.java    From yet-another-build-visualizer-plugin with MIT License 5 votes vote down vote up
public void doBuildFlow(StaplerRequest req, StaplerResponse rsp)
    throws IOException, ServletException {
  buildFlowOptions.setShowDurationInfo(
      Boolean.parseBoolean(req.getParameter("showDurationInfo")));
  buildFlowOptions.setShowBuildHistory(
      Boolean.parseBoolean(req.getParameter("showBuildHistory")));
  rsp.setContentType("text/html;charset=UTF-8");
  req.getView(this, "buildFlow.groovy").forward(req, rsp);
}
 
Example 6
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 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: ServiceException.java    From blueocean-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(status);
    rsp.setContentType("application/json");
    PrintWriter w = rsp.getWriter();
    w.write(toJson());
    w.close();
}
 
Example 9
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 10
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 11
Source File: GitHubPollingLogAction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * TODO is it secure?
 */
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
    rsp.setContentType("text/plain;charset=UTF-8");
    // Prevent jelly from flushing stream so Content-Length header can be added afterwards
    FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
    try {
        getPollingLogText().writeLogTo(0, out);
    } finally {
        closeQuietly(out);
    }
}
 
Example 12
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Serves the JSON response.
 * @param item Data to be serialized to JSON
 * @return HTTP response with application/json MIME type
 */
private static HttpResponse toJSONResponse(final Object item) {
    return new HttpResponse() {
        @Override
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
            ObjectMapper mapper = new ObjectMapper(); 
            rsp.setContentType("application/json;charset=UTF-8");
            mapper.writeValue(rsp.getWriter(), item);
        }
    };
}
 
Example 13
Source File: StatusJsonAction.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private void writeBody(StaplerResponse response, JSONObject body) throws IOException {
    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();
    writer.write(body.toString());
    writer.flush();
    writer.close();
}
 
Example 14
Source File: Export.java    From blueocean-plugin with MIT License 4 votes vote down vote up
private static void serveExposedBean(StaplerRequest req, StaplerResponse resp, Object exposedBean, ExportConfig config) throws ServletException, IOException {
    Flavor flavor = config.getFlavor();
    String pad=null;
    resp.setContentType(flavor.contentType);
    Writer w = resp.getCompressedWriter(req);

    if (flavor== Flavor.JSON || flavor== Flavor.JSONP) { // for compatibility reasons, accept JSON for JSONP as well.
        pad = req.getParameter("jsonp");
        if(pad!=null) w.write(pad+'(');
    }

    TreePruner pruner;
    String tree = req.getParameter("tree");
    if (tree != null) {
        try {
            pruner = new NamedPathPruner(tree);
        } catch (IllegalArgumentException x) {
            throw new ServletException("Malformed tree expression: " + x, x);
        }
    } else {
        int depth = 0;
        try {
            String s = req.getParameter("depth");
            if (s != null) {
                depth = Integer.parseInt(s);
            }
        } catch (NumberFormatException e) {
            throw new ServletException("Depth parameter must be a number");
        }
        pruner = new ByDepth(1 - depth);
    }

    DataWriter dw = flavor.createDataWriter(exposedBean, w, config);
    if (exposedBean instanceof Object[]) {
        // TODO: extend the contract of DataWriter to capture this
        // TODO: make this work with XML flavor (or at least reject this better)
        dw.startArray();
        for (Object item : (Object[])exposedBean)
            writeOne(pruner, dw, item);
        dw.endArray();
    } else {
        writeOne(pruner, dw, exposedBean);
    }

    if(pad!=null) w.write(')');
    w.close();
}
 
Example 15
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);
}