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.solarnetwork.node.setup.web.SolarInHttpProxy.java

/**
 * Proxy an HTTP request to SolarIn and return the result on a given HTTP
 * response./*from w ww. ja  v  a  2s  . com*/
 * 
 * @param request
 *        the request to proxy
 * @param response
 *        the response to return the proxy response to
 * @throws IOException
 *         if an IO error occurs
 */
@RequestMapping(value = { "/api/v1/sec/location", "/api/v1/sec/location/price",
        "/api/v1/sec/location/weather" }, method = RequestMethod.GET)
public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String context = request.getContextPath();
    String path = request.getRequestURI();
    if (path.startsWith(context)) {
        path = path.substring(context.length());
    }
    String query = request.getQueryString();
    String url = getIdentityService().getSolarInBaseUrl() + path;
    if (query != null) {
        url += '?' + query;
    }
    String accept = request.getHeader("Accept");
    if (accept == null) {
        accept = ACCEPT_JSON;
    }
    try {
        URLConnection conn = getURLConnection(url, request.getMethod(), accept);
        if (conn instanceof HttpURLConnection) {
            final HttpURLConnection httpConn = (HttpURLConnection) conn;
            for (Map.Entry<String, List<String>> me : httpConn.getHeaderFields().entrySet()) {
                final String headerName = me.getKey();
                if (headerName == null) {
                    continue;
                }
                for (String val : me.getValue()) {
                    response.addHeader(headerName, val);
                }
            }
            final String msg = httpConn.getResponseMessage();
            if (msg != null && !msg.equalsIgnoreCase("OK")) {
                response.sendError(httpConn.getResponseCode(), msg);
            } else {
                response.setStatus(httpConn.getResponseCode());
            }
        }
        FileCopyUtils.copy(conn.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        log.debug("Error proxying SolarIn URL [{}]", url, e);
        response.sendError(502, "Problem communicating with SolarIn: " + e.getMessage());
    }
}

From source file:com.flipkart.aesop.runtime.spring.web.BlockingBootstrapProducerController.java

/**
 * Request handling for metrics snapshot
 *///from  ww w .j  a v a 2s. co m
@RequestMapping(value = { "/metrics-json" }, method = RequestMethod.GET)
public @ResponseBody void metricsJSON(HttpServletRequest request, HttpServletResponse response) {
    try {
        // set appropriate headers for a stream
        response.setHeader("Content-Type", "application/json");
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        BlockingBootstrapServer blockingBootstrapServer = null;
        for (ServerContainer serverContainer : this.runtimeRegistry.getRuntimes()) {
            if (BlockingBootstrapServer.class.isAssignableFrom(serverContainer.getClass())) {
                blockingBootstrapServer = (BlockingBootstrapServer) serverContainer;
                break;
            }
        }
        if (blockingBootstrapServer != null) {
            if (request.getParameterMap().containsKey("full")) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("inbound", blockingBootstrapServer.getInboundEventStatisticsCollector());
                map.put("outbound", blockingBootstrapServer.getOutboundEventStatisticsCollector());
                map.put("http", blockingBootstrapServer.getHttpStatisticsCollector());
                response.getWriter().print(mapper.writeValueAsString(map));
            } else {
                response.getWriter().print(blockingBootstrapServer.getMetricsCollector().getJson());
            }
        } else {
            response.getWriter().println("{}");
        }
        response.flushBuffer();
    } catch (IOException e) {
        logger.info("Client Disconnected: " + request.getSession().getId());
    } catch (Exception e) {
        logger.error("Client Disconnected: " + request.getSession().getId() + " (Unknown Exception)", e);
    }
}

From source file:architecture.ee.web.spring.controller.DownloadController.java

@RequestMapping(value = "/logo/{type}/{name}", method = RequestMethod.GET)
@ResponseBody/*  w w  w  . j av  a  2  s.c  om*/
public void handleLogo(@PathVariable("type") String type, @PathVariable("name") String name,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    try {
        LogoImage image = null;
        if (StringUtils.equals(type, "company")) {
            Company company = companyManager.getCompany(name);
            image = logoManager.getPrimaryLogoImage(company);
        } else if (StringUtils.equals(type, "site")) {
            WebSite site = webSiteManager.getWebSiteByName(name);
            image = logoManager.getPrimaryLogoImage(site);
        }
        if (image != null) {
            InputStream input;
            String contentType;
            int contentLength;
            if (width > 0 && width > 0) {
                input = logoManager.getImageThumbnailInputStream(image, width, height);
                contentType = image.getThumbnailContentType();
                contentLength = image.getThumbnailSize();
            } else {
                input = logoManager.getImageInputStream(image);
                contentType = image.getImageContentType();
                contentLength = image.getImageSize();
            }

            response.setContentType(contentType);
            response.setContentLength(contentLength);
            IOUtils.copy(input, response.getOutputStream());
            response.flushBuffer();
        }

    } catch (Exception e) {
        log.warn(e);
        response.setStatus(301);
        String url = ApplicationHelper.getApplicationProperty("components.download.images.no-logo-url",
                "/images/common/what-to-know-before-getting-logo-design.png");
        response.addHeader("Location", url);
    }
}

