List of usage examples for java.util Locale getCountry
public String getCountry()
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 v a 2s . com // 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.gradle.integtests.fixtures.executer.AbstractGradleExecuter.java
/** * Returns the set of system properties that should be set on every JVM used by this executer. *///w ww .jav a 2 s .c o m protected Map<String, String> getImplicitJvmSystemProperties() { Map<String, String> properties = new LinkedHashMap<String, String>(); if (getUserHomeDir() != null) { properties.put("user.home", getUserHomeDir().getAbsolutePath()); } properties.put(DaemonBuildOptions.IdleTimeoutOption.GRADLE_PROPERTY, "" + (daemonIdleTimeoutSecs * 1000)); properties.put(DaemonBuildOptions.BaseDirOption.GRADLE_PROPERTY, daemonBaseDir.getAbsolutePath()); if (!noExplicitNativeServicesDir) { properties.put(NativeServices.NATIVE_DIR_OVERRIDE, buildContext.getNativeServicesDir().getAbsolutePath()); } properties.put(LoggingDeprecatedFeatureHandler.ORG_GRADLE_DEPRECATION_TRACE_PROPERTY_NAME, Boolean.toString(fullDeprecationStackTrace)); if (useOwnUserHomeServices || (gradleUserHomeDir != null && !gradleUserHomeDir.equals(buildContext.getGradleUserHomeDir()))) { properties.put(REUSE_USER_HOME_SERVICES, "false"); } if (!noExplicitTmpDir) { if (tmpDir == null) { tmpDir = getDefaultTmpDir(); } String tmpDirPath = tmpDir.createDir().getAbsolutePath(); if (!tmpDirPath.contains(" ") || (getDistribution().isSupportsSpacesInGradleAndJavaOpts() && supportsWhiteSpaceInEnvVars())) { properties.put("java.io.tmpdir", tmpDirPath); } } properties.put("file.encoding", getDefaultCharacterEncoding()); Locale locale = getDefaultLocale(); if (locale != null) { properties.put("user.language", locale.getLanguage()); properties.put("user.country", locale.getCountry()); properties.put("user.variant", locale.getVariant()); } if (eagerClassLoaderCreationChecksOn) { properties.put(DefaultClassLoaderScope.STRICT_MODE_PROPERTY, "true"); } if (interactive) { properties.put(ConsoleStateUtil.INTERACTIVE_TOGGLE, "true"); } if (!searchUpwards) { if (!isSettingsFileAvailable()) { properties.put(BuildLayoutParameters.NO_SEARCH_UPWARDS_PROPERTY_KEY, "true"); } } properties.put(CommandLineActionFactory.WELCOME_MESSAGE_ENABLED_SYSTEM_PROPERTY, Boolean.toString(renderWelcomeMessage)); return properties; }
From source file:com.salesmanager.core.module.impl.integration.payment.PaypalTransactionImpl.java
/** * Marks SetExpressCheckout/*from w ww .j av a 2 s . co m*/ */ public Map<String, String> initTransaction(CoreModuleService serviceDefinition, Order order) throws TransactionException { ConfigurationRequest vo = new ConfigurationRequest(order.getMerchantId()); MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); String paymentType = "Sale"; IntegrationProperties properties; try { ConfigurationResponse config = mservice.getConfigurationByModule(vo, PaymentConstants.PAYMENT_PAYPALNAME); if (config == null) { throw new TransactionException("Payment module " + PaymentConstants.PAYMENT_PAYPALNAME + " cannot be retreived from MerchantConfiguration"); } properties = (IntegrationProperties) config.getConfiguration("properties"); } catch (Exception e) { throw new TransactionException(e); } if (properties == null) { throw new TransactionException( "Integration properties are null for merchantId " + order.getMerchantId()); } /* * '------------------------------------ ' The currencyCodeType and * paymentType ' are set to the selections made on the Integration * Assistant '------------------------------------ */ // @todo may support order if (properties.getProperties4().equals("1")) { paymentType = "Authorization"; } /* * Construct the parameter string that describes the PayPal payment the * varialbes were set in the web form, and the resulting string is * stored in $nvpstr */ String nvpstr = null; // always pass using USD format String amount = CurrencyUtil.displayFormatedAmountNoCurrency(order.getTotal(), Constants.CURRENCY_CODE_USD); if (order.getTotal().toString().equals(new BigDecimal("0.00").toString())) { // check if recuring if (order.getRecursiveAmount().floatValue() > 0) { amount = CurrencyUtil.displayFormatedAmountNoCurrency(order.getRecursiveAmount(), order.getCurrency()); } else { amount = "0"; } } Locale locale = order.getLocale(); String sLocale = "US";// default to US english /** * supports AU DE FR GB IT ES JP US **/ if (locale != null) { /* * String language = locale.getLanguage(); int lang = * LanguageUtil.getLanguageNumberCode(language); * if(lang==Constants.FRENCH) { sLocale = "FR"; } */ String country = locale.getCountry(); if ("AU".equals(country)) { sLocale = "AU"; } else if ("DE".equals(country)) { sLocale = "DE"; } else if ("FR".equals(country)) { sLocale = "FR"; } else if ("GB".equals(country)) { sLocale = "GB"; } else if ("IT".equals(country)) { sLocale = "IT"; } else if ("ES".equals(country)) { sLocale = "ES"; } else if ("JP".equals(country)) { sLocale = "JP"; } } try { MerchantStore store = mservice.getMerchantStore(order.getMerchantId()); String cancelUrl = ""; String returnUrl = URLEncoder.encode(ReferenceUtil.buildCheckoutUri(store) + (String) conf.getString("core.salesmanager.checkout.paypalReturnAction"), "UTF-8"); cancelUrl = URLEncoder.encode(ReferenceUtil.buildCheckoutShowCartUrl(store), "UTF-8"); if (order.getChannel() == OrderConstants.INVOICE_CHANNEL) { returnUrl = URLEncoder.encode( ReferenceUtil.buildCheckoutUri(store) + (String) conf.getString("core.salesmanager.checkout.paypalInvoiceReturnAction"), "UTF-8"); CustomerService customerService = (CustomerService) ServiceFactory .getService(ServiceFactory.CustomerService); Customer customer = customerService.getCustomer(order.getCustomerId()); cancelUrl = URLEncoder.encode(new StringBuilder().append(FileUtil.getInvoiceUrl(order, customer)) .append(customer.getCustomerLang()).append("_").append(locale.getCountry()).toString(), "UTF-8"); } nvpstr = "&METHOD=SetExpressCheckout&Amt=" + amount + "&PAYMENTACTION=" + paymentType + "&LOCALECODE=" + sLocale + "&ReturnUrl=" + returnUrl + "&CANCELURL=" + cancelUrl + "&CURRENCYCODE=" + order.getCurrency(); } catch (Exception e) { log.error(e); throw new TransactionException(e); } /* * Make the call to PayPal to get the Express Checkout token If the API * call succeded, then redirect the buyer to PayPal to begin to * authorize payment. If an error occured, show the resulting errors */ Map nvp = null; try { nvp = httpcall(properties, serviceDefinition, "SetExpressCheckout", nvpstr); } catch (Exception e) { log.error(e); throw new TransactionException(e); } String strAck = nvp.get("ACK").toString(); if (strAck != null && strAck.equalsIgnoreCase("Success")) { nvp.put("PAYMENTTYPE", paymentType); return nvp; } else { LogMerchantUtil.log(order.getMerchantId(), (String) nvp.get("L_LONGMESSAGE0")); log.error("Error with paypal transaction " + (String) nvp.get("L_LONGMESSAGE0")); return null; } }
From source file:org.apache.wicket.protocol.http.mock.MockHttpServletRequest.java
public void setLocale(Locale locale) { setHeader("Accept-Language", locale.getLanguage() + '-' + locale.getCountry()); }
From source file:org.spongepowered.granite.registry.GraniteGameRegistry.java
@Override public Optional<Locale> getLocaleById(String id) { for (Locale locale : getLocales()) { String localeString = locale.getLanguage() + "_" + locale.getCountry(); if (localeString.equals(id)) { return Optional.fromNullable(locale); }/*from w ww .j a va 2 s .c o m*/ } return Optional.absent(); }
From source file:org.openmrs16.Concept.java
/** * Gets the explicitly specified short name for a locale. The name returned depends on the * specificity of the locale. If country is indicated, then the name must be tagged as short in * that country, otherwise the name must be tagged as short in that language. * //from w ww.j a v a 2 s . c o m * @param locale locale for which to return a short name * @return the short name, or null if none has been explicitly set */ public ConceptName getShortNameInLocale(Locale locale) { ConceptName shortName = null; // ABK: country will always be non-null. Empty string (instead // of null) indicates no country was specified String country = locale.getCountry(); if (country.length() != 0) { shortName = getShortNameForCountry(country); } else { shortName = getShortNameInLanguage(locale.getLanguage()); } // default to getting the name in the specific locale tagged as "short" if (shortName == null) { for (ConceptName name : getCompatibleNames(locale)) { if (name.hasTag(ConceptNameTag.SHORT)) return name; } } return shortName; }
From source file:org.dasein.persist.PersistentCache.java
@SuppressWarnings("rawtypes") protected Object toJSONValue(Object value) { if (value == null) { return null; } else if (value instanceof String) { return value; } else if (Number.class.isAssignableFrom(value.getClass())) { return value; } else if (value instanceof Enum) { return ((Enum) value).name(); } else if (value instanceof Measured) { return ((Measured) value).doubleValue(); } else if (value instanceof Locale) { Locale loc = (Locale) value; String str = loc.getLanguage(); if (loc.getCountry() != null) { str = str + "_" + loc.getCountry(); }//from w ww. ja v a2 s . c o m return str; } else if (value instanceof UUID) { return ((UUID) value).toString(); } else if (value instanceof TimeZone) { return ((TimeZone) value).getID(); } else if (value instanceof Currency) { return ((Currency) value).getCurrencyCode(); } else if (value.getClass().isArray()) { Object[] replacement; if (value.getClass().getComponentType().isPrimitive()) { if (value.getClass().getComponentType().equals(long.class)) { long[] original = (long[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else if (value.getClass().getComponentType().equals(int.class)) { int[] original = (int[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else if (value.getClass().getComponentType().equals(byte.class)) { byte[] original = (byte[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else if (value.getClass().getComponentType().equals(boolean.class)) { boolean[] original = (boolean[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else if (value.getClass().getComponentType().equals(float.class)) { float[] original = (float[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else if (value.getClass().getComponentType().equals(double.class)) { double[] original = (double[]) value; replacement = new Object[original.length]; for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } else { Object[] original = (Object[]) value; replacement = new Object[original.length]; // note: cannot do in-place editing because types may not match // with the declared type for original for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } } else { Object[] original = (Object[]) value; replacement = new Object[original.length]; // note: cannot do in-place editing because types may not match // with the declared type for original for (int i = 0; i < original.length; i++) { replacement[i] = toJSONValue(original[i]); } } return replacement; } else if (value instanceof Collection) { Collection<?> c = (Collection<?>) value; Object[] replacement = new Object[c.size()]; int i = 0; for (Object item : c) { replacement[i++] = toJSONValue(item); } return replacement; } else { Annotation[] alist = value.getClass().getDeclaredAnnotations(); boolean autoJSON = false; for (Annotation a : alist) { if (a instanceof AutoJSON) { autoJSON = true; } } if (autoJSON) { return autoJSON(value); } else { try { Method m = value.getClass().getDeclaredMethod("toJSON"); return (JSONObject) m.invoke(value); } catch (Exception e) { return value.toString(); } } } }
From source file:org.richfaces.renderkit.PickListRenderer.java
protected String findLocalisedLabel(FacesContext context, String propertyId, String bundleName) { String label = null;/*from w w w . ja v a2 s .c om*/ Locale locale = null; String userBundleName = null; ResourceBundle bundle = null; UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot != null) { locale = viewRoot.getLocale(); } else { locale = Locale.getDefault(); } if (locale != null) { try { if (null != (userBundleName = context.getApplication().getMessageBundle())) { bundle = ResourceBundle.getBundle(userBundleName, locale, getCurrentLoader(userBundleName)); if (bundle != null) { label = bundle.getString(propertyId); } } } catch (MissingResourceException e) { if (logger.isDebugEnabled()) { logger.debug("Can't find bundle properties file " + userBundleName + " " + locale.getLanguage() + " " + locale.getCountry()); } } if (label == null && bundleName != null) { try { bundle = ResourceBundle.getBundle(bundleName, locale, getCurrentLoader(bundleName)); if (bundle != null) { label = bundle.getString(propertyId); } } catch (MissingResourceException e) { if (logger.isDebugEnabled()) { logger.debug("Can't find bundle properties file " + bundleName + " " + locale.getLanguage() + " " + locale.getCountry()); } } } } return label; }
From source file:org.opencms.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> * // www .j a v a 2 s . 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<Locale> defaults, List<Locale> 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.navitproject.navit.Navit.java
/** Called when the activity is first created. */ @Override//from w w w . j ava 2 s .c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) this.requestWindowFeature(Window.FEATURE_NO_TITLE); else this.getActionBar().hide(); dialogs = new NavitDialogs(this); NavitResources = getResources(); // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.) Navit.startup_intent = this.getIntent(); // hack! Remember time stamps, and only allow 4 secs. later in onResume to set target! Navit.startup_intent_timestamp = System.currentTimeMillis(); Log.e("Navit", "**1**A " + startup_intent.getAction()); Log.e("Navit", "**1**D " + startup_intent.getDataString()); // init translated text NavitTextTranslations.init(); // NOTIFICATION // Setup the status bar notification // This notification is removed in the exit() function NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager Notification NavitNotification = new Notification(R.drawable.ic_notify, getString(R.string.notification_ticker), System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0); // FIXME : needs a fix for sdk 23 // NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", getString(R.string.notification_event_default), appIntent); // Set the text in the notification // NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT; // Ensure that the notification appears in Ongoing // nm.notify(R.string.app_name, NavitNotification); // Set the notification // Status and navigation bar sizes // These are platform defaults and do not change with rotation, but we have to figure out which ones apply // (is the navigation bar visible? on the side or at the bottom?) Resources resources = getResources(); int shid = resources.getIdentifier("status_bar_height", "dimen", "android"); int adhid = resources.getIdentifier("action_bar_default_height", "dimen", "android"); int nhid = resources.getIdentifier("navigation_bar_height", "dimen", "android"); int nhlid = resources.getIdentifier("navigation_bar_height_landscape", "dimen", "android"); int nwid = resources.getIdentifier("navigation_bar_width", "dimen", "android"); status_bar_height = (shid > 0) ? resources.getDimensionPixelSize(shid) : 0; action_bar_default_height = (adhid > 0) ? resources.getDimensionPixelSize(adhid) : 0; navigation_bar_height = (nhid > 0) ? resources.getDimensionPixelSize(nhid) : 0; navigation_bar_height_landscape = (nhlid > 0) ? resources.getDimensionPixelSize(nhlid) : 0; navigation_bar_width = (nwid > 0) ? resources.getDimensionPixelSize(nwid) : 0; Log.d(TAG, String.format( "status_bar_height=%d, action_bar_default_height=%d, navigation_bar_height=%d, navigation_bar_height_landscape=%d, navigation_bar_width=%d", status_bar_height, action_bar_default_height, navigation_bar_height, navigation_bar_height_landscape, navigation_bar_width)); if ((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) || (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { Log.d(TAG, "ask for permission(s)"); ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSIONS_REQUEST_ALL); } // get the local language ------------- Locale locale = java.util.Locale.getDefault(); String lang = locale.getLanguage(); String langu = lang; String langc = lang; Log.e("Navit", "lang=" + lang); int pos = langu.indexOf('_'); if (pos != -1) { langc = langu.substring(0, pos); NavitLanguage = langc + langu.substring(pos).toUpperCase(locale); Log.e("Navit", "substring lang " + NavitLanguage.substring(pos).toUpperCase(locale)); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = NavitLanguage.substring(pos).toUpperCase(locale); } else { String country = locale.getCountry(); Log.e("Navit", "Country1 " + country); Log.e("Navit", "Country2 " + country.toUpperCase(locale)); NavitLanguage = langc + "_" + country.toUpperCase(locale); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = country.toUpperCase(locale); } Log.e("Navit", "Language " + lang); SharedPreferences prefs = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE); map_filename_path = prefs.getString("filenamePath", Environment.getExternalStorageDirectory().getPath() + "/navit/"); // make sure the new path for the navitmap.bin file(s) exist!! File navit_maps_dir = new File(map_filename_path); navit_maps_dir.mkdirs(); // make sure the share dir exists File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR); navit_data_share_dir.mkdirs(); Display display_ = getWindowManager().getDefaultDisplay(); int width_ = display_.getWidth(); int height_ = display_.getHeight(); metrics = new DisplayMetrics(); display_.getMetrics(Navit.metrics); int densityDpi = (int) ((Navit.metrics.density * 160) - .5f); Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_); Log.e("Navit", "Navit -> dpi=" + densityDpi); Log.e("Navit", "Navit -> density=" + Navit.metrics.density); Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity); ActivityResults = new NavitActivityResult[16]; setVolumeControlStream(AudioManager.STREAM_MUSIC); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + langc); } if (densityDpi <= 120) { my_display_density = "ldpi"; } else if (densityDpi <= 160) { my_display_density = "mdpi"; } else if (densityDpi < 240) { my_display_density = "hdpi"; } else if (densityDpi < 320) { my_display_density = "xhdpi"; } else if (densityDpi < 480) { my_display_density = "xxhdpi"; } else if (densityDpi < 640) { my_display_density = "xxxhdpi"; } else { Log.e("Navit", "found device of very high density (" + densityDpi + ")"); Log.e("Navit", "using xxxhdpi values"); my_display_density = "xxxhdpi"; } if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for " + my_display_density); } // --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4 Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK)); NavitMain(this, NavitLanguage, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density, NAVIT_DATA_DIR + "/bin/navit", map_filename_path); showInfos(); Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); }