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:com.castlemock.web.basis.web.mvc.controller.project.ProjectsOverviewController.java

/**
 * The method provides the functionality to update, delete and export projects. It bases the requested functionality based
 * on the provided action./*from   w  w w .  j  ava  2s  . c  o  m*/
 * @param action The action is used to determined which action/functionality the perform.
 * @param projectModifierCommand The project overview command contains which ids going to be updated, deleted or exported.
 * @param response The HTTP servlet response
 * @return The model depending in which action was requested.
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView projectFunctionality(@RequestParam String action,
        @ModelAttribute ProjectModifierCommand projectModifierCommand, HttpServletResponse response) {
    LOGGER.debug("Project action requested: " + action);
    if (EXPORT_PROJECTS.equalsIgnoreCase(action)) {
        if (projectModifierCommand.getProjects().length == 0) {
            return redirect();
        }

        ZipOutputStream zipOutputStream = null;
        InputStream inputStream = null;
        final String outputFilename = tempFilesFolder + SLASH + "exported-projects-" + new Date().getTime()
                + ".zip";
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFilename));
            for (String project : projectModifierCommand.getProjects()) {
                final String[] projectData = project.split(SLASH);
                if (projectData.length != 2) {
                    continue;
                }

                final String projectTypeUrl = projectData[0];
                final String projectId = projectData[1];
                final String exportedProject = projectServiceFacade.exportProject(projectTypeUrl, projectId);
                final byte[] data = exportedProject.getBytes();
                final String filename = "exported-project-" + projectTypeUrl + "-" + projectId + ".xml";
                zipOutputStream.putNextEntry(new ZipEntry(filename));
                zipOutputStream.write(data, 0, data.length);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.close();

            inputStream = new FileInputStream(outputFilename);
            IOUtils.copy(inputStream, response.getOutputStream());

            response.setContentType("application/zip");
            response.flushBuffer();
            return null;
        } catch (IOException exception) {
            LOGGER.error("Unable to export multiple projects and zip them", exception);
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the zip output stream", exception);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the input stream", exception);
                }
            }
            fileManager.deleteUploadedFile(outputFilename);
        }
    } else if (DELETE_PROJECTS.equalsIgnoreCase(action)) {
        List<ProjectDto> projects = new LinkedList<ProjectDto>();
        for (String project : projectModifierCommand.getProjects()) {
            final String[] projectData = project.split(SLASH);

            if (projectData.length != 2) {
                continue;
            }

            final String projectTypeUrl = projectData[0];
            final String projectId = projectData[1];
            final ProjectDto projectDto = projectServiceFacade.findOne(projectTypeUrl, projectId);
            projects.add(projectDto);
        }
        ModelAndView model = createPartialModelAndView(DELETE_PROJECTS_PAGE);
        model.addObject(PROJECTS, projects);
        model.addObject(DELETE_PROJECTS_COMMAND, new DeleteProjectsCommand());
        return model;
    }

    return redirect();
}

From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java

