Friday Sep 19, 2008

How to do Internationalization(I18n) and Localization(L10n) in Liferay , WebSynergy

Hi .. I'm Back .. was busy exploring more on I18n of Liferay

This blog will describe how to do i18n in development environment of Liferay and WebSynergy(now on will be referred as Portal). Also while adding new Portlets to Portal how to leverage existing Portal UI tag lib and Language utility class for I18n in quicker and easier way.

Resource Bundle

Key Points

  • Portal has only One Resource Bundle for all the components . Refer my previous entry for more details
  • Location in workspace : portal-impl/content/
  •  Location in Installation :
          • Unjar portal-impl.jar (it will be lib directory of workspace)
          • file will be found in content directory
  • Either you can directly modify this OR (most preferred way) to create and bundle in same jar. Because if you directly modify then you need to manually take care of adding your changes during updated to latest default which you will get in install.

Convention to add messages in Resource bundle

  1. This file follows same convention as defined for Liferay's default liferay/trunk/portal-impl/content/
  2. Each property should key should be prefix by your portlet name .
  3. File is well-defined in to various section descried below
    1. Portlet Titles : Portlet titles of your portlet. - NEEDS TO VERIFY
      1. Portlet title key should be constructed as javax.portlet.title.PORTLETNAME , where PORTLETNAME is name which you have mentioned in portlet-name tag of your portlet.xml.
        ex. java.portlet.title.FriendsPortlet=Friends Widget
      2. This feature is yet to test (by me) so you can use Portlet specific resource bundle to define title.
    2. Category Titles : Category titles which appears in "Add Application" list
      1. It should be prefix by category.CATEGORYNAME where CATEGORYNAME is name of category.
      2. ex. category.admin=Admin
      3. this category key will be used in liferay-display.xml of portlet which are part of category
        1. ex. <display>
              <category name="category.cms">
                  <category name="category.alfresco">
                      <portlet id="1" />
    3. Model resources : Model resources should be prefix by model.
      1. ex.
      2. ex. Entry
    4. Action Items : Messages which used as action items. Should be prefix by action.. All words are in uppercase. Word seperator is _
      1. ex. action.ADD_ARTICLE=Add Article
    5. Messages : General messages
      1. Key should be construed from Message. ex Key for message My Friends will be my-friends
      2. Use x for dynamic parameter in messages ex. Key for message This {0} is great will be this-x-is-great
      3. If message is very long (ex. more then 15 words) you can use small key but make sure it is giving information about message
        ex. an-applet-version-of-the-editor-is-also-available=An applet version of the editor is also available. It is a heavier but more user friendly editor that provides colorized text, search and replace, and other functionality. You can choose to use that editor by editing your portlet preferences.
  4. Keep each section of file in ascending order

How to use liferay ui taglib to fetch messages in JSP/Java Script

There are various ways to fetch message from resource bundle.

NOTE : All the following approach will consider as Resource bundle and will fetch messages form there based on locale. However following methods support -ext mechanism i.e It will first look in file.

  1. liferay-ui:message tag
  2. LanguageUtil class
  3. UnicodeLanguageUtil class
  4. Other liferay ui tags - I18n'ed

liferay-ui:message tag

  • For simple messages which does not have dynamic parameter use this tag
    ex. < liferay-ui:message key="my-friends"/ >
  • This tag internally calls LangaugeUtil class

LangaugeUtil class

LanguageUtil class has various formatter methods use them based on situation.

  • For messages which has dynamic parameter use following method. Make last argument as "true" if you want your parameter to be translated as well
    ex. <%= LanguageUtil.format(pageContext, "upload-a-gif-or-jpeg-that-is-x-pixels-tall-and-x-pixels-wide", new Object {"120", "100"}, false) %>
  • For messages which has html code along with parameter then use LangaugeWrapper as argument instead of Object
    ex.<%= LanguageUtil.format(pageContext, "your-account-with-login-x-is-not-active", new LanguageWrapper {new LanguageWrapper("", user.getFullName(), ""), new LanguageWrapper("< b >< i >", userLogin, "< /b >")}, false) %>

