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.itsvs.cwtrpc.security.RpcRedirectStrategy.java

public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    final String responseText;

    responseText = createResponseText(request, response, url);

    response.reset();/*w w  w.  j  a  v  a 2 s.c  om*/
    addNoCacheResponseHeaders(request, response);
    if (isError()) {
        if (log.isDebugEnabled()) {
            log.debug("Instead of redirecting to url '" + url + "' error " + getStatusCode()
                    + " will be sent to client");
        }
        if (responseText.length() > 0) {
            response.sendError(getStatusCode(), responseText);
        } else {
            response.sendError(getStatusCode());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Instead of redirecting to url '" + url + "' status code will be set to "
                    + getStatusCode());
        }
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(CHARACTER_ENCODING);
        response.setStatus(getStatusCode());
        writeResponseText(request, response, CHARACTER_ENCODING, url);
        response.flushBuffer();
    }
}

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

void writeVoid(final HttpServletResponse response) throws IOException {

    // TODO//  ww w  .  ja v  a 2s .c  o  m

    /*
     * Writing no entity body in the response may be perfectly fine...depending on the intent of the request (method, desired schema, etc), which is expressed in the
     * intendedResponseDimensions.
     */

    // TODO
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentLength(0);
    response.flushBuffer();
}

From source file:edu.dfci.cccb.mev.controllers.HeatmapController.java

@RequestMapping(value = "/{id}/analysis/limma({dimension},{experiment},{control})/{output}", method = { GET,
        HEAD })/*  w ww.j  a va2  s. co m*/
