Example usage for javax.servlet ServletResponse setLocale

List of usage examples for javax.servlet ServletResponse setLocale

Introduction

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

Prototype

public void setLocale(Locale loc);

Source Link

Document

Sets the locale of the response, if the response has not been committed yet.

Usage

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void writeCacheToResponse(CacheEntry cacheEntry, ServletResponse response, boolean fragment)
        throws IOException {

    if (cacheEntry.getContentType() != null) {
        response.setContentType(cacheEntry.getContentType());
    }/*from  w  ww  .ja  va2s  .  c  o m*/

    if (!fragment) {

        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            if (cacheEntry.getLastModified() != -1) {
                httpResponse.setDateHeader("Last-Modified", cacheEntry.getLastModified());
            }

            if (cacheEntry.getExpires() != Long.MAX_VALUE) {
                httpResponse.setDateHeader("Expires", cacheEntry.getExpires());
            }

            if (cacheEntry.getMaxAge() != -1) {
                if (cacheEntry.getMaxAge() < 0) { // set max-age based on life time
                    long currentMaxAge = -cacheEntry.getMaxAge() / 1000 - System.currentTimeMillis() / 1000;
                    if (currentMaxAge < 0) {
                        currentMaxAge = 0;
                    }
                    httpResponse.addHeader("Cache-Control", "max-age=" + currentMaxAge);
                } else {
                    httpResponse.addHeader("Cache-Control", "max-age=" + cacheEntry.getMaxAge());
                }
            }

        }
    }

    if (cacheEntry.getLocale() != null) {
        response.setLocale(cacheEntry.getLocale());
    }

    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentLength(cacheEntry.getContent().length);
    out.write(cacheEntry.getContent());
    out.flush();
}

From source file:org.apache.myfaces.application.jsp.JspViewHandlerImpl.java

public void renderView(FacesContext facesContext, UIViewRoot viewToRender) throws IOException, FacesException {
    if (viewToRender == null) {
        log.fatal("viewToRender must not be null");
        throw new NullPointerException("viewToRender must not be null");
    }// w w  w.  jav  a2s .  co m

    ExternalContext externalContext = facesContext.getExternalContext();

    String viewId = facesContext.getViewRoot().getViewId();

    if (PortletUtil.isPortletRequest(facesContext)) {
        externalContext.dispatch(viewId);
        return;
    }

    ServletMapping servletMapping = getServletMapping(externalContext);

    if (servletMapping != null && servletMapping.isExtensionMapping()) {
        String defaultSuffix = externalContext.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
        String suffix = defaultSuffix != null ? defaultSuffix : ViewHandler.DEFAULT_SUFFIX;
        DebugUtils.assertError(suffix.charAt(0) == '.', log, "Default suffix must start with a dot!");
        if (!viewId.endsWith(suffix)) {
            int dot = viewId.lastIndexOf('.');
            if (dot == -1) {
                if (log.isTraceEnabled())
                    log.trace("Current viewId has no extension, appending default suffix " + suffix);
                viewId = viewId + suffix;
            } else {
                if (log.isTraceEnabled())
                    log.trace("Replacing extension of current viewId by suffix " + suffix);
                viewId = viewId.substring(0, dot) + suffix;
            }
            facesContext.getViewRoot().setViewId(viewId);
        }
    }

    if (log.isTraceEnabled())
        log.trace("Dispatching to " + viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getResponse() instanceof ServletResponse) {
        ServletResponse response = (ServletResponse) externalContext.getResponse();
        response.setLocale(viewToRender.getLocale());
    }

    // TODO: 2.5.2.2 for Portlet?  What do I do?

    externalContext.dispatch(viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getRequest() instanceof HttpServletRequest) {
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession(false);

        if (session != null) {
            session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, response.getCharacterEncoding());
        }
    }

}

From source file:org.apache.myfaces.custom.ajax.api.AjaxDecodePhaseListener.java

