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:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@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)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // 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  w  w.j a va2  s .c  om
            ArrayList<Long> 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(new Long(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(user.getId(), 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.");
    }
}

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

@RequestMapping(value = "/image/{imageId}/{filename:.+}", method = RequestMethod.GET)
@ResponseBody/*  www .jav a2 s . c om*/
public void handleImage(@PathVariable("imageId") Long imageId, @PathVariable("filename") String filename,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    log.debug(" ------------------------------------------");
    log.debug("imageId:" + imageId);
    log.debug("width:" + width);
    log.debug("height:" + height);
    log.debug("------------------------------------------");
    try {
        if (imageId > 0 && StringUtils.isNotEmpty(filename)) {
            Image image = imageManager.getImage(imageId);
            User user = SecurityHelper.getUser();
            if (hasPermissions(image, user) && StringUtils.equals(filename, image.getName())) {
                InputStream input;
                String contentType;
                int contentLength;
                if (width > 0 && width > 0) {
                    input = imageManager.getImageThumbnailInputStream(image, width, height);
                    contentType = image.getThumbnailContentType();
                    contentLength = image.getThumbnailSize();
                } else {
                    input = imageManager.getImageInputStream(image);
                    contentType = image.getContentType();
                    contentLength = image.getSize();
                }
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                IOUtils.copy(input, response.getOutputStream());
                response.flushBuffer();
            } else {
                throw new NotFoundException();
            }
        } else {
            throw new NotFoundException();
        }
    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected void serviceProxy(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.debugHook = (DebugProxyHook) DebugServiceHookFactory.get().get(Type.PROXY, request, response);
    if (debugHook != null) {
        request = debugHook.getRequestWrapper();
        response = debugHook.getResponseWrapper();
    }//  ww w . j a  va  2s .c o  m
    try {
        try {
            initProxy(request, response);
            try {
                checkRequestAllowed(request);
                String smethod = request.getMethod();
                DefaultHttpClient client = getClient(request, getSocketReadTimeout());
                URI url = getRequestURI(request);
                HttpRequestBase method = createMethod(smethod, url, request);
                if (prepareForwardingMethod(method, request, client)) {
                    HttpResponse clientResponse = executeMethod(client, method);
                    prepareResponse(method, request, response, clientResponse, true);
                }
                response.flushBuffer();
            } catch (Exception e) {
                writeErrorResponse("Unexpected Exception", new String[] { "exception" },
                        new String[] { e.toString() }, response, request);
            } finally {
                termProxy(request, response);
            }
        } catch (Exception e) {
            writeErrorResponse("Unexpected Exception", new String[] { "exception" },
                    new String[] { e.toString() }, response, request);
        }
    } finally {
        if (debugHook != null) {
            debugHook.terminate();
            debugHook = null;
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java

public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String logId = request.getParameter("logId");
    final User userView = getUserView(request);
    if (logId != null && logId.length() != 0) {
        StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId);
        if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) {
            List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>();
            studentTestLogs.add(studentTestLog);
            byte[] data = ReportsUtils.exportToPdfFileAsByteArray(
                    "net.sourceforge.fenixedu.domain.onlineTests.StudentTestLog.checksumReport", null,
                    studentTestLogs);/*from  w w w  .ja  va 2  s.  c o  m*/
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf");
            response.setContentLength(data.length);
            ServletOutputStream writer = response.getOutputStream();
            writer.write(data);
            writer.flush();
            writer.close();
            response.flushBuffer();
            return mapping.findForward("");
        }
    }
    return null;
}

From source file:org.nuxeo.ecm.platform.picture.web.PictureBookManagerBean.java

protected String createZip(List<DocumentModel> documents) throws IOException {

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

    BufferedOutputStream buff = new BufferedOutputStream(response.getOutputStream());
    ZipOutputStream out = new ZipOutputStream(buff);
    out.setMethod(ZipOutputStream.DEFLATED);
    out.setLevel(9);//  ww w . java 2  s.  com
    byte[] data = new byte[BUFFER];
    for (DocumentModel doc : documents) {

        // first check if DM is attached to the core
        if (doc.getSessionId() == null) {
            // refetch the doc from the core
            doc = documentManager.getDocument(doc.getRef());
        }

        // NXP-2334 : skip deleted docs
        if (doc.getCurrentLifeCycleState().equals("delete")) {
            continue;
        }

        BlobHolder bh = doc.getAdapter(BlobHolder.class);
        if (doc.isFolder() && !isEmptyFolder(doc)) {
            addFolderToZip("", out, doc, data);
        } else if (bh != null) {
            addBlobHolderToZip("", out, data, (PictureBlobHolder) bh);
        }
    }
    try {
        out.close();
    } catch (ZipException e) {
        // empty zip file, do nothing
        setFacesMessage("label.clipboard.emptyDocuments");
        return null;
    }
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "clipboard.zip" + "\";");
    response.setContentType("application/gzip");
    response.flushBuffer();
    context.responseComplete();
    return null;
}

From source file:org.fenixedu.academic.ui.struts.action.student.onlineTests.StudentTestsAction.java

public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String logId = request.getParameter("logId");
    final User userView = getUserView(request);
    if (logId != null && logId.length() != 0) {
        StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId);
        if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) {
            List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>();
            studentTestLogs.add(studentTestLog);
            byte[] data = ReportsUtils
                    .generateReport("org.fenixedu.academic.domain.onlineTests.StudentTestLog.checksumReport",
                            null, studentTestLogs)
                    .getData();/*from  ww w  . j a  v a2s. co  m*/
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf");
            response.setContentLength(data.length);
            ServletOutputStream writer = response.getOutputStream();
            writer.write(data);
            writer.flush();
            writer.close();
            response.flushBuffer();
            return mapping.findForward("");
        }
    }
    return null;
}