@ResponseStatus(OK)
public void limma(@PathVariable("id") String id, @PathVariable("experiment") String experiment,
        @PathVariable("control") String control, @PathVariable("output") String output,
        @PathVariable("dimension") String dimension, HttpServletResponse response)
        throws HeatmapNotFoundException, IOException, InvalidDimensionException {
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment;filename=" + output + ".txt");
    Heatmap heatmap = get(id);
    File limma;
    if (isRow(dimension)) {
        limma = heatmap.limmaRows(experiment, control, LimmaOutput.valueOf(output.toUpperCase()));
    } else if (isColumn(dimension)) {
        limma = heatmap.limmaColumns(experiment, control, LimmaOutput.valueOf(output.toUpperCase()));
    } else
        throw new InvalidDimensionException(dimension);
    IOUtils.copy(new FileInputStream(limma), response.getOutputStream());
    response.flushBuffer();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.lists.StudentsListByCurricularCourseDA.java

public ActionForward downloadStatistics(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    ExecutionYear executionYear = getDomainObject(request, "executionYearId");
    Set<Degree> degreesToInclude = AcademicAuthorizationGroup.getDegreesForOperation(AccessControl.getPerson(),
            AcademicOperationType.STUDENT_LISTINGS);

    final String filename = getResourceMessage("label.statistics") + "_"
            + executionYear.getName().replace('/', '-');
    final Spreadsheet spreadsheet = new Spreadsheet(filename);
    addStatisticsHeaders(spreadsheet);//from   ww  w .j a v  a 2 s  .  c o  m
    addStatisticsInformation(spreadsheet, executionYear, degreesToInclude);

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
    ServletOutputStream writer = response.getOutputStream();

    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();

    return null;
}

From source file:org.kuali.mobility.database.controllers.DatabaseController.java

@RequestMapping(method = RequestMethod.POST, params = "download")
public String getSchemaDownload(HttpServletRequest request, Model uiModel,
        @ModelAttribute("form") DatabaseSchemaOutputForm form, BindingResult result,
        HttpServletResponse response) {
    String viewName;// w  w w  .ja v  a2  s.c  om
    if (!isAllowedAccess("KME-ADMINISTRATORS", request)) {
        viewName = "redirect:/errors/401.jsp";
        LOG.info("Redirecting to: " + viewName);
        return viewName;
    }

    DatabaseSchemaOutputFormValidator validator = new DatabaseSchemaOutputFormValidator();
    validator.validate(form, result);

    if (result.hasErrors()) {
        uiModel.addAttribute("dialectTypes", dialectTypes);
        return "database/schemaoutputform";
    } else {
        try {
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename=schema.ddl");
            String schema = this.getSchema(form.getDialectType(), form.getDelimiter(),
                    form.isNewLineBeforeDelimiter(), form.isRemoveForeignKeys());
            InputStream is = new ByteArrayInputStream(schema.getBytes("UTF-8"));
            IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            // log.info("Error writing file to output stream. Filename was '" +
            // fileName + "'");
            throw new RuntimeException("IOError writing file to output stream");
        }
        return null;
    }
}

From source file:edu.jhu.cvrg.ceptools.main.SearchPubs.java

public void downloadFile(String filename, String filetype) {

    String contentType = "application/zip";

    if (filetype.equals("abf")) {
        contentType = "text/abf";
    }//from w w  w  .  jav a2 s.c o  m

    FacesContext facesContext = (FacesContext) FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    File file = new File(selecteddownloadfile.getFilelocation(), filename);
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        input = new BufferedInputStream(new FileInputStream(file), 10240);

        response.reset();
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.flushBuffer();
        output = new BufferedOutputStream(response.getOutputStream(), 10240);

        byte[] buffer = new byte[10240];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        output.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    facesContext.responseComplete();

}

From source file:org.ngrinder.infra.spring.ApiExceptionHandlerResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {//from   ww  w  .  j  a va  2 s  .c o  m
    if (!(handler instanceof HandlerMethod)) {
        return null;
    }

    RestAPI methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(RestAPI.class);
    if (methodAnnotation == null) {
        return null;
    }
    JsonObject object = new JsonObject();
    object.addProperty(JSON_SUCCESS, false);
    object.addProperty(JSON_CAUSE, ex.getMessage());
    StringWriter out = new StringWriter();
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable throwable = ExceptionUtils.sanitize(ex);
    PrintWriter printWriter = new PrintWriter(out);
    throwable.printStackTrace(printWriter);
    object.addProperty(JSON_STACKTRACE, out.toString());
    IOUtils.closeQuietly(printWriter);
    String jsonMessage = gson.toJson(object);
    try {
        response.setStatus(500);
        response.setContentType("application/json; charset=UTF-8");
        response.addHeader("Pragma", "no-cache");
        PrintWriter writer = response.getWriter();
        writer.write(jsonMessage);
        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.error("Exception was occurred while processing api exception.", e);
    }
    return new ModelAndView();
}

From source file:com.comcast.cmb.common.controller.EndpointServlet.java

protected void doChart(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pathInfo = request.getPathInfo();
    String id = pathInfo.substring(pathInfo.lastIndexOf("/") + 1);

    EndpointMetrics metrics = metricsMap.get(id);

    if (metrics != null) {

        byte b[] = generateChart(metrics, id);

        response.setContentLength(b.length);
        response.setContentType("image/jpeg");
        response.getOutputStream().write(b);
        response.flushBuffer();

    } else {/*ww w . java 2  s .  c o  m*/
        doOutput(404, response, "EndPoint - Chart", "Page not found");
    }
}

From source file:org.dataconservancy.dcs.ingest.ui.server.FileUploadServlet.java

private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp)
        throws IOException {
    File tmp = null;//from   w  w w  .j  av a 2  s. c o  m
    FileOutputStream fos = null;
    PostMethod post = null;

    //System.out.println(filename + " -> " + depositurl);

    try {
        tmp = File.createTempFile("fileupload", null);
        fos = new FileOutputStream(tmp);
        FileUtil.copy(is, fos);

        HttpClient client = new HttpClient();

        post = new PostMethod(depositurl);

        Part[] parts = { new FilePart(filename, tmp) };

        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) {
            resp.setStatus(status);

            String src = post.getResponseHeader("X-dcs-src").getValue();
            String atomurl = post.getResponseHeader("Location").getValue();

            resp.setContentType("text/html");
            resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>");
            resp.flushBuffer();
        } else {
            resp.sendError(status, post.getStatusText());
            return;
        }
    } finally {
        if (tmp != null) {
            tmp.delete();
        }

        if (is != null) {
            is.close();
        }

        if (fos != null) {
            fos.close();
        }

        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java

/**
 * prepares render process and gets IView2 file and combines tiles.
 * The image dimensions and path are determined from {@link HttpServletRequest#getPathInfo()}:
 * <code>/{zoomAlias}/{derivateID}/{absoluteImagePath}</code>
 * where <code>zoomAlias</code> is mapped like this:
 * <table>//from  w w  w  . j av  a 2  s  .  c o  m
 * <caption>Mapping of zoomAlias to actual zoom level</caption>
 * <tr><th>zoomAlias</th><th>zoom level</th></tr>
 * <tr><td>'MIN'</td><td>1</td></tr>
 * <tr><td>'MID'</td><td>2</td></tr>
 * <tr><td>'MAX'</td><td>3</td></tr>
 * <tr><td>default and all others</td><td>0</td></tr>
 * </table>
 * 
 * See {@link #init()} how to attach a footer to every generated image.
 */
@Override
protected void think(final MCRServletJob job) throws IOException, JDOMException {
    final HttpServletRequest request = job.getRequest();
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith("/")) {
            pathInfo = pathInfo.substring(1);
        }
        String zoomAlias = pathInfo.substring(0, pathInfo.indexOf('/'));
        pathInfo = pathInfo.substring(zoomAlias.length() + 1);
        final String derivate = pathInfo.substring(0, pathInfo.indexOf('/'));
        String imagePath = pathInfo.substring(derivate.length());
        LOGGER.info("Zoom-Level: " + zoomAlias + ", derivate: " + derivate + ", image: " + imagePath);
        final Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, imagePath);
        try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) {
            Path iviewFileRoot = fs.getRootDirectories().iterator().next();
            final MCRTiledPictureProps pictureProps = MCRTiledPictureProps
                    .getInstanceFromDirectory(iviewFileRoot);
            final int maxZoomLevel = pictureProps.getZoomlevel();
            request.setAttribute(THUMBNAIL_KEY, iviewFile);
            LOGGER.info("IView2 file: " + iviewFile);
            int zoomLevel = 0;
            switch (zoomAlias) {
            case "MIN":
                zoomLevel = 1;
                break;
            case "MID":
                zoomLevel = 2;
                break;
            case "MAX":
                zoomLevel = 3;
                break;
            }
            HttpServletResponse response = job.getResponse();
            if (zoomLevel > maxZoomLevel) {
                switch (maxZoomLevel) {
                case 2:
                    zoomAlias = "MID";
                    break;
                case 1:
                    zoomAlias = "MIN";
                    break;
                default:
                    zoomAlias = "THUMB";
                    break;
                }
                if (!imagePath.startsWith("/"))
                    imagePath = "/" + imagePath;
                String redirectURL = response.encodeRedirectURL(MessageFormat.format("{0}{1}/{2}/{3}{4}",
                        request.getContextPath(), request.getServletPath(), zoomAlias, derivate, imagePath));
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                response.setHeader("Location", redirectURL);
                response.flushBuffer();
                return;
            }
            if (zoomLevel == 0 && footerImpl == null) {
                //we're done, sendThumbnail is called in render phase
                return;
            }
            ImageReader reader = MCRIView2Tools.getTileImageReader();
            try {
                BufferedImage combinedImage = MCRIView2Tools.getZoomLevel(iviewFileRoot, pictureProps, reader,
                        zoomLevel);
                if (combinedImage != null) {
                    if (footerImpl != null) {
                        BufferedImage footer = footerImpl.getFooter(combinedImage.getWidth(), derivate,
                                imagePath);
                        combinedImage = attachFooter(combinedImage, footer);
                    }
                    request.setAttribute(IMAGE_KEY, combinedImage);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            } finally {
                reader.dispose();
            }
        }

    } finally {
        LOGGER.info("Finished sending " + request.getPathInfo());
    }
}