Example usage for javax.servlet ServletResponse setContentLength

List of usage examples for javax.servlet ServletResponse setContentLength

Introduction

In this page you can find the example usage for javax.servlet ServletResponse 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:com.iisigroup.cap.component.impl.ByteArrayDownloadResult.java

@Override
public void respondResult(ServletResponse response) {
    int length = -1;
    InputStream in = null;/*from   ww w  .  j a v a2s .  c o m*/
    OutputStream output = null;
    try {
        response.setContentType(getContentType());
        response.setContentLength(_byteArray.length);
        if (getOutputName() != null && response instanceof HttpServletResponse) {
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) _request.getServletRequest();
            String userAgent = req.getHeader("USER-AGENT");
            if (StringUtils.contains(userAgent, "MSIE")) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + _outputName + "\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + _outputName);
            }
            resp.setHeader("Cache-Control", "public");
            resp.setHeader("Pragma", "public");
        }
        output = response.getOutputStream();
        // Stream to the requester.
        byte[] bbuf = new byte[1024 * 1024];

        in = new ByteArrayInputStream(_byteArray);
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            output.write(bbuf, 0, length);
        }
        output.flush();
    } catch (IOException e) {
        e.getMessage();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(output);
    }
}

From source file:com.shopzilla.ducky.WadlXsltFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (this.requestMatcher.match(request)) {

        LOG.debug("adding transform");

        ByteBufferResponseWrapper wrapper = new ByteBufferResponseWrapper((HttpServletResponse) response);
        String styleSheetPath = makeProcessingInstruction(request);

        chain.doFilter(request, wrapper);

        wrapper.getWriter().flush();/*from w w  w  .j av a2 s. c  om*/
        String responseStr = injectStyleSheet(wrapper.toString(), styleSheetPath);
        response.setContentLength(responseStr.length());
        PrintWriter out = response.getWriter();
        out.append(responseStr);
        out.flush();

    } else {

        LOG.debug("NOT adding transform");
        // just pass it along
        chain.doFilter(request, response);
    }
}

From source file:io.scigraph.services.jersey.dynamic.SwaggerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Capture the output of the filter chain
    ByteArrayResponseWrapper wrappedResp = new ByteArrayResponseWrapper((HttpServletResponse) response);
    chain.doFilter(request, wrappedResp);
    if (isGzip(request)) {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                GZIPInputStream gis = new GZIPInputStream(is);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(bs)) {
            byte[] newApi = writeDynamicResource(gis);
            gzos.write(newApi);// w w w  .j av a  2  s  .c  o  m
            gzos.close();
            byte[] output = bs.toByteArray();
            response.setContentLength(output.length);
            response.getOutputStream().write(output);
        }
    } else {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            byte[] newApi = writeDynamicResource(is);
            response.setContentLength(newApi.length);
            response.getOutputStream().write(newApi);
        }

    }
}

From source file:edu.sdsc.scigraph.services.jersey.dynamic.SwaggerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean gzip = isGzip(request);

    // Capture the output of the filter chain
    ByteArrayResponseWrapper wrappedResp = new ByteArrayResponseWrapper((HttpServletResponse) response);
    chain.doFilter(request, wrappedResp);
    if (gzip) {// www .j  a  v  a  2  s. c o m
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                GZIPInputStream gis = new GZIPInputStream(is);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(bs)) {
            byte[] newApi = writeDynamicResource(gis);
            gzos.write(newApi);
            gzos.close();
            byte[] output = bs.toByteArray();
            response.setContentLength(output.length);
            response.getOutputStream().write(output);
        }
    } else {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            byte[] newApi = writeDynamicResource(is);
            response.setContentLength(newApi.length);
            response.getOutputStream().write(newApi);
        }

    }
}

From source file:com.iisigroup.cap.component.impl.FileDownloadResult.java

public void respondResult(ServletResponse response) {
    InputStream in = null;//w  ww .j  a  v a2  s. c om
    OutputStream output = null;
    try {
        response.setContentType(_contentType);
        if (_outputName != null && response instanceof HttpServletResponse) {
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.setHeader("Content-Disposition", "attachment;filename=\"" + _outputName + "\"");
            resp.setHeader("Cache-Control", "public");
            resp.setHeader("Pragma", "public");
        }
        output = response.getOutputStream();
        File file = new File(_file);
        int length = -1;
        // Stream to the requester.
        byte[] bbuf = new byte[1024 * 1024];
        int len = 0;
        in = new FileInputStream(file);
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            output.write(bbuf, 0, length);
            len += length;
        }
        response.setContentLength(len);
        output.flush();
    } catch (Exception e) {
        throw new CapException(e, getClass());
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(output);
    }

}

