Example usage for java.util Locale getVariant

List of usage examples for java.util Locale getVariant

Introduction

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

Prototype

public String getVariant() 

Source Link

Document

Returns the variant code for this locale.

Usage

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

/**
 * ?P?[R?[hXg???B/*from  ww  w  .j a v  a  2s.  c o 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.primeframework.mvc.parameter.convert.converters.LocaleConverterTest.java

@Test
public void fromStrings() {
    GlobalConverter converter = new LocaleConverter();
    Locale locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr",
            ArrayUtils.toArray((String) null));
    assertNull(locale);//from   w w  w. j  ava2 s  .co m

    locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr", ArrayUtils.toArray("en"));
    assertEquals(locale.getLanguage(), "en");

    locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr", ArrayUtils.toArray("en_US"));
    assertEquals(locale.getLanguage(), "en");
    assertEquals(locale.getCountry(), "US");

    locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr",
            ArrayUtils.toArray("en", "US"));
    assertEquals(locale.getLanguage(), "en");
    assertEquals(locale.getCountry(), "US");

    locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr",
            ArrayUtils.toArray("en_US_UTF8"));
    assertEquals(locale.getLanguage(), "en");
    assertEquals(locale.getCountry(), "US");
    assertEquals(locale.getVariant(), "UTF8");

    locale = (Locale) converter.convertFromStrings(Locale.class, null, "testExpr",
            ArrayUtils.toArray("en", "US", "UTF8"));
    assertEquals(locale.getLanguage(), "en");
    assertEquals(locale.getCountry(), "US");
    assertEquals(locale.getVariant(), "UTF8");
}

From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java

/**
 * Returns the first matching locale (eventually simplified) from the available locales.<p>
 * /*  ww w  . j a v a 2 s .  c  om*/
 * @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
 */
