I18n - JSF variable value translation - java

I am using Bundle Internationalization in my project. I have initialized bundle via
<f:loadBundle basename="ui.all.bundles.AppResources_en" var="msg"/>
When i need to translate some text, i am using a key to resourceBundle, to get a value of it, for example: #{msg.someText}. But, now i want to translate text, which key is a value of another variable. For example:
I have variable String textToTransl. It`s value is status_booked. In my AppResources is defined, that status_booked means "It is booked!", so, when i am pointing it to #{msg.textToTransl} i need to see "It is booked!"
How can i make it work?

Use:
value="#{msg[currentDoc.textToTransl]}"

ui.all.bundles.AppResources
Don't include the locale (_en) in the resource name. The resource bundle code should resolve the locale-specific bundle based on the request locale.

Related

Path variable having special characters like # in Spring boot

I'm using Spring Boot 2.4.6. For delete APIs getting 405 method not found. My endpoint is like: beauty/v1/sites/addressTemplates/:templateId
Path variable: ##$%#
Can someone please suggest what can be done to make this behavior as not complaining for 405? Please direct me to other questions in case I'm missing something.
I guess that your issue has nothing to do with Spring. Maybe you are trying to compose the whole URL by using reserved characters.
In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. Source.
Which means that an URL which looks like:
beauty/v1/sites/addressTemplates/##$%#
is not exactly what you imagine it to be because # is interpreted in a special way. What you have to do is to percent encode the "special" path variable so it will look like this at the end:
beauty/v1/sites/addressTemplates/%23%40%24%25%23
Then Spring will not complain anymore and will resolve properly the endpoint.

How to use String ressource in Java file in Android without a Layout

I have a Java class that mainly contains strings. It does not have a layout as it is neither a Fragment nor an Activity. It is more used as an auxilliary class. I would like to assign the String values in the class by using the Resource strings as I would like to automatically translate the Strings. Howvever, I can't access the string resources from Java. I use the following code:
static String more = getString(R.string.more);
And in the XML file I have the ressource:
<string name="more">More</string>
I get the error message
Cannot resolve method 'getString'
I also tried static String more = getContext().getString(R.string.more);
but I got the error message:
Cannot resolve method 'getContext'
Would anyone mind helping me on that? I'd appreciate every comment.
Update: I tried to use the answer from "MikaelM"
Resources.getSystem().getString(R.string.more)
However, I get an "exception in initializer error" and when I use the initial String again, I do not get this error. So I still can't get the String from the ressource. DO you have an idea what I can do? I'd appreciate every further comment.
So the error is caused by "Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f120038"
The strange thing is that the resource in fact exists (I checked this several times).
getString(R.string...
is not the same as
Resources.getSystem().getString(android.R.string...
Only the second variant you can use in the static context. Alas, you can get this way only system resources.
If you need to get your own resources, no one-line solution exists. Use https://stackoverflow.com/a/4391811/715269 solution of #Cristian. And notice: it is a very good solution, even more, it is the solution meant to be used by the creators of Android.
You should be able to get your string with:
Resources.getSystem().getString(R.string.more)
See more here, getString Outside of a Context or Activity

Thymeleaf add custom data attribute with message resource value

I have a requirement where I need to insert the value to custom data tag using thymeleaf. The code for doing it using
data-th-attr="${data-custom=#messages.msg('test')}"
as well as
th:attr="data-custom=${#messages.msg('test')}"
I am unable to get the value in both the cases.
ultimately the parsing should be like data-custom="test"
here test is key for the value test in a properties file
By using the
data-th-attr="data-custom=#{test}"
or By using
th:attr="data-custom=#{test}"
helped me out, here test is the key for the value in message resource the issue was with the intellij IDEA IDE, it was having a bug that was showing me an unnecessary error.
Use th:attr="data-custom=#{key.for.message}" , this should work.
then after parsing the Expression,
data-custom="value.for.message"

How to set the Locale Value based on the country the user belongs to

Currently my J2EE Application supports these below countries
MessagesBundle_en_GB.properties (United Kingdom )
MessagesBundle_en_US.properties (United States )
MessagesBundle_it_IT.properties (Italy )
MessagesBundle_pt_BR.properties (Brazil )
MessagesBundle_sv_SE .properties (Sweden)
So i made a properties files for all these countries above and defined the Key value pairs in it .
I am using Resource Bundle for this concept .
And the way i will be accessing the key name is this way
bundle.getString("userName"));
bundle.getString("Mobile"));
Now my question is ,
How can i set the Locale value inside the JSP Page , because the user might belong any of the country as mentioned above
Please let me know , thank you very much
// This one is hardcoded , how can i set this dynamically ??
ResourceBundle bundle = ResourceBundle.getBundle("MessagesBundle", Locale.UK);
use ResourceBundle.getBundle(BUNDLE_NAME).getString(key); to access the Strings.
when updating the Default Locale e.g. via Locale.setDefault(<REQUIRED_LOCALE>); clear the Resourcebundle cache: ResourceBundle.clearCache();
the next call of ResourceBundle.getBundle(BUNDLE_NAME).getString(key); should the return the localized String of the chosen Locale.
The simplest way to do it is to implement HttpFilter. Call it for example LocaleHttpFilter. It should be mapped to/*` in your web.xml, so it will be called every time the request arrives to your application.
The filter will discover your request and decide what should be the current locale. It may base its decision on URL parameters, HTTP headers, GeoIP lookup etc. Once it decided about the locale it should call:
Locale.setDefault(locale)
Then you can use
ResourceBundle.getBundle("MessageBundle").getString("hello");
at any place in your code. This line will return value of string "hello" according to the current locale that was set into the filter.
First thing first: you may use ResourceBundle.getBundle(Locale) in your back-end code. However, you should never use this in the JSP Page directly. You should use JSTL instead. Now, let's get into details.
There are two reasons why it is not necessary the good idea to use ResourceBundle directly. One is related to this:
<%
try {
ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
} catch (MissingResourceException mre) {
// LOG THIS!
}
%>
This looks pretty ugly, doesn't it? That's because you have to beware of MissingResourceException that will be thrown if there is no bundle for base name you are looking for. To make matters worse, the same exception might be thrown if there is no key in the given scenario:
rb.getString("key");
So you also need to take this into account:
<%
try {
rb.getString("key");
} catch (MissingResourceException mre) {
// LOG THIS!
}
%>
How does it look?
Of course you can derive from ResourceBundle and override these methods so they won't throw an exception, but this is substantially more work than just this:
<fmt:setLocale value="fr_CA" scope="session"/>
<fmt:bundle basename="com.taglib.weblog.Greeting">
<fmt:message key="com.taglib.weblog.Greeting.greeting">
This is the reason you should use JSTL with JSP. Read more about how to use JSTL for i18n in this article.
Now, your original question was about language negotiation (W3C term), or Locale detection if you prefer. How to do that in JSP application?
The easiest and most typical scenario is to read the contents of HTTP's Accept-Language header. In Java Servlet world that means calling ServletRequest's getLocale() or getLocales() method and assign to variable in HttpSession object, which is accessible from JSP page. If you wonder how to access HttpSession on the servlet side, there is a getSession() method.
That works if you have direct access to Servlet. If you don't you need to create (or assign existing) Locale filter which will do all that for you. As you may imagine, this is fairly common scenario. That's the reason people already written (long time ago) necessary classes. You can find in few frameworks, let me notably mention Spring Framework.
I know it might sound strange, but if you are looking for simple solution, learning and using common web framework (i.e. Spring MVC) is better that re-inventing the wheel. I know that learning curve might be a bit steep, but it is worth it.

NullPointer getting internationalization text at LocalizedTextUtil

I have 3 language files idioma_CA.properties idioma_EN.properties idioma_ES.properties in the package "idiomas" and one default idioma.properties.
struts.properties has this properties:
hibernatePlugin.configurationType=annotation
struts.custom.i18n.resources = idiomas/idioma
So everytime I try to change the language struts2 ignores me and get always the text from the default properties at JSP's.
But using "getText" at execute method of my Action I get that NullPointerException whatever locale i have at request_locale.
Can someone tell me what am i doing wrong?
Thank you very much
I solved the problem.
The localization letters after "idioma_" must be lowercase like "idioma_ca.properties"

Categories