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:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();// w w  w  . j  a v a2  s .  c  o m

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:com.globalsight.everest.projecthandler.MachineTranslateAdapter.java

public boolean isSupportsLocalePair(MachineTranslationProfile mt, Locale sourcelocale, Locale targetlocale) {
    boolean isSupportLocalePair = false;
    MachineTranslationExtentInfo result = null;

    EngineEnum ee = EngineEnum.getEngine(mt.getMtEngine());
    String lp = "";
    switch (ee) {
    case ProMT://  ww  w.j  a va 2 s  . co m
        lp = getLanguagePairNameForProMt(sourcelocale, targetlocale);
        break;
    case IPTranslator:
        return IPTranslatorUtil.supportsLocalePair(sourcelocale, targetlocale);
    case Asia_Online:
        lp = getLanguagePairNameForAo(sourcelocale, targetlocale);
        // Currently AO supports zh-CN, not support zh-HK and zh-TW.
        if (sourcelocale.getLanguage().equalsIgnoreCase("ZH")
                && !sourcelocale.getCountry().equalsIgnoreCase("CN")) {
            return false;
        }
        if (targetlocale.getLanguage().equalsIgnoreCase("ZH")
                && !targetlocale.getCountry().equalsIgnoreCase("CN")) {
            return false;
        }
        break;
    }
    try {
        Set lp2DomainCombinations = mt.getExInfo();
        if (lp2DomainCombinations != null && lp2DomainCombinations.size() > 0) {
            Iterator lp2DCIt = lp2DomainCombinations.iterator();
            while (lp2DCIt.hasNext()) {
                MachineTranslationExtentInfo aoLP2DC = (MachineTranslationExtentInfo) lp2DCIt.next();
                String lpName = aoLP2DC.getLanguagePairName();
                if (lpName != null && lpName.equalsIgnoreCase(lp)) {
                    result = aoLP2DC;
                    break;
                }
            }
        }
    } catch (Exception e) {
    }
    isSupportLocalePair = result == null ? false : true;

    return isSupportLocalePair;
}

From source file:org.opencommercesearch.AbstractSearchServer.java

@Override
public Facet getFacet(Site site, Locale locale, String fieldFacet, int facetLimit, int depthLimit,
        String separator, FilterQuery... filterQueries) throws SearchServerException {
    try {/*  w w w  . j ava2 s .c o m*/
        SolrQuery query = new SolrQuery();
        query.setRows(0);
        query.setQuery("*:*");
        query.addFacetField(fieldFacet);
        query.setFacetLimit(facetLimit);
        query.setFacetMinCount(1);
        query.addFilterQuery("country:" + locale.getCountry());

        RepositoryItem catalog = (RepositoryItem) site.getPropertyValue("defaultCatalog");
        String catalogId = catalog.getRepositoryId();
        query.setFacetPrefix(CATEGORY_PATH, catalogId + ".");
        query.addFilterQuery(CATEGORY_PATH + ":" + catalogId);

        if (filterQueries != null) {
            for (FilterQuery filterQuery : filterQueries) {
                query.addFilterQuery(filterQuery.toString());
            }
        }

        QueryResponse queryResponse = getCatalogSolrServer(locale).query(query);
        Facet facet = null;
        if (queryResponse != null && queryResponse.getFacetFields() != null) {
            FacetField facetField = queryResponse.getFacetField(fieldFacet);
            if (facetField != null) {
                List<Count> values = facetField.getValues();
                if (values != null && !values.isEmpty()) {
                    facet = new Facet();
                    facet.setName(StringUtils.capitalize(fieldFacet));
                    List<Filter> filters = new ArrayList<Facet.Filter>();

                    boolean filterByDepth = depthLimit > 0 && StringUtils.isNotBlank(separator);
                    for (Count count : values) {

                        if (filterByDepth
                                && StringUtils.countMatches(count.getName(), separator) > depthLimit) {
                            continue;
                        }

                        Filter filter = new Filter();
                        filter.setName(count.getName());
                        filter.setCount(count.getCount());
                        filter.setFilterQuery(count.getAsFilterQuery());
                        filter.setFilterQueries(count.getAsFilterQuery());
                        filters.add(filter);
                    }
                    facet.setFilters(filters);
                }
            }
        }
        return facet;
    } catch (SolrServerException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    } catch (SolrException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    }
}