From source file:de.betterform.agent.web.filter.XSLTFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    ServletContext servletContext = filterConfig.getServletContext();

    /* TODO: clean up, styleFile is  never used */
    String stylePath = null;/* w ww .  j  a  v  a2s . c om*/
    try {
        stylePath = WebFactory.getRealPath(xsltPath, servletContext);
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    File styleFile = new File(stylePath, xslFile);

    PrintWriter out = response.getWriter();
    CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
    try {
        URI uri = new File(WebFactory.getRealPath(xsltPath, servletContext)).toURI().resolve(new URI(xslFile));
        XSLTGenerator generator = WebFactory.setupTransformer(uri, servletContext);

        wrapper.setContentType("text/html");
        chain.doFilter(request, wrapper);

        StringReader sr = new StringReader(wrapper.toString());
        generator.setInput(sr);
        //            Source xmlSource = new StreamSource((Reader) sr);
        CharArrayWriter caw = new CharArrayWriter();
        generator.setOutput(caw);

        //            StreamResult result = new StreamResult(caw);
        //            transformer.transform(xmlSource, result);
        generator.generate();
        response.setContentLength(caw.toString().length());
        out.write(caw.toString());

    } catch (URISyntaxException e) {
        out.println(e.toString());
        out.write(wrapper.toString());
    } catch (XFormsException e) {
        out.println(e.toString());
        out.write(wrapper.toString());
    }
}

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void writeCacheToResponse(CacheEntry cacheEntry, ServletResponse response, boolean fragment)
        throws IOException {

    if (cacheEntry.getContentType() != null) {
        response.setContentType(cacheEntry.getContentType());
    }/*w w  w . j a v a  2  s .  c o m*/

    if (!fragment) {

        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            if (cacheEntry.getLastModified() != -1) {
                httpResponse.setDateHeader("Last-Modified", cacheEntry.getLastModified());
            }

            if (cacheEntry.getExpires() != Long.MAX_VALUE) {
                httpResponse.setDateHeader("Expires", cacheEntry.getExpires());
            }

            if (cacheEntry.getMaxAge() != -1) {
                if (cacheEntry.getMaxAge() < 0) { // set max-age based on life time
                    long currentMaxAge = -cacheEntry.getMaxAge() / 1000 - System.currentTimeMillis() / 1000;
                    if (currentMaxAge < 0) {
                        currentMaxAge = 0;
                    }
                    httpResponse.addHeader("Cache-Control", "max-age=" + currentMaxAge);
                } else {
                    httpResponse.addHeader("Cache-Control", "max-age=" + cacheEntry.getMaxAge());
                }
            }

        }
    }

    if (cacheEntry.getLocale() != null) {
        response.setLocale(cacheEntry.getLocale());
    }

    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentLength(cacheEntry.getContent().length);
    out.write(cacheEntry.getContent());
    out.flush();
}

From source file:com.flexive.war.servlet.CeFileUpload.java

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    String renderContent = null;//w  w  w .  j  av a2  s .  co m
    try {

        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request);

        if (ceb == null) {
            renderContent = "No Content Editor Bean is active";
        } else {

            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Parse the request
            List /* FileItem */ items = upload.parseRequest(request);

            BinaryDescriptor binary = null;

            String xpath = null;
            for (Object item1 : items) {
                FileItem item = (FileItem) item1;
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("result")) {
                        renderContent = item.getString().replaceAll("\\\\n", "\\\n");
                    } else if (item.getFieldName().equalsIgnoreCase("xpath")) {
                        xpath = item.getString();
                    }
                } else {
                    InputStream uploadedStream = null;
                    try {
                        uploadedStream = item.getInputStream();
                        String name = item.getName();
                        if (name.indexOf('\\') > 0)
                            name = name.substring(name.lastIndexOf('\\') + 1);
                        binary = new BinaryDescriptor(name, item.getSize(), uploadedStream);
                    } finally {
                        if (uploadedStream != null)
                            uploadedStream.close();
                    }
                }
                //                    System.out.println("Item: " + item.getName());
            }

            //FxContent co = ceb.getContent();
            FxBinary binProperty = new FxBinary(binary);
            //co.setValue(xpath, binProperty);
            //ceb.getContentEngine().prepareSave(co);
        }
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        t.printStackTrace();
        renderContent = t.getMessage();
    }

    // Render the result
    PrintWriter w = servletResponse.getWriter();
    if (renderContent == null) {
        renderContent = "No content";
    }
    w.print(renderContent);
    w.close();
    servletResponse.setContentType("text/html");
    servletResponse.setContentLength(renderContent.length());
    ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK);
}

From source file:org.force66.mock.servletapi.MockFilterChain.java

public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    Validate.notNull(request, "Null request not allowed.");
    Validate.notNull(response, "Null response not allowed.");

    if (this.runtimeException != null) {
        throw this.runtimeException;
    }/*from w w w  .j av  a  2  s  . c o m*/
    if (this.ioException != null) {
        throw this.ioException;
    }
    if (this.servletException != null) {
        throw this.servletException;
    }

    try {
        Thread.sleep(sleepTimeInMillis);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (outputData != null) {
        response.setContentLength(outputData.toString().length());
        response.getOutputStream().write(outputData);
    }

    if (response.getOutputStream() != null) {
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}

From source file:org.infoscoop.web.I18NFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    BufferHttpServletResponseWrapper bufResponse = new BufferHttpServletResponseWrapper(
            (HttpServletResponse) response);
    chain.doFilter(request, bufResponse);
    bufResponse.flushBuffer();//from  ww w .  ja  v  a  2 s . c o  m
    String body = bufResponse.getStringContent();

    try {
        body = I18NUtil.resolve(type, body, request.getLocale());
    } catch (Exception e) {
        log.error("database error occurred. ", e);
    }

    if (bufResponse.getLocale() != null)
        response.setLocale(bufResponse.getLocale());
    response.setContentLength(body.getBytes("utf-8").length);

    Writer out = null;
    try {
        out = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        out.write(body);
        out.flush();
    } finally {
        if (out != null)
            out.close();
    }
}