From source file:org.fenixedu.academic.ui.struts.action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = (MobilityIndividualApplicationProcess) getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.generateReport(document).getData();

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);//from   w w w.  j a v  a 2  s  . c o m
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

From source file:org.apache.roller.weblogger.ui.struts2.ajax.CommentDataServlet.java

/**
 * Accepts request with comment 'id' parameter and replaces specified
 * comment's content with the content in the request.
 *//*from ww  w .  jav a2  s.com*/
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Weblogger roller = WebloggerFactory.getWeblogger();
    try {
        WeblogEntryManager wmgr = roller.getWeblogEntryManager();
        WeblogEntryComment c = wmgr.getComment(request.getParameter("id"));
        if (c == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            // need post permission to edit comments
            RollerSession rses = RollerSession.getRollerSession(request);
            Weblog weblog = c.getWeblogEntry().getWebsite();
            if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) {
                String content = Utilities.streamToString(request.getInputStream());
                c.setContent(content);
                // don't update the posttime when updating the comment
                c.setPostTime(c.getPostTime());
                wmgr.saveComment(c);
                roller.flush();

                c = wmgr.getComment(request.getParameter("id"));
                content = Utilities.escapeHTML(c.getContent());
                content = WordUtils.wrap(content, 72);
                content = StringEscapeUtils.escapeJavaScript(content);
                String json = "{ id: \"" + c.getId() + "\"," + "content: \"" + content + "\" }";
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("text/html; charset=utf-8");
                response.getWriter().print(json);
                response.flushBuffer();
                response.getWriter().flush();
                response.getWriter().close();
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
        }

    } catch (Exception e) {
        throw new ServletException(e.getMessage());
    }
}

From source file:com.flipkart.aesop.runtime.spring.web.BlockingBootstrapProducerController.java

/**
 * Request handling for metrics stream/*from  w w  w.  j a v  a  2s . c  o  m*/
 */
