Java Code Examples for java.util.Locale#getCountry()

The following examples show how to use java.util.Locale#getCountry() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Gets a list containing the names of all possible message files
 * for a locale.
 *
 * @param prefix The file name prefix.
 * @param suffix The file name suffix.
 * @param locale The {@code Locale} to generate file names for.
 * @return A list of candidate file names.
 */
public static List<String> getLocaleFileNames(String prefix,
                                              String suffix,
                                              Locale locale) {
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();

    List<String> result = new ArrayList<>(4);

    if (!language.isEmpty()) language = "_" + language;
    if (!country.isEmpty()) country = "_" + country;
    if (!variant.isEmpty()) variant = "_" + variant;

    result.add(prefix + suffix);
    String filename = prefix + language + suffix;
    if (!result.contains(filename)) result.add(filename);
    filename = prefix + language + country + suffix;
    if (!result.contains(filename)) result.add(filename);
    filename = prefix + language + country + variant + suffix;
    if (!result.contains(filename)) result.add(filename);
    return result;
}
 
Example 2
/**
 * Finds the requested integer value for the locale.
 * Each resource consists of the following:
 *
 *    (n: cc1 cc2 ... ccx;)*
 *
 * where 'n' is the integer for the following region codes, terminated by
 * a ';'.
 *
 */
private static int findValue(String key, Locale locale) {
    Map<String, Integer> map = CalendarDataUtility.FIRST_DAY_OF_WEEK.equals(key) ?
        firstDay : minDays;
    String region = locale.getCountry();

    if (region.isEmpty()) {
        // Use "US" as default
        region = "US";
    }

    Integer val = map.get(region);
    if (val == null) {
        String valStr =
            LocaleProviderAdapter.forType(Type.CLDR).getLocaleResources(Locale.ROOT)
               .getCalendarData(key);
        val = retrieveInteger(valStr, region)
            .orElse(retrieveInteger(valStr, "001").orElse(0));
        map.putIfAbsent(region, val);
    }

    return val;
}
 
Example 3
Source Project: anno4j   File: LangString.java    License: Apache License 2.0 6 votes vote down vote up
private static String toLang(Locale locale) {
	String language = locale.getLanguage();
	String country = locale.getCountry();
	String variant = locale.getVariant();
	boolean l = language.length() != 0;
	boolean c = country.length() != 0;
	boolean v = variant.length() != 0;
	StringBuilder result = new StringBuilder(language);
	if (c || (l && v)) {
		result.append('-').append(country.toLowerCase());
	}
	if (v && (l || c)) {
		result.append('-').append(variant);
	}
	return result.toString();
}
 
Example 4
/**
 * Fallback from the given locale name by removing the rightmost _-delimited
 * element. If there is none, return the root locale ("", "", ""). If this
 * is the root locale, return null. NOTE: The string "root" is not
 * recognized; do not use it.
 * 
 * @return a new Locale that is a fallback from the given locale, or null.
 */
public static Locale fallback(Locale loc) {

    // Split the locale into parts and remove the rightmost part
    String[] parts = new String[]
        { loc.getLanguage(), loc.getCountry(), loc.getVariant() };
    int i;
    for (i=2; i>=0; --i) {
        if (parts[i].length() != 0) {
            parts[i] = "";
            break;
        }
    }
    if (i<0) {
        return null; // All parts were empty
    }
    return new Locale(parts[0], parts[1], parts[2]);
}
 
Example 5
Source Project: mapwize-ui-android   File: UnitLocale.java    License: MIT License 5 votes vote down vote up
private static UnitLocale getFrom(Locale locale) {
    String countryCode = locale.getCountry();
    if ("US".equals(countryCode)) return Imperial; // USA
    if ("LR".equals(countryCode)) return Imperial; // liberia
    if ("MM".equals(countryCode)) return Imperial; // burma
    return Metric;
}
 
Example 6
private String createLocalePath(Locale locale) {
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();
    String localePath = null;
    if (!variant.equals("")) {
        localePath = "_" + language + "/_" + country + "/_" + variant;
    } else if (!country.equals("")) {
        localePath = "_" + language + "/_" + country;
    } else {
        localePath = "_" + language;
    }

    return localePath;
}
 