From source file:com.alfaariss.oa.authentication.remote.aselect.RemoteASelectMethod.java

private UserEvent requestAuthenticate(HttpServletRequest oRequest, HttpServletResponse oResponse,
        ISession oSession, ASelectIDP oASelectOrganization, Collection cForcedOrganizations)
        throws OAException, IOException {
    UserEvent oUserEvent = UserEvent.AUTHN_METHOD_FAILED;
    Hashtable<String, String> htRequest = new Hashtable<String, String>();
    try {/*from  www  . j  av a  2  s  .c o m*/
        String sUID = null;
        IUser oUser = oSession.getUser();
        if (oUser != null)
            sUID = oUser.getID();
        else
            sUID = oSession.getForcedUserID();

        if (sUID != null) {
            if (_idMapper != null) {
                sUID = _idMapper.map(sUID);
                if (sUID == null) {
                    _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                            UserEvent.AUTHN_METHOD_NOT_SUPPORTED, this, "No user mapping"));

                    return UserEvent.AUTHN_METHOD_NOT_SUPPORTED;
                }
            }

            htRequest.put(PARAM_UID, sUID);
        }

        htRequest.put(PARAM_FORCED, String.valueOf(oSession.isForcedAuthentication()));

        StringBuffer sbMyURL = new StringBuffer();
        sbMyURL.append(oRequest.getRequestURL().toString());
        sbMyURL.append("?").append(ISession.ID_NAME);
        sbMyURL.append("=").append(URLEncoder.encode(oSession.getId(), CHARSET));

        htRequest.put(PARAM_LOCAL_AS_URL, sbMyURL.toString());
        htRequest.put(PARAM_LOCAL_ORG, _sMyOrganization);
        htRequest.put(PARAM_ASELECTSERVER, oASelectOrganization.getServerID());

        ISessionAttributes oAttributes = oSession.getAttributes();

        String sRequiredLevel = null;
        if (oAttributes.contains(ProxyAttributes.class, SESSION_PROXY_REQUIRED_LEVEL))
            sRequiredLevel = (String) oAttributes.get(ProxyAttributes.class, SESSION_PROXY_REQUIRED_LEVEL);
        else
            sRequiredLevel = String.valueOf(oASelectOrganization.getLevel());
        htRequest.put(PARAM_REQUIRED_LEVEL, sRequiredLevel);

        String sCountry = null;
        String sLanguage = null;

        Locale oLocale = oSession.getLocale();
        if (oLocale != null) {
            sCountry = oLocale.getCountry();
            sLanguage = oLocale.getLanguage();
        }

        if (sCountry == null && oASelectOrganization.getCountry() != null)
            sCountry = oASelectOrganization.getCountry();
        if (sCountry != null)
            htRequest.put(PARAM_COUNTRY, sCountry);

        if (sLanguage == null && oASelectOrganization.getLanguage() != null)
            sLanguage = oASelectOrganization.getLanguage();
        if (sLanguage != null)
            htRequest.put(PARAM_LANGUAGE, sLanguage);

        if (cForcedOrganizations != null) {//DD Only send the optional remote_organization parameter if it the value is not the target organization ID 
            Iterator iter = cForcedOrganizations.iterator();
            while (iter.hasNext()) {
                String sRemoteOrg = (String) iter.next();
                if (!sRemoteOrg.equals(oASelectOrganization.getID())) {
                    htRequest.put(PARAM_REMOTE_ORGANIZATION, sRemoteOrg);
                    break;
                }
            }
        }

        if (oASelectOrganization.isArpTargetEnabled()) {
            String sArpTarget = resolveArpTarget(oAttributes, oSession.getRequestorId());
            if (sArpTarget != null)
                htRequest.put(PARAM_ARP_TARGET, sArpTarget);
        }

        if (oASelectOrganization.doSigning()) {
            String sSignature = createSignature(htRequest);
            htRequest.put(PARAM_SIGNATURE, sSignature);
        }

        htRequest.put(PARAM_REQUEST, AUTHENTICATE);

        Hashtable<String, String> htResponse = null;

        try {
            htResponse = sendRequest(oASelectOrganization.getURL(), htRequest);
        } catch (IOException e) {
            _logger.debug("Could not send authenticate request to: " + oASelectOrganization.getURL(), e);
            throw e;
        }

        String sResultCode = htResponse.get(PARAM_RESULTCODE);
        if (sResultCode == null) {
            StringBuffer sbError = new StringBuffer("Required parameter (");
            sbError.append(PARAM_RESULTCODE);
            sbError.append(") not found in request=authenticate response (");
            sbError.append(htResponse);
            sbError.append(") from A-Select Organization: ");
            sbError.append(oASelectOrganization.getServerID());
            _logger.warn(sbError.toString());
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, "Invalid authenticate response"));
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        if (!ERROR_ASELECT_SUCCESS.equals(sResultCode)) {
            StringBuffer sbError = new StringBuffer("Response parameter (");
            sbError.append(PARAM_RESULTCODE);
            sbError.append(") from A-Select Organization '");
            sbError.append(oASelectOrganization.getServerID());
            sbError.append("' contains error code: ");
            sbError.append(sResultCode);
            _logger.warn(sbError.toString());
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                    UserEvent.AUTHN_METHOD_FAILED, this, sResultCode));

            return UserEvent.AUTHN_METHOD_FAILED;
        }
        String sRemoteRid = htResponse.get(PARAM_RID);
        if (sRemoteRid == null) {
            StringBuffer sbError = new StringBuffer("Required parameter (");
            sbError.append(PARAM_RID);
            sbError.append(") not found in request=authenticate response (");
            sbError.append(htResponse);
            sbError.append(") from A-Select Organization: ");
            sbError.append(oASelectOrganization.getServerID());
            _logger.warn(sbError.toString());
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, "Invalid authenticate response"));
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        String sRemoteLoginUrl = htResponse.get(PARAM_AS_URL);
        if (sRemoteLoginUrl == null) {
            StringBuffer sbError = new StringBuffer("Required parameter (");
            sbError.append(PARAM_AS_URL);
            sbError.append(") not found in request=authenticate response (");
            sbError.append(htResponse);
            sbError.append(") from A-Select Organization: ");
            sbError.append(oASelectOrganization.getServerID());
            _logger.warn(sbError.toString());
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, "Invalid authenticate response"));
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbRedirect = new StringBuffer(sRemoteLoginUrl);
        sbRedirect.append("&").append(PARAM_RID);
        sbRedirect.append("=").append(sRemoteRid);
        sbRedirect.append("&").append(PARAM_ASELECTSERVER);
        sbRedirect.append("=").append(oASelectOrganization.getServerID());

        _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                UserEvent.AUTHN_METHOD_IN_PROGRESS, this, "Redirect user with request=login1"));

        oSession.persist();

        oUserEvent = UserEvent.AUTHN_METHOD_IN_PROGRESS;

        try {
            oResponse.sendRedirect(sbRedirect.toString());
        } catch (IOException e) {
            _logger.debug("Could not send redirect: " + sbRedirect.toString(), e);
            throw e;
        }
    } catch (IOException e) {
        throw e;
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        if (oSession != null)
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, null));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                    oRequest.getRemoteAddr(), null, this, null));

        _logger.fatal("Internal error during 'request=authenticate' API call to: "
                + oASelectOrganization.getServerID(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return oUserEvent;
}

From source file:org.opencms.i18n.CmsLocaleManager.java

/**
 * Adds a locale to the list of available locales.<p>
 * // w w w . j  a  v a2 s  .c  o  m
 * @param localeName the locale to add
 */
public void addAvailableLocale(String localeName) {

    Locale locale = getLocale(localeName);
    // add full variation (language / country / variant)
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        }
    }
    // add variation with only language and country
    locale = new Locale(locale.getLanguage(), locale.getCountry());
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        }
    }
    // add variation with language only
    locale = new Locale(locale.getLanguage());
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        }
    }
}

