Example usage for java.util Locale getCountry

List of usage examples for java.util Locale getCountry

Introduction

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

Prototype

public String getCountry() 

Source Link

Document

Returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

Usage

From source file:org.lockss.util.TestMetadataUtil.java

void assertLocale(String lang, String country, String variant, Locale l) {
    assertEquals("Language", lang, l.getLanguage());
    assertEquals("Country", country, l.getCountry());
    assertEquals("Variant", variant, l.getVariant());
}

From source file:org.shept.org.springframework.web.servlet.mvc.support.ConfigurableLocaleDependentFormatResolver.java

@SuppressWarnings("unchecked")
protected Map<DateTimeLocaleConstants, String> getDateTimeLocaleConstants(Locale loc) {
    // search for exact match first
    Map<DateTimeLocaleConstants, String> localeConstants = dateTimeLocales.get(loc);
    if (localeConstants == null) {
        // if not found we search for country
        if (localeConstants == null && loc.getCountry() != null) {
            localeConstants = dateTimeLocales.get(new Locale(loc.getCountry()));
        }/*w w w .  j  a  va2 s . c o  m*/
        // if not found exact match we search for language
        if (localeConstants == null && loc.getLanguage() != null) {
            localeConstants = dateTimeLocales.get(new Locale(loc.getLanguage()));
        }
        // if not found we provide the default (as provided by the servers java settings)
        if (localeConstants == null) {
            if (logger.isErrorEnabled()) {
                logger.error("Locale constants definition not found for locale " + loc
                        + ". Using default locale instead");
            }
            localeConstants = dateTimeLocales.get(this.defaultLocale);
        }
    }
    return localeConstants;
}

From source file:com.norconex.jefmon.JEFMonSession.java

private void initLocale() {
    String cookieLocale = new CookieUtils().load(SessionLocaleUtils.COOKIE_LOCALE_KEY);
    Locale[] locales = getApp().getSupportedLocales();
    Locale locale = null;
    if (StringUtils.isNotBlank(cookieLocale)) {
        locale = LocaleUtils.toLocale(cookieLocale);
    }//from   w  ww .  j  ava  2 s  .c  o m
    if (!ArrayUtils.contains(locales, locale)) {
        locale = getLocale();
        if (!ArrayUtils.contains(locales, locale) && locale.getCountry() != null) {
            locale = new Locale(locale.getLanguage(), locale.getCountry());
        }
        if (!ArrayUtils.contains(locales, locale)) {
            locale = new Locale(locale.getLanguage());
        }
        if (!ArrayUtils.contains(locales, locale)) {
            locale = locales[0];
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("User initial locale is:" + locale);
        }
    }
    setLocale(locale);
}

From source file:com.cyclopsgroup.tornado.ui.view.user.UserProfile.java

/**
 * Override method execute in class UserProfile
 *
 * @see com.cyclopsgroup.waterview.Module#execute(com.cyclopsgroup.waterview.RuntimeData, com.cyclopsgroup.waterview.Context)
 *///from  w w w.  ja  v a2 s  . c o m
public void execute(RuntimeData data, Context context) throws Exception {
    RuntimeUser user = RuntimeUser.getInstance(data);
    PersistenceManager persist = (PersistenceManager) lookup(PersistenceManager.ROLE);
    User u = (User) persist.load(User.class, user.getId());
    context.put("userObject", u);

    TreeMap languages = new TreeMap();
    TreeMap countries = new TreeMap();
    Locale[] availableLocales = Locale.getAvailableLocales();
    for (int i = 0; i < availableLocales.length; i++) {
        Locale locale = availableLocales[i];
        DefaultSelectOption lang = new DefaultSelectOption(locale.getLanguage(),
                locale.getDisplayLanguage(data.getLocale()) + '(' + locale.getLanguage() + ')');
        languages.put(locale.getLanguage(), lang);

        if (StringUtils.isNotEmpty(locale.getCountry())) {
            DefaultSelectOption cout = new DefaultSelectOption(locale.getCountry(),
                    locale.getDisplayCountry(data.getLocale()) + '(' + locale.getCountry() + ')');
            countries.put(locale.getCountry(), cout);
        }
    }
    context.put("countries", countries.values());
    context.put("languages", languages.values());
}

