Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Locale logic and use Optional for null checks #33653

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.springframework.web.servlet.i18n;

import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.function.Function;

Expand Down Expand Up @@ -57,6 +58,7 @@
*
* @author Juergen Hoeller
* @author Vedran Pavic
* @author Sungbin Yang
* @since 27.02.2003
* @see #setDefaultLocale
* @see #setDefaultTimeZone
Expand Down Expand Up @@ -93,6 +95,11 @@ public class SessionLocaleResolver extends AbstractLocaleContextResolver {
return (defaultLocale != null ? defaultLocale : request.getLocale());
};

private Locale getLocaleFromRequest(HttpServletRequest request) {
return Optional.ofNullable((Locale) WebUtils.getSessionAttribute(request, this.localeAttributeName))
.orElse(this.defaultLocaleFunction.apply(request));
}

private Function<HttpServletRequest, TimeZone> defaultTimeZoneFunction = request -> getDefaultTimeZone();

/**
Expand Down Expand Up @@ -148,32 +155,21 @@ public void setDefaultTimeZoneFunction(Function<HttpServletRequest, TimeZone> de

@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale locale = (Locale) WebUtils.getSessionAttribute(request, this.localeAttributeName);
if (locale == null) {
locale = this.defaultLocaleFunction.apply(request);
}
return locale;
return getLocaleFromRequest(request);
}

@Override
public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
return new TimeZoneAwareLocaleContext() {
@Override
public Locale getLocale() {
Locale locale = (Locale) WebUtils.getSessionAttribute(request, localeAttributeName);
if (locale == null) {
locale = defaultLocaleFunction.apply(request);
}
return locale;
return getLocaleFromRequest(request);
}
@Override
@Nullable
public TimeZone getTimeZone() {
TimeZone timeZone = (TimeZone) WebUtils.getSessionAttribute(request, timeZoneAttributeName);
if (timeZone == null) {
timeZone = defaultTimeZoneFunction.apply(request);
}
return timeZone;
return Optional.ofNullable((TimeZone) WebUtils.getSessionAttribute(request, timeZoneAttributeName))
.orElse(defaultTimeZoneFunction.apply(request));
}
};
}
Expand Down