Search in sources :

Example 1 with LocaleContext

use of org.springframework.context.i18n.LocaleContext in project spring-framework by spring-projects.

the class FrameworkServlet method processRequest.

/**
	 * Process this request, publishing an event regardless of the outcome.
	 * <p>The actual event handling is performed by the abstract
	 * {@link #doService} template method.
	 */
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;
    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    LocaleContext localeContext = buildLocaleContext(request);
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
    initContextHolders(request, localeContext, requestAttributes);
    try {
        doService(request, response);
    } catch (ServletException ex) {
        failureCause = ex;
        throw ex;
    } catch (IOException ex) {
        failureCause = ex;
        throw ex;
    } catch (Throwable ex) {
        failureCause = ex;
        throw new NestedServletException("Request processing failed", ex);
    } finally {
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        if (logger.isDebugEnabled()) {
            if (failureCause != null) {
                this.logger.debug("Could not complete request", failureCause);
            } else {
                if (asyncManager.isConcurrentHandlingStarted()) {
                    logger.debug("Leaving response open for concurrent processing");
                } else {
                    this.logger.debug("Successfully completed request");
                }
            }
        }
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServletException(javax.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) NestedServletException(org.springframework.web.util.NestedServletException) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) IOException(java.io.IOException)

Example 2 with LocaleContext

use of org.springframework.context.i18n.LocaleContext in project spring-framework by spring-projects.

the class RequestContext method initContext.

/**
	 * Initialize this context with the given request, using the given model attributes for Errors retrieval.
	 * <p>Delegates to {@code getFallbackLocale} and {@code getFallbackTheme} for determining the fallback
	 * locale and theme, respectively, if no LocaleResolver and/or ThemeResolver can be found in the request.
	 * @param request current HTTP request
	 * @param servletContext the servlet context of the web application (can be {@code null}; necessary for
	 * fallback to root WebApplicationContext)
	 * @param model the model attributes for the current view (can be {@code null}, using the request attributes
	 * for Errors retrieval)
	 * @see #getFallbackLocale
	 * @see #getFallbackTheme
	 * @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE
	 * @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE
	 */
protected void initContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, Map<String, Object> model) {
    this.request = request;
    this.response = response;
    this.model = model;
    // Fetch WebApplicationContext, either from DispatcherServlet or the root context.
    // ServletContext needs to be specified to be able to fall back to the root context!
    this.webApplicationContext = (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (this.webApplicationContext == null) {
        this.webApplicationContext = RequestContextUtils.findWebApplicationContext(request, servletContext);
        if (this.webApplicationContext == null) {
            throw new IllegalStateException("No WebApplicationContext found: not in a DispatcherServlet " + "request and no ContextLoaderListener registered?");
        }
    }
    // Determine locale to use for this RequestContext.
    LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
    if (localeResolver instanceof LocaleContextResolver) {
        LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request);
        this.locale = localeContext.getLocale();
        if (localeContext instanceof TimeZoneAwareLocaleContext) {
            this.timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
        }
    } else if (localeResolver != null) {
        // Try LocaleResolver (we're within a DispatcherServlet request).
        this.locale = localeResolver.resolveLocale(request);
    }
    // Try JSTL fallbacks if necessary.
    if (this.locale == null) {
        this.locale = getFallbackLocale();
    }
    if (this.timeZone == null) {
        this.timeZone = getFallbackTimeZone();
    }
    // Determine default HTML escape setting from the "defaultHtmlEscape"
    // context-param in web.xml, if any.
    this.defaultHtmlEscape = WebUtils.getDefaultHtmlEscape(this.webApplicationContext.getServletContext());
    // Determine response-encoded HTML escape setting from the "responseEncodedHtmlEscape"
    // context-param in web.xml, if any.
    this.responseEncodedHtmlEscape = WebUtils.getResponseEncodedHtmlEscape(this.webApplicationContext.getServletContext());
    this.urlPathHelper = new UrlPathHelper();
    if (this.webApplicationContext.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
        this.requestDataValueProcessor = this.webApplicationContext.getBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
    }
}
Also used : LocaleResolver(org.springframework.web.servlet.LocaleResolver) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) UrlPathHelper(org.springframework.web.util.UrlPathHelper) LocaleContextResolver(org.springframework.web.servlet.LocaleContextResolver)

Example 3 with LocaleContext

use of org.springframework.context.i18n.LocaleContext in project spring-framework by spring-projects.

the class LocaleResolverTests method doTest.

