Java Code Examples for java.util.Locale

The following are top voted examples for showing how to use java.util.Locale. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: timemachine   File: TimeMachineTest.java View source code 7 votes vote down vote up
@Before
public void setUp() throws Exception {
	DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
	zone = DateTimeZone.getDefault();
	locale = Locale.getDefault();
	DateTimeZone.setDefault(LONDON);
	java.util.TimeZone.setDefault(LONDON.toTimeZone());
	Locale.setDefault(Locale.UK);
}
 
Example 2
Project: my-ministry-assistant   File: TimeEntriesFragment.java View source code 6 votes vote down vote up
public void calculateValues() {
	if(is_month) {
		mMonth = buttonFormat.format(date.getTime()).toString().toUpperCase(Locale.getDefault());
    	mYear = String.valueOf(date.get(Calendar.YEAR)).toUpperCase(Locale.getDefault());
    	
    	dbDateFormatted = TimeUtils.dbDateFormat.format(date.getTime());
    	dbTimeFrame = "month";
	} else {
		mMonth = getActivity().getApplicationContext().getResources().getString(R.string.service_year).toUpperCase(Locale.getDefault());
		mYear = serviceYear.get(Calendar.YEAR) + " - " + String.valueOf(serviceYear.get(Calendar.YEAR) + 1);
		
		dbDateFormatted = TimeUtils.dbDateFormat.format(serviceYear.getTime());
		dbTimeFrame = "year";
	}
}
 
