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/Language.properties
  •  Location in Installation :
          • Unjar portal-impl.jar (it will be lib directory of workspace)
          • Language.properties file will be found in content directory
  • Either you can directly modify this Language.properties OR (most preferred way) to create Language-ext.properties and bundle in same jar. Because if you directly modify Language.properties then you need to manually take care of adding your changes during updated to latest default Language.properties 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 Language.properties liferay/trunk/portal-impl/content/Language.properties.
  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" />
                  </category>
              </category>
          </display>
    3. Model resources : Model resources should be prefix by model.
      1. ex. model.resource.com.liferay.portal.model.Group=Community
      2. ex. model.resource.com.liferay.portlet.blogs.model.BlogsEntry=Blogs 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 Language.properties 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 Language-ext.properties 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="http://liferay.com/tld/ui" 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/LanguageUtil.java 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/LanguageUtil.java 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 Language.properties 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...

Friday Jun 13, 2008

Netbeans 6.1 Multilingual released , Portal Pack ML will follow soon

Checkout ML release for Netbeans 6.1  It is localized in three languages Japanese (Ja) , Simplified Chinese (zh_CN) and Portuguese (pt_BR). I have download and installed , it looks great. And major difference is perfromance from last release , it quite fast. have fun with Netbeans ..

We are working on ML release of  Portal Pack 2.0(http://portalpack.netbeans.org) It will be released soon. Watch this space for more details on Portal Pack 2.0 ML. 

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.

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:
.../openportal/portal/samples/ajaxcontainers

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

For example I will use "AJAXTableCotainerProvider".

AJAXTableCotainerProvider:

In this AJAX container thare two primary source for I18n

1)Java Server Pages(JSP) Internationalization(I18n)
Location in OpenPortal repository:
.../openportal/portal/samples/ajaxcontainers/src/channels/AJAXTableContainerProvider

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 ajaxcontainers.properties

1.3) Fetching value from resource bundle
<i18n:message key="loading.page" 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 :
.../openportal/portal/samples/ajaxcontainers/src/web-src/js

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 <http://www.json.org/> 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/>');
      pageStyles.init();
</script>

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:

sunportal.getLocalizedString=function(){
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");
_2=_2.replace(re,arguments[i]);
}
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
td.innerHTML=sunportal.getLocalizedString("full.top.portlets");
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 ...:-).

Friday Aug 03, 2007

OpenPortal at University Day in Bangalore!!

    I have been involved with Sun's University relations initiative for a few months now. The present project involves evangelizing Sun's technologies in colleges so as to capture the mindshare of students.

    Acharya Institutes is situated on the outskirts of Bangalore and we needed to get there by 8AM, so I had to pull myself out of the bed very early (I rarely see early mornings , it was beautiful :))

    As we reached the institute, all of us were amazed by this huge campus of 100 acres with around 20 buildings under construction and mind blowing architecture (award winning apparently) . Mr Vishwanathan, who is the HoD and other college authorities welcomed us and took us to the auditorium.

    Audience was final year students from various colleges of Bangalore and adding to our surprise, there were International students (from Africa) with basic knowledge of Java. My goal was to get them interested in OpenPortal and Portlets. I started with some visuals of OpenPortal samples and iGoogle to give them an idea of Portal Server. I introduced the concepts of Portlet development and explained why this is interesting since they are eager to figure out why this is important to them. I then presented the main topic of the day “OpenPortal Portlet Container” and “NetBeans Portal Pack plugins” by showing several screenshots and a demo.

     Demo got everyone's absolute attention as they were amazed to see with just few clicks on NetBeans (pre-installed with Portal Pack and configured with OpenPortal Portlet Container), a Portlet got developed, deployed and most importantly running in our OpenPortal Portlet Container. It was pretty cool to show this demo to these students (customers!) I was thrilled to see the curiosity and excitement in their eyes! Kudos to NetBeans Portal Pack and OpenPortal Portlet Container team for such a wonderful gift to industry.

    This demo resulted in healthy Q&A session as students showed a lot of interest and asked great questions about Portlet Development and NetBeans. One of common question worth to mention was “Can they really contribute with limited knowledge they have”, my answer was “Yes” with reasoning, and they can learn a lot from experts in an Open Source project and develop themselves. There is lot of scope for contributions in any Open Source project, not just 'Write Code' as they seem to think.

    As a final remark I have informed them Portlets are here to stay and conquer the web development world so be a part of it … Pointed them to Open Portal, OpenPortal Portlet Repository.

    Next in turn was “Application development using NetBeans” by Amol Desai then much deserved lunch. At the end we have received Memento and “In Office Golf Kit” which was best part according to my team mates when I reached office after long journey in peek hour traffic of Bangalore. An End of Wonderful Experience but Beginning of OpenPortal at University programs in Bangalore.

(from left) Prof . Vishwanathan , Amol , Myself , Srinith , Students @ Acharya

 


 

About

Mahipalsinh Rana

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today