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:net.imatruck.betterweather.BetterWeatherExtension.java

/**
 * Starts the update process, will verify the reason before continuing
 *
 * @param reason Update reason, provided by DashClock or this app
 *//*w  w w  .  j av  a 2s .  co m*/
@Override
protected void onUpdateData(int reason) {

    LOGD(TAG, "Update reason: " + getReasonText(reason));

    // Whenever updating, set sLang to Yahoo's format(en-US, not en_US)
    // If sLang is set in elsewhere, and user changes phone's locale
    // without entering BW setting menu, then Yahoo's place name in widget
    // may be in wrong locale.
    Locale current = getResources().getConfiguration().locale;
    YahooPlacesAPIClient.sLang = current.getLanguage() + "-" + current.getCountry();

    if (reason != UPDATE_REASON_USER_REQUESTED && reason != UPDATE_REASON_SETTINGS_CHANGED
            && reason != UPDATE_REASON_INITIAL && reason != UPDATE_REASON_INTERVAL_TOO_BIG) {
        LOGD(TAG, "Skipping update");
        if ((System.currentTimeMillis() - lastUpdateTime > (sRefreshInterval * 1000 * 60))
                && sRefreshInterval > 0)
            onUpdateData(UPDATE_REASON_INTERVAL_TOO_BIG);

        return;
    }

    LOGD(TAG, "Updating data");

    if (sPebbleEnable) {
        LOGD(TAG, "Registered Pebble Data Receiver");
        Pebble.registerPebbleDataReceived(getApplicationContext());
    }

    getCurrentPreferences();

    NetworkInfo ni = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
            .getActiveNetworkInfo();
    if (ni == null || !ni.isConnected()) {
        LOGD(TAG, "No internet connection detected, scheduling refresh in 5 minutes");
        scheduleRefresh(5);
        return;
    }

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    String provider;
    if (sUseOnlyNetworkLocation)
        provider = LocationManager.NETWORK_PROVIDER;
    else
        provider = lm.getBestProvider(sLocationCriteria, true);

    if (TextUtils.isEmpty(provider)) {
        LOGE(TAG, "No available location providers matching criteria, maybe permission is disabled.");
        provider = null;
    }

    requestLocationUpdate(lm, provider);
}

From source file:org.squale.welcom.taglib.aide.Aide.java

/**
 * Retourne la valeur d'une clef en fonction de sa Locale
 * //  w  w  w .  j  a  v a2 s . co m
 * @param key la cle
 * @param locale la locale
 * @return la valeur retournee
 * @throws AideException l'exception susceptible d'etre levee
 */