From source file:org.fao.unredd.portal.ApplicationController.java

@RequestMapping("/layers.json")
public void getLayers(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setContentType("application/json;charset=UTF-8");
    try {//from w w w . j  a  v a2 s .c o  m

        /*
          * Checking whether a custom configuration file has to be requested within an Overview Portal.
          * This feature is useful to upload different custom configuration files (i.e. layers.json) according to the country you want to select
          * within a Regional Portal.
          * 
          * FEATURE:
          * In order to load a specific layers.json, there will be a portals_config/<country_name>/ new dir in the
          * /var/portal/ main directory to host the custom layers.json configuration file. The configuration files available here have a custom
          * syntax defined to fit with the new functionality - i.e. if the portal is for Fiji 
          * Islands the configuration file name will be layers_fiji.json; in order to pick up
          * the right configuration file the head definition will be /portals_config/fiji/layers.json?fiji
          * 
          * @author Alfonsetti
          */
        if (request.getParameterMap().containsKey("fiji")) {
            System.out.println("testfiji");
            response.getWriter().print("layers_json = ");
        } else if (request.getParameterMap().containsKey("jsonp")) {
            response.getWriter().print("layers_json = ");
        }

        response.getWriter().print(setLayerTimes());
        response.flushBuffer();
    } catch (IOException e) {
        logger.error("Error reading file", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.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.exportMultipleToPdfAsByteArray(document);

    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  ww  .  ja  v  a2  s. c  om
    writer.flush();
    writer.close();

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

From source file:com.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

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

    CallContext context = null;//ww w .  j a v  a  2 s. co  m
    try {
        if (METHOD_HEAD.equals(request.getMethod())) {
            request = new HEADHttpServletRequestWrapper(request);
            response = new NoBodyHttpServletResponseWrapper(response);
        } else {
            request = new QueryStringHttpServletRequestWrapper(request);
        }

        // set default headers
        response.addHeader("Cache-Control", "private, max-age=0");
        response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);

        context = createContext(getServletContext(), request, response);
        dispatch(context, request, response);
    } catch (Exception e) {
        if (e instanceof CmisUnauthorizedException) {
            response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
        } else if (e instanceof CmisPermissionDeniedException) {
            if ((context == null) || (context.getUsername() == null)) {
                response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
            } else {
                response.sendError(getErrorCode((CmisPermissionDeniedException) e), e.getMessage());
            }
        } else {
            printError(e, response);
        }
    } finally {
        // we are done.
        response.flushBuffer();
    }
}