From source file:org.gnucash.android.ui.accounts.AccountsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_accounts);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Locale locale = Locale.getDefault();
    //sometimes the locale en_UK is returned which causes a crash with Currency
    if (locale.getCountry().equals("UK")) {
        locale = new Locale(locale.getLanguage(), "GB");
    }/*from w  w w . ja  v a  2s.  c  om*/
    String currencyCode = null;
    try { //there are some strange locales out there
        currencyCode = prefs.getString(getString(R.string.key_default_currency),
                Currency.getInstance(locale).getCurrencyCode());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        currencyCode = "USD"; //just use USD and let the user choose
    }

    Money.DEFAULT_CURRENCY_CODE = currencyCode;

    boolean firstRun = prefs.getBoolean(getString(R.string.key_first_run), true);
    if (firstRun) {
        createDefaultAccounts();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();

    AccountsListFragment accountsListFragment = (AccountsListFragment) fragmentManager
            .findFragmentByTag(FRAGMENT_ACCOUNTS_LIST);

    if (accountsListFragment == null) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, new AccountsListFragment(), FRAGMENT_ACCOUNTS_LIST);

        fragmentTransaction.commit();
    }
}

From source file:de.iew.web.view.js.RequireJSMessageBundleView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> stringObjectMap, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setContentType("text/javascript; charset=utf-8");

    PrintWriter writer = response.getWriter();

    // Ja, Javascript Hlle :-)
    writer.write("define({");
    if (isRootBundle(stringObjectMap)) {
        writer.write("'root':{");
    }/* w w w  .  j a va 2  s .co m*/

    Map<String, String> bundle = getBundle(stringObjectMap);
    int itemsLeft = bundle.size();
    for (Map.Entry<String, String> item : bundle.entrySet()) {
        writer.write("'");
        writer.write(item.getKey());
        writer.write("':'");
        writer.write(item.getValue());
        writer.write("'");
        itemsLeft--;

        if (itemsLeft > 0) {
            writer.write(",");
        }
    }

    if (isRootBundle(stringObjectMap)) {
        writer.write("}");

        List<Locale> availableLocales = getAvailableLocales(stringObjectMap);
        for (Locale locale : availableLocales) {
            if (!locale.equals(this.defaultLocale)) {
                writer.write(",");
                writer.write("'");
                writer.write(locale.getLanguage().toLowerCase() + "-" + locale.getCountry().toLowerCase());
                writer.write("':");
                writer.write("true");
            }
        }
    }
    writer.write("});");
}

From source file:com.globalsight.connector.blaise.CreateBlaiseJobThread.java

private void createJob() throws Exception {
    try {//ww  w. j a  v  a2 s.c o m
        String jobName = BlaiseHelper.getEntryJobName(curEntry);
        jobName = addJobNameSuffix(jobName);
        String comment = blaiseForm.getComment();
        String priority = blaiseForm.getPriority();

        long l10Id = curFileProfile.getL10nProfileId();
        BasicL10nProfile l10Profile = HibernateUtil.get(BasicL10nProfile.class, l10Id);
        String sourceLocaleName = l10Profile.getSourceLocale().getLocaleCode();

        Locale trgLocale = curEntry.getTargetLocale();
        String targetLocale = trgLocale.getLanguage() + "_" + trgLocale.getCountry();
        targetLocale = BlaiseHelper.fixLocale(targetLocale);

        Job job = JobCreationMonitor.initializeJob(jobName, uuid, user.getUserId(), l10Id, priority,
                Job.IN_QUEUE, Job.JOB_TYPE_BLAISE);

        // init files and file profiles infomation
        List<String> descList = new ArrayList<String>();
        retrieveRealFileFromBlaiseServer(descList, job, curEntry, sourceLocaleName);

        List<FileProfile> fpList = new ArrayList<FileProfile>();
        fpList.add(curFileProfile);
        Map<String, long[]> filesToFpId = FileProfileUtil.excuteScriptOfFileProfile(descList, fpList, job);

        Set<String> fileNames = filesToFpId.keySet();
        Integer pageCount = new Integer(fileNames.size());

        // cache job attributes if there are any
        if (jobAttribtues != null && jobAttribtues.size() != 0) {
            RuntimeCache.addJobAtttibutesCache(uuid, jobAttribtues);
        }

        int count = 0;
        for (Iterator<String> i = fileNames.iterator(); i.hasNext();) {
            String fileName = i.next();
            long[] tmp = filesToFpId.get(fileName);
            String fileProfileId = String.valueOf(tmp[0]);
            int exitValue = (int) tmp[1];

            String key = jobName + fileName + ++count;
            CxeProxy.setTargetLocales(key, targetLocale);
            CxeProxy.importFromFileSystem(fileName, String.valueOf(job.getId()), jobName, fileProfileId,
                    pageCount, count, 1, 1, Boolean.TRUE, Boolean.FALSE, CxeProxy.IMPORT_TYPE_L10N, exitValue,
                    priority);
        }

        // save job attributes if there are any
        if (jobAttribtues != null) {
            saveAttributes(jobAttribtues, currentCompanyId, job);
        }

        // save job comment
        if (!StringUtils.isEmpty(comment) || !StringUtils.isEmpty(attachFileName)) {
            String dir = convertFilePath(AmbFileStoragePathUtils.getFileStorageDirPath(currentCompanyId))
                    + File.separator + "GlobalSight" + File.separator + "CommentReference" + File.separator
                    + "tmp" + File.separator + uuid;
            File src = new File(dir + File.separator + attachFileName);
            if (attachFile != null) {
                FileUtil.copyFile(attachFile, src);
            }

            SaveCommentThread sct = new SaveCommentThread(jobName, comment, attachFileName, user.getUserId(),
                    dir);
            sct.start();
        }

        // Record this
        BlaiseConnectorJob bcj = new BlaiseConnectorJob();
        bcj.setBlaiseConnectorId(this.connector.getId());
        bcj.setBlaiseEntryId(this.curEntry.getId());
        bcj.setJobId(job.getId());
        HibernateUtil.saveOrUpdate(bcj);
    } catch (FileNotFoundException ex) {
        logger.error("Cannot find the tmp uploaded files.", ex);
    } catch (Exception e) {
        logger.error("Create job failed.", e);
    }
}

