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.kuali.rice.krad.filter.TestingLoginFilter.java

/**
 * Looks for a login user request parameter and establishs a user session for that user, then simply
 * returns a login message.//from  w  w w .  j  a  va2s  .  c o m
 *
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    if (StringUtils.isBlank(request.getParameter("login_user"))) {
        return;
    }

    final String user = request.getParameter("login_user");

    UserSession userSession = new UserSession(user);
    httpServletRequest.getSession().setAttribute(KRADConstants.USER_SESSION_KEY, userSession);

    // wrap the request with the signed in user
    // UserLoginFilter and WebAuthenticationService will build the session
    request = new HttpServletRequestWrapper(httpServletRequest) {
        @Override
        public String getRemoteUser() {
            return user;
        }
    };

    response.getWriter().print("Login Successful.");
}

From source file:com.adanac.module.blog.filter.DynamicFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String requestUri = StringUtil.replaceSlants(((HttpServletRequest) request).getRequestURI());
    try {//from  ww w  . j a v  a2 s  .c om
        Map<String, Object> data = FreemarkerHelper
                .buildCommonDataMap(FreemarkerHelper.getNamespace(requestUri), ViewMode.DYNAMIC);
        boolean forbidden = loginFilter(data, requestUri, request);
        if (forbidden) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        String template = putCustomData(data, requestUri, request, response);
        response.setCharacterEncoding("UTF-8");
        FreemarkerHelper.generateByTemplatePath(template + ".ftl", response.getWriter(), data);
    } catch (Exception e) {
        throw new RuntimeException(requestUri, e);
    }
}

From source file:org.apache.sling.dynamicinclude.IncludeTagFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final String resourceType = slingRequest.getResource().getResourceType();

    final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType);
    if (config == null) {
        chain.doFilter(request, response);
        return;/*from  w ww  . j  a  v a2 s .  c  om*/
    }

    final IncludeGenerator generator = generatorWhiteboard.getGenerator(config.getIncludeTypeName());
    if (generator == null) {
        LOG.error("Invalid generator: " + config.getIncludeTypeName());
        chain.doFilter(request, response);
        return;
    }

    final PrintWriter writer = response.getWriter();
    final String url = getUrl(config, slingRequest);
    if (url == null) {
        chain.doFilter(request, response);
        return;
    }

    if (config.getAddComment()) {
        writer.append(String.format(COMMENT, StringEscapeUtils.escapeHtml(url), resourceType));
    }

    // Only write the includes markup if the required, configurable request
    // header is present
    if (shouldWriteIncludes(config, slingRequest)) {
        String include = generator.getInclude(url);
        LOG.debug(include);
        writer.append(include);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java

@Override
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    FedizContext fedContext = federationConfig.getFedizContext();
    LOG.debug("Federation context: {}", fedContext);

    if (hrequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
            || hrequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Metadata document requested");
        }/*from   ww  w. j a v a 2s  .c o  m*/
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        try {
            Document metadata = wfProc.getMetaData(hrequest, fedContext);
            out.write(DOM2Writer.nodeToString(metadata));
            return;
        } catch (Exception ex) {
            LOG.warn("Failed to get metadata document: " + ex.getMessage());
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    String redirectUrl = null;
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());

        RedirectionResponse redirectionResponse = wfProc.createSignInRequest(hrequest, fedContext);
        redirectUrl = redirectionResponse.getRedirectionURL();

        if (redirectUrl == null) {
            LOG.warn("Failed to create SignInRequest.");
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create SignInRequest.");
        }

        Map<String, String> headers = redirectionResponse.getHeaders();
        if (!headers.isEmpty()) {
            for (String headerName : headers.keySet()) {
                hresponse.addHeader(headerName, headers.get(headerName));
            }
        }

    } catch (ProcessingException ex) {
        System.err.println("Failed to create SignInRequest: " + ex.getMessage());
        LOG.warn("Failed to create SignInRequest: " + ex.getMessage());
        hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
    }

    preCommence(hrequest, hresponse);
    if (LOG.isInfoEnabled()) {
        LOG.info("Redirecting to IDP: " + redirectUrl);
    }
    hresponse.sendRedirect(redirectUrl);

}

From source file:org.commoncrawl.service.listcrawler.ProxyServlet2.java