Other liferay ui tags and LanguageUtil class methods- I18n'ed

  • liferay-ui:icon-help - This tag is i18n'ed. You can use key value in message attribute of this tag
    • < liferay-ui:icon-help message="allow-dictionary-words-help"/ >
  • LanguageUtil.getTimeDescription - to get localized time descrption
    • <%= LanguageUtil.getTimeDescription(pageContext, _DURATIONSi? \* 1000) %>

UnicodeLanguageUtil Class

  • Use this class in Java Script in JSP pages
  • UnicodeLanguageUtil has similar method singature as found in LanguageUtil class.
  • ex. function copyFromLive() {

if (confirm('<%= UnicodeLanguageUtil.get(pageContext, "are-you-sure-you-want-to-copy-from-live-and-overwrite-the-existing-staging-configuration") %>')) { document. fm. <%= Constants.CMD %>.value = "copy_from_live"; submitForm(document. fm); } }

  • Also use in alert within jsp
  • ex2.
    " method="post" name=" fm" onSubmit="alert('<%= UnicodeLanguageUtil.get(pageContext, "please-be-patient") %>'); submitForm(this); return false;">

Import and define tag lib in your jsp or included jsp

  • <%@ taglib uri="" prefix="liferay-ui" %>
  • Import following classes
    • <%@ page import="com.liferay.portal.kernel.language.LanguageUtil" %>
    • <%@ page import="com.liferay.portal.kernel.language.LanguageWrapper" %>
    • <%@ page import="com.liferay.portal.kernel.language.UnicodeLanguageUtil" %>

How to use liferay Language Utill classes to fetch messages in JAVA programs

In order to fetch localized messages in java program we will be using same Util classes which has been used in JSP/Java Script

  • LanguageUtil class
  • If your message does not have any dynamic parameter then use any of LanguageUtil.get(...,key) method. this method will fetch message assicated with key. There are various overloaded version of LanguageUtil.get are available , use desired get method based on situation.  Some of commonely used version of get method.
    • LanguageUtil.get(pageContext,key)
    • LanguageUtil.get(companyId,key) etc.
    • there are other overloaded version of get method is available. You need to use them based on your requirement.
    • Refer class "portal/trunk/portal-kernel/src/com/liferay/portal/kernel/language/ for details.
  • If your message has  dynamic parameter then use any of LanguageUtil.format(...,key,Object) method.  this method will fetch message assicated with key. There are various overloaded version of LanguageUtil.form are available , use desired format method based on situation.  Some of commonely used version of form method.
    • LanguageUtil.get(pageContext,key, object)
    • LanguageUtil.get(pageContext,key, new Object[])
    • there are other overloaded version of format method is available. You need to use them based on your requirement.
    • Refer class "portal/trunk/portal-kernel/src/com/liferay/portal/kernel/language/ for details.

How to use liferay Language Utill classes to fetch messages in Velocity templates

Portal uses velocity engine to create templates i.e. .vm files which are used to define layout and in themes.

  • Set Language Id : #set ($language_id = $user.getLanguageId()) in your init template.
  • You can use following syntex to fetch messages from file
    • #language ("KEY-NAME")
  • Some places I have also seen usage of language util as follow.
    • $languageUtil.get($company_id, $locale, "add-application"))

There is also certain changes required in portlet.xml <resource-bundle> tag to allow container to fetch portlet title from common resource bundle. Watch out for this space , I will update it shortly. 

 Never shy away from re using stuff which already exists ... It gives more time to innovate...

Wednesday Aug 13, 2008

One resource bundle per One Application - I18n and L10n will be easy

<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-2367267-3"); pageTracker._trackPageview(); </script>

First what is with this some what mystry title.

In simple words , I would like to highlight advantage of keeping only one resource bundle( aka. one property file which contains all the localizable messages) per One Application.

Source of insipiration was Liferay.

Let me give you more idea of how it will look like.

1) Make sure all your translatable strings are put on one property file  ex.

This will help to your customer who might want to add new langauge or want to add new strings to existing language or change strings to existing langauge. Easy to find where to do localization.

2) Organized it well . Define a rule to write key name.

ex. first_name=First Name

     account_number=Account Number

