Example usage for java.util Locale Locale

List of usage examples for java.util Locale Locale

Introduction

In this page you can find the example usage for java.util Locale Locale.

Prototype

public Locale(String language, String country) 

Source Link

Document

Construct a locale from language and country.

Usage

From source file:de.iew.services.impl.MessageSourceServiceIntegrationTest.java

@Test
public void testResolveCode() {
    if (log.isDebugEnabled()) {
        log.debug("===== Starte MessageSourceServiceIntegrationTest Testcase =====");
    }/* w w  w  .j ava2 s .com*/

    // Testfix erstellen
    Locale enUs = new Locale("en", "US");

    // Test
    assertEquals("Sprachschl\u00fcssel 1", this.messageSource.getMessage("msg.key1", null, this.defaultLocale));
    assertEquals("Sprachschl\u00fcssel 1", this.messageSource.getMessage("msg.key1", null, this.defaultLocale));
    assertEquals("Sprachschl\u00fcssel 1", this.messageSource.getMessage("msg.key1", null, this.defaultLocale));
    assertEquals("Language Key 1", this.messageSource.getMessage("msg.key1", null, enUs));
    assertEquals("Sprachschl\u00fcssel 1", this.messageSource.getMessage("msg.key1", null, this.defaultLocale));
    assertEquals("Language Key 1", this.messageSource.getMessage("msg.key1", null, enUs));
    assertEquals("Sprachschl\u00fcssel 1", this.messageSource.getMessage("msg.key1", null, this.defaultLocale));

    assertEquals("Mein Name ist Max Mustermann.",
            this.messageSource.getMessage("msg.key3", new String[] { "Max Mustermann" }, enUs));
    assertEquals("Mein Name ist Max Mustermann.",
            this.messageSource.getMessage("msg.key3", new String[] { "Max Mustermann" }, this.defaultLocale));

    if (log.isDebugEnabled()) {
        log.debug("===== Beende MessageSourceServiceIntegrationTest Testcase =====");
    }
}

From source file:alpha.portal.webapp.filter.LocaleFilter.java

/**
 * This method looks for a "locale" request parameter. If it finds one, it
 * sets it as the preferred locale and also configures it to work with JSTL.
 * /*w ww .  j ava2s  .c o  m*/
 * @param request
 *            the current request
 * @param response
 *            the current response
 * @param chain
 *            the chain
 * @throws IOException
 *             when something goes wrong
 * @throws ServletException
 *             when a communication failure happens
 */
@Override
@SuppressWarnings("unchecked")
public void doFilterInternal(HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    final String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
        final int indexOfUnderscore = locale.indexOf('_');
        if (indexOfUnderscore != -1) {
            final String language = locale.substring(0, indexOfUnderscore);
            final String country = locale.substring(indexOfUnderscore + 1);
            preferredLocale = new Locale(language, country);
        } else {
            preferredLocale = new Locale(locale);
        }
    }

    final HttpSession session = request.getSession(false);

    if (session != null) {
        if (preferredLocale == null) {
            preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
        } else {
            session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
            Config.set(session, Config.FMT_LOCALE, preferredLocale);
        }

        if ((preferredLocale != null) && !(request instanceof LocaleRequestWrapper)) {
            request = new LocaleRequestWrapper(request, preferredLocale);
            LocaleContextHolder.setLocale(preferredLocale);
        }
    }

    final String theme = request.getParameter("theme");
    if ((theme != null) && request.isUserInRole(Constants.ADMIN_ROLE)) {
        final Map<String, Object> config = (Map) this.getServletContext().getAttribute(Constants.CONFIG);
        config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
}

From source file:org.alfresco.error.AlfrescoRuntimeExceptionTest.java