public String getString(final String key, final Locale locale) throws AideException {
    try {
        final ResourceBundle ressourceBundle = java.util.ResourceBundle.getBundle(fileBundle, locale);
        String value = "";

        try {
            value = ressourceBundle.getString(key);
        } catch (final MissingResourceException e) {
            // Trappe l'execption pour quelle ne remonte pas trop Haut
            // Elle est trait dans le finnaly
        } finally {
            if ((value == null) || value.equals("") || value.equals("DEFAULT")) {
                throw new AideException(
                        "Pas de valeur associ a la clef " + key + " pour la locale " + locale + "!!!");
            }
        }

        // String value = getAideRessource(locale).getString(key);
        log.info("Pour la Locale (" + locale.getCountry() + "_" + locale.getLanguage() + ") Key : " + key
                + " Value :" + value);

        return value;
    } catch (final AideException ae) {
        // La clef n'est pas trouver essaye l'url par default
        return Aide.getInstance().getUrlDefault(key, locale);
    }
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

/**
 * Generates a signed certificate for an entity.
 * //from ww w. ja v a  2 s  .c  om
 * @param country The country of org/entity
 * @param orgName The name of the organization the entity belongs to
 * @param type The type of the  entity
 * @param callName The name of the entity
 * @param email The email of the entity
 * @param publickey The public key of the entity
 * @return Returns a signed X509Certificate
 */
public X509Certificate generateCertForEntity(BigInteger serialNumber, String country, String orgName,
        String type, String callName, String email, String uid, PublicKey publickey,
        Map<String, String> customAttr) {
    PrivateKeyEntry signingCertEntry = getSigningCertEntry();
    java.security.cert.Certificate signingCert = signingCertEntry.getCertificate();
    X509Certificate signingX509Cert = (X509Certificate) signingCert;
    // Try to find the correct country code, else we just use the country name as code
    String orgCountryCode = country;
    String[] locales = Locale.getISOCountries();
    for (String countryCode : locales) {
        Locale loc = new Locale("", countryCode);
        if (loc.getDisplayCountry(Locale.ENGLISH).equals(orgCountryCode)) {
            orgCountryCode = loc.getCountry();
            break;
        }
    }
    String orgSubjectDn = "C=" + orgCountryCode + ", " + "O=" + orgName + ", " + "OU=" + type + ", " + "CN="
            + callName + ", " + "UID=" + uid;
    if (email != null && !email.isEmpty()) {
        orgSubjectDn += ", " + "E=" + email;
    }
    X509Certificate orgCert = null;
    try {
        orgCert = buildAndSignCert(serialNumber, signingCertEntry.getPrivateKey(),
                signingX509Cert.getPublicKey(), publickey,
                new JcaX509CertificateHolder(signingX509Cert).getSubject(), new X500Name(orgSubjectDn),
                customAttr, "ENTITY");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return orgCert;
}

From source file:com.aurel.track.dbase.InitDatabase.java

/**
 * This method loads resource strings from properties files (ApplicationResources.properties)
 * into the database./*from  w  w  w .ja  va  2  s  .  c o m*/
 * @throws ServletException
 */
public static void loadResourcesFromPropertiesFiles(Boolean customOnly, ServletContext servletContext) {
    Boolean useProjects = true;
    Connection con = null;
    try {
        con = getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM ID_TABLE WHERE TABLE_NAME = 'USESPACES'");
        if (rs.next()) {
            useProjects = false; // We have an installation that uses the workspace terminology
        }
    } catch (Exception e) {
        LOGGER.error("Problem reading from ID_TABLE when checking for USESPACES");
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception ee) {
                LOGGER.debug(ee);
            }
        }
    }
    List<Locale> locs = LocaleHandler.getPropertiesLocales();
    int numberOfLocales = locs.size();
    int step = Math.round((float) ApplicationStarter.RESOURCE_UPGRADE[1] / numberOfLocales);
    float delta = new Float(ApplicationStarter.RESOURCE_UPGRADE[1] / new Float(numberOfLocales)) - step;
    Iterator<Locale> it = locs.iterator();

    while (it.hasNext()) {
        Locale loc = it.next();
        String locCode = loc.getLanguage();
        if (ApplicationBean.getInstance().isInTestMode() && locCode != "en") {
            continue;
        }
        if (loc.getCountry() != null && !"".equals(loc.getCountry())) {
            locCode = locCode + "_" + loc.getCountry();
        }
        if (!customOnly) {
            ApplicationStarter.getInstance().actualizePercentComplete(step,
                    ApplicationStarter.RESOURCE_UPGRADE_LOCALE_TEXT + loc.getDisplayName() + "...");
            addResourceToDatabase(loc, locCode, useProjects);
        }
        addCustomResourceToDatabase(loc, locCode);
    }
    if (!customOnly) {
        ApplicationStarter.getInstance().actualizePercentComplete(step,
                ApplicationStarter.RESOURCE_UPGRADE_DEFAULT_LOCALE_TEXT);
        addResourceToDatabase(Locale.getDefault(), null, useProjects);
    }
    addCustomResourceToDatabase(Locale.getDefault(), null);
    if (!customOnly) {
        ApplicationStarter.getInstance().actualizePercentComplete(Math.round(delta),
                ApplicationStarter.RESOURCE_UPGRADE_DEFAULT_LOCALE_TEXT);
    }
}

From source file:org.eclipse.jubula.autagent.commands.AbstractStartJavaAut.java

/**
 * Sets -javaagent and JRE arguments as SUN environment variable.
 * @param parameters The parameters for starting the AUT
 * @return the _JAVA_OPTIONS environment variable including -javaagent
 * and jre arguments//from  ww  w. j a  v  a2s .  co  m
 */
