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.commonfarm.web.ECSideFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (isAJAXRequest(request)) {
        doAjaxFilter(request, response, chain);
        return;// w ww  .  jav a 2s  .  co  m
    }

    doEncoding(request, response);

    String easyListName = getEasyList(request);
    String easyDataAccessName = getEasyDataAccess(request);
    String easyDataExport = getEasyDataExport(request);

    Context context = new HttpServletRequestContext(request);
    boolean isExported = ExportFilterUtils.isExported(context);

    if (isExported) {
        doExportFilter(request, response, chain, context);
        return;
    }

    if (StringUtils.isNotBlank(easyDataExport)) {
        String sqlName = getSqlName(request);
        String fileName = getFileName(request);
        String type = fileName.substring(fileName.indexOf('.') + 1);
        try {
            setResponseHeaders(request, response, fileName);

            response.flushBuffer();
            response.getOutputStream().flush();
            // response.setBufferSize(8192);
            // System.out.println("======response buffer size :
            // "+response.getBufferSize());
            easyDataAccessHandler.exportList(getDataExportModelBean(request, easyDataExport), sqlName, type,
                    request, response);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            // TODO :
        }
        return;
    }

    if (StringUtils.isNotBlank(easyListName)) {
        easyDataAccessHandler.easyList(request, response, getEasyListModelBean(request, easyListName));
    } else if (StringUtils.isNotBlank(easyDataAccessName)) {
        String sqlName = getSqlName(request);
        easyDataAccessHandler.dataAccess(getDataAccessModelBean(request, easyDataAccessName), sqlName, request,
                response);
    }
    chain.doFilter(request, response);

}

From source file:org.nsesa.editor.gwt.an.amendments.server.service.PdfExportService.java

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".pdf");
    response.setCharacterEncoding("UTF8");
    final String content = object.getBody();
    final InputSource inputSource;
    byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
    inputSource = new InputSource(new ByteArrayInputStream(bytes));

    try {/* w  w w  .  j  a v a 2  s  .c  om*/
        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(sw.toString(), editorUrl + "/");
        renderer.layout();
        renderer.createPDF(response.getOutputStream());
        response.setContentLength(sw.toString().length());
        response.flushBuffer();

    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    } catch (DocumentException e) {
        throw new RuntimeException("Export to pdf failed", e);
    }

}

From source file:fedora.server.security.servletfilters.FilterEnforceAuthn.java