public void testI18NBehaviour() {
    // Ensure that the bundle is present on the classpath
    String baseResourceAsProperty = BASE_RESOURCE_NAME.replace('.', '/') + ".properties";
    URL baseResourceURL = AlfrescoRuntimeExceptionTest.class.getClassLoader()
            .getResource(baseResourceAsProperty);
    assertNotNull(baseResourceURL);/*from  w  w  w . j ava2s .  co  m*/

    baseResourceAsProperty = BASE_RESOURCE_NAME.replace('.', '/') + "_fr_FR" + ".properties";
    baseResourceURL = AlfrescoRuntimeExceptionTest.class.getClassLoader().getResource(baseResourceAsProperty);
    assertNotNull(baseResourceURL);

    // Ensure we can load it as a resource bundle
    ResourceBundle properties = ResourceBundle.getBundle(BASE_RESOURCE_NAME);
    assertNotNull(properties);
    properties = ResourceBundle.getBundle(BASE_RESOURCE_NAME, new Locale("fr", "FR"));
    assertNotNull(properties);

    // From here on in, we use Spring

    // Register the bundle
    I18NUtil.registerResourceBundle(BASE_RESOURCE_NAME);

    AlfrescoRuntimeException exception1 = new AlfrescoRuntimeException(MSG_PARAMS,
            new Object[] { PARAM_VALUE });
    assertTrue(exception1.getMessage().contains(VALUE_PARAMS));
    AlfrescoRuntimeException exception3 = new AlfrescoRuntimeException(MSG_ERROR);
    assertTrue(exception3.getMessage().contains(VALUE_ERROR));

    // Change the locale and re-test
    I18NUtil.setLocale(new Locale("fr", "FR"));

    AlfrescoRuntimeException exception2 = new AlfrescoRuntimeException(MSG_PARAMS,
            new Object[] { PARAM_VALUE });
    assertTrue(exception2.getMessage().contains(VALUE_FR_PARAMS));
    AlfrescoRuntimeException exception4 = new AlfrescoRuntimeException(MSG_ERROR);
    assertTrue(exception4.getMessage().contains(VALUE_FR_ERROR));

    AlfrescoRuntimeException exception5 = new AlfrescoRuntimeException(NON_I18NED_MSG);
    assertTrue(exception5.getMessage().contains(NON_I18NED_MSG));

    // MNT-13028
    String param1 = PARAM_VALUE + "_1";
    String param2 = PARAM_VALUE + "_2";
    String param3 = PARAM_VALUE + "_3";
    AlfrescoRuntimeException exception6 = new AlfrescoRuntimeException(NON_EXISTING_MSG,
            new Object[] { param1, param2, param3 });
    String message6 = exception6.getMessage();
    assertTrue(message6.contains(NON_EXISTING_MSG));
    assertTrue(message6.contains(param1));
    assertTrue(message6.contains(param2));
    assertTrue(message6.contains(param3));
}

From source file:com.opensymphony.xwork2.conversion.impl.StringConverterTest.java

public void testFloatToStringConversionPL() throws Exception {
    // given//from w  ww  . j a v a 2  s. co  m
    StringConverter converter = new StringConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("pl", "PL"));

    // when has max fraction digits
    Object value = converter.convertValue(context, null, null, null, Float.MIN_VALUE, null);

    // then does not lose fraction digits
    assertEquals("0," + StringUtils.repeat('0', 44) + "14", value);

    // when has max integer digits
    value = converter.convertValue(context, null, null, null, Float.MAX_VALUE, null);

    // then does not lose integer digits
    assertEquals("34028235" + StringUtils.repeat('0', 31), value);

    // when cannot be represented exactly with a finite binary number
    value = converter.convertValue(context, null, null, null, 0.1f, null);

    // then produce the shortest decimal representation that can unambiguously identify the true value of the floating-point number
    assertEquals("0,1", value);
}

From source file:com.sonicle.webtop.core.app.servlet.ServletHelper.java

public static Locale homogenizeLocale(HttpServletRequest request) {
    Locale locale = request.getLocale();
    if (locale.getLanguage().equals("it")) {
        return new Locale("it", "IT");
    } else {/*from  w ww.  j av a2 s. c  om*/
        return new Locale("en", "EN");
    }
}

From source file:backing.LocaleBean.java