private void doTest(LocaleResolver localeResolver, boolean shouldSet) {
    // create mocks
    MockServletContext context = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(context);
    request.addPreferredLocale(Locale.UK);
    MockHttpServletResponse response = new MockHttpServletResponse();
    // check original locale
    Locale locale = localeResolver.resolveLocale(request);
    assertEquals(locale, Locale.UK);
    // set new locale
    try {
        localeResolver.setLocale(request, response, Locale.GERMANY);
        if (!shouldSet)
            fail("should not be able to set Locale");
        // check new locale
        locale = localeResolver.resolveLocale(request);
        assertEquals(locale, Locale.GERMANY);
    } catch (UnsupportedOperationException ex) {
        if (shouldSet) {
            fail("should be able to set Locale");
        }
    }
    // check LocaleContext
    if (localeResolver instanceof LocaleContextResolver) {
        LocaleContextResolver localeContextResolver = (LocaleContextResolver) localeResolver;
        LocaleContext localeContext = localeContextResolver.resolveLocaleContext(request);
        if (shouldSet) {
            assertEquals(localeContext.getLocale(), Locale.GERMANY);
        } else {
            assertEquals(localeContext.getLocale(), Locale.UK);
        }
        assertTrue(localeContext instanceof TimeZoneAwareLocaleContext);
        assertNull(((TimeZoneAwareLocaleContext) localeContext).getTimeZone());
        if (localeContextResolver instanceof AbstractLocaleContextResolver) {
            ((AbstractLocaleContextResolver) localeContextResolver).setDefaultTimeZone(TimeZone.getTimeZone("GMT+1"));
            assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+1"));
        }
        try {
            localeContextResolver.setLocaleContext(request, response, new SimpleLocaleContext(Locale.US));
            if (!shouldSet) {
                fail("should not be able to set Locale");
            }
            localeContext = localeContextResolver.resolveLocaleContext(request);
            assertEquals(localeContext.getLocale(), Locale.US);
            if (localeContextResolver instanceof AbstractLocaleContextResolver) {
                assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+1"));
            } else {
                assertNull(((TimeZoneAwareLocaleContext) localeContext).getTimeZone());
            }
            localeContextResolver.setLocaleContext(request, response, new SimpleTimeZoneAwareLocaleContext(Locale.GERMANY, TimeZone.getTimeZone("GMT+2")));
            localeContext = localeContextResolver.resolveLocaleContext(request);
            assertEquals(localeContext.getLocale(), Locale.GERMANY);
            assertTrue(localeContext instanceof TimeZoneAwareLocaleContext);
            assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+2"));
            localeContextResolver.setLocaleContext(request, response, new SimpleTimeZoneAwareLocaleContext(null, TimeZone.getTimeZone("GMT+3")));
            localeContext = localeContextResolver.resolveLocaleContext(request);
            assertEquals(localeContext.getLocale(), Locale.UK);
            assertTrue(localeContext instanceof TimeZoneAwareLocaleContext);
            assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+3"));
            if (localeContextResolver instanceof AbstractLocaleContextResolver) {
                ((AbstractLocaleContextResolver) localeContextResolver).setDefaultLocale(Locale.GERMANY);
                assertEquals(localeContext.getLocale(), Locale.GERMANY);
            }
        } catch (UnsupportedOperationException ex) {
            if (shouldSet) {
                fail("should be able to set Locale");
            }
        }
    }
}
Also used : Locale(java.util.Locale) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockServletContext(org.springframework.mock.web.test.MockServletContext) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) LocaleContextResolver(org.springframework.web.servlet.LocaleContextResolver)

Example 4 with LocaleContext

use of org.springframework.context.i18n.LocaleContext in project spring-framework by spring-projects.

the class CookieLocaleResolverTests method testResolveLocaleContext.

@Test
public void testResolveLocaleContext() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    Cookie cookie = new Cookie("LanguageKoekje", "nl");
    request.setCookies(cookie);
    CookieLocaleResolver resolver = new CookieLocaleResolver();
    resolver.setCookieName("LanguageKoekje");
    LocaleContext loc = resolver.resolveLocaleContext(request);
    assertThat(loc.getLocale().getLanguage()).isEqualTo("nl");
    boolean condition = loc instanceof TimeZoneAwareLocaleContext;
    assertThat(condition).isTrue();
    assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull();
}
Also used : Cookie(jakarta.servlet.http.Cookie) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Example 5 with LocaleContext

use of org.springframework.context.i18n.LocaleContext in project spring-framework by spring-projects.

the class CookieLocaleResolverTests method testResolveLocaleContextWithCookieWithoutLocale.

@Test
public void testResolveLocaleContextWithCookieWithoutLocale() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addPreferredLocale(Locale.TAIWAN);
    Cookie cookie = new Cookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME, "");
    request.setCookies(cookie);
    CookieLocaleResolver resolver = new CookieLocaleResolver();
    LocaleContext loc = resolver.resolveLocaleContext(request);
    assertThat(loc.getLocale()).isEqualTo(request.getLocale());
    boolean condition = loc instanceof TimeZoneAwareLocaleContext;
    assertThat(condition).isTrue();
    assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull();
}
Also used : Cookie(jakarta.servlet.http.Cookie) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) SimpleTimeZoneAwareLocaleContext(org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext) TimeZoneAwareLocaleContext(org.springframework.context.i18n.TimeZoneAwareLocaleContext) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Aggregations

LocaleContext (org.springframework.context.i18n.LocaleContext)19 Test (org.junit.jupiter.api.Test)13 TimeZoneAwareLocaleContext (org.springframework.context.i18n.TimeZoneAwareLocaleContext)13 SimpleLocaleContext (org.springframework.context.i18n.SimpleLocaleContext)12 SimpleTimeZoneAwareLocaleContext (org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext)12 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)10 Cookie (jakarta.servlet.http.Cookie)8 Locale (java.util.Locale)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)3 MockServerWebExchange (org.springframework.mock.web.server.MockServerWebExchange)3 AcceptHeaderLocaleContextResolver (org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver)3 FixedLocaleContextResolver (org.springframework.web.server.i18n.FixedLocaleContextResolver)3 LocaleContextResolver (org.springframework.web.server.i18n.LocaleContextResolver)3 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)3 ServletException (jakarta.servlet.ServletException)2 LocaleContextResolver (org.springframework.web.servlet.LocaleContextResolver)2 IOException (java.io.IOException)1 URI (java.net.URI)1 TimeZone (java.util.TimeZone)1