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