001/* 002 * Copyright (C) 2014 Jörg Prante 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.xbib.elasticsearch.plugin.jdbc.util; 017 018import org.elasticsearch.common.base.Strings; 019 020import java.util.Locale; 021 022public class LocaleUtil { 023 024 public static Locale toLocale(String localeString) { 025 if (Strings.isNullOrEmpty(localeString)) { 026 return Locale.getDefault(); 027 } 028 int separatorCountry = localeString.indexOf('_'); 029 char separator; 030 if (separatorCountry >= 0) { 031 separator = '_'; 032 } else { 033 separatorCountry = localeString.indexOf('-'); 034 separator = '-'; 035 } 036 String language; 037 String country; 038 String variant; 039 if (separatorCountry < 0) { 040 language = localeString; 041 country = ""; 042 variant = ""; 043 } else { 044 language = localeString.substring(0, separatorCountry); 045 int separatorVariant = localeString.indexOf(separator, separatorCountry + 1); 046 if (separatorVariant < 0) { 047 country = localeString.substring(separatorCountry + 1); 048 variant = ""; 049 } else { 050 country = localeString.substring(separatorCountry + 1, separatorVariant); 051 variant = localeString.substring(separatorVariant + 1); 052 } 053 } 054 return new Locale(language, country, variant); 055 } 056 057 public static String fromLocale(Locale locale) { 058 return locale.getLanguage() + 059 (Strings.isNullOrEmpty(locale.getCountry()) ? "_" + locale.getCountry() : "") + 060 (Strings.isNullOrEmpty(locale.getVariant()) ? "_" + locale.getVariant() : ""); 061 } 062}