Example 7
Source Project: Xamarin-Forms-Shape   File: MonoPackageManager.java    License: MIT License 5 votes vote down vote up
public static void LoadApplication (Context context, String runtimeDataDir, String[] apks)
{
	synchronized (lock) {
		if (!initialized) {
			System.loadLibrary("monodroid");
			Locale locale       = Locale.getDefault ();
			String language     = locale.getLanguage () + "-" + locale.getCountry ();
			String filesDir     = context.getFilesDir ().getAbsolutePath ();
			String cacheDir     = context.getCacheDir ().getAbsolutePath ();
			String dataDir      = context.getApplicationInfo ().dataDir + "/lib";
			ClassLoader loader  = context.getClassLoader ();

			Runtime.init (
					language,
					apks,
					runtimeDataDir,
					new String[]{
						filesDir,
						cacheDir,
						dataDir,
					},
					loader,
					new java.io.File (
						android.os.Environment.getExternalStorageDirectory (),
						"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
					MonoPackageManager_Resources.Assemblies,
					context.getPackageName ());
			initialized = true;
		}
	}
}
 
Example 8
@SuppressLint("NewApi")
private Locale checkChineseLocale(Locale locale) {
    if ("zh".equals(locale.getLanguage())) {
        String country = locale.getCountry();
        if ("CN".equals(country) || "TW".equals(country)) {
            return null;
        } else {
            String script = locale.getScript();
            if ("Hans".equals(script)) {
                return SIMPLIFIED_CHINESE;
            } else if ("Hant".equals(script)) {
                return TRADITIONAL_CHINESE;
            } else {
                VayLog.w(TAG, String.format("Unknown zh locale script: %s. Falling back to trying countries...", script));
                if ("SG".equals(country)) {
                    return SIMPLIFIED_CHINESE;
                } else if ("HK".equals(country) || "MO".equals(country)) {
                    return TRADITIONAL_CHINESE;
                } else {
                    VayLog.w(TAG, String.format("Unknown zh locale: %s. Falling back to zh-Hans-CN...", locale.toLanguageTag()));
                    return SIMPLIFIED_CHINESE;
                }
            }
        }
    } else {
        return null;
    }
}
 
Example 9
Source Project: Android-skin-support   File: SkinDisplayUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 判断是否为中文环境
 *
 * @param context
 * @return
 */
public static boolean isZhCN(Context context) {
    Configuration config = context.getResources().getConfiguration();
    Locale sysLocale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        sysLocale = config.getLocales().get(0);
    } else {
        //noinspection deprecation
        sysLocale = config.locale;
    }
    String lang = sysLocale.getCountry();
    return lang.equalsIgnoreCase("CN");
}
 
Example 10
private String computeLanguageAndCountryCandidate(String baseName,
                                                  Locale locale) {
    String language = locale.getLanguage();
    String country = locale.getCountry();
    if (country != null && country.length() > 0) {
        return String.format("%s_%s-%s.properties", baseName, language, country);
    } else {
        return null;
    }
}
 
Example 11
private static String getFCLocaleStr() {
    Locale l = SunToolkit.getStartupLocale();
    String localeStr = l.getLanguage();
    String country = l.getCountry();
    if (!country.equals("")) {
        localeStr = localeStr + "-" + country;
    }
    return localeStr;
}
 
Example 12
private String getLang(final Locale locale) {
  if (locale == null) {
    return "";
  }
  if (locale.getCountry().isEmpty()) {
    return locale.getLanguage();
  } else {
    return locale.getLanguage() + "-" + locale.getCountry();
  }
}
 
Example 13
private static String getFCLocaleStr() {
    Locale l = SunToolkit.getStartupLocale();
    String localeStr = l.getLanguage();
    String country = l.getCountry();
    if (!country.equals("")) {
        localeStr = localeStr + "-" + country;
    }
    return localeStr;
}
 
Example 14
/**
 * Takes a DOM structure and renders a PDF
 * 
 * @param doc
 *        DOM structure
 * @param streamOut
 */