Example 3
Project: my-ministry-assistant   File: MainActivity.java View source code 6 votes vote down vote up
public void changeLang(String lang) {
	if (lang.equalsIgnoreCase(""))
		return;
	Locale myLocale = new Locale(lang);
	Locale.setDefault(myLocale);
	android.content.res.Configuration config = new android.content.res.Configuration();
	config.locale = myLocale;
	getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
 
Example 4
Project: jentrata-msh   File: EbmsUtility.java View source code 6 votes vote down vote up
/**
 * Convert an GMT representation of string <code>dateTime</code> to java Date object. 
 *  
 * @param dateTime A string representing a GMT datetime. 
 * @return A java date object representing the <code>dateTime</code>
 * @throws UtilitiesException	When unable to convert the dateTime format.
 */
public static Date
GMT2Date(String dateTime) throws UtilitiesException
{
	// GMT Example: Wed Jul 25 09:59:00 GMT+08:00 2007
	// Reminder: We need to use locale.US for parsing the above dateTime.
	Date GMTdate = DataFormatter.getInstance().parseDate(dateTime, "EEE MMM dd HH:mm:ss zz yyyy", Locale.US);
	
	if (GMTdate == null)
		throw new UtilitiesException("Unable to convert datetime to GMT format:" + dateTime);
	
	return GMTdate;
}
 
Example 5
Project: speechalyzer   File: Preprocessor.java View source code 6 votes vote down vote up
/**
 * Der Preprozessor sollte dahingehend erweitert werden, das er
 * sprachspezifische Regeln verarbeiten kann.
 * 
 * Beispiel:
 * 
 * 8_mail_vocab 8_mail_vocab.de 8_mail_vocab.en
 * 
 * Preprozessor-Klasse bietet Methode setLocale(java.util.Locale) mit der
 * festgelegt wird, welche Datei genutzt wird. Entweder eine vorhanden
 * Sprachspezifische oder die Default-Datei (ohne Sprachangabe)
 * 
 * @param locale
 *            The (global) Locale of all preprocessors.
 */
public static synchronized void setLocale(Locale locale) {
	_langId = "." + locale.getLanguage();
}
 
Example 6
Project: UnicentaPOS_AD   File: JPanelConfigLocale.java View source code 6 votes vote down vote up
public void loadProperties(AppConfig config) {
    
    String slang = config.getProperty("user.language");
    String scountry = config.getProperty("user.country");
    String svariant = config.getProperty("user.variant");
    
    if (slang != null && !slang.equals("") && scountry != null && svariant != null) {                    
        Locale currentlocale = new Locale(slang, scountry, svariant);
        for (int i = 0 ; i < jcboLocale.getItemCount(); i++)  {
            LocaleInfo l = (LocaleInfo) jcboLocale.getItemAt(i);
            if (currentlocale.equals(l.getLocale())) {
                jcboLocale.setSelectedIndex(i);
                break;
            }
        }        
    } else {
        jcboLocale.setSelectedIndex(0);
    }
    
    jcboInteger.setSelectedItem(writeWithDefault(config.getProperty("format.integer")));
    jcboDouble.setSelectedItem(writeWithDefault(config.getProperty("format.double")));
    jcboCurrency.setSelectedItem(writeWithDefault(config.getProperty("format.currency")));
    jcboPercent.setSelectedItem(writeWithDefault(config.getProperty("format.percent")));
    jcboDate.setSelectedItem(writeWithDefault(config.getProperty("format.date")));
    jcboTime.setSelectedItem(writeWithDefault(config.getProperty("format.time")));
    jcboDatetime.setSelectedItem(writeWithDefault(config.getProperty("format.datetime")));
           
    dirty.setDirty(false);
}
 
Example 7
Project: aipo   File: MetaData.java View source code 6 votes vote down vote up
/**
 Stores a property for later retrieval, uses the notation
 propertyName.localeName for locale distinction

<p>For example, title.fr_FR will store the French title, while
title.sp will keep the Spanich one. title will keep the value
which can be used when defaulting because en entry is not present
for the queried locale</p>
*/
private void setProperty(String name, Locale locale, Object value)
{
    if (name == null)
    {
        return;
    }

    if (locale != null)
    {
        name = name + "." + locale.toString();
    }

    if (value == null)
    {
        data.remove(name);
    }
    else
    {
        data.put(name, value);
    }
}
 
Example 8
Project: ilarkesto   File: DateFormField.java View source code 6 votes vote down vote up
private static String prepareValue(String s) {
	if (s == null) return null;
	s = s.trim();
	if (s.length() == 0) return null;
	try {
		return Date.parseTolerant(s).toString(Locale.GERMANY);
	} catch (ParseException ex) {
		return s;
	}
}
 
Example 9
Project: jena   File: SPARQL_REST.java View source code 6 votes vote down vote up
private void dispatch(HttpAction action) {
    HttpServletRequest req = action.request ;
    HttpServletResponse resp = action.response ;
    String method = req.getMethod().toUpperCase(Locale.ROOT) ;

    if (method.equals(METHOD_GET))
        doGet$(action);
    else if (method.equals(METHOD_HEAD))
        doHead$(action);
    else if (method.equals(METHOD_POST))
        doPost$(action);
    else if (method.equals(METHOD_PATCH))
        doPatch$(action) ;
    else if (method.equals(METHOD_OPTIONS))
        doOptions$(action) ;
    else if (method.equals(METHOD_TRACE))
        //doTrace(action) ;
        errorMethodNotAllowed("TRACE") ;
    else if (method.equals(METHOD_PUT))
        doPut$(action) ;   
    else if (method.equals(METHOD_DELETE))
        doDelete$(action) ;
    else
        errorNotImplemented("Unknown method: "+method) ;
}
 
Example 10
Project: SampleCSipSimpleApp   File: PopupMainActivity.java View source code 6 votes vote down vote up
/**
 * Ensures at least one language is available for tts
 */
private boolean checkAndSetLanguageAvailable() {
    // checks if at least one language is available in Tts
    final Locale defaultLocale = Locale.getDefault();
    // If the language for the default locale is available, then
    // use that.
    int defaultAvailability = tts.isLanguageAvailable(defaultLocale);

    if (defaultAvailability == TextToSpeech.LANG_AVAILABLE ||
            defaultAvailability == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
            defaultAvailability == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {
        tts.setLanguage(defaultLocale);
        Log.d(THIS_FILE, "Set locale " + defaultLocale.toString());
        return true;
    }

    for (Locale locale : Locale.getAvailableLocales()) {
        int availability = tts.isLanguageAvailable(locale);
        if (availability == TextToSpeech.LANG_AVAILABLE ||
                availability == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
                availability == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {
            Log.d(THIS_FILE, "Set locale " + locale.toString());
            tts.setLanguage(locale);
            return true;
        }
    }
    return false;
}
 
Example 11
Project: visuwall   File: TestTilesPlugin.java View source code 6 votes vote down vote up
/**
 * String representation of a Locale. A bug in the
 * Locale.toString() method results in Locales with
 * just a variant being incorrectly displayed.
 */
private String print(Locale locale) {

    return locale.getLanguage() + "_" +
              locale.getCountry() + "_" +
              locale.getVariant();
}
 
Example 12
Project: ilarkesto   File: LearningLocalizer.java View source code 6 votes vote down vote up
@Override
public String string(String key, Object... parameters) {
	if (!developmentMode) locale = Locale.GERMAN;

	if (parameters != null) {
		for (int i = 0; i < parameters.length; i++) {
			if (parameters[i] instanceof Throwable) parameters[i] = Str.format(parameters[i]);
		}
	}

	String template = getTemplate(locale, key);
	if (template == null) {
		StringBuilder sb = new StringBuilder();
		sb.append("@@@");
		sb.append(key);
		for (int i = 0; i < parameters.length; i++) {
			sb.append(", ").append(parameters[i]);
		}
		return sb.toString();
	}
	return format(template, parameters);
}
 
Example 13
Project: spikes   File: SmartContextInteractionService.java View source code 6 votes vote down vote up
@Override
public void onReady() {
    super.onReady();
    Log.i(TAG, "Creating " + this);
    mHotwordDetector = createAlwaysOnHotwordDetector(
            "Hello There", Locale.forLanguageTag("en-US"), mHotwordCallback);
}
 
Example 14
Project: closure-stylesheets   File: GssFunctionsTest.java View source code 6 votes vote down vote up
public void testDivGetCallResultString_otherLocale() throws GssFunctionException {
  Locale.setDefault(Locale.FRANCE);
  try {
    GssFunctions.Div funct = new GssFunctions.Div();
    assertEquals("103.06748466px",
        funct.getCallResultString(ImmutableList.of("100800px", "978")));
  } finally {
    Locale.setDefault(Locale.US);
  }
}
 
Example 15
Project: elpaaso-core   File: HeaderSignin.java View source code 6 votes vote down vote up
private void createComponents() {
        logger.debug("create header signin panel");

        PaasUser paasUser = WicketSession.get().getPaasUser();
        Label username;

        if (paasUser == null) {            // not connected
            getSession().invalidate();
            setResponsePage(HomePage.class);
            return;
        } else {
            username = new Label("loggedUserName", paasUser.getFirstName());
        }

        add(username);

//        LogoutLink logout = new LogoutLink("logoutLink");
        logout = new LogoutLink("logoutLink");
        add(logout);
//        IModel<String> onLogoutMessage = new StringResourceModel("portal.headercommon.logoutconfirm", this, null);
//        logout.add(new AttributeModifier("onclick", "return confirm('" + onLogoutMessage.getObject().replace("'", "\\'")+ "');"));

        Locale currentLocale = getSession().getLocale();
        String localeDisplayName = currentLocale.getDisplayName();
        logger.debug("refreshSwitchLangLink() : current local display name : {} ", localeDisplayName);
        if (Locale.FRENCH.equals(currentLocale)) {
            langLink = new SwitchLangLink("switchLangLink", Locale.ENGLISH);
        } else {
            langLink = new SwitchLangLink("switchLangLink", Locale.FRENCH);
        }

        add(langLink);

//        langLink.add(new Label("lang", getStringResourceModel("portal.design.header.signin.lang")));
        labelLang = new Label("lang","version anglaise");
        langLink.add(labelLang);
    }
 
Example 16
Project: assertj-db   File: HsqldbDatabase_Test.java View source code 6 votes vote down vote up
@Test
@NeedReload
public void test_ColumnEquality_containsValues() {
  Table table = new Table(source, "test");
  Changes changes = new Changes(table).setStartPointNow();
  update("update test set var2=20");
  changes.setEndPointNow();

  assertThat(table)
          .column("var1").containsValues(1)
          .column("var2").containsValues(20)
          .column("var3").containsValues(3.3)
          .column("var4").containsValues(4.4)
          .column("var5").containsValues("5")
          .column("var6").containsValues("6")
          .column("var7").containsValues("7")
          .column("var8").containsValues("8")
          .column("var9").containsValues("9")
          .column("var10").containsValues(DateValue.of(2007, 12, 23))
          .column("var11").containsValues(TimeValue.of(9, 1))
          .column("var12").containsValues(DateTimeValue.of(DateValue.of(2007, 12, 23), TimeValue.of(9, 1)))
          .column("var13").containsValues(DateTimeValue.of(DateValue.of(2007, 12, 23), TimeValue.of(9, 1)))
          .column("var14").containsValues(10)
          .column("var15").containsValues(11)
          .column("var16").containsValues(true)
          .column("var17").containsValues(false)
          .column("var18").containsValues(12)
          .column("var19").containsValues(13)
          .column("var20").containsValues(14)
          .column("var21").containsValues(15)
          .column("var22").containsValues(bytesContentFromClassPathOf("h2-logo-2.png"))
          .column("var23").containsValues(bytesContentFromClassPathOf("h2-logo-2.png"))
          .column("var24").containsValues(bytesContentFromClassPathOf("h2-logo-2.png"))
          .column("var25").containsValues(Locale.FRENCH)
          .column("var26").containsValues(Locale.FRENCH)
  ;
}
 
Example 17
Project: sinovoice-voicewake   File: HciCloudSysHelper.java View source code 6 votes vote down vote up
/**
 * ??
 * 
 * @return true ?
 */
private int checkAuth() {
    // ?????
    int initResult;
    AuthExpireTime objExpireTime = new AuthExpireTime();
    initResult = HciCloudSys.hciGetAuthExpireTime(objExpireTime);
    if (initResult == HciErrorCode.HCI_ERR_NONE) {
        // ??,û???,??
        Date date = new Date(objExpireTime.getExpireTime() * 1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
                Locale.CHINA);
        Log.i(TAG, "expire time: " + sdf.format(date));

        if (objExpireTime.getExpireTime() * 1000 < System
                .currentTimeMillis()) {
            // ??, ??
            Log.i(TAG, "expired date");

            initResult = HciCloudSys.hciCheckAuth();
            if (initResult == HciErrorCode.HCI_ERR_NONE) {
                Log.i(TAG, "checkAuth success");
                return initResult;
            } else {
                Log.e(TAG, "checkAuth failed: " + initResult);
                return initResult;
            }
        } else {
            // ????,????(>7)
            Log.i(TAG, "checkAuth success");
            return initResult;
        }
    } else if (initResult == HciErrorCode.HCI_ERR_SYS_AUTHFILE_INVALID) {
        // ?Auth??(?,û??),???
        Log.i(TAG, "authfile invalid");

        initResult = HciCloudSys.hciCheckAuth();
        if (initResult == HciErrorCode.HCI_ERR_NONE) {
            Log.i(TAG, "checkAuth success");
            return initResult;
        } else {
            Log.e(TAG, "checkAuth failed: " + initResult);
            return initResult;
        }
    } else {
        // ??,SDK?"??"???
        Log.e(TAG, "getAuthExpireTime Error:" + initResult);
        return initResult;
    }
}
 
Example 18
Project: LanguageBuddy   File: Iso3166.java View source code 6 votes vote down vote up
/** Creates a new instance of Iso3166 */
public Iso3166()
{
    codeMap = new HashMap<String,IsoCountry>();
    countries = new TreeSet<IsoCountry>();
    String [] countryCodes = Locale.getISOCountries();
    
    for (int c = 0; c<countryCodes.length; c++)
    {
        Locale tempLocale = new Locale("en",countryCodes[c]);
        IsoCountry ic = new IsoCountry(countryCodes[c],
            tempLocale.getDisplayCountry());
        countries.add(ic);
        //codeMap.put(countryCodes[c], tempLocale.getDisplayCountry());
        codeMap.put(countryCodes[c], ic);
    }
}
 
Example 19
Project: aipo   File: ALLocalizationService.java View source code 6 votes vote down vote up
@Override
public ResourceBundle getBundle(String bundleName, Locale locale) {
  try {
    return super.getBundle(bundleName, locale);
  } catch (MissingResourceException e) {
    return super.getBundle(bundleName, Locale.JAPANESE);
  }
}
 
Example 20
Project: Magnolia   File: FreemarkerHelperTest.java View source code 6 votes vote down vote up
@Test
public void testUuidLinksAreTransformedToRelativeLinksInWebContext() throws IOException, TemplateException, RepositoryException {
    final MockContent page = new MockContent("baz");
    final MockHierarchyManager hm = prepareHM(page);

    final AggregationState agg = new AggregationState();
    agg.setMainContent(page);
    final WebContext context = createStrictMock(WebContext.class);
    final MockSession session = new MockSession("website");
    MgnlContext.setInstance(context);
    expect(context.getContextPath()).andReturn("/");
    expect(context.getLocale()).andReturn(Locale.CANADA);
    expect(context.getAggregationState()).andReturn(agg);
    expect(MgnlContext.getJCRSession("website")).andReturn(session).times(2);

    LinkTransformerManager.getInstance().setMakeBrowserLinksRelative(true);

    replay(context);
    agg.setOriginalURI("/foo/bar/boo.html");
    doTestUuidLinksAreTransformed(context, "== Some text... blah blah... <a href=\"baz.html\">Bleh</a> ! ==");
    verify(context);
}
 
Example 21
Project: android-platform-tools-base   File: LocaleManagerTest.java View source code 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public void testGetLanguageRegion() {
    Locale prevLocale = Locale.getDefault();
    TimeZone prevTimeZone = TimeZone.getDefault();
    try {
        assertFalse("The envvar $STUDIO_LOCALES should not be set during unit test runs",
                System.getenv("STUDIO_LOCALES") != null);
        assertNull(System.getProperty("studio.locales"), System.getProperty("studio.locales"));
        Locale.setDefault(Locale.US);

        // Pick English=>GU based on options
        System.setProperty("studio.locales", "es_US, en_GU");
        assertEquals("GU", LocaleManager.getLanguageRegion("en"));

        System.setProperty("studio.locales", "es-rUS, en-rGU"); // alternate supported syntax
        assertEquals("GU", LocaleManager.getLanguageRegion("en"));
        System.setProperty("studio.locales", "");

        // Pick English=>GB based on timezone
        Locale.setDefault(Locale.ITALY);
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
        assertEquals("GB", LocaleManager.getLanguageRegion("en"));

        // Pick English=>CA based on system locale country
        Locale.setDefault(Locale.CANADA);
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Oslo"));
        assertEquals("CA", LocaleManager.getLanguageRegion("en"));

        // Swedish should map to Sweden even though FI is a relevant region for sv
        // Regression test for issue 136001
        Locale.setDefault(Locale.FRANCE); // unrelated locale to this test
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Helsinki"));
        assertEquals("SE", LocaleManager.getLanguageRegion("sv"));

        TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
        assertEquals("GB", LocaleManager.getLanguageRegion("en"));
        TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
        assertEquals("US", LocaleManager.getLanguageRegion("en"));
        assertEquals("ES", LocaleManager.getLanguageRegion("es"));
        TimeZone.setDefault(TimeZone.getTimeZone("America/Manaus"));
        assertEquals("BR", LocaleManager.getLanguageRegion("pt"));
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Lisbon"));
        assertEquals("PT", LocaleManager.getLanguageRegion("pt"));
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Oslo"));
        assertEquals("PT", LocaleManager.getLanguageRegion("pt"));
    } finally {
        Locale.setDefault(prevLocale);
        TimeZone.setDefault(prevTimeZone);
    }
}
 
Example 22
Project: cafeUnoesc   File: TimeSpanConverterTest.java View source code 6 votes vote down vote up
public void testItalian() throws Exception {
    converter = new TimeSpanConverter(Locale.ITALIAN);
    assertTimeSpanString("Ora", System.currentTimeMillis() - second);
    assertTimeSpanString("4 secondi fa", System.currentTimeMillis() - second * 4);
    assertTimeSpanString("1 minuto fa", System.currentTimeMillis() - second * 61);
    assertTimeSpanString("3 minuti fa", System.currentTimeMillis() - minute * 3);
    assertTimeSpanString("1 ora fa", System.currentTimeMillis() - hour);
    assertTimeSpanString("3 ore fa", System.currentTimeMillis() - hour * 3);
    assertTimeSpanString("18 dic 09", getSpecificLocalDateInMillis(2009, 11, 18));
}
 
Example 23
Project: BigPangOrderManager   File: LocaleManager.java View source code 6 votes vote down vote up
private static String getSystemLanguage() {
  Locale locale = Locale.getDefault();
  if (locale == null) {
    return DEFAULT_LANGUAGE;
  }
  String language = locale.getLanguage();
  // Special case Chinese
  if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(language)) {
    return language + "-r" + getSystemCountry();
  }
  return language;
}
 
Example 24
Project: RapidBeans   File: CurrencyTest.java View source code 6 votes vote down vote up
/**
 * test java currency.
 */
public void testJavaCurrency() {

	java.util.Currency cur = java.util.Currency.getInstance(Locale.GERMANY);
	assertEquals("EUR", cur.getCurrencyCode());
	// "\u20AC" is the Unicode for the Euro symbol '€'
	assertTrue(cur.getSymbol().equals("\u20AC") || cur.getSymbol().equals("EUR"));

	final HashMap<String, java.util.Currency> currencyMap = new HashMap<String, java.util.Currency>();
	for (String isoLanguage : Locale.getISOLanguages()) {
		for (String isoCountry : Locale.getISOCountries()) {
			final Locale locale = new Locale(isoLanguage, isoCountry);
			if (locale != null) {
				final java.util.Currency currency = java.util.Currency.getInstance(locale);
				if (currency != null) {
					if (!currencyMap.containsKey(currency.getCurrencyCode())) {
						currencyMap.put(currency.getCurrencyCode(), currency);
					}
				}
			}
		}
	}
	// final String[] currencyCodes = new
	// String[currencyMap.keySet().size()];
	// int i = 0;
	// for (final Object o : currencyMap.keySet()) {
	// currencyCodes[i++] = (String) o;
	// }
	// Arrays.sort(currencyCodes);
	// for (final String currencyCode : currencyCodes) {
	// final java.util.Currency currency = (java.util.Currency)
	// currencyMap.get(currencyCode);
	// System.out.println("Currency: " + currency.getCurrencyCode()
	// + ", Symbol: " + currency.getSymbol(Locale.GERMANY));
	// }
}
 
Example 25
Project: TestingStaff   File: LocaleServiceImpl.java View source code 6 votes vote down vote up
@Override
public Locale getCurrentLocale() {
	if (currentLanguage.equals(LANGUAGE_TYPE.EN)) {
		return Locale.ENGLISH;
	} else if (currentLanguage.equals(LANGUAGE_TYPE.TC)) {
		return Locale.TRADITIONAL_CHINESE;
	} else if (currentLanguage.equals(LANGUAGE_TYPE.SC)) {
		return Locale.SIMPLIFIED_CHINESE;
	} else {
		return Locale.ENGLISH;
	}
}
 
Example 26
Project: cms-ce   File: LocaleXmlCreator.java View source code 6 votes vote down vote up
private String getISO3Language( final Locale locale )
{
    try
    {
        return locale.getISO3Language();
    }
    catch ( final Exception e )
    {
        return null;
    }
}
 
Example 27
Project: collect-mobile   File: LanguageNames.java View source code 6 votes vote down vote up
private static Map<String, Locale> mapLocaleByIso3() {
    String[] languages = Locale.getISOLanguages();
    Map<String, Locale> localeByIso3 = new HashMap<String, Locale>(languages.length);
    for (String language : languages) {
        Locale locale = new Locale(language);
        localeByIso3.put(locale.getISO3Language().toLowerCase(), locale);
    }
    return localeByIso3;
}
 
Example 28
Project: Contacts   File: HanziToPinyin.java View source code 6 votes vote down vote up
public static HanziToPinyin getInstance() {
    synchronized (HanziToPinyin.class) {
        if (sInstance != null) {
            return sInstance;
        }
        // Check if zh_CN collation data is available
        final Locale locale[] = Collator.getAvailableLocales();
        for (int i = 0; i < locale.length; i++) {
            if (locale[i].equals(Locale.CHINESE)) {
                // Do self validation just once.
                if (DEBUG) {
                    Log.d(TAG, "Self validation. Result: " + doSelfValidation());
                }
                sInstance = new HanziToPinyin(true);
                return sInstance;
            }
        }
        Log.w(TAG, "There is no Chinese collator, HanziToPinyin is disabled");
        sInstance = new HanziToPinyin(false);
        return sInstance;
    }
}
 
Example 29
Project: cms-ce   File: LocaleXmlCreator.java View source code 6 votes vote down vote up
private String getISO3Country( final Locale locale )
{
    try
    {
        return locale.getISO3Country();
    }
    catch ( final Exception e )
    {
        return null;
    }
}
 
Example 30
Project: TerasologyLauncher   File: SettingsController.java View source code 6 votes vote down vote up
private void populateLanguage() {
    languageBox.getItems().clear();
    for (Locale locale : Languages.SUPPORTED_LOCALES) {
        String item = locale.toLanguageTag() + " : " + BundleUtils.getLabel(locale, Languages.SETTINGS_LABEL_KEYS.get(locale));
        if (!locale.equals(Languages.getCurrentLocale())) {
            item += " (" + BundleUtils.getLabel(Languages.SETTINGS_LABEL_KEYS.get(locale)) + ")";
        }
        languageBox.getItems().add(item);

        if (Languages.getCurrentLocale().equals(locale)) {
            languageBox.getSelectionModel().select(item);
        }
    }
}
 
Example 31
Project: ecms   File: WindowKey.java View source code 6 votes vote down vote up
WindowKey(String windowId,
          WindowState windowState,
          PortletMode portletMode,
          Locale locale,
          Map<String, String[]> parameters,
          Map<String, String[]> query)
{

  // Clone parameter map
  parameters = Util.clone(parameters);
  query = Util.clone(query);

  // Compute hashCode;
  int hashCode =
    windowId.hashCode() ^
    windowState.hashCode() ^
    portletMode.hashCode() ^
    locale.hashCode() ^
    Util.hashCode(parameters) ^
    Util.hashCode(query);

  //
  this.windowId = windowId;
  this.windowState = windowState.toString();
  this.portletMode = portletMode.toString();
  this.parameters = parameters;
  this.locale = locale;
  this.hashCode = hashCode;
  this.query = query;
}
 
Example 32
Project: c10n   File: DefaultC10NAnnotationsTest.java View source code 6 votes vote down vote up
@Test
public void testDefaultLocales() {
    assertMsgForLocaleIs(Locale.GERMAN, "de");
    assertMsgForLocaleIs(Locale.ENGLISH, "en");
    assertMsgForLocaleIs(Locale.FRENCH, "fr");
    assertMsgForLocaleIs(Locale.ITALIAN, "it");
    assertMsgForLocaleIs(Locale.JAPANESE, "ja");
    assertMsgForLocaleIs(Locale.KOREAN, "ko");
    assertMsgForLocaleIs(new Locale("ru"), "ru");
    assertMsgForLocaleIs(Locale.CHINESE, "zh");
}
 
Example 33
Project: c10n   File: DefaultLocaleMapping.java View source code 6 votes vote down vote up
@Override
public Locale findClosestMatch(Set<Locale> fromSet, Locale forLocale) {
    String variant = forLocale.getDisplayVariant();
    String country = forLocale.getCountry();
    String language = forLocale.getLanguage();
    Locale[] c = new Locale[4];
    if (null != variant && !variant.isEmpty()) {
        c[0] = forLocale;
    }
    if (null != country && !country.isEmpty()) {
        c[1] = new Locale(language, country);
    }
    if (null != language && !language.isEmpty()) {
        c[2] = new Locale(language);
    }
    c[3] = Locale.ROOT;
    for (Locale candidateLocale : c) {
        if (fromSet.contains(candidateLocale)) {
            return candidateLocale;
        }
    }
    //This code intentionally uses Locale.getDefault()
    //in order to behave in the same was as the default
    //resource bundle locale search mechanism.
    //source: http://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html
    Locale systemDefaultLocale = Locale.getDefault();
    if (!systemDefaultLocale.equals(forLocale)) {
        return findClosestMatch(fromSet, systemDefaultLocale);
    }
    return null;
}
 
Example 34
Project: Magnolia   File: FreemarkerHelperTest.java View source code 6 votes vote down vote up
private void doTestUuidLinksAreTransformed(Context webCtx, String expectedOutput) throws IOException, TemplateException, RepositoryException {
    MockHierarchyManager cfgHM = MockUtil.createHierarchyManager(RepositoryConstants.WEBSITE, "fakeemptyrepo");
    MockUtil.mockObservation(cfgHM);
    final MockSession session = new MockSession("website");

    final SystemContext sysMockCtx = createStrictMock(SystemContext.class);

    if (webCtx == null) {
        expect(sysMockCtx.getLocale()).andReturn(Locale.KOREA);
        final MockHierarchyManager hm = prepareHM(new MockContent("baz"));
        expect(sysMockCtx.getJCRSession("website")).andReturn(session).anyTimes();
    }
    ComponentsTestUtil.setInstance(SystemContext.class, sysMockCtx);
    replay(sysMockCtx);

    ComponentsTestUtil.setImplementation(URI2RepositoryManager.class, URI2RepositoryManager.class);
    final I18nContentSupport i18NSupportMock = createStrictMock(I18nContentSupport.class);
    ComponentsTestUtil.setInstance(I18nContentSupport.class, i18NSupportMock);

    expect(i18NSupportMock.toI18NURI("/foo/bar.html")).andReturn("/foo/bar/baz.html").times(1, 2);

    final String text = "Some text... blah blah... <a href=\"${link:{uuid:{" + SOME_UUID + "},repository:{website},handle:{/foo/bar},nodeData:{},extension:{html}}}\">Bleh</a> !";
    final MockContent c = new MockContent("content");
    c.addNodeData("text", text);
    tplLoader.putTemplate("test", "== ${text} ==");

    replay(i18NSupportMock);
    MgnlContext.setInstance(webCtx == null ? sysMockCtx : webCtx);
    assertRendereredContentWithoutCheckingContext(expectedOutput, c, "test");
    verify(i18NSupportMock);
    verify(sysMockCtx);
}
 
Example 35
Project: magnificent-mileage   File: TestMessages.java View source code 6 votes vote down vote up
public void testLanguages() {

        // Force default to make test work on non-US machines
        Locale.setDefault(new Locale("en", "US"));

        String e = Message.GEOCODE_FROM_AMBIGUOUS.get();
        String f = Message.GEOCODE_FROM_AMBIGUOUS.get(Locale.CANADA_FRENCH);
        String s = Message.GEOCODE_FROM_AMBIGUOUS.get(new Locale("es"));

        TestCase.assertNotNull(e);
        TestCase.assertNotNull(f);
        TestCase.assertNotNull(s);
        TestCase.assertNotSame(e, f);
        TestCase.assertNotSame(e, s);
        TestCase.assertNotSame(f, s);
    }
 
Example 36
Project: fenixedu-cms   File: CMSURLHandler.java View source code 6 votes vote down vote up
private void handleRSS(HttpServletRequest req, HttpServletResponse res, Site site, String slug) throws IOException,
        XMLStreamException, ServletException {
    slug = slug.replaceFirst("/", "");

    Locale locale =
            Strings.isNullOrEmpty(req.getParameter("locale")) ? I18N.getLocale() : new Locale.Builder().setLanguageTag(
                    req.getParameter("locale")).build();

    String[] parts = slug.split("/");

    if (parts.length == 1) {
        res.setContentType("application/rss+xml;charset=UTF-8");
        res.getOutputStream().write(RSSService.generateRSSForSite(site, locale).getBytes(StandardCharsets.UTF_8));
    } else {
        Category category = site.categoryForSlug(parts[1]);
        if (category == null) {
            errorPage(req, res, site, 404);
        } else {
            res.setContentType("application/rss+xml;charset=UTF-8");
            res.getOutputStream().write(RSSService.generateRSSForCategory(category, locale).getBytes(StandardCharsets.UTF_8));
        }
    }

}
 
Example 37
Project: openjdk8-jdk   File: CalendarNameProviderImpl.java View source code 6 votes vote down vote up
@Override
public boolean isSupportedLocale(Locale locale) {
    if (Locale.ROOT.equals(locale)) {
        return true;
    }
    String calendarType = null;
    if (locale.hasExtensions()) {
        calendarType = locale.getUnicodeLocaleType("ca");
        locale = locale.stripExtensions();
    }

    if (calendarType != null) {
        switch (calendarType) {
        case "buddhist":
        case "japanese":
        case "gregory":
        case "islamic":
        case "roc":
            break;
        default:
            // Unknown calendar type
            return false;
        }
    }
    if (langtags.contains(locale.toLanguageTag())) {
        return true;
    }
    if (type == LocaleProviderAdapter.Type.JRE) {
        String oldname = locale.toString().replace('_', '-');
        return langtags.contains(oldname);
    }
    return false;
}
 
Example 38
Project: iot-server-appliances   File: HttpServer.java View source code 5 votes vote down vote up
private void handleInternal(final HttpRequest request, final HttpResponse response,
							final HttpContext context) throws HttpException, IOException {

	String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
	if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
		throw new MethodNotSupportedException(method + " method not supported");
	}

	String target = request.getRequestLine().getUri();
	File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
	if (!file.exists()) {

		response.setStatusCode(HttpStatus.SC_NOT_FOUND);
		log.severe("File " + file.getPath() + " not found");
		return;

	} else if (!file.canRead()) {

		response.setStatusCode(HttpStatus.SC_FORBIDDEN);
		log.severe("Cannot read file " + file.getPath());
		return;

	} else if (file.isDirectory()) {

		if (target.endsWith("/")) {

			boolean isExist = false;
			for (String index : DEFAULT_INDEX_FILES_LIST) {
				final File t_file = new File(this.docRoot + File.separator + target, index);
				if (t_file.exists()) {
					file = t_file;
					isExist = true;
					break;
				}
			}
			if(!isExist)return;

		} else {
			//redirect browser - doing basically what apache does
			response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY);
			String newUrl = target + "/";
			response.setHeader("Location", newUrl);
			return;
		}

	}

	HttpCoreContext coreContext = HttpCoreContext.adapt(context);
	HttpConnection conn = coreContext.getConnection(HttpConnection.class);
	response.setStatusCode(HttpStatus.SC_OK);

	String displayAgentHome = ResourceUtil.getDisplayAgentHome();
	System.setProperty("content.types.user.table",displayAgentHome + File.separator + LauncherConstants.CONF_PATH + File.separator + "content-types.properties");
	String mimeType= URLConnection.guessContentTypeFromName(file.getName());

	NFileEntity body = new NFileEntity(file, ContentType.create(mimeType));
	response.setEntity(body);
	//log.info(conn + ": serving file " + file.getPath());
}
 