private void encodeAjax(UIComponent component, FacesContext context) {
    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    ServletRequest request = (ServletRequest) context.getExternalContext().getRequest();
    UIViewRoot viewRoot = context.getViewRoot();
    Map requestMap = context.getExternalContext().getRequestParameterMap();

    String charset = (String) requestMap.get("charset");

    /* Handle character encoding as of section 2.5.2.2 of JSF 1.1:
     * At the beginning of the render-response phase, the ViewHandler must ensure
     * that the response Locale is set to that of the UIViewRoot, for exampe by
     * calling ServletResponse.setLocale() when running in the servlet environment.
     * Setting the response Locale may affect the response character encoding.
     *//from  w w  w  . j  a v a 2s .c om
     * Since there is no 'Render Response' phase for AJAX requests, we have to handle
     * this manually.
     */
    response.setLocale(viewRoot.getLocale());

    if (component instanceof DeprecatedAjaxComponent) {
        try {
            String contentType = getContentType("text/xml", charset);
            response.setContentType(contentType);

            StringBuffer buff = new StringBuffer();
            buff.append("<?xml version=\"1.0\"?>\n");
            buff.append("<response>\n");

            PrintWriter out = response.getWriter();
            out.print(buff);

            // imario@apache.org: setup response writer, otherwise the component will fail with an NPE. I dont know why this worked before.
            context.setResponseWriter(
                    new HtmlResponseWriterImpl(out, contentType, request.getCharacterEncoding()));

            if (component instanceof HtmlCommandButtonAjax) {
                buff = new StringBuffer();
                buff.append("<triggerComponent id=\"");
                buff.append(component.getClientId(context));
                buff.append("\" />\n");
                out.print(buff);

                // special treatment for this one, it will try to update the entire form
                // 1. get surrounding form
                //String elname = (String) requestMap.get("elname");
                FormInfo fi = RendererUtils.findNestingForm(component, context);
                UIComponent form = fi.getForm();
                //System.out.println("FOUND FORM: " + form);
                if (form != null) {
                    // special case, add responses from all components in form
                    encodeChildren(form, context, requestMap);
                }
            } else if (component instanceof AjaxComponent) {
                // let component render xml response
                // NOTE: probably don't need an encodeAjax in each component, but leaving it in until that's for sure
                ((AjaxComponent) component).encodeAjax(context);
            } else {
                // just get latest value
                AjaxRendererUtils.encodeAjax(context, component);
            }
            // end response
            out.print("</response>");
            out.flush();
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    } else if (component instanceof AjaxComponent) {
        try {
            if (context.getResponseWriter() == null) {
                String contentType = getContentType("text/html", charset);
                response.setContentType(contentType);
                PrintWriter writer = response.getWriter();
                context.setResponseWriter(
                        new HtmlResponseWriterImpl(writer, contentType, response.getCharacterEncoding()));
            }

            ((AjaxComponent) component).encodeAjax(context);
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    }

}

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./*from   w  w  w.  j a v a 2  s. c om*/
 *
 * @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:org.apache.myfaces.tomahawk.application.jsp.JspTilesTwoViewHandlerImpl.java

private void handleCharacterEncoding(String viewId, ExternalContext externalContext, UIViewRoot viewToRender) {
    if (log.isTraceEnabled())
        log.trace("Dispatching to " + viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getResponse() instanceof ServletResponse) {
        ServletResponse response = (ServletResponse) externalContext.getResponse();
        response.setLocale(viewToRender.getLocale());
    }/*from  w  w  w.j a  va2  s  .co  m*/
}

From source file:org.apache.myfaces.tomahawk.application.jsp.JspTilesViewHandlerImpl.java

private void dispatch(ExternalContext externalContext, UIViewRoot viewToRender, String viewId)
        throws IOException {
    if (log.isTraceEnabled())
        log.trace("Dispatching to " + viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getResponse() instanceof ServletResponse) {
        ServletResponse response = (ServletResponse) externalContext.getResponse();
        response.setLocale(viewToRender.getLocale());
    }/*from  w w w . ja v a 2 s.  com*/

    externalContext.dispatch(viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getRequest() instanceof HttpServletRequest) {
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession(false);

        if (session != null) {
            session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, response.getCharacterEncoding());
        }
    }

}

From source file:org.infoscoop.web.I18NFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    BufferHttpServletResponseWrapper bufResponse = new BufferHttpServletResponseWrapper(
            (HttpServletResponse) response);
    chain.doFilter(request, bufResponse);
    bufResponse.flushBuffer();//from w w w  .  ja va 2  s.  co  m
    String body = bufResponse.getStringContent();

    try {
        body = I18NUtil.resolve(type, body, request.getLocale());
    } catch (Exception e) {
        log.error("database error occurred. ", e);
    }

    if (bufResponse.getLocale() != null)
        response.setLocale(bufResponse.getLocale());
    response.setContentLength(body.getBytes("utf-8").length);

    Writer out = null;
    try {
        out = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        out.write(body);
        out.flush();
    } finally {
        if (out != null)
            out.close();
    }
}