From source file:org.apache.beehive.netui.compiler.model.validation.ValidationModel.java

private void writeLocaleSets(XmlModelWriter xw, Element element) {
    ////from   www.  ja  v a2 s  .c  o m
    // Commons Validator behavior is to build a key from the locale of a FormSet
    // or uses the default Locale (Locale.getDefault() - the system locale) to
    // track different  elements. This implies that the 
    // without language or country attributes could be mapped to "en_US"
    // if that's the default locale.
    // See org.apache.commons.validator.ValidatorResources.buildKey()
    //
    // Therefor, to ensure the validator uses  rules for of a specific
    // locale before the FormSet with no language or country attributes (even
    // if it is the locale of the system), write the most specific locales first.
    //
    List allLocales = new ArrayList(_localeSets.keySet());
    List langCountryVariant = new ArrayList();
    List langCountry = new ArrayList();
    List lang = new ArrayList();

    for (java.util.Iterator ii = allLocales.iterator(); ii.hasNext();) {
        Locale locale = (Locale) ii.next();
        if (locale.getCountry().length() > 0) {
            if (locale.getVariant().length() > 0) {
                langCountryVariant.add(locale);
            } else {
                langCountry.add(locale);
            }
        } else {
            lang.add(locale);
        }
    }

    writeLocaleSets(xw, element, langCountryVariant);
    writeLocaleSets(xw, element, langCountry);
    writeLocaleSets(xw, element, lang);
}

From source file:org.smigo.species.vernacular.VernacularHandler.java

public CrudResult addVernacular(Vernacular vernacular, AuthenticatedUser user, Locale locale) {
    Species species = speciesHandler.getSpecies(vernacular.getSpeciesId());
    List<Vernacular> currentVernaculars = vernacularDao.getVernacularBySpecies(species.getId());
    vernacular.setLanguage(locale.getLanguage());
    vernacular.setCountry(locale.getCountry());

    boolean isCreator = species.getCreator() == user.getId();
    if (isCreator || user.isModerator()) {
        int id = vernacularDao.insertVernacular(vernacular);
        return new CrudResult(id, Review.NONE);
    }/*from w  w  w .ja  va2 s.c o m*/

    mailHandler.sendReviewRequest("Add vernacular", currentVernaculars, vernacular, user);
    return new CrudResult(null, Review.MODERATOR);
}

From source file:io.uengine.web.configuration.ConfigurationController.java

/**
 *  ??   ? ./*from   w  ww . j  a  v  a2s.  c  om*/
 */
@RequestMapping(value = "bundle", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Response getBundle(final Locale locale) throws IOException {
    Response response = new Response();
    try {
        Map map = Messages.toMap(locale);
        map.put("browser.language", locale.getLanguage());
        map.put("browser.country", locale.getCountry());
        map.put("browser.locale", locale.toString());

        MultiValueMap headers = new HttpHeaders();
        response.getMap().putAll(map);
        response.setSuccess(true);
    } catch (Exception ex) {
        response.getError().setMessage(ex.getMessage());
        if (ex.getCause() != null)
            response.getError().setCause(ex.getCause().getMessage());
        response.getError().setException(ExceptionUtils.getFullStackTrace(ex));
    }
    return response;
}