Example usage for javax.servlet ServletResponse getWriter

List of usage examples for javax.servlet ServletResponse getWriter

Introduction

In this page you can find the example usage for javax.servlet ServletResponse getWriter.

Prototype

public PrintWriter getWriter() throws IOException;

Source Link

Document

Returns a PrintWriter object that can send character text to the client.

Usage

From source file:org.apache.shale.tiles.TilesViewHandler.java

/**
 * <p>Render a view according to the algorithm described in this class's
 * description: Based on the view Id of the <code>viewToRender</code>,
 * this method either renders a tile or delegates rendering to the default
 * view handler, which takes care of business as usual.</p>
 *
 * @param facesContext The faces context object for this request
 * @param viewToRender The view that we're rendering
 *
 * Modified to do the same thing as SunRI wjb Oct 2006 courtesy sdoglesby
 *
 * March 2007 significantly rewritten /*from ww w. j  a  va 2  s.co  m*/
 * @author wbossons
 */
public void renderView(FacesContext facesContext, UIViewRoot viewToRender) throws IOException, FacesException {
    String viewId = viewToRender.getViewId();
    String tileName = getTileName(viewId);
    ComponentDefinition tile = getTile(tileName);
    //DEBUG: Significant rewrite.
    if (!viewToRender.isRendered()) {
        return;
    }

    if (tile != null) {
        ExternalContext extContext = facesContext.getExternalContext();

        dispatchToTile(extContext, tile);

        ServletRequest request = (ServletRequest) extContext.getRequest();
        ServletResponse response = (ServletResponse) extContext.getResponse();

        try {
            if (executePageToBuildView(facesContext, viewToRender, tile)) {
                response.flushBuffer();
                ApplicationAssociate applicationassociate = ApplicationAssociate.getInstance(extContext);
                this.responseRendered();
                return;
            }
        } catch (IOException e) {
            throw new FacesException(e);
        }
        if (logger.isLoggable(Level.WARNING)) { //default was fine
            logger.log(Level.FINE, "Completed building view for : \n" + viewToRender.getViewId());
        }
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.FINEST);
        }

        // set up the ResponseWriter

        RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder
                .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
        RenderKit renderKit = renderFactory.getRenderKit(facesContext, viewToRender.getRenderKitId());

        ResponseWriter oldWriter = facesContext.getResponseWriter();

        if (bufSize == -1) {
            WebConfiguration webConfig = WebConfiguration.getInstance(facesContext.getExternalContext());
            try {
                bufSize = Integer.parseInt(
                        webConfig.getContextInitParameter(WebContextInitParameter.ResponseBufferSize));
            } catch (NumberFormatException nfe) {
                bufSize = Integer.parseInt(WebContextInitParameter.ResponseBufferSize.getDefaultValue());
            }
        }
        WriteBehindStringWriter strWriter = new WriteBehindStringWriter(facesContext, bufSize);
        ResponseWriter newWriter;
        if (null != oldWriter) {
            newWriter = oldWriter.cloneWithWriter(strWriter);
        } else {
            newWriter = renderKit.createResponseWriter(strWriter, null, request.getCharacterEncoding());
        }
        facesContext.setResponseWriter(newWriter);

        newWriter.startDocument();

        doRenderView(facesContext, viewToRender);

        newWriter.endDocument();

        // replace markers in the body content and write it to response.

        ResponseWriter responseWriter;
        if (null != oldWriter) {
            responseWriter = oldWriter.cloneWithWriter(response.getWriter());
        } else {
            responseWriter = newWriter.cloneWithWriter(response.getWriter());
        }
        facesContext.setResponseWriter(responseWriter);

        strWriter.flushToWriter(responseWriter);

        if (null != oldWriter) {
            facesContext.setResponseWriter(oldWriter);
        }

        // write any AFTER_VIEW_CONTENT to the response
        writeAfterViewContent(extContext, response);
    } else { // no tile, use default viewhandler
        if (logger.isLoggable(Level.WARNING)) //default was fine
            logger.log(Level.WARNING, "tiles.dispatchingToViewHandler");
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.INFO);
        }
        getWrapped().renderView(facesContext, viewToRender);
    }
}

From source file:org.b3log.solo.filter.PageCacheFilter.java

