Update the current user's locale to match the selected locale. This implementation will
update the session locale, and if the user is not a guest, will also update the locale in the
user's persisted preferences.

@param request
@param localeString
556575
public void updateUserLocale(HttpServletRequest request, String localeString) {

        IUserInstance ui = userInstanceManager.getUserInstance(request);
        IUserPreferencesManager upm = ui.getPreferencesManager();
        final IUserProfile userProfile = upm.getUserProfile();
        LocaleManager localeManager = userProfile.getLocaleManager();

        if (localeString != null) {

            // build a new List<Locale> from the specified locale
            Locale userLocale = localeManagerFactory.parseLocale(localeString);
            List<Locale> locales = Collections.singletonList(userLocale);

            // set this locale in the session
            localeManager.setSessionLocales(locales);

            // if the current user is logged in, also update the persisted
            // user locale
            final IPerson person = ui.getPerson();
            if (!person.isGuest()) {
                try {
                    localeManager.setUserLocales(Collections.singletonList(userLocale));
                    localeStore.updateUserLocales(person, new Locale[] {userLocale});

                    // remove person layout framgent from session since it contains some of the data
                    // in previous
                    // translation and won't be cleared until next logout-login (applies when using
                    // RDBMDistributedLayoutStore as user layout store).
                    person.setAttribute(Constants.PLF, null);
                    upm.getUserLayoutManager().loadUserLayout(true);
                } catch (Exception e) {
                    throw new PortalException(e);
                }
            }
        }
    }
1048985
public function setLocale()
    {
        $locale = app('session')->get('administrator_locale');

        if ($locale) {
            $this->app->translator->setLocale($locale);
        }
    }
119408
public void onChanged(ChangedEvent event) {
		String selectedLocale = (String) event.getValue();
		for (Entry<String, String> entry : locales.entrySet()) {
			if (entry.getValue().equals(selectedLocale)) {
				SC.showPrompt(I18nProvider.getGlobal().localeReload() + ": " + selectedLocale);
				Window.Location.assign(buildLocaleUrl(entry.getKey()));
			}
		}
	}
308773
public function detectLocale(HTTPRequest $request)
    {
        // Given multiple canditates, narrow down the final result using the client's preferred languages
        $inputLocales = $request->getHeader('Accept-Language');
        if (empty($inputLocales)) {
            return null;
        }

        // Generate mapping of priority => list of locales at this priority
        // break up string into pieces (languages and q factors)
        preg_match_all(
            '/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?<priority>1|0\.[0-9]+))?/i',
            $inputLocales,
            $parsedLocales
        );

        $prioritisedLocales = [];
        if (count($parsedLocales['code'])) {
            // create a list like "en" => 0.8
            $parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']);

            // Generate nested list of priorities => [locales]
            foreach ($parsedLocales as $locale => $priority) {
                $priority = empty($priority) ? "1.0" : (string)floatval($priority);
                if (empty($prioritisedLocales[$priority])) {
                    $prioritisedLocales[$priority] = [];
                }
                $prioritisedLocales[$priority][] = $locale;
            }

            // sort list based on value
            krsort($prioritisedLocales, SORT_NUMERIC);
        }

        // Check each requested locale against loaded locales
        $locales = Locale::getLocales(true);
        foreach ($prioritisedLocales as $priority => $parsedLocales) {
            foreach ($parsedLocales as $browserLocale) {
                foreach ($locales as $localeObj) {
                    /** @var Locale $localeObj */
                    if ($localeObj->isLocale($browserLocale)) {
                        return $localeObj;
                    }
                }
            }
        }
        return null;
    }
447962
public function changeAction(Request $request, $locale)
    {
        if (($token = $this->tokenStorage->getToken()) && 'anon.' !== $token->getUser()) {
            $this->localeManager->setUserLocale($locale);
        }

        $request->setLocale($locale);
        $request->getSession()->set('_locale', $locale);

        return new RedirectResponse(
            $request->headers->get('referer')
        );
    }
916028
public void onSessionUpdate(Request currentRequest, Session session)
	{
		HttpServletResponse response = (HttpServletResponse)httpResponse.get();
		storeSessionDataInCookie(SESSION_TOKEN_KEY, session.getToken(), response);
		if(session.getUser(/*realm.getId()*/) != null)
		{
			storeSessionDataInCookie(USER_ID_KEY, session.getUser(/*realm.getId()*/).getId(), response);
		}
		else
		{
			storeSessionDataInCookie(USER_ID_KEY, null, response);
		}
	}
929534
public void setLocale(Locale locale) {
        mLocale = locale;
        mWeekStart = Calendar.getInstance(mTimezone, mLocale).getFirstDayOfWeek();
        YEAR_FORMAT = new SimpleDateFormat("yyyy", locale);
        MONTH_FORMAT = new SimpleDateFormat("MMM", locale);
        DAY_FORMAT = new SimpleDateFormat("dd", locale);
    }
1214029
public void checkRefreshXslt(final HttpServletRequest request) {
    String reqpar = request.getParameter(getRefreshXSLTRequestName());

    if (reqpar == null) {
      return;
    }

    if (reqpar.equals("yes")) {
      setForceXSLTRefresh(true);
    }

    if (reqpar.equals("always")) {
      setForceXSLTRefreshAlways(true);
    }

    if (reqpar.equals("!")) {
      setForceXSLTRefreshAlways(false);
    }
  }
450709
Locale getLocale(HandshakeRequest request) {
		if(null != request) {
			Map<String, List<String>> headers = request.getHeaders();
			if(null != headers) {
				List<String> accepts = headers.get(HttpHeaders.ACCEPT_LANGUAGE);
				logger.debug("Get accept-language from client headers : {}", accepts);
				if (null != accepts) {
					for (String accept : accepts) {
						try {
							return localeExtractor.extractFromAccept(accept);
						} catch (LocaleNotFoundException ex) {
						}
					}
				}
			}
		}
		return Locale.US;
	}
