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:org.italiangrid.storm.webdav.server.MiltonFilter.java

public void doMilton(HttpServletRequest request, HttpServletResponse response) {

    LOG.trace("doMilton: req: {}, res: {}", request, response);

    try {/*from  w  w  w .  ja  va 2 s. co m*/
        // Is this really needed?
        MiltonServlet.setThreadlocals((HttpServletRequest) request, (HttpServletResponse) response);

        Request miltonReq = new StoRMMiltonRequest(request, servletContext);

        Response miltonRes = new io.milton.servlet.ServletResponse(response);
        miltonHTTPManager.process(miltonReq, miltonRes);

    } finally {

        MiltonServlet.clearThreadlocals();

        try {

            response.getOutputStream().flush();
            response.flushBuffer();

        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }

    }

}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_MULTIPART_CONTENT);
        resp.flushBuffer();
        return; // send response
    }//w  w  w . j ava 2 s.c o  m

    FileItemFactory factory = new DiskFileItemFactory();
    List<?> items = null;
    Iterator<?> iter = null;
    FileItem item = null;
    String name = null;
    String libraryId = null;
    String contentId = null;
    String file = null;
    String contentType = null;
    File uploadedFile = null;

    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    }

    // now the downloading begins
    if (items == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_BAD_REQUEST);
        resp.flushBuffer();
        return;
    }

    // first get only parameters
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();

        if (item.getFieldName().equals("libId")) {
            libraryId = item.getString();
        } else if (item.getFieldName().equals("contentId")) {
            contentId = item.getString();
        } else if (item.getFieldName().equals("languageName")) {
            processUploadNewLanguage(items, resp);
            return;
        }
    }
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (!item.isFormField()) {
            name = item.getName();
            int slashindex = name.lastIndexOf('\\');
            if (slashindex > -1) {
                file = name.substring(slashindex + 1, name.length());
            } else {
                file = name.substring(name.lastIndexOf('/') + 1, name.length());
            }

            contentType = getMediaType(name);
            if (contentType == null || contentType.isEmpty()) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                resp.getWriter().print(NedServerResponses.ERROR_WRONG_FILE_TYPE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }

            // FILE PATH CONSISTS OF
            // ROOT - TOMCAT_PATH\webapps\ROOT
            // BASEROOT - PASSED FROM CLIENT - librartId(signifies the catalogue instance)
            // nokiaecd\videos
            // FILENAME - GET FROM CHOSEN FILE

            String directory = createDirectory(libraryId);

            File fDir = new File(directory);
            fDir.getAbsolutePath();
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            file = createFilePath(directory, file);
            String uf = directory + file;
            uploadedFile = new File(uf);

            // //////////////////////////////////////////////
            InputStream uploadedStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(uploadedFile);
            byte[] myarray = new byte[1024];
            int i = 0;
            while ((i = uploadedStream.read(myarray)) != -1) {
                fos.write(myarray, 0, i);
            }
            fos.flush();
            fos.close();
            uploadedStream.close();

            // update database
            try {
                getPosgresConnection().updateContentData(file, contentType, contentId);
            } catch (Exception ex) {
                // TODO delete file
                Logger.getLogger(NedFileUploadServlet.class.getSimpleName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().print(NedServerResponses.ERROR_DATABASE_UPDATE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }
        }
    }

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().print(contentType);
    resp.flushBuffer();
    disconnectPostgres();
}

From source file:eionet.transfer.controller.FileOpsController.java

/**
 * Download a file.//  w ww  . ja v a  2s. c om
 */
@RequestMapping(value = "/download/{file_name}", method = RequestMethod.GET)
public void downloadFile(@PathVariable("file_name") String fileId, HttpServletResponse response)
        throws IOException {

    Upload uploadRec = uploadsService.getById(fileId);
    response.setContentType("application/octet-stream");
    //response.setContentLength(uploadRec.getSize()); // Too small - max 2.1 GB.
    response.setHeader("Content-Length", Long.toString(uploadRec.getSize()));
    response.setHeader("Content-Disposition", "attachment; filename=" + uploadRec.getFilename());

    InputStream is = uploadRec.getContentAsStream();
    org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
    is.close();
    deleteExpired();
}

From source file:pdl.web.service.common.FileService.java