Example 39
Project: aipo   File: JetspeedTemplateLocatorService.java View source code 5 votes vote down vote up
/**
 * Helper function for template locator to find a localized (NLS) resource.
 * Considers both language and country resources as well as all the possible
 * media-types for the request
 * 
 * @param data
 *          The rundata for the request.
 * @param locale
 *          The locale for the request.
 * 
 * @return The possible paths to a localized template ordered by descending
 *         preference
 */
private List localizeTemplateName(RunData data, Locale inLocale) {
  List templates = new ArrayList();
  Locale tmplocale = null;

  if (inLocale != null) {
    tmplocale = inLocale;
  } else {
    CustomLocalizationService locService =
      (CustomLocalizationService) ServiceUtil
        .getServiceByName(LocalizationService.SERVICE_NAME);
    tmplocale = locService.getLocale(data);
  }

  // Get the locale store it in the user object
  if (tmplocale == null) {
    tmplocale =
      new Locale(
        TurbineResources.getString("locale.default.language", "en"),
        TurbineResources.getString("locale.default.country", "US"));
  }

  if (data.getUser() != null) {
    data.getUser().setTemp("locale", tmplocale);
  }

  StringBuffer templatePath = new StringBuffer();

  // retrieve all the possible media types
  String type =
    data.getParameters().getString(Profiler.PARAM_MEDIA_TYPE, null);
  List types = new ArrayList();
  CapabilityMap cm = ((JetspeedRunData) data).getCapability();

  // Grab the Locale from the temporary storage in the User object
  Locale locale =
    data.getUser() != null
      ? (Locale) data.getUser().getTemp("locale")
      : tmplocale;
  String language = locale.getLanguage();
  String country = locale.getCountry();

  if (null != type) {
    types.add(type);
  } else {
    Iterator i = cm.listMediaTypes();
    while (i.hasNext()) {
      types.add(i.next());
    }
  }

  Iterator typeIterator = types.iterator();

  while (typeIterator.hasNext()) {
    type = (String) typeIterator.next();

    if ((type != null) && (type.length() > 0)) {
      templatePath.append(PATH_SEPARATOR).append(type);
    }

    if ((language != null) && (language.length() > 0)) {
      templatePath.append(PATH_SEPARATOR).append(language);
    }

    if ((country != null) && (country.length() > 0)) {
      templatePath.append(PATH_SEPARATOR).append(country);
    }

    templates.add(templatePath.toString());
    templatePath.setLength(0);
  }

  return templates;
}
 
