Example usage for javax.servlet.http HttpServletResponse setContentLength

List of usage examples for javax.servlet.http HttpServletResponse setContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setContentLength.

Prototype

public void setContentLength(int len);

Source Link

Document

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Usage

From source file:ch.ralscha.extdirectspring.controller.ApiController.java

/**
 * Method that handles api.js and api-debug.js calls. Generates a javascript with the
 * necessary code for Ext Direct.//  www .j  a va2s.c o m
 *
 * @param apiNs name of the namespace the variable remotingApiVar will live in.
 * Defaults to Ext.app
 * @param actionNs name of the namespace the action will live in.
 * @param remotingApiVar name of the remoting api variable. Defaults to REMOTING_API
 * @param pollingUrlsVar name of the polling urls object. Defaults to POLLING_URLS
 * @param group name of the api group. Multiple groups delimited with comma
 * @param fullRouterUrl if true the router property contains the full request URL with
 * method, server and port. Defaults to false returns only the URL without method,
 * server and port
 * @param format only valid value is "json2. Ext Designer sends this parameter and the
 * response is a JSON. Defaults to null and response is Javascript.
 * @param baseRouterUrl Sets the path to the router and poll controllers. If set
 * overrides default behavior that uses request.getRequestURI
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @throws IOException
 */
@SuppressWarnings({ "resource" })
@RequestMapping(value = { "/api.js", "/api-debug.js", "/api-debug-doc.js" }, method = RequestMethod.GET)
public void api(@RequestParam(value = "apiNs", required = false) String apiNs,
        @RequestParam(value = "actionNs", required = false) String actionNs,
        @RequestParam(value = "remotingApiVar", required = false) String remotingApiVar,
        @RequestParam(value = "pollingUrlsVar", required = false) String pollingUrlsVar,
        @RequestParam(value = "group", required = false) String group,
        @RequestParam(value = "fullRouterUrl", required = false) Boolean fullRouterUrl,
        @RequestParam(value = "format", required = false) String format,
        @RequestParam(value = "baseRouterUrl", required = false) String baseRouterUrl,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (format == null) {
        response.setContentType(this.configurationService.getConfiguration().getJsContentType());
        response.setCharacterEncoding(ExtDirectSpringUtil.UTF8_CHARSET.name());

        String apiString = buildAndCacheApiString(apiNs, actionNs, remotingApiVar, pollingUrlsVar, group,
                fullRouterUrl, baseRouterUrl, request);

        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    } else {
        response.setContentType(RouterController.APPLICATION_JSON.toString());
        response.setCharacterEncoding(RouterController.APPLICATION_JSON.getCharset().name());

        String requestUrlString = request.getRequestURL().toString();

        boolean debug = requestUrlString.contains("api-debug.js");
        String routerUrl = requestUrlString.replaceFirst("api[^/]*?\\.js", "router");

        String apiString = buildApiJson(apiNs, actionNs, remotingApiVar, routerUrl, group, debug);
        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    }
}

From source file:org.chtijbug.drools.platform.web.filter.DynamicBaseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug(">> doFilterInternal()");
    try {/*from ww w.  ja  v a  2 s.c  om*/
        PrintWriter out = response.getWriter();
        CharResponseWrapper wrapper = new CharResponseWrapper(response);
        filterChain.doFilter(request, wrapper);

        String baseHref = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/";
        logger.debug("About to replace the base href element with {}", baseHref);
        String modifiedHtml = baseElementPattern.matcher(wrapper.toString())
                .replaceAll("<base href=\"" + baseHref + "\"");
        logger.debug("Modified HTML content : {}", modifiedHtml);
        // Write our modified text to the real response
        response.setContentLength(modifiedHtml.getBytes().length);
        out.write(modifiedHtml);
        out.close();
    } catch (Throwable t) {
        logger.error(t.getMessage());
    } finally {
        logger.debug("<< doFilterInternal()");
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);

    OntologyFormat format = mediaTypes.get(mediaType);
    if (format != null) {
        // Preflight CORS support
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,PUT");
        response.setIntHeader("Access-Control-Max-Age", 60 * 60 * 24);
        response.setContentType(mediaType + ";charset=utf-8");
        response.setContentLength(0);
    } else {/*ww  w  . ja va2  s.  com*/
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}

From source file:org.wrml.server.WrmlServlet.java

void writeNotFound(final HttpServletResponse response) throws IOException {

    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    response.setContentLength(0);
    response.flushBuffer();//w  w w.  ja  v  a 2s.  c  om
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String filePath = request.getParameter("fileName");

    if (filePath == null || filePath.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }//from  ww w.jav a  2s  .co m

    File file = new File(filePath);

    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }

    ServletContext ctx = getServletContext();

    try (InputStream fis = new FileInputStream(file)) {
        String mimeType = ctx.getMimeType(file.getAbsolutePath());

        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        try (ServletOutputStream os = response.getOutputStream()) {
            byte[] bufferData = new byte[1024];
            int read = 0;

            while ((read = fis.read(bufferData)) != -1) {
                os.write(bufferData, 0, read);
            }
            os.flush();
            os.close();
            fis.close();
        }
    }
}

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MaintenanceEventMultiUploadController.java

@RequestMapping(value = "/getAttachmentForEvent.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "eventAttachment");
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService//  w  w  w  .  j av  a 2  s. c o m
            .getInputStream(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(TechnologyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MachinePartMultiUploadController.java

@RequestMapping(value = "/getAttachment.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "machinePartAttachment");
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService//  ww w .j  a  v  a 2 s.  c om
            .getInputStream(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(TechnologyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView json(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//w  w  w.  j a v a  2 s  .c o m
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        String json = feedsBo.buildJson(events, Utilities.getBaseUrl(req), true);
        // flush it in the res
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store");
        res.setHeader("Pragma", "public, no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("application/json");
        res.setContentLength(json.getBytes().length);
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8");
        writer.write(json);
        writer.flush();
        writer.close();
    } catch (Exception exception) {
        logger.error("Error producing JSON", exception);
        throw exception;
    }
    return null;
}