public void serviceProxyInternalRequest(ServletRequest request, ServletResponse response) throws IOException {
    String uri = ((HttpServletRequest) request).getRequestURI();

    if (uri.equalsIgnoreCase("/dumpCookies")) {
        Vector<CanonicalCookie> cookies = new Vector<CanonicalCookie>();

        // get a copy of all the cookie objects ... 
        _cookieStore.GetAllCookies(cookies);

        PrintWriter writer = response.getWriter();

        HttpServletResponse resp = (HttpServletResponse) response;

        resp.setStatus(200);//from w  w  w  . ja  v  a 2  s.co  m
        resp.setContentType("text/html");

        writer.println("<pre>");
        for (CanonicalCookie cookie : cookies) {
            writer.println(cookie.toString());
        }
        writer.println("</pre>");
    }
}

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 {//  www.  ja  v  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.myfaces.custom.ppr.PPRPhaseListener.java

/**
 * Respond to an AJAX request from a {@link PPRPanelGroup}. The
 * triggered components are determined by reading the
 * TRIGGERED_COMPONENTS_PARAMETER from either the RequestParameterMap or
 * the Request Map. Those componenets are encoded into an XML response.
 * The lifecycle is quit afterwards.//w  w w  .ja va  2s.  com
 *
 * @param context         the current {@link FacesContext}
 * @param externalContext the current {@link ExternalContext}
 * @param requestMap      Map containing the request attributes
 */
private void processPartialPageRequest(FacesContext context, final ExternalContext externalContext,
        Map requestMap) {

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

    UIViewRoot viewRoot = context.getViewRoot();

    // Set Character encoding, contentType and locale for the response
    final String characterEncoding = request.getCharacterEncoding();
    String contentType = getContentType("text/xml", characterEncoding);
    response.setContentType(contentType);
    response.setLocale(viewRoot.getLocale());

    // Fetch the comma-separated list of triggered components
    String triggeredComponents = getTriggeredComponents(context);

    try {
        PrintWriter out = response.getWriter();
        context.setResponseWriter(new HtmlResponseWriterImpl(out, contentType, characterEncoding));
        out.print(XML_HEADER);
        out.print("<response>\n");
        encodeTriggeredComponents(out, triggeredComponents, viewRoot, context);
        out.print("</response>");
        out.flush();
    } catch (IOException e) {
        throw new FacesException(e);
    }

    context.responseComplete();
}

From source file:cc.kune.core.server.rack.filters.rest.RESTServiceFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final String methodName = RackHelper.getMethodName(request, pattern);
    final ParametersAdapter parameters = new ParametersAdapter(request);
    LOG.debug("JSON METHOD: '" + methodName + "' on: " + serviceClass.getSimpleName());

    response.setCharacterEncoding("utf-8");

    final String callbackMethod = getCallbackMethod(request);
    final boolean isJsonP = isJSONPRequest(callbackMethod);

    response.setContentType(isJsonP ? "text/javascript" : "text/json");

    final RESTResult result = transactionalFilter.doService(serviceClass, methodName, parameters,
            getInstance(serviceClass));//from   ww w .j  a  va 2 s  .  c om
    if (result != null) {
        if (result.getOutput() != null) {
            final Object output = wrap(result.getOutput(), isJsonP, callbackMethod);
            if (output != null) {
                final PrintWriter writer = response.getWriter();
                writer.print(output);
                writer.flush();
            } else {
                chain.doFilter(request, response);
            }

        } else {
            chain.doFilter(request, response);
        }
    }
}

From source file:com.github.diluka.dynamic.web.staticizer.filter.DynamicWebStaticizerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    for (IStaticizeDecider decider : deciders) {
        if (request instanceof HttpServletRequest) {

            HttpServletRequest req = (HttpServletRequest) request;
            CacheHttpServletResponseWrapper chsrw = new CacheHttpServletResponseWrapper(
                    (HttpServletResponse) response);

            if (decider.decide(req)) {

                File html = prepareStaticPage(decider, req);
                if (html != null) {
                    response.setCharacterEncoding("utf-8");
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(new FileInputStream(html), "utf-8"));

                    String s = reader.readLine();
                    while (s != null) {
                        response.getWriter().write(s);
                        s = reader.readLine();
                    }//from w  w  w . j a v a 2 s. com
                    reader.close();
                    return;
                } else {
                    chain.doFilter(request, chsrw);
                    saveHtmlFile(decider, req, chsrw);
                    return;
                }

            }
        }
    }

    chain.doFilter(request, response);

}