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:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/downloadSubscriptionBillingActivityDetail", method = RequestMethod.GET)
public void downloadSubscriptionBillingActivityDetail(
        @RequestParam(value = "billingActivityId", required = true) final String billingActivityId,
        final HttpServletResponse response) {
    try {/*from   ww  w . j  av a 2  s. c  om*/
        final SubscriptionBillingDetailFileStream fileStream = subscriptionFacade
                .getBillingActivityDetail(billingActivityId, MapUtils.EMPTY_MAP);

        response.setContentType(fileStream.getMimeType());
        response.setHeader("Content-Disposition", "attachment; filename=" + fileStream.getFileName());

        IOUtils.copy(fileStream.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    } catch (final SubscriptionFacadeException | IOException e) {
        LOG.warn(
                String.format("Download of details for billing activity with id %s failed.", billingActivityId),
                e);
    }

}

From source file:org.apache.accumulo.monitor.servlets.OperationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Verify that this is the active Monitor instance
    if (!isActiveMonitor()) {
        resp.sendError(HttpURLConnection.HTTP_UNAVAILABLE, STANDBY_MONITOR_MESSAGE);
        return;// w w  w  . j a va 2 s  . com
    }
    String redir = null;
    List<Cookie> cookiesToSet = Collections.emptyList();
    try {
        String operation = req.getParameter("action");
        redir = req.getParameter("redir");

        if (operation != null) {
            for (Class<?> subclass : OperationServlet.class.getClasses()) {
                Object t;
                try {
                    t = subclass.newInstance();
                } catch (Exception e) {
                    continue;
                }
                if (t instanceof WebOperation) {
                    WebOperation op = (WebOperation) t;
                    if (op.getClass().getSimpleName().equalsIgnoreCase(operation + "Operation")) {
                        cookiesToSet = op.execute(req, log);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.error(t, t);
    } finally {
        try {
            for (Cookie c : cookiesToSet) {
                resp.addCookie(c);
            }
            resp.sendRedirect(sanitizeRedirect(redir));
            resp.flushBuffer();
        } catch (Throwable t) {
            log.error(t, t);
        }
    }
}

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

private void writeException(final Exception e, final HttpServletResponse response, final boolean noBody)
        throws IOException {

    LOGGER.error("An exception was thrown during request processing.", e);

    response.setContentType(ContentType.TEXT_PLAIN.toString());
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    if (!noBody) {
        // NullPointerExceptions don't have messages.
        if (null != e.getMessage()) {
            response.setContentLength(e.getMessage().length());

            final OutputStream responseOut = response.getOutputStream();

            if (responseOut != null) {
                IOUtils.write((e.getMessage()), responseOut);
                responseOut.flush();/*from   w w  w . j a  v a2 s.com*/
                responseOut.close();
            }
        }
    }

    response.flushBuffer();
}

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

/**
 * Request handling for metrics stream/*from  w w  w . j av a  2s .com*/
 */
@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
            DefaultRelay relay = null;
            for (ServerContainer serverContainer : this.runtimeRegistry.getRuntimes()) {
                if (DefaultRelay.class.isAssignableFrom(serverContainer.getClass())) {
                    relay = (DefaultRelay) serverContainer;
                    break;
                }
            }

            if (relay != 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: " + relay.getMetricsCollector().getJson() + "\n");
                    response.flushBuffer();
                    Thread.sleep(relay.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:architecture.ee.web.spring.controller.DownloadController.java

@RequestMapping(value = "/file/{attachmentId}/{filename:.+}", method = RequestMethod.GET)
@ResponseBody/*ww  w  . java2 s .  c  o  m*/
public void handleFile(@PathVariable("attachmentId") Long attachmentId,
        @PathVariable("filename") String filename,
        @RequestParam(value = "thumbnail", defaultValue = "false", required = false) boolean thumbnail,
        @RequestParam(value = "width", defaultValue = "150", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "150", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    log.debug(" ------------------------------------------");
    log.debug("attachment:" + attachmentId);
    log.debug("filename:" + filename);
    log.debug("thumbnail:" + thumbnail);
    log.debug("------------------------------------------");
    try {
        if (attachmentId > 0 && StringUtils.isNotEmpty(filename)) {
            Attachment attachment = attachmentManager.getAttachment(attachmentId);
            if (StringUtils.equals(filename, attachment.getName())) {

                if (thumbnail) {
                    if (StringUtils.startsWithIgnoreCase(attachment.getContentType(), "image")
                            || StringUtils.endsWithIgnoreCase(attachment.getContentType(), "pdf")) {
                        InputStream input = attachmentManager.getAttachmentImageThumbnailInputStream(attachment,
                                width, height);
                        response.setContentType(attachment.getThumbnailContentType());
                        response.setContentLength(attachment.getThumbnailSize());
                        IOUtils.copy(input, response.getOutputStream());
                        response.flushBuffer();
                    }
                } else {
                    InputStream input = attachmentManager.getAttachmentInputStream(attachment);
                    response.setContentType(attachment.getContentType());
                    response.setContentLength(attachment.getSize());
                    IOUtils.copy(input, response.getOutputStream());
                    response.setHeader("contentDisposition",
                            "attachment;filename=" + getEncodedFileName(attachment));
                    response.flushBuffer();
                }
            } else {
                throw new NotFoundException();
            }
        } else {
            throw new NotFoundException();
        }
    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:com.talis.platform.testsupport.VerifyableHandler.java

@Override
public void handle(final String target, final HttpServletRequest req, final HttpServletResponse resp,
        final int dispatch) throws IOException, ServletException {
    try {/*from   w  w  w  .j a va 2 s  . co m*/
        StubCallDefn defn = getExpectedCallDefn(target, req);
        if (defn == null) {
            assertionLog.append(String.format("Unexpected call: %s %s\n", req.getMethod(), target));
            fail("fail test, no more handlers");
        }

        assertEquals(defn.getExpectedPath(), target);
        assertEquals(defn.getExpectedMethod(), req.getMethod());

        BufferedReader reader = req.getReader();

        String entity = IOUtils.toString(reader);
        assertEquals(defn.getExpectedEntity(), entity);

        for (String key : defn.getHeaders().keySet()) {
            String expected = defn.getHeaders().get(key);
            String value = req.getHeader(key);
            assertEquals("Headers don't match for header " + key, expected, value);
        }

        resp.setStatus(defn.getExpectedReturnStatus());
        resp.setHeader("Content-Type", defn.getExpectedReturnType());
        Map<String, String> returnHeaders = defn.getReturnHeaders();
        if (null != returnHeaders) {
            for (Entry<String, String> header : returnHeaders.entrySet()) {
                resp.setHeader(header.getKey(), header.getValue());
            }
        }

        byte[] expectedReturnEntity = defn.getExpectedReturnEntity();
        if (expectedReturnEntity != null) {
            resp.getOutputStream().write(expectedReturnEntity);
        }
        resp.flushBuffer();
    } catch (RuntimeException t) {
        isOk.set(false);
        assertionLog.append(t.getStackTrace());
        assertionLog.append('\n');
        throw t;
    } catch (Error t) {
        isOk.set(false);
        assertionLog.append(t.getMessage());
        assertionLog.append('\n');
        throw t;
    }
}

From source file:org.eclipse.orion.server.authentication.formopenid.FormOpenIdLoginServlet.java

private void displayError(String error, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // redirection from
    // FormAuthenticationService.setNotAuthenticated
    String versionString = req.getHeader("Orion-Version"); //$NON-NLS-1$
    Version version = versionString == null ? null : new Version(versionString);

    // TODO: This is a workaround for calls
    // that does not include the WebEclipse version header
    String xRequestedWith = req.getHeader("X-Requested-With"); //$NON-NLS-1$

    if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$
        String url = "/mixloginstatic/LoginWindow.html";
        if (req.getParameter("redirect") != null) {
            url += "?redirect=" + req.getParameter("redirect");
        }// ww w  .j av a 2  s .  c  om

        if (error == null) {
            error = "Invalid login";
        }
        url += url.contains("?") ? "&" : "?";
        url += "error=" + new String(Base64.encode(error.getBytes()));

        resp.sendRedirect(url);

    } else {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = resp.getWriter();
        JSONObject jsonError = new JSONObject();
        try {
            jsonError.put("error", error); //$NON-NLS-1$
            writer.print(jsonError);
            resp.setContentType("application/json"); //$NON-NLS-1$
        } catch (JSONException e) {/* ignore */
        }
    }
    resp.flushBuffer();
}

From source file:com.alexkli.osgi.troubleshoot.impl.TroubleshootServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String action = WebConsoleUtil.getParameter(request, "action");
    if ("startInactiveBundles".equals(action)) {
        startActionResponse(request, response);

        PrintWriter out = response.getWriter();
        int bundlesTouched = 0;
        int bundlesActive = 0;

        final Bundle[] bundles = getBundleContext().getBundles();
        for (Bundle bundle : bundles) {
            if (isFragmentBundle(bundle)) {
                continue;
            }//from  w  ww  .j ava 2  s . c  o  m
            if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.INSTALLED) {
                bundlesTouched++;

                try {
                    out.printf("Trying to start %s (%s)... ", bundle.getSymbolicName(),
                            getStatusString(bundle));
                    response.flushBuffer();

                    bundle.start(Bundle.START_TRANSIENT);

                    bundlesActive += 1;

                    out.printf("<span class='log-ok'>OK: %s.</span>", getStatusString(bundle));

                } catch (BundleException e) {
                    out.printf("<span class='ui-state-error-text'>Failed:</span> %s", e.getMessage());
                } catch (IllegalStateException e) {
                    out.printf("<span class='ui-state-error-text'>Failed, state changed:</span> %s",
                            e.getMessage());
                } catch (SecurityException e) {
                    out.printf("<span class='ui-state-error-text'>Denied:</span> %s", e.getMessage());
                }

                out.println("<br/>");
                insertScrollScript(out);
                response.flushBuffer();
            }
        }

        out.println("<br/>");
        if (bundlesTouched == 0) {
            out.println("<span class='log-end'>No installed or resolved bundles found</span><br/>");
        } else {
            out.printf("<span class='log-end'>Successfully started %s out of %s bundles.</span><br/>",
                    bundlesActive, bundlesTouched);
        }

        insertScrollScript(out);
        endActionResponse(response);
    }
}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws 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 {//from w  ww .j  a va  2  s  . c  om
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}