Demonstrating i18n

Embed Size (px)

Citation preview

  • 7/30/2019 Demonstrating i18n

    1/15

    Creating an Internationalized Application

    June 2006[Revision number: V2.1-2]Copyright 2006 Sun Microsystems, Inc.

    This tutorial explains how to internationalize a web application using the Sun Java Studio Creator application development tool (or IDE).The application described in this tutorial enables a client browser to set the application's locale and character encoding at runtime. Thiscapability is useful when your application must support multiple languages, different encodings of the same language, or legacyencodings. The application responds to user choice of one of four locales and three character encodings. After the user chooses a localeand encoding, the application server sends text for display in that encoding and accepts text entered by the user in the same encoding.

    Contents

    - Setting Up Your System

    -Designing the UserInterface

    - Providing Action Methods

    - Creating Properties Bundle

    - Testing Your Application

    Example used in this tutorial demonstrating_i18n_ex.zip

    Setting Up Your System

    Before working through this tutorial, setup your system so that the following languages and the fonts needed to display them are present:English, Russian, Japanese, and Simplified Chinese. The process for installing languages and fonts depends on the platform on which youare working. Please consult your system documentation for instructions.

    Designing the User Interface

    You will use Grid Panel components to organize the user interface elements and help to isolate the layout from differences amongbrowsers and operating systems at runtime. Grid Panel components are especially useful in internationalized applicationswhen you useGrid Panel components, page layout is less affected by differences in string length for various languages.

    1. Create a new web application project and name it HelloBundledWorld.

    2. From the Components Palette, choose the 14 components shown in the following table and drag them onto the page in the VisualDesigner. As you drag each component on the page, change its id property to the value shown in the third column of the table.

    Table 1: Components to Place on Page

    Quantity Component Type ID Properties

    3 Layout > Grid Panel gridLarge, gridUpperRight, gridCenterRight6 Basic > Static Text helloText, chosenOption, chosenIndex, chosenLocale,

    chosenEncoding, youEnteredDisplay2 Basic > Label enterTextLabel, youEnteredLabel1 Basic > Button submitButton1 Basic > Text Field textEntry1 Basic > Drop Down List localeDropDown

    Placement of the components is not critical at the moment, but your page should look something like the following figure:

    1

  • 7/30/2019 Demonstrating i18n

    2/15

    Figure 1: Initial Page Layout

    3. Select each Grid Panel component in turn and, in the Properties window, change each of their columns properties to 2 and eachof their rules properties to all. Displaying the rule lines will help you adjust the layout.

    You will now arrange the components into their final configuration. The easiest way to do so is to drag their names into the Outlinewindow.

    4. In the Outline window, expand the page1 > html1 > body1 > form1 node if it is not already expanded. Drag the component namesto organize them as shown in the following figure.

    Figure 2: Organizing Page Layout in OutlineWindow

    The page in the Visual Designer should now look something like the following figure.

    2

  • 7/30/2019 Demonstrating i18n

    3/15

    Figure 3: Grid-Organized Page Layout

    5. Select each Grid Panel component in the Outline window and change its rules property to none to remove the rule lines fromthe display, as shown in the following figure.

    Figure 4: Adjusting Grid Panel Sizes

    6. Select the Button component and, in the Appearance section of the Properties window, set the text property to Submit.

    7. Select the Drop Down List component, right-click, and choose Auto-Submit on Change from the pop-up menu.

    Providing Action Methods

    You now edit the submit_action()method for the Button and the localeDropDown_processValueChange()method forthe Drop Down List.

    1. With Page1 displayed in the Visual Designer, double-click the Submit button. The IDE creates an action method for the Buttoncomponent, opens the Java Editor, and places the editing cursor in the method.

    2. Edit the submitButton_action()method to read as shown in the following code example:

    Code Example 1: submitButton Action Method

    public String submitButton_action() {

    // Get value of drop-down list and process it

    String str = this.localeDropDown.getValue().toString();

    processLocaleChange(str);

    return null;

    }

    You will fix the symbol not found error in the next section.

    3. Return to the Visual Designer for the page and double-click the Drop Down List. The IDE creates a process value change methodfor the component, opens the Java Editor, and places the editing cursor in the method.

    3

  • 7/30/2019 Demonstrating i18n

    4/15

    4. Edit the localeDropDown_processValueChange()method by adding the following code shown in bold.

    Code Example 2: Drop Down List Value Change Method

    public void localeDropDown_processValueChange(ValueChangeEvent event) {

    // Process new drop-down list value

    processLocaleChange((String)localeDropDown.getSelected());

    }

    Adding theprocessLocaleChange()Method

    Both of the methods you have just edited call the processLocaleChange()method. You now provide the method.

    1. With Page1 displayed in the Java Editor, scroll to the beginning of the Page1 class and add three lines to define the variablesindex, encodings, and locales. The first five lines of the class should look like the code shown in the following codeexample.

    Code Example 3: Initializing index, encodings, and locales Variables

    public class Page1 extends AbstractPageBean {

    Creator-managed Component Definition

    private int index =-1;

    String[] encodings = {"UTF-8", "UTF-8", "Shift_JIS", "GB2312"};

    String[] locales = {"en_US", "ru_RU", "ja_JP", "zh_CN"};

    2. Scroll to the end of the file and insert the code shown in the following code sample just before the final closing brace (}). The

    processLocaleChange()method obtains the language and locale chosen by the user in the drop-down list, determines thefirst two characters and uses them to set the locale for rendering the JavaServer Faces components. Following theprocessLocaleChange()method, a String object is created to store the text entered by the user.

    Code Example 4: Code for processLocaleChange() Method

    private void processLocaleChange(String str) {

    chosenOption.setValue(":::"+str+":::");

    String encString = str;

    // Get items from localeDropDown

    Option[] options = (Option[])localeDropDown.getItems();

    String[] items = new String[options.length];

    for (int i=0; i < options.length; i++) {

    items[i] = (String)options[i].getValue();

    }

    for (index = 0; index < items.length; index++) {

    if (items[index].startsWith(encString))

    break;

    }

    chosenIndex.setValue("# "+index);

    if (index>=0&&index < items.length) {

    String locStr = locales[index];Locale locale;

    if (locStr.length()>3)

    locale = new Locale(locStr.substring(0,2), locStr.substring(3,5));

    else

    locale = new Locale(locStr.substring(0,2));

    // Set the locale for rendering JSF components...

    FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);

    // Save the encoding to use for this locale...

    getSessionBean1().setSessionEncoding(encodings[index]);

    chosenLocale.setValue(" = "+locStr);

    4

  • 7/30/2019 Demonstrating i18n

    5/15

    chosenEncoding.setValue(encodings[index]);

    } else {

    index =-1;

    }

    }

    /**

    * Holds value of property capturedText.*/

    private String capturedText;

    /**

    * Getter for property capturedText.

    * @return Value of property capturedText.

    */

    public String getCapturedText() {

    return this.capturedText;

    }

    /**

    * Setter for property capturedText.

    * @param capturedText New value of property capturedText.

    */public void setCapturedText(String capturedText) {

    this.capturedText = capturedText;

    }

    3. To eliminate errors due to unresolved symbols in the file, right-click in the Java Editor and choose Fix Imports from the pop-up

    menu. If a dialog box opens because more than one package contains a class name, choose the fully qualified name that containscom.sun.rave.web.ui.model.Option, as shown in the following figure, and click OK.

    Figure 5: Choosing Class Names for Import Statement

    One error remains on the line getSessionBean1().setSessionEncoding(encodings[index]);. You will fix this

    error later in the tutorial.

    Adding Properties to the Session Bean

    You now add properties to the Session Bean to store the values of the Drop Down List component.

    1. Open Page1 in the Visual Designer and view the contents of the project in the Outline window. Right-click the SessionBean1 nodeand choose Add > Property from the pop-up menu. The New Property Pattern dialog box opens.

    2. In the New Property Pattern dialog box, type sessionEncoding as the property name and choose String as the type, as

    5

  • 7/30/2019 Demonstrating i18n

    6/15

    shown in the following figure. Click OK.

    Figure 6: New Property Pattern DialogBox

    3. Again, right-click the SessionBean1 node in the Outline window and choose Add > Property from the pop-up menu. In the New

    Property Pattern dialog box, type dropDownOptionsDescriptions as the property name and Option[] as the type, asshown in the following figure.Click OK.

    Figure 7: Adding a New Property to the

    Session Bean

    Adding Initialization Code to the Session Bean

    You will now add initialization code to the Session Bean that defines the choices shown to the user in the Drop Down List component.

    1. In the Outline window, double-click the SessionBean1 node to open theSessionBean1.java file in the Java Editor. Locatethe following comment lines in the init() method:

    6

  • 7/30/2019 Demonstrating i18n

    7/15

    // Perform application initialization that must complete

    // *after* managed components are initialized

    // TODO - add your own initialization code here

    2. Insert initialization code below the comment lines as shown in bold in the following code sample.

    Code Example 5: Session Bean Initialization Code

    // Perform application initialization that must complete

    // *after* managed components are initialized

    // TODO - add your own initialization code here

    // Keep the same locale across requests...

    sessionEncoding = new String("UTF-8");

    // Description settings for initializing localeDropDown on Page1

    dropDownOptionsDescriptions = new com.sun.rave.web.ui.model.Option[] {

    new Option("en_US", "English" ),

    new Option("ru_RU ", "Russian " ),

    new Option("ja_JP ", "Japanese " ),

    new Option("zh_CN ", "Chinese")

    };

    3. To eliminate errors due to unresolved symbols in the file, right-click in the Java Editor and choose Fix Imports from the pop-up

    menu. If a dialog box opens because more than one package contains a class name, select the fully qualified name that containscom.sun.rave.web.ui.model.Option, then click OK.

    Your SessionBean.java file should now show no errors due to unresolved symbols.

    Creating Properties Bundle

    1. In the Projects window, expand the HelloBundledWorld > Source Packages > hellobundledworld node. Right-click the Bundle.properties node and choose Open from the pop-up menu. The Properties Editor opens.

    2. Click New Property to open the New Property dialog box. Enter the following values, then click OK:

    r Key: hellor Value: Hello, whole world!r Comment: Greeting

    3. Again, click New Property to open the New Property dialog box. Enter the following values, then click OK:

    r Key: enterSomeTextr Value: Enter some text:r Comment: Text getter function

    4. One last time, click New Property to open the New Property dialog box. Enter the following values, then click OK:

    r Key: youEnteredr Value: You entered:r Comment: Text user entered

    You should now see the keys and values you entered in the Properties Editor as shown in the following figure. These values will beused as default strings when the application replies to client browser requests.

    7

  • 7/30/2019 Demonstrating i18n

    8/15

    Figure 8: Properties Editor Showing New Keys and Values

    Adding Locales to the Properties Bundle

    You now add locales to the properties bundle and provide key values that can be used for other languages.

    1. In the Projects window, right-click the HelloBundledWorld > Source Packages > hellobundledworld > Bundle.properties node andchoose Add Locale from the pop-up menu. The New Locale dialog box opens.

    2. In the New Locale dialog box, scroll down the Predefined Locales list and select the ru_RU - Russian/Russia locale asshown in the following figure. Click OK.

    Figure 9: New Locale Dialog Box, Showing RussianLocale

    3. Again, right-click Bundle.properties and choose Add Locale. In the New Locale dialog box, select the ja_JP - Japanese /Japan locale, and click OK.

    4. Again, right-click Bundle.properties and choose Add Locale. In the New Locale dialog box, select the zh_CN - Chinese/

    China locale, and click OK.The Properties Editor should now display the additional locales in new columns, as shown in the following figure.

    8

  • 7/30/2019 Demonstrating i18n

    9/15

    Figure 10: Properties Editor Showing Added Locales

    Supplying Language-Specific Values

    You now supply language-specific values for the keys in each locale.

    1. In the Projects window, go to the HelloBundledWorld > Source Packages > hellobundledworld > Bundle.properties node anddouble-click the ja_JP - Japanese (Japan) node. The properties file opens in a text editor.

    2. Edit the file to match the following code sample:

    Code Example 6: ASCII Code for Japanese (Japan) Text

    # Sample ResourceBundle properties file

    #Greeting

    hello=\u4E16\u754C\u3001\u4ECA\u65E5\u306F \!

    #Text getter function

    enterSomeText=\u5165\u529B\u3057\u3066\u4E0B\u3055\u3044\uFF1A\:

    #Text user entered

    youEntered=\u3042\u306A\u305F\u306F\u3053\u308C\u3092\u5165\u308C\u307E\u3057\u305F\:

    The values you enter are character codes for the Japanese characters that will be displayed. Save the file and close the text editor.

    3. Return to the Properties Editor and view the values in the Japanese column. If your system is able to display Japanese, yourProperties Editor should look like the following figure.

    Figure 11: Properties Editor Showing Japanese CharactersNote that you can also enter international characters directly into the Properties Editor instead of entering their codes in the texteditor. You can also copy and paste international characters into the value fields in the Properties Editor.

    4. Enter Russian and Simplified Chinese characters either into the Properties editor or into the individual properties files with the texteditor. The ASCII text in your properties files should look like code samples 7 and 8, and your Properties Editor should look like

    9

  • 7/30/2019 Demonstrating i18n

    10/15

    Figure 12.

    NOTE: Due to space constraints, the enterSomeText line is wrapped across three lines in the sample Russian code below. In yourfile, be sure to include the enterSomeText information on a single line.

    Code Example 7: ASCII Code for Russian (Russia) Text

    #Greeting

    hello=\u0412\u0441\u0435\u043C \u043F\u0440\u0438\u0432\u0435\u0442 \!

    #Text getter function

    enterSomeText=\u0412\u0432\u0435\u0434\u0438\u0442\u0435

    \u043A\u0430\u043A\u043E\u0439-\u043B\u0438\u0431\u043E

    \u0442\u0435\u043A\u0441\u0442\:

    #Text user entered

    youEntered=\u0412\u044B \u0432\u0432\u0435\u043B\u0438\:

    Code Example 8: ASCII Code for Simplified Chinese Text

    #Greeting

    hello=\u4E16\u754C, \u60A8\u597D\! \u4ECA\u65E5\!

    #Text getter functionenterSomeText=\u8F93\u5165\:

    #Text user entered

    youEntered=\u4F60\u9009\u62E9\:

    Figure 12: Properties Editor Showing Internationalized Text

    5. Save and close the Properties Editor.

    Adding a Tag in Page1.jsp

    You will now add a tag in the Page1.jsp file that directs the application to the resource bundle.

    1. View Page1 in the Visual Designer. From the Advanced section of the Components Palette, drag a Load Bundle component onto

    an empty part of the page. The Load Bundle component creates the directive in the Page1.jsp code.2. In Outline window, ensure that Page1 > f:loadBundle:messages1 node is selected and view its properties in the Properties window,

    as shown in the following figure. Note that the value ofvar is messages1. You will use this value to bind Static Text and Labelcomponents in the user interface to strings in the properties bundle.

    10

  • 7/30/2019 Demonstrating i18n

    11/15

    Figure 13: Viewing Properties for f :loadBundle:messages1

    3. In the Outline window, select the page1 > html1 > body1 > form1 > gridLarge > helloText component, right-click, and chooseBind to Data from the pop-up menu. In the resulting dialog box, click Bind to an Object and enter #{Page1.helloText} as theCurrent Text property setting. Click OK.

    4. With the helloText component selected in the Outline window, locate thetext property in the Properties window. Enter thefollowing value for the property: #{messages1.hello}. This value is a binding expression that will bind the displayed text forthe component to the value of the hello key at run time.

    5. In the Outline window, select the enterTextLabel component. In the Properties window, enter the following value for the textproperty: #{messages1.enterSomeText}.

    6. In the Outline window, select the youEnteredLabel component. In the Properties window, enter the following value for the textproperty: #{messages1.youEntered}.

    7. In the Outline window, select the youEnteredDisplay component, right-click, and choose Property Bindings from the pop-up menu.In the Property Bindings dialog box, select the text property and the binding target Page1 > capturedText, as shown in thefollowing figure. Click Apply, then Close.

    Figure 14: Binding the text Property for the youEnteredDisplay Component

    8. In the Outline window, select the textEntry component, right-click, and choose Property Bindings from the pop-up menu. In theProperty Bindings dialog box, again select the text property and the Page1 > capturedText target. Click Apply, then Close.

    9. In the Outline window, select the page1 > html1 > body1 > form1 > gridLarge > gridUpperRight > localeDropDown component,right-click, and choose Property Bindings from the contextual menu. In the Property Bindings dialog box, select the itemsproperty and the SessionBean1 > dropDownOptionsDescriptions target. Click Apply, then Close.

    11

  • 7/30/2019 Demonstrating i18n

    12/15

    Editing the faces-config.xmlFile

    You now edit the faces-config.xml file to configure the supported locales for your application.

    1. Open the Files window, expand the HelloBundledWorld > web > WEB-INF node and right-click the faces-config.xml node.

    Choose Edit from the pop-up menu, and the file opens for editing.2. Edit the tag to match the following code sample. Make sure you have removed the comment lines that are

    present in the default file around the tag.

    Code Example 9: Specifying Default and Supported Locales in faces-config.xml

    en

    ru

    ja

    zh

    Note that the tags above specify only the language codes (for example, ja) and do not include thelocale codes (for example, ja_JP). Not all browsers can accept locale codes, so they have been omitted.

    3. Save the file and close the editor.

    Testing Your Application

    Build and run the application by choosing Run > Run Main Project. If all goes well, your browser will open to show the English versionof the application. By choosing different languages from the drop-down list, you will see the values you entered in the bundled propertiesfiles substituted in the user interface. When you enter text in the text field (the text was copied and pasted in the following figure), it willbe echoed in the Static Text component below the Text Field.

    12

  • 7/30/2019 Demonstrating i18n

    13/15

    Figure 15: Application at Run Time Displaying International Text

    Summary

    In this tutorial, you first set up your system and browser to display English, Russian, Japanese, and Simplified Chinese characters, in UTF-8, Shift_JIS, and GB2312 encodings. You then laid out a page using Basic components. You created a resource bundle, entering valuesthat were strings in the four languages. You then bound the display properties of the components to keys in the resource bundle.

    At run time, the user was able to select one of the languages from a drop-down list. The selection caused the client browser to request theapplication server to compose a page in the chosen language. By referring to the values in the bundled properties files, the servercomposed and served a page in the requested language and encoding.

    Making use of a bundled resource of properties, the sample application responds to user choice of one of four locales and charactersencodings. After the user chooses a locale and encoding, the application server sends text for display in that encoding and accepts textentered by the user in the same encoding.

    Giving users the ability to specify a locale and encoding lets your application accommodate the broadest possible number of users,including those with legacy encodings or other unusual needs.See Also:

    q Understanding Internationalization

    13

    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/internationalizingapps.htmlhttp://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/internationalizingapps.html
  • 7/30/2019 Demonstrating i18n

    14/15

    For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator developer resources onthe Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

    This page was last modified: June 23, 2006

    Sun and Third-party Trademarked Terminology

    The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:

    q Sun Java Studio Creator integrated development environment (IDE)q Sun Java System Application Server version number(Application Server)q Java Platform, Standard Edition technology (Java SE(tm) platform)q JavaServer(tm) Faces technologyq JavaServer Pages(tm) technology (JSP(tm) technology)q Sun Java System Web Server version number(Web Server)q Java Database Connectivity software (JDBC software)q Enterprise JavaBeans(tm) specification (EJB(tm) specification)q Solaris(tm) Operating System software (Solaris OS software)

    The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:

    q UNIX(R) softwareq SPARC(R) processor

    Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

    Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. Inparticular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries.

    U.S. Government Rights - Commercial software.

    Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and itssupplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks orregistered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. ExportControl laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclearmaritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or toentities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists isstrictly prohibited.

    Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not endorse and is notresponsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not beresponsible or liable for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content,goods, or services available on or through any such sites or resources.

    Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tats-Unis. Tous droits rservs.

    Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs la technologie incorpore dans le produit qui est dcrit dans cedocument. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricains lists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tats-Unis et dans lesautres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont desmarques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays.Ce produit est soumis lalgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueur dans d'autres pays dans ledomaine des exportations et importations. Les utilisations, ou utilisateurs finaux, pour des armes nuclaires,des missiles, des armesbiologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ourexportations vers les pays sous embargo amricain, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, ycompris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte,aux exportations des produits ou des services qui sont rgis par la lgislation amricaine en matire de contrle des exportations et la liste deressortissants spcifiquement dsigns, sont rigoureusement interdites.

    More Developer Resources:

    14

    http://developers.sun.com/jscreatorhttp://developers.sun.com/jscreator
  • 7/30/2019 Demonstrating i18n

    15/15

    Sun Microsystems n'est pas responsable de la disponibilit de tiers emplacements d'enchanement mentionns dans ce document et n'approuvepas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicit, de produits, ou d'autres matriaux dessus ou fournis par de telsemplacements ou ressources. Sun ne sera pas responsable ou iresponsable d'aucuns dommages ou perte causs ou allgus pour tre caus parou en liaison avec l'utilisation de ce produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des telsemplacements ou ressources.

    15