|
| 1 | +package org.utplsql.cli; |
| 2 | + |
| 3 | +import java.util.Locale; |
| 4 | +import java.util.regex.Matcher; |
| 5 | +import java.util.regex.Pattern; |
| 6 | + |
| 7 | +/** This class makes sure the java locale is set according to the environment variables LC_ALL and LANG |
| 8 | + * We experienced that, in some cases, the locale was not set as expected, therefore this class implements some clear |
| 9 | + * rules: |
| 10 | + * 1. If environment variable NLS_LANG is set, we try to parse its content and set locale according to its value if valid |
| 11 | + * 2. If environment variable LC_ALL is set, we try to parse its content and set locale according to its value if valid |
| 12 | + * 3. If environment variable LANG is set, we try to parse its content and set locale according to its value if valid |
| 13 | + * 4. Otherwise we use default locale |
| 14 | + * |
| 15 | + * @author pesse |
| 16 | + */ |
| 17 | +class LocaleInitializer { |
| 18 | + |
| 19 | + private static final Pattern REGEX_LOCALE = Pattern.compile("^([a-zA-Z]+)[_-]([a-zA-Z]+)"); // We only need the very first part and are pretty forgiving in parsing |
| 20 | + |
| 21 | + /** Sets the default locale according to the rules described above |
| 22 | + * |
| 23 | + */ |
| 24 | + static void initLocale() { |
| 25 | + |
| 26 | + boolean localeChanged = setDefaultLocale(System.getenv("NLS_LANG")); |
| 27 | + |
| 28 | + if ( !localeChanged ) |
| 29 | + localeChanged = setDefaultLocale(System.getenv("LC_ALL")); |
| 30 | + if ( !localeChanged ) |
| 31 | + setDefaultLocale(System.getenv("LANG")); |
| 32 | + } |
| 33 | + |
| 34 | + /** Set the default locale from a given string like LC_ALL or LANG environment variable |
| 35 | + * |
| 36 | + * @param localeString Locale-string from LC_ALL or LANG, e.g "en_US.utf-8" |
| 37 | + * @return true if successful, false if not |
| 38 | + */ |
| 39 | + private static boolean setDefaultLocale( String localeString ) { |
| 40 | + if ( localeString == null || localeString.isEmpty() ) |
| 41 | + return false; |
| 42 | + |
| 43 | + try { |
| 44 | + Matcher m = REGEX_LOCALE.matcher(localeString); |
| 45 | + if (m.find()) { |
| 46 | + StringBuilder sb = new StringBuilder(); |
| 47 | + sb.append(m.group(1)); |
| 48 | + if (m.group(2) != null) |
| 49 | + sb.append("-").append(m.group(2)); |
| 50 | + |
| 51 | + Locale l = new Locale.Builder().setLanguageTag(sb.toString()).build(); |
| 52 | + if ( l != null ) { |
| 53 | + Locale.setDefault(l); |
| 54 | + return true; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + catch ( Exception e ) { |
| 59 | + System.out.println("Could not get locale from " + localeString); |
| 60 | + } |
| 61 | + |
| 62 | + return false; |
| 63 | + } |
| 64 | +} |
0 commit comments