Example usage for javax.servlet ServletResponse flushBuffer

List of usage examples for javax.servlet ServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet ServletResponse 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.apache.shale.tiles.TilesViewHandler.java

private void writeAfterViewContent(ExternalContext extContext, ServletResponse response) throws IOException {
    Object content = extContext.getRequestMap().get(AFTER_VIEW_CONTENT);
    assert (null != content);
    if (content instanceof char[]) {
        response.getWriter().write((char[]) content);
    } else if (content instanceof byte[]) {
        response.getWriter().write(new String((byte[]) content));
    } else {/*w ww.jav a  2  s  .c o m*/
        assert (false);
    }

    response.flushBuffer();

    // remove the AFTER_VIEW_CONTENT from the view root
    extContext.getRequestMap().remove(AFTER_VIEW_CONTENT);
}

From source file:org.apache.unomi.web.ContextServlet.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    final Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }//from  w w w  . java2  s.  c  om
    // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the
    // script output.
    String profileId;

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String httpMethod = httpServletRequest.getMethod();
    //        logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest));

    // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors
    HttpUtils.setupCORSHeaders(httpServletRequest, response);

    if ("options".equals(httpMethod.toLowerCase())) {
        response.flushBuffer();
        return;
    }

    Profile profile = null;

    String cookieProfileId = null;
    Cookie[] cookies = httpServletRequest.getCookies();
    for (Cookie cookie : cookies) {
        if (profileIdCookieName.equals(cookie.getName())) {
            cookieProfileId = cookie.getValue();
        }
    }

    Session session = null;

    String personaId = request.getParameter("personaId");
    if (personaId != null) {
        PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId);
        if (personaWithSessions == null) {
            logger.error("Couldn't find persona with id=" + personaId);
            profile = null;
        } else {
            profile = personaWithSessions.getPersona();
            session = personaWithSessions.getLastSession();
        }
    }

    String sessionId = request.getParameter("sessionId");

    if (cookieProfileId == null && sessionId == null && personaId == null) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    boolean profileCreated = false;

    ContextRequest contextRequest = null;
    String scope = null;
    String stringPayload = HttpUtils.getPayload(httpServletRequest);
    if (stringPayload != null) {
        ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
        JsonFactory factory = mapper.getFactory();
        try {
            contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
        } catch (Exception e) {
            logger.error("Cannot read payload " + stringPayload, e);
            return;
        }
        scope = contextRequest.getSource().getScope();
    }

    int changes = EventService.NO_CHANGE;

    if (profile == null) {
        if (sessionId != null) {
            session = profileService.loadSession(sessionId, timestamp);
            if (session != null) {
                profileId = session.getProfileId();
                profile = profileService.load(profileId);
                profile = checkMergedProfile(response, profile, session);
            }
        }
        if (profile == null) {
            // profile not stored in session
            if (cookieProfileId == null) {
                // no profileId cookie was found, we generate a new one and create the profile in the profile service
                profile = createNewProfile(null, response, timestamp);
                profileCreated = true;
            } else {
                profile = profileService.load(cookieProfileId);
                if (profile == null) {
                    // this can happen if we have an old cookie but have reset the server,
                    // or if we merged the profiles and somehow this cookie didn't get updated.
                    profile = createNewProfile(null, response, timestamp);
                    profileCreated = true;
                    HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
                } else {
                    profile = checkMergedProfile(response, profile, session);
                }
            }
        } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId()))
                && !profile.isAnonymousProfile()) {
            // profile if stored in session but not in cookie
            HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
        }
        // associate profile with session
        if (sessionId != null && session == null) {
            session = new Session(sessionId, profile, timestamp, scope);
            changes |= EventService.SESSION_UPDATED;
            Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp);

            event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            changes |= eventService.send(event);
        }
    }

    if (profileCreated) {
        changes |= EventService.PROFILE_UPDATED;

        Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp);
        profileUpdated.setPersistent(false);
        profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
        profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);

        logger.debug("Received event {} for profile={} {} target={} timestamp={}",
                profileUpdated.getEventType(), profile.getItemId(),
                session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(),
                timestamp);
        changes |= eventService.send(profileUpdated);
    }

    ContextResponse data = new ContextResponse();
    data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId());

    if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
        profile = privacyService.getAnonymousProfile();
        session.setProfile(profile);
        changes = EventService.SESSION_UPDATED;
    }

    if (contextRequest != null) {
        changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp);
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) {
        profileService.saveSession(session);
    }

    String extension = httpServletRequest.getRequestURI()
            .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1);
    boolean noScript = "json".equals(extension);
    String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data);
    Writer responseWriter;
    if (noScript) {
        response.setCharacterEncoding("UTF-8");
        responseWriter = response.getWriter();
        response.setContentType("application/json");
        IOUtils.write(contextAsJSONString, responseWriter);
    } else {
        responseWriter = response.getWriter();
        responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ")
                .append(contextAsJSONString).append(";\n");

        // now we copy the base script source code
        InputStream baseScriptStream = getServletContext().getResourceAsStream(
                profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION);
        IOUtils.copy(baseScriptStream, responseWriter);
    }

    responseWriter.flush();
}

From source file:org.ireland.jnetty.webapp.RequestDispatcherImpl.java

private void finishResponse(ServletResponse res) throws ServletException, IOException {

    if (res instanceof HttpServletResponseImpl) {
        res.flushBuffer(); // we sure that all data has already put to the ByteBuf?
    } else {//ww w . j  a v  a 2s. c  o  m
        try {
            OutputStream os = res.getOutputStream();
            os.flush();
            // os.close();
        } catch (Exception e) {
        }

        try {
            PrintWriter out = res.getWriter();
            out.flush();
            // out.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.polymap.service.fs.webdav.WebDavServer.java

public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    Timer timer = new Timer();
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    DefaultSessionContextProvider contextProvider = FsPlugin.getDefault().sessionContextProvider;

    try {/*from  w  w w  .j ava 2s  . com*/
        Request request = new com.bradmcevoy.http.ServletRequest(req);
        Response response = new com.bradmcevoy.http.ServletResponse(resp);
        threadRequest.set(request);
        threadResponse.set(response);

        Auth auth = request.getAuthorization();
        log.debug("Auth: " + auth);

        // map/create session context
        final HttpSession session = req.getSession(true);
        if (auth != null) {
            contextProvider.mapContext(auth.getUser(), true);
            log.debug("SessionContext: " + SessionContext.current());
        }

        httpManager.process(request, response);
        log.debug("Request: " + Request.Header.ACCEPT_ENCODING.code + ": "
                + request.getHeaders().get(Request.Header.ACCEPT_ENCODING.code) + " --> Response: "
                + Response.Header.CONTENT_ENCODING.code + ": "
                + response.getHeaders().get(Response.Header.CONTENT_ENCODING.code));
        log.debug("Response: " + response.getStatus());
    } finally {
        if (contextProvider.currentContext() != null) {
            contextProvider.unmapContext();
        }

        threadRequest.set(null);
        threadResponse.set(null);

        servletResponse.getOutputStream().flush();
        servletResponse.flushBuffer();
    }
    log.info("WebDAV request: " + timer.elapsedTime() + "ms");
}