This will help to easily find of what this key represents in localized bundle.

3) Keep it in Alphabetical order

This will ensure that duplicate properties does not exists in your bundle.

4) Now you can keep common utility class which will load the bundle based on Locale user wanted

This will help all your other class as they do not need to bother about loading bundle. They can focus on solving business logic (that's where money comes from)

Last but not the least ... Innovation is mother of all invension ... so innovate whether it is necessasity or not :-) ...

Wednesday Jun 11, 2008

Localization in Portal Server 7.2 (recently released)

Recently Portal Server 7.2 is released. Checkout more details about new features and download at this blog.

In this release we have localized in seven languages as done in earlier releases.

German (de) , Spanish (es) , French (fr) , Japanese (ja) , Korean (ko) , Simplified Chinese (zh_CN) , Tranditional Chinese (zh_TW).

I will talk some key changes we have done in localization.

1) There is NO l10n packages. then where is l10n files? , L10n files are packaged in base packages. We call it "Unified Packaging" 

What is advantage of this?

- Customer does not need to perform any special step to install  and configure localized version of portal. It will give seamless experience to l10n users

- Upgrade and migration would be much easier

2) In open source workspace , location of l10n files has been changed from what it was in close source workspace. Now each l10n file is placed along with corresponding english. It will also community/developer to easily find localized files in workspace.

Visit  localization wiki page to get more details on localization activities in portal server. It is also provides various useful "How to" to help l10n users.

Wednesday Jan 30, 2008

I18n 360' testing approach at Step-IN 2008 Conference

Recently I had been to one of the most beautiful hotel aka. palace in Bangalore.  No marks for guessing its Leela Palace.
I had been there before but this time reason was not for pubbing (athena)  as it used to be.I was there to give talk at Step-in 2008 Conference (ASIA's biggest testing conference - as organizers claims).

My talk was on Internationalization(I18n) 360' testing approach , the concept which close to my heart and job. Its fresh , unique and quick at results. Implemented in Portal Server 7.2 aka.OpenPortal development.

My topic was selected for Pre-conference tutorial , A long 210 minutes( 3 hours and 30 minutes). It was indeed long time to stand , deliver and interact but my passion toward the subject was a big help. Curiosity of delegates in terms of their questions regarding I18n , their day to day use cases , their business case has never made me felt that it was long. In fact I had to rush a bit in last stage of Presentation.


Let move to what I shared there.

It was started with Introduction of I18n world (I18n , L10n , G11n) which also covered all the basic terminologies like Character , Charset , Unicode , UTF-x , Glyph , Font , Locale. My audience was enjoying every bit of information as most of them were aware about I18n but this details made them realize what the hack it is. This session was resulted in lots of questions and interesting discussion. They allowed to move ahead with the promise that I will spend quality time after talk  to share more of my understanding about I18n world.

Next session was regarding I18n 360' testing approach , which in simple teams means involving I18n in every stage of product development , starting as early as product planning. How I18n play role in Requirement phase , Design phase , Implementation phase and most importantly QA phase. Even in documentation also I18n has role to play. Usage of real time example and case study has made this session most entertain one. If it got you curious enough here is the Presentation for you

After that I had shown them live demo of how to do i18n testing in stand alone application and web application. This followed by demo of  I18n testing automation using Open Source automation tool Canoo. At last as a common practice Question and Answers.

 It was a wonderful and memorable experience for me. It was first time I had been to such reputed conference to represent Sun. I had been to Universities for talk earlier but this was unique and challenging as audience was mix of managers , consultants  and testing engineers.

Tuesday Sep 18, 2007

AJAX Internationalization (I18n) in Portal Server

In latest release of Portal Server AJAX capability has been introduced in the form of AJAX containers.

First ,  What is  AJAX containers in Portal Server?

The AJAXTableContainerProvider integrates Asynchronous JavaScript and XML (AJAX) capabilities at the portal framework level. The container provides asynchronous loading of individual channels and portlets. Therefore, a slow channel or portlet will not affect the loading time of the other channels and portlets on a page, improving overall performance. The AJAXTableContainerProvider includes AJAX based interaction for all container controls and features which provides for a much richer and faster user experience.

Let move to core item of this blog,  AJAX I18n.

Some clerification before we procedd.
- Sources(js , jsp , java) are referred from OpenPortal repository.
Location of ajaxcontainers in portal source code:

Thare are two containers provided in Portal Server
1) AJAXEditContainer
2) AJAXTableCotainerProvider

