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:com.willwinder.universalgcodesender.i18n.Localization.java

public static String getString(String id) {
    String result = "";
    try {//  w w w  .  j  a va 2 s  .  c om
        String val = bundle.getString(id);
        result = new String(val.getBytes("ISO-8859-1"), "UTF-8");
    } catch (Exception e) {
        // Ignore this error, we will later try to fetch the string from the english bundle
    }

    if (StringUtils.isEmpty(StringUtils.trimToEmpty(result))) {
        try {
            if (english == null) {
                english = ResourceBundle.getBundle("resources.MessagesBundle", new Locale("en", "US"));
            }
            String val = english.getString(id);
            result = new String(val.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
            result = "<" + id + ">";
        }
    }

    return result;
}

From source file:de.cosmocode.commons.converter.LocaleCountryIsoConverter.java

@Override
public String toAlpha2(String iso3166Alpha3) {
    Preconditions.checkNotNull(iso3166Alpha3, "iso3166Alpha3 must not be null");
    if (Patterns.ISO_3166_1_ALPHA_2.matcher(iso3166Alpha3).matches()) {
        // already ISO 3166-1 alpha-2 (two letter)
        return iso3166Alpha3;
    } else if (StringUtils.isBlank(iso3166Alpha3)) {
        // this is here for convenience, to allow empty languages
        return TrimMode.EMPTY.apply(iso3166Alpha3);
    }/*from   w  w w. j  a  va2 s.  c  o  m*/
    Preconditions.checkArgument(Patterns.ISO_3166_1_ALPHA_3.matcher(iso3166Alpha3).matches(),
            "Language Code %s not in ISO 3166 alpha-3", iso3166Alpha3);

    // try to get two letter code from cache
    final String fromCache = cache.get(iso3166Alpha3);
    if (fromCache != null) {
        return fromCache;
    }

    // search for three letter code in the known country codes of Locale
    for (final String alpha2 : Locale.getISOCountries()) {
        final String alpha3 = new Locale("", alpha2).getISO3Country();
        if (iso3166Alpha3.equals(alpha3)) {
            LOG.trace("Found alpha-2: {} for alpha-3: {}", alpha2, alpha3);
            cache.put(iso3166Alpha3, alpha2);
            return alpha2;
        }
    }

    // if we arrive here then the Locale class could not find the iso3 code
    throw new IsoConversionException("No known alpha-2 code for " + iso3166Alpha3);
}

From source file:com.googlecode.l10nmavenplugin.model.PropertiesFileUtils.java

/**
 * Parent locale , ex: en_US => en/*from w  ww  .  j  av a 2s  . c  o m*/
 * 
 * @param locale
 * @return null if no parent locale
 */
public static Locale getParentLocale(Locale locale) {
    Locale parentLocale = null;
    if (locale != null) {
        String language = locale.getLanguage();
        String country = locale.getCountry();
        String variant = locale.getVariant();

        if (!StringUtils.isEmpty(language)) {
            if (!StringUtils.isEmpty(variant)) {
                parentLocale = new Locale(language, country);
            } else if (!StringUtils.isEmpty(country)) {
                parentLocale = new Locale(language);
            }
        }
    }
    return parentLocale;
}

From source file:com.github.mrstampy.gameboot.messages.context.GameBootContextTest.java

/**
 * Test intl./*  w ww.ja va  2  s . com*/
 *
 * @throws Exception
 *           the exception
 */
@Test
public void testIntl() throws Exception {
    ResponseContext rc = lookup.lookup(UNEXPECTED_ERROR, Locale.getDefault());
    assertRC(rc, UNEXPECTED_ERROR, DEFAULT);

    rc = lookup.lookup(UNEXPECTED_ERROR, Locale.FRENCH);
    assertRC(rc, UNEXPECTED_ERROR, FRENCH);

    rc = lookup.lookup(UNEXPECTED_ERROR, Locale.UK);
    assertRC(rc, UNEXPECTED_ERROR, DEFAULT);

    rc = lookup.lookup(UNEXPECTED_ERROR, new Locale("r2", "D2"));
    assertRC(rc, UNEXPECTED_ERROR, DEFAULT);
}

From source file:com.surveypanel.utils.DBMessageSource.java

/**
 * build an array of alternative locales for the given locale <br/>
 * result does not contain original locale
 * @param locale the locale to find alternatives for
 * @return an array of alternative locales
 */// w ww.  j  av a2s .  c om
private Locale[] getAlternativeLocales(Locale locale) {
    Locale[] locales = new Locale[3];
    int count = 0;
    if (locale.getVariant().length() > 0) {
        // add a locale without the variant
        locales[count] = new Locale(locale.getLanguage(), locale.getCountry());
        count++;
    }
    if (locale.getCountry().length() > 0) {
        // add a locale without the country
        locales[count] = new Locale(locale.getLanguage());
        count++;
    }
    if (fallbackLocale != null) {
        locales[count] = fallbackLocale;
    }
    return locales;
}

From source file:org.openmrs.module.bom.web.controller.LoginPageOverrideController.java

@RequestMapping(value = "/myLogin.htm", method = RequestMethod.POST)
public String loginUser(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {//from   w w w . j  a va2s.  co  m

    String redirect = null;

    try {
        String username = request.getParameter("uname");
        String password = request.getParameter("pw");

        // get the place to redirect: for touch screen this is simple
        redirect = determineRedirect(request);

        // only try to authenticate if they actually typed in a username
        if (username != null && username.length() > 0) {

            Context.authenticate(username, password);

            if (Context.isAuthenticated()) {

                User user = Context.getAuthenticatedUser();

                // load the user's default locale if possible
                if (user.getUserProperties() != null) {
                    if (user.getUserProperties().containsKey(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)) {
                        String localeString = user
                                .getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
                        Locale locale = null;
                        if (localeString.length() == 5) {
                            //user's locale is language_COUNTRY (i.e. en_US)
                            String lang = localeString.substring(0, 2);
                            String country = localeString.substring(3, 5);
                            locale = new Locale(lang, country);
                        } else {
                            // user's locale is only the language (language plus greater than 2 char country code
                            locale = new Locale(localeString);
                        }
                        OpenmrsCookieLocaleResolver oclr = new OpenmrsCookieLocaleResolver();
                        oclr.setLocale(request, response, locale);
                    }
                }

                // In case the user has no preferences, make sure that the context has some locale set
                if (Context.getLocale() == null) {
                    Context.setLocale(OpenmrsConstants.GLOBAL_DEFAULT_LOCALE);
                }

            }

            if (log.isDebugEnabled()) {
                log.debug("Redirecting after login to: " + redirect);
                log.debug("Locale address: " + request.getLocalAddr());
            }

            response.sendRedirect(redirect);

            //return redirect;
        }
    } catch (ContextAuthenticationException e) {
        // set the error message for the user telling them
        // to try again
        //session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.password.invalid");
        log.error("failed to authenticate: ", e);
    } catch (Exception e) {
        log.error("Uexpected auth error", e);
    }

    // send the user back the login page because they either 
    // had a bad password or are locked out

    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("rwandaprimarycare.loginFailed"));
    session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, redirect);

    return "/module/bom/bomLogin";
}