@SuppressWarnings("unchecked")
protected void generatePDF(Document doc, OutputStream streamOut)
{
	String xslFileName = "participants-all-attrs.xsl";
	Locale currentLocale = rb.getLocale();
	if (currentLocale!=null){
		String fullLocale = currentLocale.toString();
		xslFileName = "participants-all-attrs_" + fullLocale + ".xsl";
		InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
		if (inputStream == null){
			xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl";
			inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
			if (inputStream == null){
				//We use the default file
				xslFileName = "participants-all-attrs.xsl";
			}
		}

		IOUtils.closeQuietly(inputStream);
	}
	String configFileName = "userconfig.xml";
	DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
	InputStream configInputStream = null;
	try 
	{
		configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName);
		Configuration cfg = cfgBuilder.build(configInputStream);
		
		FopFactory fopFactory = FopFactory.newInstance();
		fopFactory.setUserConfig(cfg);
		fopFactory.setStrictValidation(false);
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) {
		    // this allows font substitution to support i18n chars in PDFs - SAK-21909
		    FontQualifier fromQualifier = new FontQualifier();
		    fromQualifier.setFontFamily("DEFAULT_FONT");
		    FontQualifier toQualifier = new FontQualifier();
		    toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica"));
		    FontSubstitutions result = new FontSubstitutions();
		    result.add(new FontSubstitution(fromQualifier, toQualifier));
		    fopFactory.getFontManager().setFontSubstitutions(result);
		}
		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut);
		InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
		Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
		transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name"));
		transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id"));
		transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section"));
		transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit"));
		transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role"));
		transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status"));

		Source src = new DOMSource(doc);
		transformer.transform(src, new SAXResult(fop.getDefaultHandler()));
	}
	catch (Exception e)
	{
		log.warn("{}.generatePDF(): {}", this, e.toString());
	}
	finally
	{
		IOUtils.closeQuietly(configInputStream);
	}
}
 
Example 15
public static String localeString(Locale locale)
{
    return locale.getLanguage() + (locale.getCountry().isEmpty() ? "" : "-" + locale.getCountry());
}
 
Example 16
Source Project: birt   File: Messages.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resource bundle which is most match to specified locale.
 * <p>
 * As expected, if specified locale hasn't defined valid resource file, we
 * want to load English(default) resource file instead of the resource file
 * of default locale.
 * 
 * @param locale
 *            specified locale.
 * @param baseName
 *            the path of resource.
 * @param clazz
 *            the class whose class loader will be used by loading resource
 *            bundle.
 * @return instance of resource bundle.
 */