protected String setJavaOptions(Map<String, String> parameters) {
    StringBuffer sb = new StringBuffer();
    if (isRunningFromExecutable(parameters)) {
        Locale locale = LocaleUtils.toLocale(parameters.get(AutConfigConstants.AUT_LOCALE));

        // set agent and locals
        sb.append(JAVA_OPTIONS_INTRO);
        if (org.eclipse.jubula.tools.internal.utils.MonitoringUtil.shouldAndCanRunWithMonitoring(parameters)) {
            String monAgent = getMonitoringAgent(parameters);
            if (monAgent != null) {
                sb.append(monAgent).append(StringConstants.SPACE);
            }
        }
        sb.append(StringConstants.QUOTE).append("-javaagent:") //$NON-NLS-1$
                .append(getAbsoluteAgentJarPath()).append(StringConstants.QUOTE);

        if (locale != null) {
            sb.append(StringConstants.SPACE).append(JAVA_COUNTRY_PROPERTY).append(locale.getCountry());
            sb.append(StringConstants.SPACE).append(JAVA_LANGUAGE_PROPERTY).append(locale.getLanguage());
        }
    } else {
        if (org.eclipse.jubula.tools.internal.utils.MonitoringUtil.shouldAndCanRunWithMonitoring(parameters)) {
            String monAgent = getMonitoringAgent(parameters);
            if (monAgent != null) {
                sb.append(JAVA_OPTIONS_INTRO).append(monAgent);
            }
        }
    }

    return sb.toString();
}

From source file:org.apache.click.extras.control.DateField.java

/**
 * Return the first day of the week. For example e.g., Sunday in US,
 * Monday in France and Australia.//from w w w  . ja va2  s .com
 *
 * @return the first day of the week
 */
protected int getFirstDayOfWeek() {
    Locale locale = getLocale();

    if ("AU".equals(locale.getCountry())) {
        return Calendar.MONDAY;
    }
    Calendar calendar = Calendar.getInstance(locale);

    return calendar.getFirstDayOfWeek();
}

From source file:com.salesmanager.core.util.LocaleUtil.java