Example 40
Project: funCKit   File: FunckitMenuBar.java View source code 5 votes vote down vote up
private void createSettingsMenu() {
    Settings settings = view.getSessionModel().getSettings();
    // create settings menu
    JMenu settingsMenu = new JMenu(tr("menuBar.settings"));
    settingsMenu.setMnemonic(tr("menuBar.Mnemonic.settings").charAt(0));
    add(settingsMenu);

    JMenu languageMenu = new JMenu(tr("menuBar.settings.language"));
    languageMenu.setMnemonic(tr("menuBar.Mnemonic.settings.language").charAt(0));

    lafMenu = new JMenu(tr("menuBar.settings.lafSubMenu"));
    lafMenu.setMnemonic(tr("menuBar.Mnemonic.settings.lafSubMenu").charAt(0));
    fillLafSubmenu();

    languageItems = new LinkedHashSet<JCheckBoxMenuItem>();
    for (Locale loc : Language.getAvailableLocales()) {
        JCheckBoxMenuItem languageItem = new JCheckBoxMenuItem(loc.getDisplayLanguage());
        languageMenu.add(languageItem);
        languageItem.setActionCommand(loc.getLanguage());
        languageItem.addActionListener(new LanguageChangeActionListener(view, view
                .getController()));
        languageItem.setSelected(loc.equals(Language.getCurrentLocale()));

        languageItems.add(languageItem);
    }


    liveCheckItem = new JCheckBoxMenuItem(tr("menuBar.settings.liveCheck"));
    liveCheckItem.setMnemonic(tr("menuBar.Mnemonic.settings.liveCheck").charAt(0));
    liveCheckItem.addActionListener(new RealTimeValidationOnOffActionListener(view));
    liveCheckItem.setSelected(view.getSessionModel().getSettings()
            .getBoolean(Settings.REALTIME_VALIDATION));

    gridLockItem = new JCheckBoxMenuItem(tr("menuBar.settings.lockGrid"));
    gridLockItem.addActionListener(new GridLockActionListener(view, view.getController()));
    gridLockItem.setSelected(view.getSessionModel().getSettings()
            .getBoolean(Settings.GRID_LOCK));
    gridLockItem.setMnemonic(tr("menuBar.Mnemonic.settings.lockGrid").charAt(0));

    simulationUndoItem = new JCheckBoxMenuItem(tr("menuBar.settings.simulationUndo"));
    simulationUndoItem.addActionListener(new SimulationUndoActionListener(view, view
            .getController()));
    simulationUndoItem.setSelected(settings
            .getBoolean(Settings.SIMULATION_UNDO_ENABLED));
    simulationUndoItem.setMnemonic(tr("menuBar.Mnemonic.settings.simulationUndo").charAt(0));

    toggleLowQualityItem = new JCheckBoxMenuItem(tr("menuBar.settings.toggleLowQuality"));
    toggleLowQualityItem.setSelected(view.getSessionModel().getSettings()
            .getBoolean(Settings.LOW_RENDERING_QUALITY_MODE));
    toggleLowQualityItem
            .setMnemonic(tr("menuBar.Mnemonic.settings.toggleLowQuality").charAt(0));
    toggleLowQualityItem.addActionListener(new LowQualityOnOffActionListener(view, view
            .getController()));
    toggleTooltipsItem = new JCheckBoxMenuItem(
            tr("menuBar.settings.toggleTooltips"));
    toggleTooltipsItem.setSelected(view.getSessionModel().getSettings()
            .getBoolean(Settings.SHOW_TOOLTIPS));
    toggleTooltipsItem.setMnemonic(tr("menuBar.Mnemonic.settings.toggleTooltips").charAt(0));
    toggleTooltipsItem.addActionListener(new ToggleTooltipsActionListener(view, view
            .getController()));


    JMenuItem restoreDefaultItem = new JMenuItem(tr("menuBar.settings.restoreDefault"));
    restoreDefaultItem.addActionListener(new RestoreDefaultActionListener(view, view
            .getController()));

    if (settings.getBoolean(Settings.EXPERT_MODE)) {
        colorMenu = new JMenu(tr("menuBar.settings.colorMenu"));
        colorMenu.setMnemonic(tr("menuBar.Mnemonic.settings.colorMenu").charAt(0));
        fillColorMenu();
        settingsMenu.add(colorMenu);
    }


    switch (view.getSessionModel().getViewType()) {
    case VIEW_TYPE_ELEANING_SOLVE:
        settingsMenu.add(liveCheckItem);
        settingsMenu.add(gridLockItem);
        settingsMenu.add(simulationUndoItem);
        settingsMenu.add(toggleLowQualityItem);
        settingsMenu.add(toggleTooltipsItem);
        break;
        
    case VIEW_TYPE_STANDALONE :
        settingsMenu.add(languageMenu);
        settingsMenu.add(lafMenu);
        settingsMenu.addSeparator();
        settingsMenu.add(liveCheckItem);
        settingsMenu.add(gridLockItem);
        settingsMenu.add(simulationUndoItem);
        settingsMenu.add(toggleLowQualityItem);
        settingsMenu.add(toggleTooltipsItem);
        settingsMenu.addSeparator();
        settingsMenu.add(restoreDefaultItem);
        break;
    case VIEW_TYPE_PRESENTER:
        settingsMenu.add(gridLockItem);
        settingsMenu.add(simulationUndoItem);
        settingsMenu.add(toggleLowQualityItem);
        settingsMenu.add(toggleTooltipsItem);
        break;
    }
    
}
 
