Example usage for javax.servlet.http HttpServletResponse flushBuffer

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

Introduction

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

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.base.FenixDispatchAction.java

protected void writeFile(final HttpServletResponse response, final String filename, final String contentType,
        final byte[] content) throws IOException {

    response.setContentLength(content.length);
    response.setContentType(contentType);
    response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    try (ServletOutputStream outputStream = response.getOutputStream()) {
        outputStream.write(content);/* www.jav a 2 s  . c  o m*/
        outputStream.flush();
        response.flushBuffer();
    }
}

From source file:es.ucm.fdi.storage.web.StorageController.java

@RequestMapping(method = RequestMethod.GET, value = "/storage/**")
public void servirArchivos(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String ctxPath = request.getContextPath();
    String objectId = request.getRequestURI();
    objectId = objectId.substring(ctxPath.length() + "/storage/".length());
    int pos = objectId.indexOf('/');
    if (pos < 0) {
        response.sendError(400, "Upps");
        return;/* w w w.  j a v  a2  s  . c om*/
    }
    String bucket = objectId.substring(0, pos);
    String key = objectId.substring(pos + 1);
    StorageObject object = storage.getObject(bucket, key);
    String mimeType = object.getMimeType();
    long length = object.getContentLength();

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) length);

    try {
        object.transferTo(response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        logger.error("Error writing file to output stream. bucket=>'{}', key=>'{}'", bucket, key, ex);
        response.sendError(500, "Upps");
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.manager.enrolments.CurriculumLineLogsDA.java

public ActionForward viewCurriculumLineLogStatisticsChartOperations(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterId");

    if (executionSemester != null) {
        final CurriculumLineLogStatisticsCalculator curriculumLineLogStatisticsCalculator = new CurriculumLineLogStatisticsCalculator(
                executionSemester);/* www  .  ja  v a  2  s.c  o  m*/

        ServletOutputStream writer = null;
        try {
            writer = response.getOutputStream();
            response.setContentType("image/jpeg");
            writer.write(curriculumLineLogStatisticsCalculator.getOperationsChart());
            writer.flush();
        } finally {
            writer.close();
            response.flushBuffer();
        }

    }

    return null;
}

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

private void getCache(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String id = request.getParameter("id");
    String url = request.getParameter("url");

    if (log.isInfoEnabled())
        log.info("get cache : id = " + id + ", url = " + url);

    try {/*from  w  w w . j a  va 2 s.c o  m*/
        Cache cache = CacheService.getHandle().getCacheById(id);
        if (cache != null) {
            response.setHeader("Cache-Control", "no-cache");

            List<Header> headers = cache.getHeaderList();
            for (Header header : headers) {
                String name = header.getName();
                if (!name.equalsIgnoreCase("transfer-encoding")) {
                    response.setHeader(name, header.getValue());
                }
            }

            response.flushBuffer();

            InputStream body = new ByteArrayInputStream(cache.getBodyBytes());
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[1024];
            int c = 0;
            while ((c = body.read(b)) != -1) {
                bos.write(b, 0, c);
                bos.flush();
            }

            bos.flush();
            bos.close();
            if (log.isInfoEnabled())
                log.info("get cache completed : id = " + id + ", url = " + cache.getUrl());
            return;
        }
    } catch (Exception e) {
        log.error("unexpected error occurred", e);
        response.sendError(500, e.getMessage());

        return;
    }

    if (url != null) {
        if (log.isInfoEnabled())
            log.info("redirect : url = " + url);
        response.sendRedirect(url);
    }

    response.setStatus(404);
}

From source file:com.rabbitstewdio.build.maven.tomcat.AbstractContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getPathInfo();

    InputStream in = findResource(filename);
    if (in == null) {
        log.warn("Unable to find [" + filename + "] on " + getServletName());
        response.setStatus(404);/* ww  w . j  a v  a  2 s  .co  m*/
        return;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(in, bout);

    response.setCharacterEncoding("UTF-8");

    String mimeType = getServletContext().getMimeType(filename);
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    response.addDateHeader("Expires", 0L);
    response.setDateHeader(LAST_MODIFIED, new Date().getTime());
    response.setContentLength(bout.size());
    response.getOutputStream().write(bout.toByteArray());
    response.flushBuffer();
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

public void handleDelete(HttpServletRequest request, HttpServletResponse response, String pathInContext,
        Resource resource) throws ServletException, IOException {
    if (!resource.exists() || !passConditionalHeaders(request, response, resource))
        return;/*from  w  w  w . ja  v  a 2  s . c  om*/
    try {
        // delete the file
        if (resource.delete()) {
            response.setStatus(HttpResponse.__204_No_Content);
            response.flushBuffer();
        } else
            response.sendError(HttpResponse.__403_Forbidden);
    } catch (SecurityException sex) {
        log.warn(LogSupport.EXCEPTION, sex);
        response.sendError(HttpResponse.__403_Forbidden, sex.getMessage());
    }
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Streams the file specified by the path
 */// ww  w  . j a v a  2  s .c o  m
@RequestMapping(value = "/file/{clientId}/{file:.*}", method = RequestMethod.GET)
public void streamFile(@PathVariable("clientId") String clientId, @PathVariable("file") String file,
        HttpServletResponse response) throws IOException {

    Path path = repoRoot.resolve(clientId).resolve(file);

    if (Files.notExists(path) || Files.isDirectory(path)) {
        log.log(Level.WARNING, "Failed streaming file: " + path);
        response.setStatus(404);
        return;
    }

    response.setContentType(Files.probeContentType(path));
    try (InputStream in = Files.newInputStream(path)) {
        IOUtils.copy(in, response.getOutputStream());
        response.flushBuffer();
    }
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Handle hand shake./*  w w  w.  ja  v a  2s  .c o m*/
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException {
    final String time = req.getHeader("X-Eve-requestToken");

    if (time == null) {
        return false;
    }

    final String token = TokenStore.get(time);
    if (token == null) {
        res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
    } else {
        res.setHeader("X-Eve-replyToken", token);
        res.setStatus(HttpServletResponse.SC_OK);
        res.flushBuffer();
    }
    return true;
}

From source file:org.eclipse.vorto.repository.web.ModelRepositoryController.java

@ApiOperation(value = "Returns the image of a Model")
@RequestMapping(value = "/image/{namespace}/{name}/{version:.+}", method = RequestMethod.GET)
public void getModelImage(@ApiParam(value = "Namespace", required = true) final @PathVariable String namespace,
        @ApiParam(value = "Namespace", required = true) final @PathVariable String name,
        @ApiParam(value = "Namespace", required = true) final @PathVariable String version,
        @ApiParam(value = "Response", required = true) final HttpServletResponse response) {
    Objects.requireNonNull(namespace, "namespace must not be null");
    Objects.requireNonNull(name, "name must not be null");
    Objects.requireNonNull(version, "version must not be null");

    final ModelId modelId = new ModelId(name, namespace, version);
    byte[] modelImage = modelRepository.getModelImage(modelId);
    response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + modelId.getName() + ".png");
    response.setContentType(APPLICATION_OCTET_STREAM);
    try {//w w w. j  a va 2 s.com
        IOUtils.copy(new ByteArrayInputStream(modelImage), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException("Error copying file.", e);
    }
}

From source file:nl.mineleni.cbsviewer.servlet.ReverseProxyServlet.java

/**
 * Process the HTTP Get request. Voor een Openlayers proxy wordt de url dan
 * iets van: <br>// w w  w.  j ava2s. c  o  m
 * <code>WMSproxy/proxy?</code> <br>
 * waarin WMSproxy de naam van de webapp is en proxy de servlet mapping.
 *
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws ServletException
 *             the servlet exception
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    try {
        String serverUrl = request.getQueryString();
        serverUrl = URLDecoder.decode(serverUrl, "UTF-8");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            // check if allowed
            if (!this.checkUrlAllowed(serverUrl)) {
                LOGGER.warn(serverUrl + ERR_MSG_FORBIDDEN);
                response.sendError(SC_FORBIDDEN, serverUrl + ERR_MSG_FORBIDDEN);
                response.flushBuffer();
            } else {
                // intercept and modify request
                if (serverUrl.contains("GetFeatureInfo")) {
                    serverUrl = serverUrl.replace("text%2Fhtml", URLEncoder.encode(type.toString(), "UTF-8"));
                    serverUrl = serverUrl.replace("text/html", URLEncoder.encode(type.toString(), "UTF-8"));
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("proxy GetFeatureInfo GET param: " + serverUrl);
                    }
                }
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Execute proxy GET param:" + serverUrl);
                }
                final HttpGet httpget = new HttpGet(serverUrl);
                httpget.setConfig(this.requestConfig);
                final HttpResponse get = this.client.execute(httpget);
                if (get.getStatusLine().getStatusCode() == SC_OK) {
                    String responseBody;
                    if (serverUrl.contains("GetFeatureInfo")) {
                        String lName = "";
                        String styles = "";
                        // uitzoeken querylayers
                        final String[] params = serverUrl.split("&");
                        for (final String s : params) {
                            if (s.contains("QUERY_LAYERS=")) {
                                lName = EncodingUtil
                                        .decodeURIComponent(s.substring("QUERY_LAYERS=".length(), s.length()));
                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("Query layers = " + lName);
                                }
                            }
                            if (s.contains("STYLES=")) {
                                styles = EncodingUtil
                                        .decodeURIComponent(s.substring("STYLES=".length(), s.length()));
                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("Layer styles = " + styles);
                                }
                            }
                        }
                        final String wmsUrl = serverUrl.substring(0, serverUrl.indexOf('?'));
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("WMS url = " + wmsUrl);
                        }
                        responseBody = FeatureInfoResponseConverter.convertToHTMLTable(
                                get.getEntity().getContent(), type,
                                this.layers.getLayerByLayers(lName, wmsUrl, styles));
                        response.setContentType("text/html; charset=UTF-8");
                    } else {
                        // force the response to have XML content type (WMS
                        // servers generally don't)
                        if (this.forceXmlResponse) {
                            response.setContentType("text/xml");
                        }
                        responseBody = EntityUtils.toString(get.getEntity()).trim();
                    }
                    response.setCharacterEncoding("UTF-8");
                    // in het geval van multi byte chars, bijv 'Skarsterln'
                    // is de lengte incorrect, laat voorlopig maar aan de
                    // container over..
                    // response.setContentLength(responseBody.length());
                    final PrintWriter out = response.getWriter();
                    out.print(responseBody);
                    response.flushBuffer();
                } else {
                    LOGGER.warn("Onverwachte fout(server url=" + serverUrl + "): "
                            + get.getStatusLine().toString());
                    response.sendError(get.getStatusLine().getStatusCode(), get.getStatusLine().toString());
                }
                httpget.reset();
            }
        } else {
            throw new ServletException("Only HTTP(S) protocol is supported");
        }
    } catch (final UnsupportedEncodingException e) {
        LOGGER.error("Proxy fout.", e);
        throw new ServletException(e);
    } catch (final IOException e) {
        LOGGER.error("Proxy IO fout.", e);
        throw new ServletException(e);
    }
}