001/**
002 * Copyright (C) 2006-2025 Talend Inc. - www.talend.com
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 */
016package org.talend.sdk.component.server.service;
017
018import static java.util.stream.Collectors.toMap;
019
020import java.io.IOException;
021import java.io.StringReader;
022import java.util.Locale;
023import java.util.Map;
024import java.util.Properties;
025import java.util.function.Predicate;
026
027import javax.annotation.PostConstruct;
028import javax.enterprise.context.ApplicationScoped;
029import javax.inject.Inject;
030
031import org.talend.sdk.component.server.configuration.ComponentServerConfiguration;
032
033@ApplicationScoped
034public class LocaleMapper {
035
036    @Inject
037    private ComponentServerConfiguration configuration;
038
039    private Map<Predicate<String>, String> mapping;
040
041    @PostConstruct
042    private void init() {
043        final Properties properties = new Properties();
044        try (final StringReader reader = new StringReader(configuration.getLocaleMapping())) {
045            properties.load(reader);
046        } catch (final IOException e) {
047            throw new IllegalArgumentException(e);
048        }
049        mapping = properties.stringPropertyNames().stream().collect(toMap(it -> {
050            if (it.endsWith("*")) {
051                final String prefix = it.substring(0, it.length() - 1);
052                return (Predicate<String>) s -> s.startsWith(prefix);
053            }
054            return (Predicate<String>) s -> s.equals(it);
055        }, properties::getProperty));
056    }
057
058    // intended to limit and normalize the locales to avoid a tons when used with caching
059    public Locale mapLocale(final String requested) {
060        final String lc = getLanguage(requested);
061        final String lang = lc.substring(0, 2);
062        final String lcreg[] = lc.split("_");
063        final String region = lcreg.length == 2 ? lcreg[1] : "";
064
065        return new Locale(lang, region);
066    }
067
068    private String getLanguage(final String requested) {
069        if (requested == null) {
070            return "en";
071        }
072        return mapping
073                .entrySet()
074                .stream()
075                .filter(it -> it.getKey().test(requested))
076                .findFirst()
077                .map(Map.Entry::getValue)
078                .orElse("en");
079    }
080}