@SuppressWarnings("rawtypes")
private static ResourceBundle getMatchedResourceBundle( ULocale locale,
		String baseName, Class clazz )
{
	ResourceBundle bundle;
	bundle = UResourceBundle.getBundleInstance( baseName,
			locale,
			SecurityUtil.getClassLoader( clazz ) );

	if ( bundle != null )
	{
		// Bundle could be in default locale instead of English
		// if resource for the locale cannot be found.
		String language = locale.getLanguage( );
		String country = locale.getCountry( );
		boolean useDefaultResource = true;
		if ( language.length( ) == 0 && country.length( ) == 0 )
		{
			// it is definitely the match, no need to get the
			// default resource file again.
			useDefaultResource = false;
		}
		else
		{
			Locale bundleLocale = bundle.getLocale( );
			if ( bundleLocale.getLanguage( ).length( ) == 0
					&& bundleLocale.getCountry( ).length( ) == 0 )
			{
				// it is the match, no need to get the default
				// resource file again.
				useDefaultResource = false;
			}
			else if ( language.equals( bundleLocale.getLanguage( ) ) )
			{
				// Language matched
				String bundleCountry = bundleLocale.getCountry( );
				if ( country.equals( bundleCountry )
						|| bundleCountry.length( ) == 0 )
				{
					// Country matched or Bundle has no Country
					// specified.
					useDefaultResource = false;
				}
			}
		}
		if ( useDefaultResource )
		{
			bundle = ResourceBundle.getBundle( baseName,
					new Locale( "", "" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}
	return bundle;
}
 
Example 17
Source Project: sagetv   File: Sage.java    License: Apache License 2.0 4 votes vote down vote up
public static void setTimeZone(String x)
{
  String myTimeZone = get("time_zone", "");
  if (!myTimeZone.equals(x))
  {
    put("time_zone", x);
    myTimeZone = x;

    TimeZone tz = null;
    try {
      tz = new TimeZoneParse(myTimeZone).parse().convertToTz();
      if (DBG) System.out.println("Parsed TZ format:" + myTimeZone + " to: " + tz);
    } catch (ParseException e) {
      if(DBG) System.out.println("Error processing TZ:" + myTimeZone + " threw:" + e);
    }
    if(tz == null) {
      tz = TimeZone.getTimeZone(myTimeZone);
    }
    TimeZone.setDefault(tz);
    if (DBG) System.out.println("Changed default timezone to:" + tz.getDisplayName());

    // We now recreate the Locale so it's a new object and anything that's dependent upon
    // it will get recalculated then.
    userLocale = new Locale(userLocale.getLanguage(), userLocale.getCountry());

    createDFFormats();
    sage.epg.sd.SDUtils.resetTimeZoneOffset();

    // We need to re-thread this because otherwise we could deadlock on the server side waiting
    // for the quanta update to return from an API request made in the UI as part of refreshing this
    // which was originally triggered by the time zone change in the gfiber properties sent over.
    Pooler.execute(new Runnable()
    {
      public void run()
      {
        // Just refresh the UI fully, we don't need to retranslate all of the widgets
        Iterator<UIManager> walker = UIManager.getUIIterator();
        while (walker.hasNext())
        {
          UIManager theUI = walker.next();
          theUI.fullyRefreshCurrUI();
        }
      }
    });
  }
}
 
Example 18
public static void LoadApplication (Context context, ApplicationInfo runtimePackage, String[] apks)
{
	synchronized (lock) {
		if (context instanceof android.app.Application) {
			Context = context;
		}
		if (!initialized) {
			android.content.IntentFilter timezoneChangedFilter  = new android.content.IntentFilter (
					android.content.Intent.ACTION_TIMEZONE_CHANGED
			);
			context.registerReceiver (new mono.android.app.NotifyTimeZoneChanges (), timezoneChangedFilter);
			
			System.loadLibrary("monodroid");
			Locale locale       = Locale.getDefault ();
			String language     = locale.getLanguage () + "-" + locale.getCountry ();
			String filesDir     = context.getFilesDir ().getAbsolutePath ();
			String cacheDir     = context.getCacheDir ().getAbsolutePath ();
			String dataDir      = getNativeLibraryPath (context);
			ClassLoader loader  = context.getClassLoader ();

			Runtime.init (
					language,
					apks,
					getNativeLibraryPath (runtimePackage),
					new String[]{
						filesDir,
						cacheDir,
						dataDir,
					},
					loader,
					new java.io.File (
						android.os.Environment.getExternalStorageDirectory (),
						"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
					MonoPackageManager_Resources.Assemblies,
					context.getPackageName ());
			
			mono.android.app.ApplicationRegistration.registerApplications ();
			
			initialized = true;
		}
	}
}
 
Example 19
/**
 * Converts Locale object to the BCP 47 compliant string format.
 * This works for API level lower than 24.
 *
 * Note that for Android M or before, we cannot use Locale.getLanguage() and
 * Locale.toLanguageTag() for this purpose. Since Locale.getLanguage() returns deprecated
 * language code even if the Locale object is constructed with updated language code. As for
 * Locale.toLanguageTag(), it does a special conversion from deprecated language code to updated
 * one, but it is only usable for Android N or after.
 * @return a well-formed IETF BCP 47 language tag with language and country code that
 *         represents this locale.
 */
public static String toLanguageTag(Locale locale) {
    String language = getUpdatedLanguageForChromium(locale.getLanguage());
    String country = locale.getCountry();
    if (language.equals("no") && country.equals("NO") && locale.getVariant().equals("NY")) {
        return "nn-NO";
    }
    return country.isEmpty() ? language : language + "-" + country;
}
 
Example 20
Source Project: uavstack   File: StringHelper.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Determine the RFC 3066 compliant language tag, as used for the HTTP "Accept-Language" header.
 * 
 * @param locale
 *            the Locale to transform to a language tag
 * @return the RFC 3066 compliant language tag as String
 */
public static String toLanguageTag(Locale locale) {

    return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
}