public LocaleBean() {
    locales = new HashMap();
    locales.put("NAmerica", new Locale("en", "US"));
    locales.put("SAmerica", new Locale("es", "MX"));
    locales.put("Germany", new Locale("de", "DE"));
    locales.put("France", new Locale("fr", "FR"));
}

From source file:org.killbill.billing.plugin.simpletax.internal.Country.java

/**
 * Computes the name of this country, in the specified language, or in
 * English if the language is not {@linkplain Locale#getAvailableLocales()
 * supported}./*from w  ww .  j  a v  a2s. co  m*/
 *
 * @param language
 *            The preferred language in which the country name should be
 *            expressed.
 * @return The name of the country in the specified language, or in English.
 */
public String computeName(Locale language) {
    return new Locale("", code).getDisplayCountry(language);
}

From source file:br.com.hslife.orcamento.controller.AbstractController.java

public Usuario getUsuarioLogado() {
    if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuarioLogado") == null) {
        Usuario u = new Usuario();
        try {//from   w ww  .  j a va 2 s.  c  om
            u = usuarioComponent.getUsuarioLogado();
            u.setSenha(null);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuarioLogado", u);
        } catch (Exception e) {
            errorMessage(e.getMessage());
        }
    }

    // Aplica as configuraes de locale para pt_BR
    // Tentativa de definir o pt_BR para a aplicao inteira independente das configuraes do servidor de aplicao
    FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("pt", "BR"));

    return (Usuario) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
            .get("usuarioLogado");
}

From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java

/**
 * Initialise the System.properties according to Silverpeas needs and configuration.
 *
 * @param sce//w  w w  .j a va 2  s  .com
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    ResourceBundle silverpeasInitialisationSettings = FileUtil.loadBundle(
            "org.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
            new Locale("fr", ""));

    loadExternalJarLibraries();

    String systemSettingsPath = silverpeasInitialisationSettings.getString("pathInitialize");
    if (!StringUtil.isDefined(systemSettingsPath)) {
        Logger.getLogger("bootstrap").log(Level.SEVERE,
                "Repository Initialize for systemSettings.properties file is not defined in Settings.");
    } else {
        File pathInitialize = new File(systemSettingsPath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(pathInitialize, "systemSettings.properties"));
            Properties systemFileProperties = new Properties(System.getProperties());
            systemFileProperties.load(fis);

            // Fix - empty proxy port and proxy host not supported by Spring Social
            if (!StringUtil.isDefined(systemFileProperties.getProperty("http.proxyPort"))) {
                systemFileProperties.remove("http.proxyPort");
            }
            if (!StringUtil.isDefined(systemFileProperties.getProperty("http.proxyHost"))) {
                systemFileProperties.remove("http.proxyHost");
            }

            System.setProperties(systemFileProperties);
            if (isTrustoreConfigured()) {
                registerSSLSocketFactory();
            }
        } catch (FileNotFoundException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE,
                    "File systemSettings.properties in directory {0} not found.", pathInitialize);
        } catch (IOException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE, "Unable to read systemSettings.properties.");
        } catch (GeneralSecurityException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE, "Unable to configure the trustore.");
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
    URLManager.setSilverpeasVersion(sce.getServletContext().getInitParameter("SILVERPEAS_VERSION"));
    springContextListener.contextInitialized(sce);
}

From source file:cn.vlabs.umt.services.user.service.impl.UserServiceImpl.java

@Override
public void sendWarnUCUser(String username, String baseUrl) {
    Properties prop = new Properties();
    String mergeUrl;//from w w  w . j a  v a  2  s.  c o  m
    try {
        mergeUrl = URLEncoder.encode(baseUrl + "/user/merge.do?act=show", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        mergeUrl = "";
    }
    String fullUrl = RequestUtil.addParam(baseUrl + "/login", "WebServerURL", mergeUrl);
    fullUrl = RequestUtil.addParam(fullUrl, "appname", "mirror");
    prop.setProperty("fullUrl", fullUrl);
    try {
        email.send(new Locale("zh", "cn"), username, EmailTemplate.MERGE_USER, prop);
    } catch (MailException e) {
        LOGGER.error(e.getMessage(), e);
    }
}