From source file:org.apache.click.servlet.MockRequest.java

/**
 * Helper method to create some default headers for the request.
 *//*from   ww w  . ja va2s  .  c o m*/
private void setDefaultHeaders() {
    headers.clear();
    addHeader("Accept", "text/xml,application/xml,application/xhtml+xml,"
            + "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
    addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    Locale l = locale;
    addHeader("Accept-Language", l.getLanguage().toLowerCase() + "-" + l.getCountry().toLowerCase() + ","
            + l.getLanguage().toLowerCase() + ";q=0.5");
    addHeader("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2");
}

From source file:org.springframework.extensions.webscripts.AbstractWebScript.java

/**
 * <p>A locale based lookup sequence is build using the supplied {@link Locale} and (if it is 
 * different) the default {@link Locale}.
 * <ol><li>Lookup <{@code}descid><{@code}language_country_variant>.properties</li>
 * <li>Lookup <{@code}descid><{@code}language_country>.properties</li>
 * <li>Lookup <{@code}descid><{@code}language>.properties</li>
 * </ol>//from ww  w.  ja  v a2  s  .c  o  m
 * The repeat but with the default {@link Locale}. Finally lookup <descid>.properties
 * </p>
 * @param path String
 * @param locale The requested {@link Locale}.
 * @return LinkedHashSet<String>
 */
@SuppressWarnings("static-access")
private LinkedHashSet<String> buildLocalePathList(final String path, final Locale locale) {
    final LinkedHashSet<String> pathSet = new LinkedHashSet<String>();

    // Add the paths for the current locale...
    pathSet.add(path + '_' + locale.toString() + DOT_PROPS);
    if (locale.getCountry().length() != 0) {
        pathSet.add(path + '_' + locale.getLanguage() + '_' + locale.getCountry() + DOT_PROPS);
    }
    pathSet.add(path + '_' + locale.getLanguage() + DOT_PROPS);

    if (locale.equals(Locale.getDefault())) {
        // We're already using the default Locale, so don't add it's paths again.
    } else {
        // Use the default locale to add some more possible paths...
        final Locale defLocale = locale.getDefault();
        pathSet.add(path + '_' + defLocale.toString() + DOT_PROPS);
        if (defLocale.getCountry().length() != 0) {
            pathSet.add(path + '_' + defLocale.getLanguage() + '_' + defLocale.getCountry() + DOT_PROPS);
        }
        pathSet.add(path + '_' + defLocale.getLanguage() + DOT_PROPS);
    }

    // Finally add a path with no locale information...
    pathSet.add(path + DOT_PROPS);
    return pathSet;
}

From source file:org.opencms.i18n.CmsLocaleManager.java

/**
 * Returns the first matching locale (eventually simplified) from the available locales.<p>
 * /*from w w  w  .  j  a  v  a 2 s.  c o m*/
 * In case no match is found, code <code>null</code> is returned.<p>
 * 
 * @param locales must be an ascending sorted list of locales in order of preference
 * @param available the available locales to find a match in
 * 
 * @return the first precise or simplified match, or <code>null</code> in case no match is found
 */
public Locale getFirstMatchingLocale(List<Locale> locales, List<Locale> available) {

    Iterator<Locale> i;
    // first try a precise match
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = i.next();
        if (available.contains(locale)) {
            // precise match
            return locale;
        }
    }

    // now try a match only with language and country
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = i.next();
        if (locale.getVariant().length() > 0) {
            // the locale has a variant, try to match without the variant
            locale = new Locale(locale.getLanguage(), locale.getCountry(), "");
            if (available.contains(locale)) {
                // match
                return locale;
            }
        }
    }

    // finally try a match only with language
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = i.next();
        if (locale.getCountry().length() > 0) {
            // the locale has a country, try to match without the country
            locale = new Locale(locale.getLanguage(), "", "");
            if (available.contains(locale)) {
                // match
                return locale;
            }
        }
    }

    // no match
    return null;
}