From source file:com.cotrino.knowledgemap.db.Question.java

/**
 * http://stackoverflow.com/questions/2103598/java-simple-sentence-parser
 * @param text/*from  w w  w .  j  a v a2s  .  c o m*/
 * @param language
 * @param country
 * @return
 */
public static List<String> tokenize(String text, String language, String country) {
    List<String> sentences = new ArrayList<String>();
    Locale currentLocale = new Locale(language, country);
    BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(currentLocale);
    sentenceIterator.setText(text);
    int boundary = sentenceIterator.first();
    int lastBoundary = 0;
    while (boundary != BreakIterator.DONE) {
        boundary = sentenceIterator.next();
        if (boundary != BreakIterator.DONE) {
            sentences.add(text.substring(lastBoundary, boundary));
        }
        lastBoundary = boundary;
    }
    return sentences;
}

From source file:com.nexmo.client.verify.endpoints.VerifyEndpointTest.java

@Test
public void testConstructVerifyParamsNullNumber() throws Exception {
    try {/*www .ja va2s.com*/
        new VerifyRequest(null, "Brand.com", "Your friend", 4, new Locale("en", "GB"),
                VerifyClient.LineType.MOBILE);
        fail("A null 'number' argument should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // this is expected
    }
}

From source file:com.smi.travel.datalayer.view.dao.impl.AgentCommissionReportImpl.java

@Override
public List getAgentReportSummary(String datefrom, String dateto, String user, String agentid) {
    Session session = this.sessionFactory.openSession();
    List data = new ArrayList();
    Date thisdate = new Date();
    UtilityFunction util = new UtilityFunction();
    String sql = AGENTCOM_SUMMARY_QUERY + " where db.tour_date >= '" + datefrom + "' and db.tour_date <= '"
            + dateto + "'";

    if ((agentid != null) && (!"".equalsIgnoreCase(agentid))) {
        sql += " and agt.id =" + agentid;
    }/*w  ww.  ja va  2s .c  o  m*/
    sql += " GROUP BY agt.`code`,agt.`name` HAVING  comission <> 0 ORDER BY `agt`.`name`";
    System.out.println("sql :" + sql);
    List<Object[]> QueryAgentComSummaryList = session.createSQLQuery(sql).addScalar("code", Hibernate.STRING)
            .addScalar("name", Hibernate.STRING).addScalar("count_booking", Hibernate.STRING)
            .addScalar("comission", Hibernate.INTEGER).list();

    System.out.println("QueryAgentComSummaryList.size : " + QueryAgentComSummaryList.size());
    for (Object[] B : QueryAgentComSummaryList) {
        AgentCommissionSummaryReport report = new AgentCommissionSummaryReport();
        report.setCode(util.ConvertString(B[0]));
        report.setName(util.ConvertString(B[1]));
        report.setCountbook(
                StringUtils.isEmpty(util.ConvertString(B[2])) ? 0 : Integer.parseInt(util.ConvertString(B[2])));
        report.setCommission(B[3] == null ? 0 : (Integer) B[3]);
        report.setSystemdate(new SimpleDateFormat("dd MMM yy hh:mm", new Locale("us", "us")).format(thisdate));
        report.setDatefrom(new SimpleDateFormat("dd MMM yyyy", new Locale("us", "us"))
                .format(util.convertStringToDate(datefrom)));
        report.setDateto(new SimpleDateFormat("dd MMM yyyy", new Locale("us", "us"))
                .format(util.convertStringToDate(dateto)));
        report.setUser(user);
        data.add(report);
    }
    return data;
}

From source file:com.googlecode.noweco.webmail.lotus.LotusWebmailConnection.java

@SuppressWarnings("unchecked")
public LotusWebmailConnection(final HttpClient httpclient, final HttpHost host, final String prefix)
        throws IOException {
    this.prefix = prefix;
    HttpGet httpGet;//from  w w  w  .  jav a2 s.co  m
    HttpResponse rsp;
    HttpEntity entity;

    String baseName = getClass().getPackage().getName().replace('.', '/') + "/lotus";
    ResourceBundle bundleBrowser = null;

    for (Header header : (Collection<Header>) httpclient.getParams()
            .getParameter(ClientPNames.DEFAULT_HEADERS)) {
        if (header.getName().equals("Accept-Language")) {
            Matcher matcher = LANGUAGE_PATTERN.matcher(header.getValue());
            if (matcher.find()) {
                String region = matcher.group(2);
                if (region != null && region.length() != 0) {
                    bundleBrowser = ResourceBundle.getBundle(baseName, new Locale(matcher.group(1), region));
                } else {
                    bundleBrowser = ResourceBundle.getBundle(baseName, new Locale(matcher.group(1)));
                }
            }
        }
    }

    ResourceBundle bundleEnglish = ResourceBundle.getBundle(baseName, new Locale("en"));

    String deletePattern = "(?:" + Pattern.quote(bundleEnglish.getString("Delete"));
    if (bundleBrowser != null) {
        deletePattern = deletePattern + "|" + Pattern.quote(bundleBrowser.getString("Delete")) + ")";
    }
    String emptyTrashPattern = "(?:" + Pattern.quote(bundleEnglish.getString("EmptyTrash"));
    if (bundleBrowser != null) {
        emptyTrashPattern = emptyTrashPattern + "|" + Pattern.quote(bundleBrowser.getString("EmptyTrash"))
                + ")";
    }

    deleteDeletePattern = Pattern.compile(
            "_doClick\\('([^/]*/\\$V\\d+ACTIONS/[^']*)'[^>]*>" + deletePattern + "\\\\" + deletePattern);
    deleteEmptyTrashPattern = Pattern.compile(
            "_doClick\\('([^/]*/\\$V\\d+ACTIONS/[^']*)'[^>]*>" + deletePattern + "\\\\" + emptyTrashPattern);

    httpGet = new HttpGet(prefix + "/($Inbox)?OpenView");

    rsp = httpclient.execute(host, httpGet);

    entity = rsp.getEntity();
    String string = EntityUtils.toString(entity);
    if (entity != null) {
        LOGGER.trace("inbox content : {}", string);
        EntityUtils.consume(entity);
    }

    Matcher matcher = MAIN_PAGE_PATTERN.matcher(string);
    if (!matcher.find()) {
        throw new IOException("Unable to parse main page");
    }
    pagePrefix = matcher.group(1);

    this.httpclient = httpclient;
    this.host = host;
}