private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp)
        throws IOException {
    /*    File tmp = null;
        FileOutputStream fos = null;/*from  w  w  w. ja v a  2 s .  c om*/
        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()));
            */
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(depositurl);

        InputStreamEntity data = new InputStreamEntity(is, -1);
        data.setContentType("binary/octet-stream");
        data.setChunked(false);
        post.setEntity(data);

        HttpResponse response = client.execute(post);
        System.out.println(response.toString());
        int status = 202;//response.getStatusLine();
        // int status = client.executeMethod(post);

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

            String src = response.getHeaders("X-dcs-src")[0].getValue();
            String atomurl = response.getHeaders("Location")[0].getValue();

            resp.setContentType("text/html");
            resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>");
            resp.flushBuffer();
        } else {
            resp.sendError(status, response.getStatusLine().toString());
            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:com.surveypanel.form.FormHandler.java

public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    response.setContentType("text/html;charset=UTF-8");
    Map<String, String> values = new HashMap<String, String>();
    Map params = request.getParameterMap();
    try {/*w w  w .  ja  va  2  s . c o m*/
        for (Object key : params.keySet()) {
            Object object = params.get(key);
            if (object instanceof String) {
                values.put((String) key, (String) object);
            } else if (object.getClass().isArray()) {
                StringBuilder sb = new StringBuilder();
                String[] value = (String[]) object;
                for (String content : value) {
                    sb.append(content).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                values.put((String) key, sb.toString());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    if (params.containsKey("quit")) {
        quit = true;
    }
    Form form = null;
    if (!values.containsKey("formId")) {
        form = formFactory.create(surveyId, devMode);
    } else {
        form = formFactory.load(values.get("formId"), surveyId, devMode);
    }
    form.setValues(values);
    form.setDevMode(devMode);
    Result execute;
    try {
        execute = (Result) jsManager.execute(form, "flow.execute(survey); save();");
        System.out.println(execute.getLogs());
        if (execute.hasError()) {
            response.getWriter().write(execute.getError());
        } else {
            response.getWriter().write(execute.getDisplay());
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write(e.getMessage());
    }
    response.flushBuffer();
}

From source file:guru.nidi.raml.doc.servlet.MirrorServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final int delay = req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay"));
    try {/*from ww w  .  j  a v  a  2  s.c o m*/
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        //ignore
    }
    final String q = req.getParameter("q") == null ? "" : req.getParameter("q");
    if (q.equals("png")) {
        final ServletOutputStream out = res.getOutputStream();
        res.setContentType("image/png");
        copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out);
    } else {
        final PrintWriter out = res.getWriter();
        switch (q) {
        case "html":
            res.setContentType("text/html");
            out.print("<html><body><ul>");
            for (int i = 0; i < 50; i++) {
                out.println("<li>" + i + "</li>");
            }
            out.print("</ul></body></html>");
            break;
        case "json":
            res.setContentType("application/json");
            final ObjectMapper mapper = new ObjectMapper();
            final Map<String, Object> map = new HashMap<>();
            map.put("method", req.getMethod());
            map.put("url", req.getRequestURL().toString());
            map.put("headers", headers(req));
            map.put("query", query(req));
            mapper.writeValue(out, map);
            break;
        case "error":
            res.sendError(500, "Dummy error message");
            break;
        default:
            out.println(req.getMethod() + " " + req.getRequestURL());
            headers(req, out);
            query(req, out);
            copy(req.getReader(), out);
        }
    }
    res.flushBuffer();
}

From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getRequestURI().endsWith(RAW_FILE_MARKER) || req.getRequestURI().endsWith(ZIP_FILE_MARKER)) {

        InputStream input = null;
        OutputStream output = null;
        try {/*from w  ww.ja v a2s . c o  m*/
            input = new FileInputStream(this.logFile);
            output = resp.getOutputStream();

            if (req.getRequestURI().endsWith(ZIP_FILE_MARKER)) {
                ZipOutputStream zip = new ZipOutputStream(output);
                zip.setLevel(Deflater.BEST_SPEED);

                ZipEntry entry = new ZipEntry(this.logFile.getName());
                entry.setTime(this.logFile.lastModified());
                entry.setMethod(ZipEntry.DEFLATED);

                zip.putNextEntry(entry);

                output = zip;
                resp.setContentType("application/zip");
            } else {
                resp.setContentType("text/plain");
                resp.setCharacterEncoding("UTF-8");
                resp.setHeader("Content-Length", String.valueOf(this.logFile.length())); // might be bigger than
            }
            resp.setDateHeader("Last-Modified", this.logFile.lastModified());

            IOUtils.copy(input, output);
        } catch (IOException ioe) {
            throw new ServletException("Cannot create copy of log file", ioe);
        } finally {
            IOUtils.closeQuietly(input);

            if (output instanceof ZipOutputStream) {
                ((ZipOutputStream) output).closeEntry();
                ((ZipOutputStream) output).finish();
            }
        }

        resp.flushBuffer();

    } else if (req.getRequestURI().endsWith(WINDOW_MARKER)) {

        if (canOpenSwingGui(req)) {
            showWindow();
        }

        String target = req.getRequestURI();
        target = target.substring(0, target.length() - WINDOW_MARKER.length());
        resp.sendRedirect(target);
        resp.flushBuffer();

    } else {

        super.service(req, resp);

    }
}

From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosAuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (skipIfAlreadyAuthenticated) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated()
                && !(existingAuth instanceof AnonymousAuthenticationToken)) {
            chain.doFilter(request, response);
            return;
        }/*from   w  w w.j  a  va 2  s.  c om*/
    }
    String header = request.getHeader("Authorization");
    if ((header != null) && header.startsWith("Negotiate ")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(10).getBytes("UTF-8");
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationRequest);
        } catch (AuthenticationException e) {
            //That shouldn't happen, as it is most likely a wrong
            //configuration on the server side
            logger.warn("Negotiate Header was invalid: " + header, e);
            SecurityContextHolder.clearContext();
            if (failureHandler != null) {
                failureHandler.onAuthenticationFailure(request, response, e);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.flushBuffer();
            }
            return;
        }
        sessionStrategy.onAuthentication(authentication, request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (successHandler != null) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

private void flushError(HttpServletResponse response, HttpServletResponse wrappedResponse) throws IOException {
    if (!response.isCommitted()) {
        final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
        if (data != null) {
            response.setContentType(wrappedResponse.getContentType());
            response.setCharacterEncoding(wrappedResponse.getCharacterEncoding());
            response.getOutputStream().write(data);
            response.flushBuffer();
        }//from www. jav  a  2s  . c  om
    }
}

From source file:io.lightlink.servlet.JsMethodsDefinitionServlet.java

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

    resp.setContentType("application/javascript");
    resp.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);

    Cookie[] cookies = req.getCookies();
    String debugMethods = "";
    for (int i = 0; cookies != null && i < cookies.length; i++) {
        Cookie cookie = cookies[i];//w ww. jav  a  2  s .com
        if ("lightlink.debug".equalsIgnoreCase(cookie.getName()))
            debugMethods = cookie.getValue();
    }

    PrintWriter writer = resp.getWriter();
    writer.print(getDeclarationScript(debugMethods, req));

    if (StringUtils.isNotEmpty(debugMethods) && ConfigManager.isInDebugMode()) {
        writer.print("\n// DEBUG PART \n");
        writer.print("\n\n    /***** io/lightlink/core/sqlFunctions.js   - for debugging *****/\n");
        writer.print(Utils.getResourceContent("io/lightlink/core/sqlFunctions.js"));
        writer.print("\n\n    /***** io/lightlink/core/debugProxy.js - for debugging *****/\n");
        writer.print(Utils.getResourceContent("io/lightlink/core/debugProxy.js"));
        writer.print("\n\n    /***** io/lightlink/core/LightLinkDebugSession.js - for debugging *****/\n");
        writer.print(Utils.getResourceContent("io/lightlink/core/LightLinkDebugSession.js"));
    }

    if (ConfigManager.isInDebugMode()) {
        writer.print("\n\n    /***** io/lightlink/core/IDDQD.js - for debugging *****/\n");
        writer.print(Utils.getResourceContent("io/lightlink/core/IDDQD.js"));
    }

    writer.print("\n" + "LL.JsApi.CSRF_Token = '"
            + CSRFTokensContainer.getInstance(req.getSession()).createNewToken() + "'\n");

    writer.close();
    resp.flushBuffer();
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcFailureHandler.java