389065
public void setAcceptLanguage(Locale locale) {
		checkCommitted();
		AcceptLanguageHeader alh = SipFactoryImpl.headerFactory
				.createAcceptLanguageHeader(locale);

		this.message.setHeader(alh);
	}
735104
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.EmptyCatchBlock" })
    @RequestHandler(priority = 990, dynamic = true)
    public void onRequest(Request.In event) {
        @SuppressWarnings("PMD.AccessorClassGeneration")
        final Selection selection = event.associated(Session.class)
            .map(session -> (Selection) session.computeIfAbsent(
                Selection.class, newKey -> new Selection(cookieName, path)))
            .orElseGet(() -> new Selection(cookieName, path));
        selection.setCurrentEvent(event);
        event.setAssociated(Selection.class, selection);
        if (selection.isExplicitlySet()) {
            return;
        }

        // Try to get locale from cookies
        final HttpRequest request = event.httpRequest();
        Optional<String> localeNames = request.findValue(
            HttpField.COOKIE, Converters.COOKIE_LIST)
            .flatMap(cookieList -> cookieList.valueForName(cookieName));
        if (localeNames.isPresent()) {
            try {
                List<Locale> cookieLocales = LOCALE_LIST
                    .fromFieldValue(localeNames.get());
                if (!cookieLocales.isEmpty()) {
                    Collections.reverse(cookieLocales);
                    cookieLocales.stream()
                        .forEach(locale -> selection.prefer(locale));
                    return;
                }
            } catch (ParseException e) {
                // Unusable
            }
        }

        // Last resport: Accept-Language header field
        Optional<List<ParameterizedValue<Locale>>> accepted = request.findValue(
            HttpField.ACCEPT_LANGUAGE, Converters.LANGUAGE_LIST);
        if (accepted.isPresent()) {
            Locale[] locales = accepted.get().stream()
                .sorted(ParameterizedValue.WEIGHT_COMPARATOR)
                .map(value -> value.value()).toArray(Locale[]::new);
            selection.updateFallbacks(locales);
        }
    }
695006
private void checkLocaleChange(Context context) {
        if (!isCurrentLanguageSetting(context, currentLanguage)) {
            sendOnBeforeLocaleChangedEvent();
            isLocalizationChanged = true;
            callDummyActivity();
            activity.recreate();
        }
    }
496046
public void setLocale(final Locale LOCALE) {
        if (null == locale) {
            _locale = LOCALE;
            fireUpdateEvent(REDRAW_EVENT);
        } else {
            locale.set(LOCALE);
        }
    }
131557
public static Locale getLocale(final String localeString) {
        final String language = getLanguage(localeString);
        final String country = getCountry(localeString);

        // // XXX: variant
        return new Locale(language, country);
    }
558723
public String resolveLocaleCode(HttpServletRequest request) {
		org.springframework.web.servlet.LocaleResolver resolver = RequestContextUtils.getLocaleResolver(request);
		Locale resolved = resolver.resolveLocale(request);
		if(resolved != Locale.getDefault())
			return resolved.toString();
		else return null;
	}
643086
protected Locale getBestLocale(HttpServletRequest request, Map<String,Locale> supportedLocales) throws ServletException {
		@SuppressWarnings("unchecked")
		Enumeration<String> acceptLanguages = request.getHeaders("accept-language");
		if(acceptLanguages == null) {
			// No header, use default
			return getDefaultLocale(request, supportedLocales);
		}
		// Select the best locale from the Accept-Language header(s).
		Locale bestExact = null;
		float bestExactQ = Float.NaN;
		Locale bestApprox = null;
		float bestApproxQ = Float.NaN;
		while(acceptLanguages.hasMoreElements()) {
			for(String pair : StringUtility.splitString(acceptLanguages.nextElement(), ',')) {
				String acceptLanguage;
				float q;
				int semiPos = pair.indexOf(';');
				if(semiPos == -1) {
					acceptLanguage = pair.trim();
					q = 1;
				} else {
					acceptLanguage = pair.substring(0, semiPos).trim();
					try {
						q = Float.parseFloat(pair.substring(semiPos + 1).trim());
					} catch(NumberFormatException e) {
						// Invalid value, use q=0 to ignore the language
						q = 0;
					}
				}
				if(
					q > 0
					&& (Float.isNaN(bestExactQ) || q > bestExactQ)
					&& (Float.isNaN(bestApproxQ) || q > bestApproxQ)
				) {
					MatchedLocale match = getBestMatch(supportedLocales, acceptLanguage);
					if(match != null) {
						if(match.exact) {
							if(Float.isNaN(bestExactQ) || q > bestExactQ) {
								bestExact = match.locale;
								bestExactQ = q;
							}
						} else {
							if(Float.isNaN(bestApproxQ) || q > bestApproxQ) {
								bestApprox = match.locale;
								bestApproxQ = q;
							}
						}
					}
				}
			}
		}
		// Select best exact, best approximate, then default
		Locale selected;
		if(bestExact != null) {
			selected = bestExact;
		} else if(bestApprox != null) {
			selected = bestApprox;
		} else {
			selected = getDefaultLocale(request, supportedLocales);
		}
		return selected;
	}
1142436
public function setLocale(SetLocaleRequest $request)
    {
        $locale = $request->input('locale');

        if ( ! $this->repository->isAvailable($locale)) {
            return redirect()->back()->withErrors("Locale {$locale} is not available");
        }

        session()->put($this->getSessionKey(), $locale);

        return redirect()->back();
    }