public static void setLocaleForRequest(HttpServletRequest request, HttpServletResponse response,
        ActionContext ctx, MerchantStore store) throws Exception {

    /**//  w w  w .  ja  v  a 2  s  .  c  o  m
     * LOCALE
     */

    Map sessions = ctx.getSession();

    if (ctx == null) {
        throw new Exception("This request was not made inside Struts request, ActionContext is null");
    }

    Locale locale = null;

    // check in http request
    String req_locale = (String) request.getParameter("request_locale");
    if (!StringUtils.isBlank(req_locale)) {

        String l = null;
        String c = null;

        if (req_locale.length() == 2) {//assume it is the language
            l = req_locale;
            c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        }

        if (req_locale.length() == 5) {

            try {
                l = req_locale.substring(0, 2);
                c = req_locale.substring(3);
            } catch (Exception e) {
                log.warn("Invalid locale format " + req_locale);
                l = null;
                c = null;
            }

        }

        if (l != null && c != null) {

            String storeLang = null;
            Map languages = store.getGetSupportedLanguages();
            if (languages != null && languages.size() > 0) {
                Iterator i = languages.keySet().iterator();
                while (i.hasNext()) {
                    Integer langKey = (Integer) i.next();
                    Language lang = (Language) languages.get(langKey);
                    if (lang.getCode().equals(l)) {
                        storeLang = l;
                        break;
                    }
                }
            }

            if (storeLang == null) {
                l = store.getDefaultLang();
                if (StringUtils.isBlank(l)) {
                    l = LanguageUtil.getDefaultLanguage();
                }
            }

            locale = new Locale(l, c);
            if (StringUtils.isBlank(locale.getLanguage()) || StringUtils.isBlank(locale.getCountry())) {
                log.error("Language or Country is not set in the new locale " + req_locale);
                return;
            }
            sessions.put("WW_TRANS_I18N_LOCALE", locale);

        }
    }

    locale = (Locale) sessions.get("WW_TRANS_I18N_LOCALE");
    request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);

    if (locale == null) {

        String c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        String lang = store.getDefaultLang();
        if (!StringUtils.isBlank(c) && !StringUtils.isBlank(lang)) {
            locale = new Locale(lang, c);
        } else {
            locale = LocaleUtil.getDefaultLocale();
            String langs = store.getSupportedlanguages();
            if (!StringUtils.isBlank(langs)) {
                Map languages = store.getGetSupportedLanguages();
                String defaultLang = locale.getLanguage();
                if (languages != null && languages.size() > 0) {
                    Iterator i = languages.keySet().iterator();
                    String storeLang = "";
                    while (i.hasNext()) {
                        Integer langKey = (Integer) i.next();
                        Language l = (Language) languages.get(langKey);
                        if (l.getCode().equals(defaultLang)) {
                            storeLang = defaultLang;
                            break;
                        }
                    }
                    if (!storeLang.equals(defaultLang)) {
                        defaultLang = storeLang;
                    }
                }

                if (!StringUtils.isBlank(defaultLang) && !StringUtils.isBlank(c)) {
                    locale = new Locale(defaultLang, c);
                }

            }
        }

        sessions.put("WW_TRANS_I18N_LOCALE", locale);
    }

    if (locale != null) {
        LabelUtil label = LabelUtil.getInstance();
        label.setLocale(locale);
        String lang = label.getText("label.language." + locale.getLanguage());
        request.setAttribute("LANGUAGE", lang);
    }

    if (store.getLanguages() == null || store.getLanguages().size() == 0) {

        // languages
        if (!StringUtils.isBlank(store.getSupportedlanguages())) {
            List languages = new ArrayList();
            List langs = LanguageUtil.parseLanguages(store.getSupportedlanguages());
            for (Object o : langs) {
                String lang = (String) o;
                Language l = LanguageUtil.getLanguageByCode(lang);
                if (l != null) {
                    l.setLocale(locale, store.getCurrency());
                    languages.add(l);
                }
            }
            store.setLanguages(languages);
        }
    }

    request.setAttribute("LOCALE", locale);
    Cookie c = new Cookie("LOCALE", locale.getLanguage() + "_" + locale.getCountry());
    c.setPath("/");
    c.setMaxAge(2 * 24 * 24);
    response.addCookie(c);

}

From source file:jp.terasoluna.fw.web.codelist.AbstractMultilingualCodeListLoader.java