protected void writeExpectedException(HttpServletRequest request, HttpServletResponse response,
        Exception remoteException) throws IOException {
    final RPCRequest rpcRequest;
    final String responsePayload;

    rpcRequest = AbstractRpcAuthenticationProcessingFilter.getRpcRequest(request);
    try {//from  ww  w.  j  a v  a  2s .  co  m
        if (rpcRequest != null) {
            /* checked exceptions must be declared by service method */
            responsePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), remoteException,
                    rpcRequest.getSerializationPolicy());
        } else {
            log.warn("Could not determine RPC request. Using default serialization.");
            responsePayload = RPC.encodeResponseForFailure(null, remoteException);
        }
    } catch (UnexpectedException e) {
        if (rpcRequest != null) {
            log.error("Exception " + remoteException.getClass().getName() + " is unexpected for method "
                    + rpcRequest.getMethod() + " of declaring class "
                    + rpcRequest.getMethod().getDeclaringClass().getName(), e);
        } else {
            log.error("Exception " + remoteException.getClass().getName() + " is unexpected for unknown method",
                    e);
        }
        writeUnexpectedException(request, response, remoteException);
        return;
    } catch (SerializationException e) {
        log.error("Error while serializing " + remoteException.getClass().getName(), e);
        writeUnexpectedException(request, response, remoteException);
        return;
    }

    if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnExpectedException()) {
        invalidateSession(request);
    }

    response.reset();
    addNoCacheResponseHeaders(request, response);
    RPCServletUtils.writeResponse(getServletContext(), response, responsePayload, false);
    response.flushBuffer();
}

From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java

/**
 * Delegates to jasper servlet with a controlled context class loader.
 * /*from  w  w w. j  a v  a  2s .  com*/
 * @see JspServletWrapper#service(HttpServletRequest, HttpServletResponse)
 */
public void serviceJavaServerPage(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    final HttpServletRequest request;
    final HttpServletResponse response;
    boolean originalRequest = true;

    // Wrap request and response if necessary
    if (httpRequest instanceof SiteRequestWrapper) {
        request = httpRequest;
        response = httpResponse;
        originalRequest = false;
    } else if (httpRequest instanceof WebloungeRequest) {
        request = new SiteRequestWrapper((WebloungeRequest) httpRequest, httpRequest.getPathInfo(), false);
        response = httpResponse;
        originalRequest = false;
    } else {
        WebloungeRequestImpl webloungeRequest = new WebloungeRequestImpl(httpRequest, environment);
        webloungeRequest.init(site);
        webloungeRequest.setUser(securityService.getUser());
        String requestPath = UrlUtils.concat("/site", httpRequest.getPathInfo());
        request = new SiteRequestWrapper(webloungeRequest, requestPath, false);
        response = new WebloungeResponseImpl(httpResponse);
        ((WebloungeResponseImpl) response).setRequest(webloungeRequest);
    }

    // Make sure the resource exists, Jasper will not produce a meaningful error
    // message, but a PWC6117: File "null" not found
    String requestPath = request.getRequestURI();
    if (bundle.getEntry(requestPath) == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Configure request and response objects

    try {
        jasperServlet.service(request, response);
        if (originalRequest) {
            ((WebloungeResponseImpl) response).endResponse();
            response.flushBuffer();
        }
    } catch (ServletException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (Throwable t) {
        // Don't log errors during precompilation
        if (!RequestUtils.isPrecompileRequest(request))
            logger.error("Error while serving jsp {}: {}", request.getRequestURI(), t.getMessage());
        response.sendError(SC_INTERNAL_SERVER_ERROR, t.getMessage());
    }
}