1 /*
2 * JBoss, Home of Professional Open Source.
3 * Copyright 2014 Red Hat, Inc., and individual contributors
4 * as indicated by the @author tags.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package io.undertow.util;
20
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Locale;
25
26 /**
27 * Utility methods for getting the locale from a request.
28 *
29 * @author Stuart Douglas
30 */
31 public class LocaleUtils {
32
33 public static Locale getLocaleFromString(String localeString) {
34 if (localeString == null) {
35 return null;
36 }
37 return Locale.forLanguageTag(localeString);
38 }
39
40 /**
41 * Parse a header string and return the list of locales that were found.
42 *
43 * If the header is empty or null then an empty list will be returned.
44 *
45 * @param acceptLanguage The Accept-Language header
46 * @return The list of locales, in order of preference
47 */
48 public static List<Locale> getLocalesFromHeader(final String acceptLanguage) {
49 if(acceptLanguage == null) {
50 return Collections.emptyList();
51 }
52 return getLocalesFromHeader(Collections.singletonList(acceptLanguage));
53 }
54
55 /**
56 * Parse a header string and return the list of locales that were found.
57 *
58 * If the header is empty or null then an empty list will be returned.
59 *
60 * @param acceptLanguage The Accept-Language header
61 * @return The list of locales, in order of preference
62 */
63 public static List<Locale> getLocalesFromHeader(final List<String> acceptLanguage) {
64 if (acceptLanguage == null || acceptLanguage.isEmpty()) {
65 return Collections.emptyList();
66 }
67 final List<Locale> ret = new ArrayList<>();
68 final List<List<QValueParser.QValueResult>> parsedResults = QValueParser.parse(acceptLanguage);
69 for (List<QValueParser.QValueResult> qvalueResult : parsedResults) {
70 for (QValueParser.QValueResult res : qvalueResult) {
71 if (!res.isQValueZero()) {
72 Locale e = LocaleUtils.getLocaleFromString(res.getValue());
73 ret.add(e);
74 }
75 }
76 }
77 return ret;
78 }
79 }
80