public Map<String, String> downloadFile(String fileId, HttpServletResponse res, String username) {
    //TODO check user permission for downloading a file
    Map<String, String> rtnJson = new TreeMap<String, String>();
    try {//  w w  w  .j  a v a  2  s  . c o  m
        String filePath = this.getFilePathById(fileId);
        if (filePath != null && !filePath.isEmpty() && ToolPool.canReadFile(filePath)) {
            String fileName = fileId.concat(".json");
            res.setContentType("application/json");
            res.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            IOUtils.copy(new FileInputStream(filePath), res.getOutputStream());
            res.flushBuffer();
            rtnJson.put("file name", fileName);
        }
    } catch (Exception ex) {
        rtnJson.put("error", "Downloading file failed");
        rtnJson.put("message", ex.toString());
    }

    return rtnJson;
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo(); //$NON-NLS-1$

    if (pathInfo.startsWith("/form")) { //$NON-NLS-1$
        try {//from w w w  .j a  v a2  s  . c  o m
            if (FormAuthHelper.performAuthentication(req, resp)) {
                if (req.getParameter(OpenIdHelper.REDIRECT) != null
                        && !req.getParameter(OpenIdHelper.REDIRECT).equals("")) { //$NON-NLS-1$
                    resp.sendRedirect(req.getParameter(OpenIdHelper.REDIRECT));
                } else {
                    resp.flushBuffer();
                }
            } else {
                // 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$

                String invalidLoginError = "Invalid user or password";

                if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$
                    RequestDispatcher rd = req.getRequestDispatcher(
                            "/mixlogin?error=" + new String(Base64.encode(invalidLoginError.getBytes()))); //$NON-NLS-1$
                    rd.include(req, resp);
                } else {
                    PrintWriter writer = resp.getWriter();
                    JSONObject jsonError = new JSONObject();
                    try {
                        jsonError.put("error", invalidLoginError); //$NON-NLS-1$
                        writer.print(jsonError);
                        resp.setContentType("application/json"); //$NON-NLS-1$
                    } catch (JSONException e) {/* ignore */
                    }
                    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                }
                resp.flushBuffer();
            }
        } catch (UnsupportedUserStoreException e) {
            LogHelper.log(e);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        }
        return;
    }

    if (pathInfo.startsWith("/openid")) { //$NON-NLS-1$
        String openid = req.getParameter(OpenIdHelper.OPENID);
        if (openid != null) {
            consumer = OpenIdHelper.redirectToOpenIdProvider(req, resp, consumer);
            return;
        }

        String op_return = req.getParameter(OpenIdHelper.OP_RETURN);
        if (op_return != null) {
            OpenIdHelper.handleOpenIdReturn(req, resp, consumer);
            return;
        }
    }

    String user;
    if ((user = authenticationService.getAuthenticatedUser(req, resp,
            authenticationService.getDefaultAuthenticationProperties())) != null) {
        resp.setStatus(HttpServletResponse.SC_OK);
        try {
            JSONObject array = new JSONObject();
            array.put("login", user); //$NON-NLS-1$
            resp.getWriter().print(array.toString());
        } catch (JSONException e) {
            handleException(resp, "An error occured when creating JSON object for logged in user", e);
        }
        return;
    }
}

From source file:org.kaaproject.avro.ui.sandbox.services.FileUploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String jsonKey = request.getParameter(JSON_KEY);
    String fileName = request.getParameter(FILE_NAME);
    if (jsonKey != null && fileName != null) {
        try (OutputStream os = response.getOutputStream()) {
            response.setContentType("application/json");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            byte[] content = jsonCacheService.getJson(jsonKey).getBytes();
            os.write(content, 0, content.length);
            logger.debug("Returning text file with name '{}'", fileName);
            response.flushBuffer();
        } catch (IOException e) {
            logger.error("Unexpected error in FileUploadServlet.doGet: ", e);
            throw new RuntimeException(e);
        }/*from  w ww . ja  v  a2  s .co m*/
    } else {
        logger.error("Empty parameter with file content in get file request!");
        throw new RuntimeException("Empty parameter with file content in get file request!");
    }
}

From source file:com.casker.portfolio.controller.FileController.java

/**
 *  //from ww  w  .j a v  a2  s .  c o m
 * 
 * @return
 */
@ResponseBody
@RequestMapping("/portfolio/{portfolioNo}/{imageType}")
public void editPassword(HttpServletResponse response, @PathVariable long portfolioNo,
        @PathVariable String imageType) throws Exception {

    Portfolio portfolio = portfolioService.getPortfolioDetail(portfolioNo);

    File file = portfolioService.getImageFile(portfolio, imageType);

    response.setContentLength((int) file.length());

    String fileName = URLEncoder.encode(file.getName(), "utf-8");

    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
    response.setHeader("Content-Transfer-Encoding", "binary");

    InputStream inputStream = new FileInputStream(file);
    IOUtils.copy(inputStream, response.getOutputStream());
    IOUtils.closeQuietly(inputStream);

    response.flushBuffer();
}

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

@RequestMapping(value = "/export", method = RequestMethod.POST)
public void exportProxy(@RequestParam(value = "fileName", required = true) String fileName,
        @RequestParam(value = "contentType", required = true) String contentType,
        @RequestParam(value = "base64", required = true) String base64, HttpServletResponse response)
        throws IOException {

    byte[] content = Base64.decodeBase64(base64);
    response.setContentType(contentType);
    response.setContentLength(content.length);
    response.setHeader("ContentDisposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    response.getOutputStream().write(content);
    response.flushBuffer();
}

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

@RequestMapping(value = "/streams/photo/{linkId}", method = RequestMethod.GET)
@ResponseBody/* ww w .  j  a v a2 s.c  o m*/
public void handleStreamPhoto(@PathVariable("linkId") String linkId, HttpServletResponse response)
        throws IOException {

    try {
        Photo photo = photoStreamsManager.getPhotoById(linkId);
        Image image = imageManager.getImage(photo.getImageId());
        InputStream input = imageManager.getImageInputStream(image);
        String contentType = image.getContentType();
        int contentLength = image.getSize();

        response.setContentType(contentType);
        response.setContentLength(contentLength);
        IOUtils.copy(input, response.getOutputStream());
        response.flushBuffer();
    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:com.google.code.pathlet.web.json.JsonResponseProcessor.java

public boolean processResult(Path requestPath, Object returnResult, HttpServletResponse response)
        throws JsonResourceIOException {
    response.setContentType("text/plain");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache, must-revalidate");

    try {//  ww w.  j a  v  a2  s .co m

        if (returnResult != null) {
            if (String.class.isAssignableFrom(returnResult.getClass())) {
                //If returnResult is String, it will not convert into JSON, but directly write into response writer.
                response.getWriter().write((String) returnResult);
            } else {
                writeResult(response.getWriter(), returnResult);
            }
        }

        response.flushBuffer();
    } catch (Exception e) {
        throw new JsonResourceIOException(e);
    }

    return false;
}