public Locale getFirstMatchingLocale(List locales, Collection available) {

    Iterator i;
    // first try a precise match
    i = locales.iterator();
    while (i.hasNext()) {
        Locale 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 = (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 = (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;
}

From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java

/**
 * Tries to find the given requested locale (eventually simplified) in the collection of available locales, 
 * if the requested locale is not found it will return the first match from the given list of default locales.<p>
 * // ww  w.java2s .co  m
 * @param requestedLocale the requested locale, if this (or a simplified version of it) is available it will be returned
 * @param defaults a list of default locales to use in case the requested locale is not available
 * @param available the available locales to find a match in
 * 
 * @return the best matching locale name or null if no name matches
 */
public Locale getBestMatchingLocale(Locale requestedLocale, List defaults, Collection available) {

    if ((available == null) || available.isEmpty()) {
        // no locales are available at all
        return null;
    }

    // the requested locale is the match we want to find most
    if (available.contains(requestedLocale)) {
        // check if the requested locale is directly available
        return requestedLocale;
    }
    if (requestedLocale.getVariant().length() > 0) {
        // locale has a variant like "en_EN_whatever", try only with language and country 
        Locale check = new Locale(requestedLocale.getLanguage(), requestedLocale.getCountry(), "");
        if (available.contains(check)) {
            return check;
        }
    }
    if (requestedLocale.getCountry().length() > 0) {
        // locale has a country like "en_EN", try only with language
        Locale check = new Locale(requestedLocale.getLanguage(), "", "");
        if (available.contains(check)) {
            return check;
        }
    }

    // available locales do not match the requested locale
    if ((defaults == null) || defaults.isEmpty()) {
        // if we have no default locales we are out of luck
        return null;
    }

    // no match found for the requested locale, return the first match from the default locales
    return getFirstMatchingLocale(defaults, available);
}

From source file:org.acmsl.commons.BundleI14able.java

/**
 * Third attempt to retrieve the bundle.
 * @param bundleName the bundle name.//from  w  ww  .j av  a  2s. c om
 * @param locale the locale.
 * @return the bundle.
 * @throws MissingResourceException if the resource is missing.
 */
@Nullable
protected final ResourceBundle thirdTry(@NotNull final String bundleName, @NotNull final Locale locale)
        throws MissingResourceException {
    @Nullable
    ResourceBundle result = null;

    Throwable exceptionThrown = null;

    MissingResourceException exceptionToThrow = null;

    try {
        // treating bundle name as the first part of the file.
        result = new PropertyResourceBundle(new FileInputStream(bundleName + "_" + locale.getLanguage() + "_"
                + locale.getCountry() + "_" + locale.getVariant() + Literals.PROPERTIES));
    } catch (final FileNotFoundException firstFileNotFoundException) {
        exceptionThrown = firstFileNotFoundException;
    } catch (final IOException firstIOException) {
        exceptionThrown = firstIOException;
    } finally {
        if (exceptionThrown != null) {
            try {
                result = fourthTry(bundleName, locale);
            } catch (final MissingResourceException missingResource) {
                exceptionToThrow = missingResource;
            }
        }
    }

    if (exceptionToThrow != null) {
        throw exceptionToThrow;
    }

    return result;
}

From source file:net.sourceforge.subsonic.service.SettingsService.java

/**
 * Sets the locale (for language, date format etc.)
 *
 * @param locale The locale./*from   www.j  a va2  s . c  o  m*/
 */
public void setLocale(Locale locale) {
    setProperty(KEY_LOCALE_LANGUAGE, locale.getLanguage());
    setProperty(KEY_LOCALE_COUNTRY, locale.getCountry());
    setProperty(KEY_LOCALE_VARIANT, locale.getVariant());
}

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

/**
 * Returns the first matching locale (eventually simplified) from the available locales.<p>
 * // w w w.ja  v a2  s. c  om
 * 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;
}

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 av  a 2s  .  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:gr.abiss.calipso.wicket.CalipsoApplication.java

@Override
public void init() {

    super.init();
    // DEVELOPMENT or DEPLOYMENT
    RuntimeConfigurationType configurationType = this.getConfigurationType();
    if (RuntimeConfigurationType.DEVELOPMENT.equals(configurationType)) {
        logger.info("You are in DEVELOPMENT mode");
        // getResourceSettings().setResourcePollFrequency(Duration.ONE_SECOND);
        // getDebugSettings().setComponentUseCheck(true);
        getResourceSettings().setResourcePollFrequency(null);
        getDebugSettings().setComponentUseCheck(false);
        // getDebugSettings().setSerializeSessionAttributes(true);
        // getMarkupSettings().setStripWicketTags(false);
        // getExceptionSettings().setUnexpectedExceptionDisplay(
        // UnexpectedExceptionDisplay.SHOW_EXCEPTION_PAGE);
        // getAjaxSettings().setAjaxDebugModeEnabled(true);
    } else if (RuntimeConfigurationType.DEPLOYMENT.equals(configurationType)) {
        getResourceSettings().setResourcePollFrequency(null);
        getDebugSettings().setComponentUseCheck(false);
        // getDebugSettings().setSerializeSessionAttributes(false);
        // getMarkupSettings().setStripWicketTags(true);
        // getExceptionSettings().setUnexpectedExceptionDisplay(
        // UnexpectedExceptionDisplay.SHOW_INTERNAL_ERROR_PAGE);
        // getAjaxSettings().setAjaxDebugModeEnabled(false);
    }/*from  w  w  w . j a va 2 s .  c  om*/
    // initialize velocity
    try {
        Velocity.init();
        if (logger.isInfoEnabled()) {
            logger.info("Initialized Velocity engine");
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        logger.error("Failed to initialize velocity engine", e);
    }

    // Set custom page for internal errors
    getApplicationSettings().setInternalErrorPage(CalipsoErrorPage.class);

    // don't break down on missing resources
    getResourceSettings().setThrowExceptionOnMissingResource(false);

    // Redirect to PageExpiredError Page if current page is expired
    getApplicationSettings().setPageExpiredErrorPage(CalipsoPageExpiredErrorPage.class);

    // get hold of spring managed service layer (see BasePage, BasePanel etc
    // for how it is used)
    ServletContext sc = getServletContext();
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
    calipsoService = (CalipsoService) applicationContext.getBean("calipsoService");

    calipsoPropertiesEditor = new CalipsoPropertiesEditor();

    // check if acegi-cas authentication is being used, get reference to
    // object to be used
    // by wicket authentication to redirect to right pages for login /
    // logout
    try {
        calipsoCasProxyTicketValidator = (CalipsoCasProxyTicketValidator) applicationContext
                .getBean("casProxyTicketValidator");
        logger.info("casProxyTicketValidator retrieved from application context: "
                + calipsoCasProxyTicketValidator);
    } catch (NoSuchBeanDefinitionException nsbde) {
        logger.info(
                "casProxyTicketValidator not found in application context, CAS single-sign-on is not being used");
    }
    // delegate wicket i18n support to spring i18n
    getResourceSettings().getStringResourceLoaders().add(new IStringResourceLoader() {

        @Override
        public String loadStringResource(Class<?> clazz, String key, Locale locale, String style,
                String variation) {
            return applicationContext.getMessage(key, null, null, locale);
        }

        @Override
        public String loadStringResource(Component component, String key, Locale locale, String style,
                String variation) {
            return applicationContext.getMessage(key, null, null, locale);
        }
    });

    // add DB i18n resources
    getResourceSettings().getStringResourceLoaders().add(new IStringResourceLoader() {
        @Override
        public String loadStringResource(Class<?> clazz, String key, Locale locale, String style,
                String variation) {
            if (StringUtils.isNotBlank(locale.getVariant())) {
                // always ignore the variant
                locale = new Locale(locale.getLanguage(), locale.getCountry());
            }
            String lang = locale.getLanguage();
            I18nStringResource resource = CalipsoApplication.this.calipsoService
                    .loadI18nStringResource(new I18nStringIdentifier(key, lang));
            if (resource == null && !lang.equalsIgnoreCase("en")) {
                resource = CalipsoApplication.this.calipsoService
                        .loadI18nStringResource(new I18nStringIdentifier(key, "en"));
            }
            return resource != null ? resource.getValue() : null;
        }

        @Override
        public String loadStringResource(Component component, String key, Locale locale, String style,
                String variation) {
            locale = component == null ? Session.get().getLocale() : component.getLocale();
            if (StringUtils.isNotBlank(locale.getVariant())) {
                // always ignore the variant
                locale = new Locale(locale.getLanguage(), locale.getCountry());
            }
            String lang = locale.getLanguage();
            I18nStringResource resource = CalipsoApplication.this.calipsoService
                    .loadI18nStringResource(new I18nStringIdentifier(key, lang));
            if (resource == null && !lang.equalsIgnoreCase("en")) {
                resource = CalipsoApplication.this.calipsoService
                        .loadI18nStringResource(new I18nStringIdentifier(key, "en"));
            }
            return resource != null ? resource.getValue() : null;
        }
    });
    // cache resources. resource cache is cleared when creating/updating a space
    getResourceSettings().getLocalizer().setEnableCache(true);
    getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {
        @Override
        public boolean isActionAuthorized(Component c, Action a) {
            return true;
        }

        @Override
        public boolean isInstantiationAuthorized(Class clazz) {
            if (BasePage.class.isAssignableFrom(clazz)) {
                if (((CalipsoSession) Session.get()).isAuthenticated()) {
                    return true;
                }
                if (calipsoCasProxyTicketValidator != null) {
                    // attempt CAS authentication
                    // ==========================
                    // logger.debug("checking if context contains CAS authentication");
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    if (authentication != null && authentication.isAuthenticated()) {
                        // logger.debug("security context contains CAS authentication, initializing session");
                        ((CalipsoSession) Session.get()).setUser((User) authentication.getPrincipal());
                        return true;
                    }
                }
                // attempt remember-me auto login
                // ==========================
                if (attemptRememberMeAutoLogin()) {
                    return true;
                }

                // attempt *anonymous* guest access if there are
                // spaces that allow it
                if (((CalipsoSession) Session.get()).getUser() == null) {
                    List<Space> anonymousSpaces = getCalipso().findSpacesWhereAnonymousAllowed();
                    if (anonymousSpaces.size() > 0) {
                        // logger.debug("Found "+anonymousSpaces.size()
                        // +
                        // " anonymousSpaces allowing ANONYMOUS access, initializing anonymous user");
                        User guestUser = new User();//getCalipso().loadUser(2);
                        guestUser.setLoginName("guest");
                        guestUser.setName("Anonymous");
                        guestUser.setLastname("Guest");
                        guestUser.setLocale(Session.get().getLocale().getLanguage());
                        getCalipso().initImplicitRoles(guestUser, anonymousSpaces, RoleType.ANONYMOUS);
                        // store user in session
                        ((CalipsoSession) Session.get()).setUser(guestUser);
                        return true;
                    } else {
                        if (logger.isDebugEnabled()) {
                            // logger.debug("Found no public spaces.");
                        }
                    }
                }

                // allow registration
                if (clazz.equals(RegisterUserFormPage.class)) {
                    return true;
                }
                // not authenticated, go to login page
                // logger.debug("not authenticated, forcing login, page requested was "
                // + clazz.getName());
                if (calipsoCasProxyTicketValidator != null) {
                    String serviceUrl = calipsoCasProxyTicketValidator.getLoginUrl();
                    //                              .getServiceProperties().getService();
                    String loginUrl = calipsoCasProxyTicketValidator.getLoginUrl();
                    // logger.debug("cas authentication: service URL: "
                    // + serviceUrl);
                    String redirectUrl = loginUrl + "?service=" + serviceUrl;
                    // logger.debug("attempting to redirect to: " +
                    // redirectUrl);
                    throw new RestartResponseAtInterceptPageException(new RedirectPage(redirectUrl));
                } else {
                    throw new RestartResponseAtInterceptPageException(LoginPage.class);
                }
            }
            return true;
        }
    });
    // TODO: create friendly URLs for all created pages
    // friendly URLs for selected pages
    if (calipsoCasProxyTicketValidator != null) {
        mountPage("/login", CasLoginPage.class);
    } else {
        mountPage("/login", LoginPage.class);
    }
    mountPage("/register", RegisterAnonymousUserFormPage.class);
    mountPage("/logout", LogoutPage.class);
    mountPage("/svn", SvnStatsPage.class);
    mountPage("/test", TestPage.class);
    mountPage("/casError", CasLoginErrorPage.class);
    mountPage("/item/", ItemViewPage.class);
    mountPage("/item/${itemId}", ItemViewPage.class);
    mountPage("/itemreport/", ItemTemplateViewPage.class);
    mountPage("/newItem/${spaceCode}", NewItemPage.class);
    //      MixedParamUrlCodingStrategy newItemUrls = new MixedParamUrlCodingStrategy(
    //                "/newItem",
    //                NewItemPage.class,
    //                new String[]{"spaceCode"}
    //        );
    //        mount(newItemUrls);

    //fix for tinyMCE bug, see https://github.com/wicketstuff/core/issues/113
    SecurePackageResourceGuard guard = (SecurePackageResourceGuard) getResourceSettings()
            .getPackageResourceGuard();
    guard.addPattern("+*.htm");

    this.getRequestCycleSettings().setTimeout(Duration.minutes(6));
    this.getPageSettings().setVersionPagesByDefault(true);
    this.getExceptionSettings().setThreadDumpStrategy(ThreadDumpStrategy.THREAD_HOLDING_LOCK);
}

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());/* w ww . jav  a 2s .  c o 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);
    }
}