Example 41
Project: aipo   File: EventlogCsvExportScreen.java View source code 5 votes vote down vote up
/**
 *
 */
@Override
protected String getCSVString(RunData rundata) throws Exception {
  if (ALEipUtils.isAdmin(rundata)) {
    SelectQuery<EipTEventlog> query = Database.query(EipTEventlog.class);

    Date startDay =
      DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.JAPAN).parse(
        rundata.getParameters().get("start_day"));
    Date endDay =
      DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.JAPAN).parse(
        rundata.getParameters().get("end_day"));
    Calendar cal = Calendar.getInstance();
    cal.setTime(endDay);
    cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 1);
    endDay = cal.getTime();
    Expression exp1 =
      ExpressionFactory.greaterOrEqualExp(
        EipTEventlog.EVENT_DATE_PROPERTY,
        startDay);
    Expression exp2 =
      ExpressionFactory.lessExp(EipTEventlog.EVENT_DATE_PROPERTY, endDay);
    query.andQualifier(exp1.andExp(exp2));
    ResultList<EipTEventlog> list = query.getResultList();
    String LINE_SEPARATOR = System.getProperty("line.separator");
    try {
      StringBuffer sb =
        new StringBuffer("\"??\",\"??\",\"???\",\"??\",\"??IP\",\"??\"");
      EventlogResultData data;
      for (ListIterator<EipTEventlog> iterator =
        list.listIterator(list.size()); iterator.hasPrevious();) {
        sb.append(LINE_SEPARATOR);
        data = getResultData(iterator.previous());
        sb.append("\"");
        sb.append(data.getEventDate());
        sb.append("\",\"");
        sb.append(data.getUserFullName());
        sb.append("\",\"");
        sb.append(data.getPortletName());
        sb.append("\",\"");
        sb.append(data.getEventName());
        sb.append("\",\"");
        sb.append(data.getIpAddr());
        sb.append("\",\"");
        sb.append(data.getNote());
        sb.append("\"");
      }
      return sb.toString();
    } catch (Exception e) {
      logger.error("EventlogCsvExportScreen.getCSVString", e);
      return null;
    }
  } else {
    throw new ALPermissionException();
  }
}