@RequestMapping(value = { "/metrics-stream" }, method = RequestMethod.GET)
public @ResponseBody void metricsStream(HttpServletRequest request, HttpServletResponse response) {

    try {
        // restrict max concurrency
        if (concurrentConnections.incrementAndGet() > MAX_CONNECTIONS) {
            logger.info("Client refused due to max concurrency reached");
            response.sendError(503, "Max concurrent connections reached: " + MAX_CONNECTIONS);
        } else {
            // find the relay
            BlockingBootstrapServer blockingBootstrapServer = null;
            for (ServerContainer serverContainer : this.runtimeRegistry.getRuntimes()) {
                if (BlockingBootstrapServer.class.isAssignableFrom(serverContainer.getClass())) {
                    blockingBootstrapServer = (BlockingBootstrapServer) serverContainer;
                    break;
                }
            }

            if (blockingBootstrapServer != null) {
                logger.info("Client connected: " + request.getSession().getId());
                // set appropriate headers for a stream
                response.setHeader("Content-Type", "text/event-stream;charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                // loop metrics
                while (true) {
                    response.getWriter()
                            .println("data: " + blockingBootstrapServer.getMetricsCollector().getJson() + "\n");
                    response.flushBuffer();
                    Thread.sleep(blockingBootstrapServer.getMetricsCollector().getRefreshInterval() * 1000);
                }
            } else {
                logger.info("Relay not found!");
                response.sendError(404, "Relay not found!");
            }
        }
    } catch (IOException e) {
        logger.info("Client Disconnected: " + request.getSession().getId());
    } catch (InterruptedException e) {
        logger.info("Client Disconnected: " + request.getSession().getId() + " (Interrupted)");
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        logger.error("Client Disconnected: " + request.getSession().getId() + " (Unknown Exception)", e);
    } finally {
        concurrentConnections.decrementAndGet();
    }

}

From source file:org.dspace.rdf.negotiation.Negotiator.java

public static boolean sendRedirect(HttpServletResponse response, String handle, String extraPathInfo,
        int serialization, boolean redirectHTML) throws IOException {
    if (extraPathInfo == null)
        extraPathInfo = "";

    StringBuilder urlBuilder = new StringBuilder();
    String lang = null;/*from www .j  a  v  a  2 s  .co m*/
    switch (serialization) {
    case (Negotiator.UNSPECIFIED):
    case (Negotiator.WILDCARD): {
        lang = DEFAULT_LANG;
        break;
    }
    case (Negotiator.HTML): {
        lang = "html";
        break;
    }
    case (Negotiator.RDFXML): {
        lang = "rdf";
        break;
    }
    case (Negotiator.TURTLE): {
        lang = "turtle";
        break;
    }
    case (Negotiator.N3): {
        lang = "n3";
        break;
    }
    default: {
        lang = DEFAULT_LANG;
        break;
    }
    }
    assert (lang != null);

    if (StringUtils.isEmpty(handle)) {
        log.warn("Handle is empty, set it to Site Handle.");
        handle = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix")
                + "/0";
    }

    // don't redirect if HTML is requested and content negotiation is done
    // in a ServletFilter, as the ServletFilter should just let the request
    // pass.
    if ("html".equals(lang) && !redirectHTML) {
        return false;
    }

    // as we do content negotiation and we'll redirect the request, we 
    // should send a vary caching so browsers can adopt their caching strategy
    response.setHeader("Vary", "Accept");

    // if html is requested we have to forward to the repositories webui.
    if ("html".equals(lang)) {
        urlBuilder.append(
                DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url"));
        if (!handle.equals(
                DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix")
                        + "/0")) {
            urlBuilder.append("/handle/");
            urlBuilder.append(handle).append("/").append(extraPathInfo);
        }
        String url = urlBuilder.toString();

        log.debug("Will forward to '" + url + "'.");
        response.setStatus(HttpServletResponse.SC_SEE_OTHER);
        response.setHeader("Location", url);
        response.flushBuffer();
        return true;
    }

    // currently we cannot serve statistics as rdf
    if ("statistics".equals(extraPathInfo)) {
        log.info("Cannot send statistics as RDF yet. => 406 Not Acceptable.");
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
        response.flushBuffer();
        return true;
    }

    // load the URI of the dspace-rdf module.
    urlBuilder.append(DSpaceServicesFactory.getInstance().getConfigurationService()
            .getProperty(RDFUtil.CONTEXT_PATH_KEY));
    if (urlBuilder.length() == 0) {
        log.error("Cannot load URL of dspace-rdf module. " + "=> 500 Internal Server Error");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.flushBuffer();
        return true;
    }
    // and build the uri to the DataProviderServlet
    urlBuilder.append("/handle/").append(handle);
    urlBuilder.append("/").append(lang);
    String url = urlBuilder.toString();
    log.debug("Will forward to '" + url + "'.");
    response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    response.setHeader("Location", url);
    response.flushBuffer();
    return true;
}

From source file:cn.lhfei.fu.web.controller.AdminController.java

@RequestMapping(value = "downloadArchive", method = RequestMethod.GET)
public void downloadArchive(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("id") int id) throws IOException {
    try {/*from  w  w w .j  av a 2  s .  co  m*/
        ThesisArchive thesisAtchive = thesisArchiveService.read(id);

        if (null != thesisAtchive) {
            String archivePath = thesisAtchive.getArchivePath();
            String[] separatorPaths = archivePath.split("\\" + File.separator);
            String archiveName = separatorPaths[separatorPaths.length - 1];

            File file = new File(archivePath);
            //String fileName = thesisAtchive.getArchiveName();

            // get your file as InputStream
            InputStream is = new FileInputStream(file);
            response.setContentType("application/image;charset=UTF-8");
            response.setContentLength(new Long(file.length()).intValue());
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + archiveName + "; charset=UTF-8");

            // copy it to response's OutputStream
            org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}

From source file:edu.iastate.airl.semtus.server.UploadServiceController.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // 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
        try {// w  w w .jav  a2s.  c  om
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField())
                    continue;

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName);

                // first clean-up the folder; we want no clutter on the server :-)
                String[] ls = new File(Utils.UPLOAD_DIRECTORY).list();

                for (int idx = 0; idx < ls.length; idx++) {

                    File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]);
                    file.delete();
                }

                if (uploadedFile.createNewFile()) {

                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();

                } else {

                    throw new IOException("The file already exists in repository.");
                }
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}