@Override
public boolean doThisSubclass(ExtendedHttpServletRequest request, HttpServletResponse response)
        throws Throwable {
    String method = "doThisSubclass() ";
    if (log.isDebugEnabled()) {
        log.debug(enter(method));/*ww  w .j a  v a2s  . c om*/
    }
    super.doThisSubclass(request, response);
    request.lockWrapper();

    boolean terminateServletFilterChain = request.getUserPrincipal() == null;
    if (terminateServletFilterChain) {
        if (log.isDebugEnabled()) {
            log.debug(format(method, "no principal found, sending 401"));
        }
        String realm = "fedora";
        String value = "BASIC realm=\"" + realm + "\"";
        String name = "WWW-Authenticate";
        int sc = HttpServletResponse.SC_UNAUTHORIZED;
        response.reset();
        //httpServletResponse.sendError(sc, "supply credentials"); //same as after
        if (response.containsHeader(name)) {
            response.setHeader(name, value);
        } else {
            response.addHeader(name, value);
        }
        try {
            response.sendError(sc, "supply credentials");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } //here, no bad auth msg at wget
        response.setContentType("text/plain");
        try {
            response.flushBuffer();
        } catch (IOException e) {
            showThrowable(e, log, "response flush error");
        }
    }
    return terminateServletFilterChain;
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response,
        Resource resource) throws IOException {
    if (!request.getMethod().equals(HttpRequest.__HEAD)
            && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) {
        // If we have meta data for the file
        // Try a direct match for most common requests. Avoids
        // parsing the date.
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
        if (metaData != null) {
            String ifms = request.getHeader(HttpFields.__IfModifiedSince);
            String mdlm = metaData.getLastModified();
            if (ifms != null && mdlm != null && ifms.equals(mdlm)) {
                response.reset();//from w w  w .  j a v  a 2  s  .  c  o  m
                response.setStatus(HttpResponse.__304_Not_Modified);
                response.flushBuffer();
                return false;
            }
        }

        long date = 0;
        // Parse the if[un]modified dates and compare to resource

        if ((date = request.getDateHeader(HttpFields.__IfUnmodifiedSince)) > 0) {
            if (resource.lastModified() / 1000 > date / 1000) {
                response.sendError(HttpResponse.__412_Precondition_Failed);
                return false;
            }
        }

        if ((date = request.getDateHeader(HttpFields.__IfModifiedSince)) > 0) {
            if (resource.lastModified() / 1000 <= date / 1000) {
                response.reset();
                response.setStatus(HttpResponse.__304_Not_Modified);
                response.flushBuffer();
                return false;
            }
        }
    }
    return true;
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

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

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = RequestMethod.POST)
public void exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
        HttpServletRequest request) throws ServletException, IOException, InterruptedException,
        SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

    long start1 = System.currentTimeMillis();

    MimeType mime = getMime(type);
    filename = getFilename(filename);/*from  www.j  av a  2 s  .  c  o  m*/
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    String inputs;

    boolean convertSvg = false;

    // Create return JSON object
    JSONObject jobj = new JSONObject();

    if (options != null) {
        // create a svg file out of the options
        inputs = options;
        callback = sanitize(callback);
    } else {
        jobj.put("status", -1);
        jobj.put("msg", "The svg POST is not supported.");
        response.reset();
        response.setContentType("application/json");
        response.getWriter().print(jobj);
        response.flushBuffer();
        return;
    }

    String[] inputList = inputs.split("!#!");
    String input;

    ByteArrayOutputStream stream = null;
    //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);

    String fileList = "";
    String chartFilename = "";
    for (int i = 0; i < inputList.length; i++) {
        input = inputList[i];
        stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);

        if (stream == null) {
            //throw new ServletException("Error while converting");
            jobj.put("status", -1);
            jobj.put("msg", "Error while converting.");
            response.reset();
            response.setContentType("application/json");
            response.getWriter().print(jobj);
            response.flushBuffer();
            return;
        }

        logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

        // Now Save the it to file. And return the path.
        String uuid = UUID.randomUUID().toString();
        String extension = ".png";
        if (mime.compareTo(MimeType.JPEG) == 0) {
            extension = ".jpg";
        } else if (mime.compareTo(MimeType.PDF) == 0) {
            extension = ".pdf";
        } else if (mime.compareTo(MimeType.PNG) == 0) {
            extension = ".png";
        } else if (mime.compareTo(MimeType.SVG) == 0) {
            extension = ".svg";
        }

        chartFilename = uuid + extension;
        //OutputStream chartFile = new FileOutputStream ("C:\\inetpub\\wwwroot\\tmp\\"+chartFilename);
        OutputStream chartFile = new FileOutputStream(
                "C:\\Users\\mc142\\Source\\Repos\\JourneyCompass\\website\\tmp\\" + chartFilename);
        stream.writeTo(chartFile);
        chartFile.close();

        if (i == inputList.length - 1) {
            fileList += chartFilename;
        } else {
            fileList += chartFilename + "!#!";
        }
        stream = null;
    }

    jobj.put("filenames", fileList);
    jobj.put("status", 0);
    jobj.put("msg", "success");
    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json");
    response.setStatus(HttpStatus.OK.value());
    response.addHeader("Access-Control-Allow-Origin", "*");
    //response.setHeader("Access-Control-Allow-Headers", "X-MYRESPONSEHEADER");
    response.getWriter().print(jobj);
    response.flushBuffer();
    /**** This is the original code that let browser saves the file.
    response.reset();      
    response.setCharacterEncoding("utf-8");
    response.setContentLength(stream.size());
    response.setStatus(HttpStatus.OK.value());
    response.setHeader("Content-disposition", "attachment; filename=\""
    + filename + "." + mime.name().toLowerCase() + "\"");
            
    IOUtils.write(stream.toByteArray(), response.getOutputStream());
    response.flushBuffer();
    ****/
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc./*from ww  w . j av  a2 s  . co  m*/
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponseX(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
        }

        try {

            res.setContentType(contentType);
            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

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

@RequestMapping(value = "/profile/{username}", method = RequestMethod.GET)
@ResponseBody/*  w ww.j  a va 2  s . co m*/
public void handleProfile(@PathVariable("username") String username,
        @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("userName:" + username);
    log.debug("width:" + width);
    log.debug("height:" + height);
    log.debug("------------------------------------------");
    try {
        ProfileImage image = profileManager.getProfileImageByUsername(username);
        log.debug("using profile image : " + image.getFilename());
        InputStream input;
        String contentType;
        int contentLength;
        if (width > 0 && width > 0) {
            input = profileManager.getImageThumbnailInputStream(image, width, height);
            contentType = image.getThumbnailContentType();
            contentLength = image.getThumbnailSize();
        } else {
            input = profileManager.getImageInputStream(image);
            contentType = image.getImageContentType();
            contentLength = image.getImageSize();
        }

        response.setContentType(contentType);
        response.setContentLength(contentLength);
        IOUtils.copy(input, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        response.setStatus(301);
        String url = ApplicationHelper.getApplicationProperty("components.download.images.no-avatar-url",
                "/images/common/anonymous.png");
        response.addHeader("Location", url);
    }
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

public void executeDeleteBucket(HttpServletRequest request, HttpServletResponse response) throws IOException {
    S3DeleteBucketRequest engineRequest = new S3DeleteBucketRequest();
    engineRequest.setBucketName((String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY));
    S3Response engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
    response.setStatus(engineResponse.getResultCode());
    response.flushBuffer();
}

From source file:org.eclipse.vorto.repository.web.ModelRepositoryController.java

@ApiOperation(value = "Download a specified Model by Model ID, including all References")
@RequestMapping(value = "/zip/{namespace}/{name}/{version:.+}", method = RequestMethod.GET)
public void downloadModelByIdWithReferences(
        @ApiParam(value = "Namespace", required = true) final @PathVariable String namespace,
        @ApiParam(value = "Name", required = true) final @PathVariable String name,
        @ApiParam(value = "Version", required = true) final @PathVariable String version,
        @ApiParam(value = "Output Type", required = true) final @RequestParam(value = "output", required = false) String outputType,
        @ApiParam(value = "Response", required = true) final HttpServletResponse response) {

    Objects.requireNonNull(namespace, "namespace must not be null");
    Objects.requireNonNull(name, "name must not be null");
    Objects.requireNonNull(version, "version must not be null");

    final ModelId modelId = new ModelId(name, namespace, version);

    logger.info("downloadModelById: [" + modelId.toString() + "] - Fullpath: [" + modelId.getFullPath() + "]");

    final ContentType contentType = getContentType(outputType);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {//from   w  ww .j  av a  2 s .c  o  m
        addModelToZip(zos, modelId, contentType);

        zos.close();
        baos.close();

        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + modelId.getNamespace() + "_"
                + modelId.getName() + "_" + modelId.getVersion() + ".zip");
        response.setContentType(APPLICATION_OCTET_STREAM);
        try {
            IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException("Error copying file.", e);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}