For example I will use "AJAXTableCotainerProvider".


In this AJAX container thare two primary source for I18n

1)Java Server Pages(JSP) Internationalization(I18n)
Location in OpenPortal repository:

How these JSPs are I18n'ed?
JSP I18n is quite straight forward , lets understand it by example of one of the jsp from source i.e. table.jsp

Steps for JSP i18n: 

1.1) Defining I18n tag library:
<%@ taglib uri="/tld/i18n.tld" prefix="i18n"%>
This tag libarary contains various tags required to perform I18n functions.

1.2) Loading the resource bundle:
<i18n:setBundle baseName="ajaxcontainers" var="ajaxcontainersRB"/>
This tag will load resource bundle "ajaxcontainers"  based on user locale.
Have a look at base resource bundle

1.3) Fetching value from resource bundle
<i18n:message key="" bundle="ajaxcontainersRB"/>
"message" tag will fetch value from resource bundles for specified key.

2)Java Scripts(JS) Internationalization(I18n)

You have reached to most interesting part of this blog i.e Java Script I18n.
The fact that java script does not have any defined framework for I18n makes it very interesting and scope of innovation. In this blog I will explain one of the innovative and well proven approach used for I18n of java script in AJAX container.

Location of Java Scripts in Source :

Following steps are require for JS I18n.
2.1) Method to fetch all the properties from resource bundle in table.jsp.
public JSONObject getLocalizedStrings(java.util.ResourceBundle rb)
      throws JSONException {
JSONObject localizedStrings = new JSONObject();
      if (rb == null) {
                      localizedStrings.put("x", "y");
      if (rb != null) {
              for (Enumeration e = rb.getKeys() ; e.hasMoreElements()  ;)   {
                      String key = (String)e.nextElement();
                      String val = rb.getString(key);
                      localizedStrings.put(key, val);
      return localizedStrings;

2.2)  Creating  "tableContainerProviderModel" JSON <> object in table.jsp.
JSONObject tableContainerProviderModel = new JSONObject();
This JSON object will be used to hold localized values in terms of property along with other properties

2.4) Next step would be to add localized value to this JSON object using method to fetch localized value from resource bundle.
tableContainerProviderModel.put("localizedStrings", getLocalizedStrings(ajaxcontainersRB));

2.5) Now we need variable which can be used in Java Script. Creating "containerModel" variable in table.jsp and assigning "tableContainerProviderModle" JSON Object to it.

<script type="text/javascript">
      var containerModel = <%=tableContainerProviderModel.toString(4)%>
      var pageStyles = new sunportal.AJAXPageStyles('<dtpc:getStaticContentPath/>');

2.6) Loading of java script in table.jsp using <script> tag
<script type="text/javascript" src="<dt:scontent/>/desktop/ajaxcontainers/js/sunportal/AJAXUtils.js"></script>

We done with our intial setup i.e these steps will be performed intially when user makes request to server.  All the further interaction will be through Java Scripts and localized string will be fetched from JSON object.

How lets see?

2.7)  JS Function below used by all JS to fetch localized value : sunportal.getLocalizedString
This  function is defined in AJAXUtils.js as below:

var _1=arguments[0];
var _2=containerModel.localizedStrings[_1];
for(var i=1;i<arguments.length;i++){
var j=i-1;
var re=new RegExp("\\\\{"+j+"\\\\}","g");
return _2;
As you can see this function takes "key" as argument and fetch loalized value from containerModel.localizedStrings Map which we have poplulated in step 2.2.

2.8) Let see how this functions is used in Java Scripts at Client side.
eg. AJAXChangeLayout.js
This function used by all the Java Scripts to fetch localized values without  accessing resource bundles stored at Server side.

I hope , I am able explain it correctly ... Any questions/comments are welcome ...:-).


Mahipalsinh Rana


« April 2014