001/*
002 * Copyright 2017-2022 Product Mog LLC, 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.lokalized;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import java.util.List;
023import java.util.Locale;
024import java.util.Locale.LanguageRange;
025
026/**
027 * Contract for matching an input {@link Locale} or {@link List}{@code <}{@link LanguageRange}{@code >} to an appropriate localized strings {@link Locale}.
028 * <p>
029 * Lokalized's implementation prefers exact and CLDR-canonical matches, then CLDR parent-locale fallback,
030 * then script-aware likely-subtag matches. If multiple supported localized strings files still share the same language,
031 * configured tiebreakers determine which locale wins. Unmatched, root, and undetermined requests resolve to the
032 * configured fallback locale when using {@code bestMatchFor(...)}. The strict {@code matchFor(...)} methods represent
033 * the same state as an unmatched {@link LocaleMatchResult} instead of manufacturing a match.
034 * <p>
035 * Non-bare wildcard language ranges use RFC 4647 extended filtering only; they are not broadened through
036 * CLDR, likely-subtag, or primary-language heuristics, and successful results report
037 * {@link LocaleMatchType#EXTENDED_RANGE}. When multiple ranges match one supported locale, the most-specific exact,
038 * canonical, or structural range determines its effective quality, including a {@code q=0} exclusion.
039 *
040 * @author <a href="https://revetkn.com">Mark Allen</a>
041 */
042public interface LocaleMatcher {
043        /**
044         * Maximum number of parsed language ranges accepted by one matching operation: 32.
045         * <p>
046         * Parsing a header, whether with {@link #parseLanguageRanges(String)} or {@link LanguageRange#parse(String)}, may
047         * add IANA-equivalent ranges, so this limit applies to the parsed list, not the number of comma-separated ranges in
048         * the source header. The two parsers can add different equivalents, and {@link LanguageRange#parse(String)} adds
049         * whatever the running JDK's table holds, so the same header can be within the limit under one and over it under
050         * the other.
051         *
052         * @since 3.0.0
053         */
054        @NonNull
055        public static final Integer MAXIMUM_LANGUAGE_RANGES = 32;
056
057        /**
058         * Strictly negotiates a locale without manufacturing a configured-fallback match.
059         *
060         * @param locale requested locale, not null
061         * @return diagnostic match result, not null
062         * @throws IllegalArgumentException if the locale is not well-formed
063         * @since 3.0.0
064         */
065        @NonNull
066        default LocaleMatchResult matchFor(@NonNull Locale locale) {
067                LocaleUtils.requireWellFormed(locale, "Requested locale");
068                return matchFor(ImmutableCollections.listOf(new LanguageRange(locale.toLanguageTag())));
069        }
070
071        /**
072         * Strictly negotiates language ranges without manufacturing a configured-fallback match.
073         *
074         * @param languageRanges requested language ranges, not null
075         * @return diagnostic match result, not null
076         * @throws IllegalArgumentException if more than {@link #MAXIMUM_LANGUAGE_RANGES} language ranges are supplied
077         * @since 3.0.0
078         */
079        @NonNull
080        LocaleMatchResult matchFor(@NonNull List<@NonNull LanguageRange> languageRanges);
081
082        /**
083         * Given a locale, determine the best-matching localized strings file's locale.
084         *
085         * @param locale the locale for which to find the best match.
086         * @return the best-matching locale, not null
087         * @throws IllegalArgumentException if the locale is not well-formed
088         */
089        @NonNull
090        Locale bestMatchFor(@NonNull Locale locale);
091
092        /**
093         * Given a list of language ranges (e.g. as parsed from an {@code Accept-Language} HTTP request header), determine the best-matching localized strings file's locale.
094         *
095         * @param languageRanges the ordered list of language ranges for which to find the best match.
096         * @return the best-matching locale, not null
097         * @throws IllegalArgumentException if more than {@link #MAXIMUM_LANGUAGE_RANGES} language ranges are supplied
098         */
099        @NonNull
100        Locale bestMatchFor(@NonNull List<@NonNull LanguageRange> languageRanges);
101
102        /**
103         * Given a raw {@code Accept-Language} HTTP field value, determines the best-matching localized strings
104         * file's locale.
105         * <p>
106         * This is a fail-soft convenience for request handling. A missing, blank, malformed, or longer than 4,096 UTF-16
107         * code-unit value returns the configured fallback locale. The length limit is applied before parsing so parser work
108         * is bounded independently of the parsed-range limit. HTTP optional whitespace and empty list elements are
109         * normalized before parsing, and the value is then parsed with {@link #parseLanguageRanges(String)}. The configured
110         * fallback is also returned if parsing produces more than {@link #MAXIMUM_LANGUAGE_RANGES} ranges, which can happen
111         * when parsing adds IANA-equivalent ranges. A valid parsed list is passed through whole; preferences are never
112         * truncated. Use {@link #matchFor(List)} or {@link #bestMatchFor(List)} when language ranges have already been
113         * parsed and strict limit enforcement is desired.
114         *
115         * @param acceptLanguage raw, already-combined {@code Accept-Language} field value, or null if absent
116         * @return the best-matching locale, or the configured fallback for unusable input, not null
117         * @since 3.0.0
118         */
119        @NonNull
120        default Locale bestMatchForAcceptLanguage(@Nullable String acceptLanguage) {
121                if (acceptLanguage == null ||
122                                acceptLanguage.length() > 4_096 ||
123                                acceptLanguage.trim().isEmpty())
124                        return bestMatchFor(ImmutableCollections.listOf());
125
126                String normalizedAcceptLanguage = normalizeAcceptLanguage(acceptLanguage);
127
128                if (normalizedAcceptLanguage.isEmpty())
129                        return bestMatchFor(ImmutableCollections.listOf());
130
131                List<@NonNull LanguageRange> languageRanges;
132
133                try {
134                        languageRanges = parseLanguageRanges(normalizedAcceptLanguage);
135                } catch (IllegalArgumentException | IndexOutOfBoundsException exception) {
136                        return bestMatchFor(ImmutableCollections.listOf());
137                }
138
139                if (languageRanges.size() > MAXIMUM_LANGUAGE_RANGES)
140                        return bestMatchFor(ImmutableCollections.listOf());
141
142                return bestMatchFor(languageRanges);
143        }
144
145        /**
146         * Parses a language-range list, such as an {@code Accept-Language} field value, adding IANA-equivalent ranges.
147         * <p>
148         * The grammar, weights, result order, de-duplication, and exceptions are those of {@link LanguageRange#parse(String)}:
149         * spaces are removed, the value is lowercased, an {@code accept-language:} prefix is dropped, members are separated by
150         * commas, and each member may carry a {@code ;q=} weight. Only the source of the added equivalent ranges differs. This
151         * default takes them from the IANA Language Subtag Registry snapshot bundled in Lokalized
152         * ({@link LanguageRangeEquivalents#IANA_REGISTRY}), so the equivalents it adds are the same on every JDK, where
153         * {@link LanguageRange#parse(String)} uses the running JDK's table. A {@link Strings} instance uses the source
154         * configured with {@link Strings.Builder#languageRangeEquivalents(LanguageRangeEquivalents)}.
155         * <p>
156         * Unlike {@link #bestMatchForAcceptLanguage(String)}, this method is strict: it applies no length limit, rejects an
157         * empty value, horizontal tabs, and empty list elements other than trailing ones instead of normalizing them, and
158         * propagates every failure. It does not enforce {@link #MAXIMUM_LANGUAGE_RANGES}; {@link #matchFor(List)} and
159         * {@link #bestMatchFor(List)} reject a longer list.
160         *
161         * @param ranges comma-separated language ranges, optionally weighted, not null
162         * @return the parsed ranges and their equivalents in descending weight order, as an unmodifiable list, not null
163         * @throws NullPointerException      if {@code ranges} is null
164         * @throws IllegalArgumentException  if a language range or weight is ill-formed, or a weight is not between
165         *                                   {@code 0.0} and {@code 1.0}
166         * @throws IndexOutOfBoundsException if a language range consists only of hyphens and the running JDK's
167         *                                   {@link LanguageRange} constructor rejects it this way, as it does on JDK 17
168         *                                   and 21 (JDK 25 through 27 throw {@link IllegalArgumentException} instead);
169         *                                   {@link LanguageRange#parse(String)} fails the same way on each JDK
170         * @since 3.1.0
171         */
172        @NonNull
173        default List<@NonNull LanguageRange> parseLanguageRanges(@NonNull String ranges) {
174                return IanaLanguageEquivalents.parse(ranges);
175        }
176
177        /**
178         * Converts RFC 9110 horizontal-tab whitespace to the space form understood by
179         * {@link #parseLanguageRanges(String)} and removes empty HTTP list elements.
180         */
181        @NonNull
182        private static String normalizeAcceptLanguage(@NonNull String acceptLanguage) {
183                StringBuilder normalizedAcceptLanguage = new StringBuilder(acceptLanguage.length());
184                int memberStartIndex = 0;
185
186                for (int index = 0; index <= acceptLanguage.length(); ++index) {
187                        if (index < acceptLanguage.length() && acceptLanguage.charAt(index) != ',')
188                                continue;
189
190                        int firstContentIndex = memberStartIndex;
191
192                        while (firstContentIndex < index && isOptionalWhitespace(acceptLanguage.charAt(firstContentIndex)))
193                                ++firstContentIndex;
194
195                        int contentEndIndex = index;
196
197                        while (contentEndIndex > firstContentIndex &&
198                                        isOptionalWhitespace(acceptLanguage.charAt(contentEndIndex - 1)))
199                                --contentEndIndex;
200
201                        if (firstContentIndex < contentEndIndex) {
202                                if (normalizedAcceptLanguage.length() > 0)
203                                        normalizedAcceptLanguage.append(',');
204
205                                for (int contentIndex = firstContentIndex; contentIndex < contentEndIndex; ++contentIndex) {
206                                        char character = acceptLanguage.charAt(contentIndex);
207                                        normalizedAcceptLanguage.append(character == '\t' ? ' ' : character);
208                                }
209                        }
210
211                        memberStartIndex = index + 1;
212                }
213
214                return normalizedAcceptLanguage.toString();
215        }
216
217        private static boolean isOptionalWhitespace(char character) {
218                return character == ' ' || character == '\t';
219        }
220}