/**
 * Try to write response from cache./*from  w ww  .j ava  2 s . c  o  m*/
 *
 * @param request the specified request
 * @param response the specified response
 * @param chain filter chain
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
        final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
        LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
        request.getRequestDispatcher(path).forward(request, response);

        return;
    }

    if (!Latkes.isPageCacheEnabled()) {
        LOGGER.log(Level.FINEST, "Page cache is disabled");
        chain.doFilter(request, response);

        return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
        // Mobile request, bypasses page caching
        chain.doFilter(request, response);

        return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
        pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
        request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest,
            (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
        LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
        chain.doFilter(request, response);

        return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
        // If cached an article that has view password, dispatches the password form
        if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
                && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
            JSONObject article = new JSONObject();

            final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

            article.put(Keys.OBJECT_ID, articleId);
            article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

            if (articles.needViewPwd(httpServletRequest, article)) {
                article = articleRepository.get(articleId); // Loads the article entity

                final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                try {
                    httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd"
                            + articles.buildArticleViewPwdFormParameters(article));
                    return;
                } catch (final Exception e) {
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }

    try {
        LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        final PrintWriter writer = response.getWriter();
        String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
        final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request,
                (HttpServletResponse) response);
        cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

        final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
        LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]",
                new Object[] { pageCacheKey, cachedType, cachedTitle });

        statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

        final long endimeMillis = System.currentTimeMillis();
        final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
        final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
                endimeMillis - startTimeMillis, dateString);
        LOGGER.finer(msg);
        cachedPageContent += Strings.LINE_SEPARATOR + msg;
        writer.write(cachedPageContent);
        writer.flush();
        writer.close();
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_RegistrationTCCL1() {
    final Set<String> filterTCCL = Collections.synchronizedSet(new HashSet<String>());
    final Set<String> servletTCCL = Collections.synchronizedSet(new HashSet<String>());
    Filter tcclFilter = new Filter() {

        @Override/*from w ww. jav a  2s  .co m*/
        public void init(FilterConfig filterConfig) throws ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }
    };
    HttpServlet tcclServlet = new HttpServlet() {

        @Override
        public void destroy() {
            super.destroy();
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            response.getWriter().print(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

    };

    ClassLoader originalTCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader dummy = new ClassLoader() {
    };
    Thread.currentThread().setContextClassLoader(dummy);
    String expected = dummy.getClass().getName();
    String actual = null;
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/tccl", tcclFilter, null, null);
        extendedHttpService.registerServlet("/tccl", tcclServlet, null, null);
        actual = requestAdvisor.request("tccl");
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalTCCL);
        try {
            extendedHttpService.unregister("/tccl");
            extendedHttpService.unregisterFilter(tcclFilter);
        } catch (IllegalArgumentException e) {
            // ignore
        }
    }
    assertEquals(expected, actual);
    assertEquals("Wrong filterTCCL size: " + filterTCCL, 1, filterTCCL.size());
    assertTrue("Wrong filterTCCL: " + filterTCCL, filterTCCL.contains(expected));
    assertEquals("Wrong httpTCCL size: " + servletTCCL, 1, servletTCCL.size());
    assertTrue("Wrong servletTCCL: " + servletTCCL, servletTCCL.contains(expected));

}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException {

    // Reset any output that has been buffered, but keep headers/cookies
    if (response.isCommitted()) {
        if (log.isDebugEnabled())
            log.debug("  Forward on committed response --> ISE");
        throw new IllegalStateException(sm.getString("applicationDispatcher.forward.ise"));
    }//from ww  w.ja va 2  s  .  c o m
    try {
        response.resetBuffer();
    } catch (IllegalStateException e) {
        if (log.isDebugEnabled())
            log.debug("  Forward resetBuffer() returned ISE: " + e);
        throw e;
    }

    // Set up to handle the specified request and response
    setup(request, response, false);

    // Identify the HTTP-specific request and response objects (if any)
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;

    // Handle a non-HTTP forward by passing the existing request/response
    if ((hrequest == null) || (hresponse == null)) {

        if (log.isDebugEnabled())
            log.debug(" Non-HTTP Forward");

        processRequest(hrequest, hresponse);

    }

    // Handle an HTTP named dispatcher forward
    else if ((servletPath == null) && (pathInfo == null)) {

        if (log.isDebugEnabled())
            log.debug(" Named Dispatcher Forward");

        processRequest(request, response);

    }

    // Handle an HTTP path-based forward
    else {

        if (log.isDebugEnabled())
            log.debug(" Path Based Forward");

        ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest();
        String contextPath = context.getPath();
        wrequest.setContextPath(contextPath);
        wrequest.setRequestURI(requestURI);
        wrequest.setServletPath(servletPath);
        wrequest.setPathInfo(pathInfo);

        wrequest.setAttribute(Globals.FORWARD_REQUEST_URI_ATTR, hrequest.getRequestURI());
        wrequest.setAttribute(Globals.FORWARD_CONTEXT_PATH_ATTR, hrequest.getContextPath());
        wrequest.setAttribute(Globals.FORWARD_SERVLET_PATH_ATTR, hrequest.getServletPath());
        wrequest.setAttribute(Globals.FORWARD_PATH_INFO_ATTR, hrequest.getPathInfo());
        wrequest.setAttribute(Globals.FORWARD_QUERY_STRING_ATTR, hrequest.getQueryString());

        if (queryString != null) {
            wrequest.setQueryString(queryString);
            wrequest.setQueryParams(queryString);
        }

        processRequest(request, response);
        unwrapRequest();

    }

    // This is not a real close in order to support error processing
    if (log.isDebugEnabled())
        log.debug(" Disabling the response for futher output");

    if (response instanceof ResponseFacade) {
        ((ResponseFacade) response).finish();
    } else {
        // Servlet SRV.6.2.2. The Resquest/Response may have been wrapped
        // and may no longer be instance of RequestFacade 
        if (log.isDebugEnabled()) {
            log.debug(" The Response is vehiculed using a wrapper: " + response.getClass().getName());
        }

        // Close anyway
        try {
            PrintWriter writer = response.getWriter();
            writer.close();
        } catch (IllegalStateException e) {
            try {
                ServletOutputStream stream = response.getOutputStream();
                stream.close();
            } catch (IllegalStateException f) {
                ;
            } catch (IOException f) {
                ;
            }
        } catch (IOException e) {
            ;
        }
    }

}

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 www.j ava 2  s. com
    // 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();
}