/**
 * ?P?[R?[hXg???B/*  w w w. j a  v a 2s .  co  m*/
 * <p>
 * ?w?P?[R?[hXg????A
 * ??P?[R?[hXg???B
 * 
 * @param locale ?P?[
 * @return R?[hXg
 */
protected CodeBean[] createCodeBeans(Locale locale) {

    if (log.isDebugEnabled()) {
        log.debug("createCodeBeans(" + locale + ") called.");
    }

    if (localeMap == null) {
        if (log.isDebugEnabled()) {
            log.debug("field codeListsMap is null.");
        }
        // codeListsMap?z?B
        return new CodeBean[0];
    }

    if (locale == null) {
        if (log.isDebugEnabled()) {
            log.debug("arg locale is null. replace locale default : " + defaultLocale);
        }
        if (defaultLocale == null) {
            throw new IllegalStateException("Default locale is null.");
        }
        locale = defaultLocale;
    }

    List<CodeBean> codeLists = localeMap.get(locale);

    // R?[hXg???A??P?[???
    if (codeLists == null) {
        if (locale.getVariant().length() > 0) {
            return createCodeBeans(new Locale(locale.getLanguage(), locale.getCountry()));
        } else if (locale.getCountry().length() > 0) {
            return createCodeBeans(new Locale(locale.getLanguage()));
        }

        // codeLists?z?B
        return new CodeBean[0];
    }

    CodeBean[] cb = new CodeBean[codeLists.size()];
    for (int i = 0; i < codeLists.size(); i++) {
        cb[i] = new CodeBean();
        cb[i].setId(codeLists.get(i).getId());
        cb[i].setName(codeLists.get(i).getName());
    }
    return cb;
}

From source file:org.marketcetera.client.rpc.RpcClientImpl.java

@Override
protected void connectWebServices() throws I18NException, RemoteException {
    SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", mParameters.getHostname(),
            mParameters.getPort());/*from  w w  w .j  av  a2  s . co  m*/
    PeerInfo server = new PeerInfo(mParameters.getHostname(), mParameters.getPort());
    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
    executor = new ThreadPoolCallExecutor(1, 10);
    clientFactory.setRpcServerCallExecutor(executor);
    clientFactory.setConnectResponseTimeoutMillis(10000);
    clientFactory.setCompression(true);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    try {
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcClientService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(ClientVersion.APP_ID.getValue())
                .setVersionId(ClientVersion.APP_ID_VERSION.getVersionInfo())
                .setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry())
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage())
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant())
                        .build())
                .setUsername(mParameters.getUsername()).setPassword(new String(mParameters.getPassword()))
                .build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
    } catch (IOException | ServiceException e) {
        throw new RemoteException(e);
    }
}

From source file:edu.ku.brc.specify.prefs.SystemPrefs.java

@Override
public void savePrefs() {
    if (form.getValidator() == null || form.getValidator().hasChanged()) {
        super.savePrefs();

        ValCheckBox chk = form.getCompById("2");
        localPrefs.putBoolean(VERSION_CHECK, (Boolean) chk.getValue());

        chk = form.getCompById("3");
        remotePrefs.putBoolean(SEND_STATS, (Boolean) chk.getValue());

        chk = form.getCompById("9");
        remotePrefs.putBoolean(SEND_ISA_STATS, (Boolean) chk.getValue());

        /* remove if worldwind is broken*/chk = form.getCompById(USE_WORLDWIND);
        /* remove if worldwind is broken*/localPrefs.putBoolean(USE_WORLDWIND, (Boolean) chk.getValue());
        //            
        /* remove if worldwind is broken*/chk = form.getCompById(SYSTEM_HasOpenGL);
        /* remove if worldwind is broken*/localPrefs.putBoolean(SYSTEM_HasOpenGL, (Boolean) chk.getValue());
        //            
        /* remove if worldwind is broken*/chk = form.getCompById(USE_WORLDWIND);
        /* remove if worldwind is broken*/localPrefs.putBoolean(USE_WORLDWIND, (Boolean) chk.getValue());

        //chk = form.getCompById(ALWAYS_ASK_COLL);
        //localPrefs.putBoolean(ALWAYS_ASK_COLL, (Boolean)chk.getValue());

        ValComboBox localeCBX = form.getCompById("5");
        Locale item = (Locale) localeCBX.getComboBox().getSelectedItem();
        if (item != null) {
            if (item.equals(UIRegistry.getPlatformLocale())) {
                localPrefs.remove("locale.lang");
                localPrefs.remove("locale.country");
                localPrefs.remove("locale.var");

                //System.out.println("["+localPrefs.get("locale.lang", null)+"]");
                Locale.setDefault(UIRegistry.getPlatformLocale());

            } else {
                if (item.getLanguage() == null) {
                    localPrefs.remove("locale.lang");
                } else {
                    localPrefs.put("locale.lang", item.getLanguage());
                }/*from  www  .  ja va2 s . c  om*/

                if (item.getCountry() == null) {
                    localPrefs.remove("locale.country");
                } else {
                    localPrefs.put("locale.country", item.getCountry());
                }

                if (item.getVariant() == null) {
                    localPrefs.remove("locale.var");
                } else {
                    localPrefs.put("locale.var", item.getVariant());
                }
            }

            ValBrowseBtnPanel browse = form.getCompById("7");
            if (browse != null) {
                String newSplashPath = browse.getValue().toString();
                if (newSplashPath != null && (oldSplashPath == null || !oldSplashPath.equals(newSplashPath))) {
                    if (newSplashPath.isEmpty()) {
                        resetSplashImage();
                        localPrefs.remove(SPECIFY_BG_IMG_PATH);

                    } else {
                        localPrefs.put(SPECIFY_BG_IMG_PATH, newSplashPath);
                        changeSplashImage();
                    }
                }
            }
            File cp = JasperReportsCache.getImagePath();

            try {
                localPrefs.flush();

            } catch (BackingStoreException ex) {
            }
        }
    }
}