Oracle® Application Server Globalization Support Guide
10g Release 2 (10.1.2) B14004-02 |
|
Previous |
Next |
This chapter includes the following sections:
The Oracle Globalization Development Kit (GDK) simplifies the development process and reduces the cost of developing Internet applications used to support a global environment.
The GDK includes comprehensive programming APIs for both Java and PL/SQL, code samples, and documentation that address many of the design, development, and deployment issues encountered while creating global applications.
The GDK mainly consists of two parts: GDK for Java and GDK for PL/SQL. GDK for Java provides globalization support to Java applications. GDK for PL/SQL provides globalization support to the PL/SQL programming environment. The features offered in GDK for Java and GDK for PL/SQL are not identical.
The GDK for Java provides a J2EE application framework and Java APIs to develop global Internet applications using the best globalization practices and features designed by Oracle. It reduces the complexities and simplifies the code required to develop global Java applications.
GDK for Java complements the existing globalization features in J2EE. Although the J2EE platform already provides a strong foundation for building global applications, its globalization functionalities and behaviors can be quite different from Oracle functionalities. GDK for Java provides synchronization of locale-sensitive behaviors between the middle-tier Java application and the database server.
GDK for PL/SQL contains a suite of PL/SQL packages that provide additional globalization functionalities for applications written in PL/SQL.
Figure 3-1 shows the major components of the GDK and how they relate to each other. User applications run on the J2EE container of Oracle Application Server in the middle tier. GDK provides the application framework that the J2EE application uses to simplify coding to support globalization. Both the framework and the application call the GDK Java API to perform locale-sensitive tasks. GDK for PL/SQL offers PL/SQL packages that help to resolve globalization issues specific to the PL/SQL environment.
The functionalities offered by GDK for Java can be divided into two categories:
The GDK application framework for J2EE provides the globalization framework for building J2EE-based Internet application. The framework encapsulates the complexity of globalization programming, such as determining user locale, maintaining locale persistency, and processing locale information. It consists of a set of Java classes through which applications can gain access to the framework. These associated Java classes enable applications to code against the framework so that globalization behaviors can be extended declaratively.
The GDK Java API offers development support in Java applications and provides consistent globalization operations as provided in Oracle database servers. The API is accessible and is independent of the GDK framework so that standalone Java applications and J2EE applications not based on the GDK framework are able to access the individual features offered by the Java API. The features provided in the Java API include data and number formatting, sorting and character set handling in the same way as the Oracle database.
Note: The GDK Java API is certified with JDK versions 1.3 and later with the following exception: The character set conversion classes depend on thejava.nio.charset package, which is available in JDK 1.4 and later.
|
GDK for Java is contained in two files: orai18n.jar
and orai18n-lcsd.jar
. The files are shipped with Oracle Application Server. GDK is a pure Java library that runs on every platform. The Oracle client parameters NLS_LANG
and ORACLE_HOME
are not required.
This section explains how to modify a monolingual application to be a global, multilingual application using GDK. The subsequent sections in this chapter provide detailed information on using GDK.
Figure 3-2 shows a monolingual Web application page.
The initial, non-GDK HelloWorld Web application simply prints a "Hello World!" message, along with the current date and time in the top right hand corner of the page. The following code shows the original HelloWorld JSP source code for the preceding image.
Example 3-1 HelloWorld JSP Page Code
<%@ page contentType="text/html;charset=windows-1252"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Hello World Demo</title> </head> <body> <div style="color: blue;" align="right"> <%= new java.util.Date(System.currentTimeMillis()) %> </div> <hr/> <h1>Hello World!</h1> </body> </html>
The following code example shows the corresponding Web application descriptor file for the HelloWorld message.
Example 3-2 HelloWorld web.xml Code
<?xml version = '1.0' encoding = 'windows-1252'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>web.xml file for the monolingual Hello World</description> <session-config> <session-timeout>35</session-timeout> </session-config> <mime-mapping> <extension>html</extension> <mime-type>text/html</mime-type> </mime-mapping> <mime-mapping> <extension>txt</extension> <mime-type>text/plain</mime-type> </mime-mapping> </web-app>
The HelloWorld JSP code in Example 3-1 is only for English-speaking users. Some of the problems with this code are as follows:
There is no locale determination based on user preference or browser setting.
The title and the heading are included in the code.
The date and time value is not localized based on any locale preference.
The character encoding is for Latin-1.
The GDK framework can be integrated into the HelloWorld code to make it a global, multilingual application. The preceding code can be modified to include the following features:
Automatic locale negotiation to detect the user's browser locale and serve the client with localized HTML pages. The supported application locales are configured in the GDK configuration file.
Locale selection list to map the supported application locales. The list can have application locale display names which are the name of the country representing the locale. The list will be included on the Web page so users can select a different locale.
GDK framework and API for globalization support for the HelloWorld JSP. This involves selecting display strings in a locale-sensitive manner and formatting the date and time value.
This section explains how to modify the HelloWorld application to support globalization. The application will be modified to support three locales, Simplified Chinese (zh-CN), Swiss German (de-CH), and American English (en-US). The following rules will be used for the languages:
If the client locale supports one of these languages, then that language will be used for the application.
If the client locale does not support one of these languages, then American English will be used for the application.
In addition, the user will be able to change the language by selecting a supported locales from the locale selection list. The following tasks describe how to modify the application:
Task 1: Enable the Hello World Application to use the GDK Framework
In this task, the GDK filter and a listener are configured in the Web application deployment descriptor file, web.xml
. This allows the GDK framework to be used with the HelloWorld application. Example 3-3 shows the GDK-enabled web.xml
file.
Example 3-3 The GDK-enabled web.xml File
<?xml version = '1.0' encoding = 'windows-1252'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>web.xml file for Hello World</description> <!-- Enable the application to use the GDK Application Framework.--> <filter> <filter-name>GDKFilter</filter-name> <filter-class>oracle.i18n.servlet.filter.ServletFilter</filter-class> </filter> <filter-mapping> <filter-name>GDKFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <listener> <listener-class>oracle.i18n.servlet.listener.ContextListener</listener-class> </listener> <session-config> <session-timeout>35</session-timeout> </session-config> <mime-mapping> <extension>html</extension> <mime-type>text/html</mime-type> </mime-mapping> <mime-mapping> <extension>txt</extension> <mime-type>text/plain</mime-type> </mime-mapping> </web-app>
The following tags were added to the file:
<filter>
The filter name is GDKFilter, and the filter class is oracle.i18n.servlet.filter.ServletFilter
.
<filter-mapping>
The GDKFilter is specified in the tag, as well as the URL pattern.
<listener>
The listener class is oracle.i18n.servlet.listener.ContextListener
. The default GDK listener is configured to instantiate GDK ApplicationContext, which controls application scope operations for the framework.
Task 2: Configure the GDK Framework for Hello World
The GDK application framework is configured with the application configuration file gdkapp.xml
. The configuration file is located in the same directory as the web.xml
file. Example 3-4 shows the gdkapp.xml
file.
Example 3-4 GDK Configuration File gdkapp.xml
<?xml version="1.0" encoding="UTF-8"?> <gdkapp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="gdkapp.xsd"> <!-- The Hello World GDK Configuration --> <page-charset default="yes">UTF-8</page-charset> <!-- The supported application locales for the Hello World Application --> <application-locales> <locale>de-CH</locale> <locale default="yes">en-US</locale> <locale>zh-CN</locale> </application-locales> <locale-determine-rule> <locale-source>oracle.i18n.servlet.localesource.UserInput</locale-source> <locale-source>oracle.i18n.servlet.localesource.HttpAcceptLanguage</locale-source> </locale-determine-rule> <message-bundles> <resource-bundle name="default">com.oracle.demo.Messages</resource-bundle> </message-bundles> </gdkapp>
The file must be configured for J2EE applications. The following tags are used in the file:
<page-charset>
The page encoding tag specifies the character set used for HTTP requests and responses. The UTF-8 encoding is used as the default because many languages can be represented by this encoding.
<application-locales>
Configuring the application locales in the gdkapp.xml
file makes a central place to define locales. This makes it easier to add and remove locales without changing source code. The locale list can be retrieved using the GDK API call ApplicationContext.getSupportedLocales
.
<locale-determine-rule>
The language of the initial page is determined by the language setting of the browser. The user can override this language by choosing from the list. The locale-determine-rule
is used by GDK to first try the Accept-Language HTTP header as the source of the locale. If the user selects a locale from the list, then the JSP posts a locale parameter value containing the selected locale. The GDK then sends a response with the contents in the selected language.
<message-bundles>
The message resource bundles allow an application access to localized static content that may be displayed on a Web page. The GDK framework configuration file allows an application to define a default resource bundle for translated text for various languages. In the HelloWorld example, the localized string messages are stored in the Java ListResourceBundle bundle named Messages
. The Messages
bundle consists of base resources for the application which are in the default locale. Two more resource bundles provide the Chinese and German translations. These resource bundles are named Messages_zh_CN.java
and Messages_de.java
respectively. The HelloWorld application will select the right translation for "Hello World!" from the resource bundle based on the locale determined by the GDK framework. The <message-bundles>
tag is used to configure the resource bundles that the application will use.
Task 3: Enable the JSP or Java Servlet
JSPs and Java servlets must be enabled to use the GDK API. Example 3-5 shows a JSP that has been modified to use the GDK API and services. This JSP can accommodate any language and locale.
Example 3-5 Enabled HelloWorld JSP
. . . <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><%= localizer.getMessage("helloWorldTitle") %></title> </head> <body> <div style="color: blue;" align="right"> <% Date currDate= new Date(System.currentTimeMillis()); %> <%=localizer.formatDateTime(currDate, OraDateFormat.LONG)%> </div> <hr/> <div align="left"> <form> <select name="locale" size="1"> <%= getCountryDropDown(request)%> </select> <input type="submit" value="<%= localizer.getMessage("changeLocale") %>"> </input> </form> </div> <h1><%= localizer.getMessage("helloWorld") %></h1> </body> </html>
Figure 3-3 shows the HelloWorld application that has been configured with the zh-CN locale as the primary locale for the browser preference. The HelloWorld string and page title are displayed in Simplified Chinese. In addition, the date is formatted in the zh-CN locale convention. This example allows the user to override the locale from the locale selection list.
Figure 3-3 HelloWorld Localized for the zh-CN Locale
When the locale changes or is initialized using the HTTP Request Accept-Language header or the locale selection list, the GUI behaves appropriately for that locale. This means the date and time value in the upper right corner is localized properly. In addition, the strings are localized and displayed on the HelloWorld page.
The GDK Java Localizer class provides capabilities to localize the contents of a Web page based on the automatic detection of the locale by the GDK framework.
The following code retrieves an instance of the localizer based on the current HTTPServletRequest object. In addition, several imports are declared for use of the GDK API within the JSP page. The localizer retrieves localized strings in a locale-sensitive manner with fallback behavior, and formats the date and time.
<%@page contentType="text/html;charset=UTF-8"%> <%@page import="java.util.*, oracle.i18n.servlet.*" %> <%@page import="oracle.i18n.util.*, oracle.i18n.text.*" %> <% Localizer localizer = ServletHelper.getLocalizerInstance(request); %>
The following code retrieves the current date and time value stored in the currDate variable. The value is formatted by the localizer formatDateTime method. The OraDateFormat.LONG parameter in the formatDateTime method instructs the localizer to format the date using the locale's long formatting style. If the locale of the incoming request is changed to a different locale with the locale selection list, then the date and time value will be formatted according to the conventions of the new locale. No code changes need to be made to support newly-introduced locales.
div style="color: blue;" align="right"> <% Date currDate= new Date(System.currentTimeMillis()); %> <%=localizer.formatDateTime(currDate, OraDateFormat.LONG)%> </div>
The HelloWorld JSP can be reused for any locale because the HelloWorld string and title are selected in a locale-sensitive manner. The translated strings are selected from a resource bundle.
The GDK uses the OraResourceBundle class for implementing the resource bundle fallback behavior. The following code shows how the Localizer picks the HelloWorld message from the resource bundle.
The default application resource bundle Messages is declared in the gdkapp.xml
file. The localizer uses the message resource bundle to pick the message and apply the locale-specific logic. For example, if the current locale for the incoming request is Òde-CHÓ, then the message will first be looked for in the messages_de_CH bundle. If it does not exist, then it will look up in the Messages_de resource bundle.
<h1><%= localizer.getMessage("helloWorld") %></h1>
Task 4: Create the Locale Selection List
The locale selection list is used to override the selected locale based on the HTTP Request Accept-Language header. The GDK framework checks the locale parameter passed in as part of the HTTP POST request as a value for the new locale. A locale selected with the locale selection list is posted as the locale parameter value. GDK uses this value for the request locale. All this happens implicitly within the GDK code.
The following code sample displays the locale selection list as an HTML select tag with the name locale. The submit tag causes the new value to be posted to the server. The GDK framework retrieves the correct selection.
<form> <select name="locale" size="1"> <%= getCountryDropDown(request)%> </select> <input type="submit" value="<%= localizer.getMessage("changeLocale") %>"> </input> </form>
The locale selection list is constructed from the HTML code generated by the getCountryDropDown
method. The method converts the configured application locales into localized country names.
A call is made to the ServletHelper class to get the ApplicationContext object associated with the current request. This object provides the globalization context for an application, which includes information such as supported locales and configuration information. The getSupportedLocales
call retrieves the list of locales in the gdkapp.xml
file. The configured application locale list is displayed as options of the HTML select. The OraDisplayLocaleInfo
class is responsible for providing localization methods of locale-specific elements such as country and language names.
An instance of this class is created by passing in the current locale automatically determined by the GDK framework. GDK creates requests and response wrappers for HTTP request and responses. The request.getLocale() method returns the GDK determined locale based on the locale determination rules.
The OraDsiplayLocaleInfo.getDisplayCountry
method retrieves the localized country names of the application locales. An HTML option list is created in the ddOptBuffer string buffer. The getCountryDropDown
call returns a string containing the following HTML values:
<option value="en_US" selected>United States [en_US]</option> <option value="zh_CN">China [zh_CN]</option> <option value="de_CH">Switzerland [de_CH]</option>
In the preceding values, the en-US locale is selected for the locale. Country names are generated are based on the current locale.
Example 3-6 shows the code for constructing the locale selection list.
Example 3-6 Constructing the Locale Selection List
<%! public String getCountryDropDown(HttpServletRequest request) { StringBuffer ddOptBuffer=new StringBuffer(); ApplicationContext ctx = ServletHelper.getApplicationContextInstance(request); Locale[] appLocales = ctx.getSupportedLocales(); Locale currentLocale = request.getLocale(); if (currentLocale.getCountry().equals("")) { // Since the Country was not specified get the Default Locale // (with Country) from the GDK OraLocaleInfo oli = OraLocaleInfo.getInstance(currentLocale); currentLocale = oli.getLocale(); } OraDisplayLocaleInfo odli = OraDisplayLocaleInfo.getInstance(currentLocale); for (int i=0;i<appLocales.length; i++) { ddOptBuffer.append("<option value=\"" + appLocales[i] + "\"" + (appLocales[i].getLanguage().equals(currentLocale.getLanguage()) ? " selected" : "") + ">" + odli.getDisplayCountry(appLocales[i]) + " [" + appLocales[i] + "]</option>\n"); } return ddOptBuffer.toString(); } %>
Task 5: Build the Application
In order to build the application, the following files must be specified in the classpath:
orai18n.jar
regexp.jar
The orai18n.jar
file contains the GDK framework and the API. The regexp.jar
file contains the regular expression library. The GDK API also has locale determination capabilities. The classes are supplied by the ora18n-lcsd.jar
file.
The GDK application configuration file dictates the behavior and properties of the GDK application framework and the application that is using it. It contains locale mapping tables and parameters for the configuration of the application. One configuration file is required for each application.
The gdkapp.xml
application configuration file is an XML document. This file resides in the ./WEB-INF
directory of the J2EE environment of the application.
The following sections describe the contents and the properties of the application configuration file in detail:
This tag enables applications to override the mapping from language to default character set provided by the GDK. This mapping is used when the page-charset
is set to AUTO-CHARSET
.
For example, for the en
locale, the default GDK character set is WINDOWS-1252. However, if the application requires ISO-8859-1, this can be specified as follows:
<locale-charset-maps> <locale-charset> <locale>en</locale> <charset>ISO_8859-1</charset> </locale-charset> </locale-charset-maps>
The locale name is comprised of the language code and the country code, and they should follow the ISO naming convention as defined in ISO 639 and ISO 3166, respectively. The character set name follows the Internet Assigned Numbers Authority (IANA) convention.
Optionally, the user-agent parameter can be specified in the mapping table to distinguish different clients.
<locale-charset> <locale>en,de</locale> <user-agent>^Mozilla/4.0</user-agent> <charset>ISO-8859-1</charset> </locale-charset>
The preceding code shows that if the user-agent
value in the HTTP header starts with Mozilla/4.0
(which indicates older version of Web clients) for English (en
) and German (de
) locales, then the GDK sets the character set to ISO-8859-1.
Multiple locales can be specified in a comma-delimited list.
This tag defines the character set of the application pages. If this is explicitly set to a given character set, then all pages use this character set. The character set name must follow the IANA character set convention.
<page-charset>UTF-8</page-charset>
However, if the page-charset
is set to AUTO-CHARSET
, then the character set is based on the default character set of the current user locale. The default character set is derived from the locale to character set mapping table specified in the application configuration file.
If the character set mapping table in the application configuration file is not available, then the character set is based on the default locale name to IANA character set mapping table in the GDK. Default mappings are derived from OraLocaleInfo
class.
This tag defines a list of the locales supported by the application.
<application-locales> <locale default="yes">en-US</locale> <locale>de</locale> <locale>zh-CN</locale> </application-locales>
If the language component is specified with the *
country code, then all locale names with this language code qualify. For example, if de-*
(the language code for German) is defined as one of the application locales, then this supports de-AT
(German
- Austria), de
(German-Germany), de-LU
(German-Luxembourg), de-CH
(German-Switzerland), and even irregular locale combination such as de-CN
(German-China). However, the application can be restricted to support a predefined set of locales.
It is recommended to set one of the application locales as the default application locale (by specifying default="yes"
) so that it can be used as a fall back locale for customers who are connecting to the application with an unsupported locale.
This tag defines the order in which the preferred user locale is determined. The locale sources should be specified based on the scenario in the application. The following scenarios describe how the locale-determine-rule is used with the GDK framework:
Scenario 1: The GDK framework uses the accept language at all times.
<locale-determine-rule> <locale-source>oracle.i18n.servlet.localesource.HTTPAcceptLanguage </locale-source> </locale-determine-rule>
Scenario 2: The GDK framework uses the accept language. After the user specifies the locale, the locale is used for further operations.
<locale-determine-rule> <locale-source>oracle.i18n.servlet.localesource.UserInput</locale-source> <locale-source>oracle.i18n.servlet.localesource.HTTPAcceptLanguage </locale-source> </locale-determine-rule>
Scenario 3: The GDK framework uses the accept language. After the user is authenticated, the GDK framework uses the database locale source. The database locale source is cached until the user logs out. After the user logs out, the accept language is used again.
<locale-determine-rule> <db-locale-source data-source-name="jdbc/OracleCoreDS" locale-source-table="customer" user-column="customer_email" user-key="userid" language-column="nls_language" territory-column="nls_territory" timezone-column="timezone"> oracle.i18n.servlet.localesource.DBLocaleSource</db-locale-source> <locale-source>oracle.i18n.servlet.localesource.HttpAcceptLanguage </locale-source> </locale-determine-rule>
Scenario 3 includes the predefined database locale source, DBLocaleSource
. It enables the user profile information to be specified in the configuration file without writing a custom database locale source. In the example, customer
is the user profile table. The table has the following columns:
customer_email
for the unique e-mail address
nls_language
for the preferred language
nls_territory
for the Oracle name of the preferred territory
timezone
for the customer timezone
The user-key
is a mandatory attribute that specifies the attribute name used to pass the user ID from the application to the GDK framework.
Scenario 4: The GDK framework uses the accept language in the first page. When the user inputs a locale, it is cached and used until the user logs into the application. After the user is authenticated, the GDK framework uses the database locale source. The database locale source is cached until the user logs out. After the user logs out, the accept language is used or the user input is used, if the user inputs a locale.
<locale-determine-rule> <locale-source>demo.DatabaseLocaleSource</locale-source> <locale-source>oracle.i18n.servlet.localesource.UserInput</locale-source> <locale-source>oracle.i18n.servlet.localesource.HttpAcceptLanguage </locale-source> </locale-determine-rule>
Scenario 4 uses the custom database locale source. If the user profile schema is complex, such as user profile information separated into multiple tables, then the custom locale source should be provided by the application. Examples of custom locale sources can be found in the $ORACLE_HOME/nls/gdk/demo
directory.
This tag defines the name of the locale parameters that are used in the user input so that the current user locale can be passed between requests.
<locale-parameter-name> <timezone>ti</timezone> <linguistic-sort>ls</linguistic-sort> <date-format>df</date-format> </locale-parameter-name>
Table 3-1 shows the parameters used in the GDK framework.
Table 3-1 Locale Parameters Used in the GDK Framework
Default Parameter Name | Value |
---|---|
|
Character set. For example, |
|
GDK command. For example, |
|
Currency format. For example, |
|
Date format pattern mask. For example, |
|
Date and time format pattern mask. For example, |
|
ISO 4217 currency code. For example, |
|
Oracle language name. For example, |
|
Linguistic sort order name. For example, |
|
ISO locale where ISO 639 language code and ISO 3166 country code are connected with an underscore ( |
|
Long date format pattern mask. For example, |
|
Long date and time format pattern mask. For example, |
|
Number format. For example, |
|
Oracle territory name. For example, |
|
Time format pattern mask. For example, |
|
Timezone name. For example, |
|
Writing direction string. |
The parameter names are used in either the parameter in the HTML form or in the URL.
This tag defines the base class names of the resource bundles used in the application. The mapping is used in the Localizer.getMessage
method for locating translated text in the resource bundles.
<message-bundles> <resource-bundle>Messages</resource-bundle> <resource-bundle name="newresource">NewMessages</resource-bundle> </message-bundles>
If the name attribute is not specified or if it is specified as name="default"
for the <resource-bundle>
tag, then the corresponding resource bundle is used as the default message bundle. To support more than one resource bundle in an application, resource bundle names must be assigned to the nondefault resource bundles. The nondefault bundle names must be passed as a parameter of the getMessage
method.
For example:
Localizer loc = ServletHelper.getLocalizerInstance(request); String translatedMessage = loc.getMessage("Hello"); String translatedMessage2 = loc.getMessage("World", "newresource");
This tag is used to control the behavior of the URL rewrite operations. The rewriting rule is a regular expression.
<url-rewrite-rule fallback="no"> <pattern>(.*)/([^/]+)$</pattern> <result>$1/$L/$2</result> </url-rewrite-rule>
If the localized content for the requested locale is not available, then it is possible for the GDK framework to trigger the locale fallback mechanism by mapping it to the closest translation locale. By default, the fallback option is turned off. This can be turned on by specifying fallback="yes"
in the expression.
For example, suppose an application has fallback="yes"
and supports only the following translations en
, de
, and ja
, with en
as the default locale of the application. If the current application locale is de-US
, then it falls back to de
. If the user selects zh-TW
as its application locale, then it falls back to en
.
A fallback mechanism is often necessary if the number of supported application locales is greater than the number of the translation locales. This usually happens when multiple locales share one translation. One example is Spanish. The application may need to support multiple Spanish-speaking countries and not just Spain, with one set of translation files.
Multiple URL rewrite rules can be specified by assigning the name attribute to nondefault URL rewrite rules. To use the nondefault URL rewrite rules, the name must be passed as a parameter of the rewrite URL method. For example:
<img src="<%=ServletHelper.rewriteURL("images/welcome.gif", request) %>"> <img src="<%=ServletHelper.rewriteURL("US.gif", "flag", request) %>">
The first rule changes the "images/welcome.gif"
URL to the localized welcome image file. The second rule named "flag"
changes the "US.gif"
URL to the user's country flag image file. The rule definition should be as follows:
<url-rewrite-rule fallback="yes"> <pattern>(.*)/([^/]+)$</pattern> <result>$1/$L/$2</result> </url-rewrite-rule> <url-rewrite-rule name="flag"> <pattern>US.gif</pattern> <result>$C.gif</result> </url-rewrite-rule>
Example 3-7 shows an application configuration file with the following application properties:
The application supports the following locales:
Arabic (ar
)
Greek (el
)
English (en
)
German (de
)
French (fr
)
Japanese (ja
)
Simplified Chinese for China (zh-CN
)
English is the default application locale.
The page character set for the ja
locale is always UTF-8.
The page character set for the en
and de
locales when using an Internet Explorer client is WINDOWS-1252.
The page character set for the en
, de
, and fr
locales on other Web browser clients is ISO-8859-1.
The page character sets for all other locales are the default character set for the locale.
The user locale is determined in order by user input locale, then the Accept-Language
tag.
The localized contents are stored in their appropriate language subfolders. The folder names are derived from the ISO 639 language code. The folders are located in the root directory of the application. For example, the Japanese file for /shop/welcome.jpg
is stored in /ja/shop/welcome.jpg
.
Example 3-7 GDK Application Configuration File
<?xml version="1.0" encoding="utf-8"?> <gdkapp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="gdkapp.xsd"> <!-- Language to Character set mapping --> <locale-charset-maps> <locale-charset> <locale>ja</locale> <charset>UTF-8</charset> </locale-charset> <locale-charset> <locale>en,de</locale> <user-agent>^Mozilla\/[0-9\. ]+\(compatible; MSIE [^;]+; \)</user-agent> <charset>WINDOWS-1252</charset> </locale-charset> <locale-charset> <locale>en,de,fr</locale> <charset>ISO-8859-1</charset> </locale-charset> </locale-charset-maps> <!-- Application Configurations --> <page-charset>AUTO-CHARSET</page-charset> <application-locales> <locale>ar</locale> <locale>de</locale> <locale>fr</locale> <locale>ja</locale> <locale>el</locale> <locale>zh-CN</locale> <locale default="yes">en</locale> </application-locales> <locale-determine-rule> <locale-source>oracle.i18n.servlet.localesource.UserInput</locale-source> <locale-source>oracle.i18n.servlet.localesource.HttpAcceptLanguage</locale-source> </locale-determine-rule> <!-- URL rewriting rule --> <url-rewrite-rule fallback="no"> <pattern>(.*)/([^/]+)$</pattern> <result>/$L/$1/$2</result> </url-rewrite-rule> </gdkapp>
GDK for Java provides the globalization framework for middle-tier J2EE applications. The framework encapsulates the complexity of globalization programming, such as determining user locale, maintaining locale persistency, and processing locale information. This framework minimizes the effort required to make Internet applications global-ready. The GDK application framework is shown in Figure 3-4.
Figure 3-4 GDK Application Framework for J2EE
The main Java classes composing the framework are as follows:
ApplicationContext
provides the globalization context of an application. The context information includes the list of supported locales and the rule for determining user-preferred locale. The context information is obtained from the GDK application configuration file for the application.
The set of LocaleSource
classes can be plugged into the framework. Each LocaleSource
class implements the LocaleSource
interface to get the locale from the corresponding source. Oracle bundles several LocaleSource
classes in GDK. For example, the DBLocaleSource
class obtains the locale information of the current user from a database schema. You can also write a customized LocaleSource
class by implementing the same LocaleSource
interface and plugging it into the framework.
ServletRequestWrapper
and ServletResponseWrapper
are the main classes of the GDK Servlet filter that transforms HTTP requests and HTTP responses. ServletRequestWrapper
instantiates a Localizer
object for each HTTP request based on the information gathered from the ApplicationContext
and LocaleSource
objects and ensures that forms parameters are handled properly. ServletResponseWrapper
controls how HTTP response should be constructed.
Localizer
is the object that exposes the important functions sensitive to the current user locale and application context. It provides a centralized set of methods for you to call and make your applications behave appropriately to the current user locale and application context.
The GDK Java API is always available for applications to enable finer control of globalization behavior.
The GDK application framework simplifies the coding required for your applications to support different locales. When you write a J2EE application according to the application framework, the application code is independent of what locales the application supports, and you control the globalization support in the application by defining it in the GDK application configuration file. There is no code change required when you add or remove a locale from the list of supported application locales.
The following list are some of the ways you can define globalization support in the GDK application configuration file:
Add and remove a locale from the list of supported locales.
Change the way the user locale is determined.
Change the HTML page encoding of your application.
Specify how to locate the translated resources.
Implement a new LocaleSource
object into the framework and use it to detect a user locale.
The behavior of the GDK application framework for J2EE is controlled by the GDK application configuration file, gdkapp.xml
. The application configuration file allows developers to specify the behaviors of global applications in one centralized place. One application configuration file is required for each J2EE application using the GDK.
The gdkapp.xml
file should be placed in the ./WEB-INF
directory of the J2EE environment of the application. It contains locale mapping tables, character sets of content files, and globalization parameters for the configuration of the application. The application administrator can modify the application configuration file to change the globalization behavior in the application, without changing the programs and recompiling them.
For a J2EE application to use the GDK application framework defined by the corresponding GDK application configuration file, the GDK Servlet filter and the GDK context listener must be defined in the web.xml
file of the application. The web.xml
file should be modified to include the following at the beginning of the file:
<web-app> <!-- Add GDK filter that is called after the authentication --> <filter> <filter-name>gdkfilter</filter-name> <filter-class>oracle.i18n.servlet.filter.ServletFilter</filter-class> </filter> <filter-mapping> <filter-name>gdkfilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <!-- Include the GDK context listener --> <listener> <listener-class>oracle.i18n.servlet.listener.ContextListener</listener-class> </listener> </web-app>
Examples of the gdkapp.xml
and web.xml
files can be found in the $ORACLE_HOME/nls/gdk/demo
directory.
The GDK application framework supports servlet container version 2.3 and later. It uses the servlet filter facility for transparent globalization operations such as determining the user locale and specifying the character set for content files. The ContextListener
instantiates GDK application parameters described in the GDK application configuration file. The ServletFilter
overrides the request and response objects with a GDK request (ServletRequestWrapper
) and response (ServletResponseWrapper
) objects, respectively.
If other application filters are used in the application to override the same methods, then the filter in the GDK framework may return incorrect results. For example, if getLocale
returns en_US
, but the result is overridden by other filters, then the result of the GDK locale detection mechanism is affected. Be aware of potential conflicts when using other filters together with the GDK framework.
See Also:
|
Determining the user's preferred locale is the first step in making an application global-ready. The locale detection offered by the J2EE application framework is primitive. It lacks a method that transparently retrieves the most appropriate user locale among locale sources. It provides locale detection by the HTTP language preference only, and it cannot support a multilevel locale fallback mechanism. The GDK application framework provides support for predefined locale sources to complement J2EE. In a Web application, several locale sources are available. Table 3-2 summarizes locale sources provided by the GDK.
Table 3-2 Locale Resources Provided by the GDK
Locale | Description |
---|---|
Application default locale |
A locale defined in the GDK application configuration file. This locale is defined as the default locale for the application. Typically, this is used as a fallback locale when the other locale sources are not available. |
HTTP language preference |
Locales included in the HTTP protocol as a value of |
User input locale |
Locale specified by the user from a menu or a parameter in the HTTP protocol. |
User profile locale preference from database |
Locale preference stored in the database as part of the user profiles. |
The GDK application framework provides seamless support for predefined locale sources, such as user input locale, HTTP language preference, user profile locale preference in the database, and the application default locale. You can incorporate the locale sources to the framework by defining them under the <locale-determine-rule>
tag in the GDK application configuration file as follows:
<locale-determine-rule> <locale-source>oracle.i18n.servlet.localesource.UserInput</locale-source> <locale-source>oracle.i18n.servlet.localesource.HTTPAcceptLanguage</locale-source> </locale-determine-rule>
The GDK framework uses the locale source declaration order and determines whether a particular locale source is available. If it is available, then it is used as the source. If it is not available, then it tries to find the next available locale source for the list. In the preceding example, if the UserInput
locale source is available, then it is used. If it is not, then the HTTPAcceptLanguage
locale source will be used.
Custom locale sources, such as locale preference from an LDAP server, can be implemented and integrated into the GDK framework. You need to implement the LocaleSource
interface and specify the corresponding implementation class under the locale-determine-rule
tag in the same way as the predefined locale sources.
The LocaleSource
implementation not only retrieves the locale information from the corresponding source to the framework but also updates the locale information to the corresponding source when the framework tells it to do so. Locale sources can be read-only or read/write, and they can be cacheable or noncacheable. The GDK framework initiates updates only to read/write locale sources and caches the locale information from cacheable locale sources. Examples of custom locale sources can be found in the $ORACLE_HOME/nls/gdk/demo
directory.
See Also:
|
The GDK offers automatic locale detection to determine the current locale of the user. For example, the following code retrieves the current user locale in Java. It uses a Locale
object explicitly.
Locale loc = request.getLocale();
The getLocale()
method returns the Locale
that represents the current locale. This is similar to invoking the HttpServletRequest.getLocale()
method in JSP or Java Servlet code. However, the logic in determining the user locale is different, because multiple locale sources are being considered in the GDK framework.
Alternatively, you can get a Localizer
object that encapsulates the Locale
object determined by the GDK framework.
Localizer localizer = ServletHelper.getLocalizerInstance(request); Locale loc = localizer.getLocale();
See Also: "Implementing Locale Awareness Using the GDK Localizer" for information about the benefits of theLocalizer object
|
The locale detection logic of the GDK framework depends on the locale sources defined in the GDK application configuration file. The names of the locale sources are registered in the application configuration file. The following example shows the locale determination rule section of the application configuration file. It indicates that the user-preferred locale can be determined from either the LDAP server or from the HTTP Accept-Language
header. The LDAPUserSchema
locale source class should be provided by the application. Note that all of the locale source classes have to be extended from the LocaleSource
abstract class.
<locale-determine-rule> <locale-source>LDAPUserSchema</locale-source> <locale-source>oracle.i18n.localesource.HTTPAcceptLanguage</locale-source> </locale-determine-rule>
For example, when the user is authenticated in the application and the user locale preference is stored in an LDAP server, then the LDAPUserSchema
class connects to the LDAP server to retrieve the user locale preference. When the user is anonymous, the HttpAcceptLanguage
class returns the language preference of the Web browser.
The cache is maintained for the duration of a HTTP session. If the locale source is obtained from the HTTP language preference, then the locale information is passed to the application in the HTTP Accept-Language
header and not cached. This enables flexibility so that the locale preference can change between requests. The cache is available in the HTTP session.
The GDK framework has a method for the application to overwrite the locale preference information persistently stored in locale sources such as the LDAP server or the user profile table in the database. This method also resets the current locale information stored inside the cache for the current HTTP session. The following is an example of overwriting the preferred locale using the store
command.
<input type="hidden" name="<%=appctx.getParameterName(LocaleSource.Parameter.COMMAND)%>" value="store">
To discard the current locale information stored inside the cache, the clean
command can be specified as the input parameter. The following table shows the commands supported by the GDK:
Command | Functionality |
---|---|
clean
|
Discards the current locale information in the cache. |
store
|
Updates user locale preferences in the available locale sources with the specified locale information. This command is ignored by the read-only locale sources. |
Note that the GDK parameter names can be customized in the application configuration file to avoid name conflicts with other parameters used in the application.
The Localizer
object obtained from the GDK application framework provides access to functions that are commonly used in building locale awareness in your applications. In addition, it provides functions to get information about the application context, such as the list of supported locales. The Localizer
object simplifies and centralizes the code required to build consistent locale awareness behavior in your applications.
The oracle.i18n.servlet
package contains the Localizer
class. You can get the Localizer instance as follows:
Localizer lc = ServletHelper.getLocalizerInstance(request);
The Localizer
object encapsulates the most commonly used locale-sensitive information determined by the GDK framework and exposes it as locale-sensitive methods. This object includes the following functionalities pertaining to the user locale:
Format date in long and short formats
Format numbers and currencies
Get collation key value of a string
Get locale data such as language, country and currency names
Get locale data to be used for constructing user interface
Get a translated message from resource bundles
Get text formatting information such as writing direction
Encode and decode URLs
Get the common list of time zones and linguistic sorts
For example, when you want to display a date in your application, you may want to call the Localizer.formatDate()
or Localizer.formateDateTime()
methods. When you want to determine the writing direction of the current locale, you can call the Localizer.getWritingDirection()
and Localizer.getAlignment()
to determine the value used in the <DIR>
tag and <ALIGN>
tag respectively.
The Localizer
object also exposes methods to enumerate the list of supported locales and their corresponding languages and countries in your applications.
The Localizer
object actually makes use of the classes in the GDK Java API to accomplish its tasks. These classes includes, but are not limited to, the following:
OraDateFormat
OraNumberFormat
OraCollator
OraLocaleInfo
oracle.i18n.util.LocaleMapper
oracle.i18n.net.URLEncoder
oracle.i18n.net.URLDecoder
The Localizer
object simplifies the code you need to write for locale awareness. It maintains caches of the corresponding objects created from the GDK Java API so that the calling application does not need to maintain these objects for subsequent calls to the same objects. If you require more than the functionality the Localizer
object can provide, then you can always call the corresponding methods in the GDK Java API directly.
See Also: Oracle Globalization Development Kit Java API Reference for detailed information about theLocalizer object
|
The number of locales and the names of the locales that an application needs to support are based on the business requirements of the application. The names of the locales that are supported by the application are registered in the application configuration file. The following example shows the application locales section of the application configuration file. It indicates that the application supports German (de
), Japanese (ja
), and English for the US (en-US
), with English defined as the default fallback application locale. Note the locale names are based on the IANA convention.
<application-locales> <locale>de</locale> <locale>ja</locale> <locale default="yes">en-US</locale> </application-locales>
When the GDK framework detects the user locale, it verifies whether the locale that is returned is one of the supported locales in the application configuration file. The verification algorithm is as follows:
Retrieve the list of supported application locales from the application configuration file.
Check whether the detected locale is included in the list. If it is included in the list, then use this locale as the current client's locale.
If there is a variant detected in the locale, then remove the variant and check whether the resulting locale is in the list. For example, the Java locale de_DE_EURO
has a EURO
variant. Remove the variant so that the resulting locale is de_DE
.
If the locale includes a country code, then remove the country code and check whether the resulting locale is in the list. For example, the Java locale de_DE
has a country code of DE
. Remove the country code so that the resulting locale is de
.
If the detected locale does not match any of the locales in the list, then use the default locale that is defined in the application configuration file as the client locale.
By performing steps 3 and 4, the application can support users with the same language requirements but with different locale settings than those defined in the application configuration file. For example, the GDK can support de-AT
(the Austrian variant of German), de-CH
(the Swiss variant of German), and de-LU
(the Luxembourg variant of German) locales.
The locale fallback detection in the GDK framework is similar to that of the Java resource bundle, except that it is not affected by the default locale of the JVM. This exception occurs because the application default locale can be used during the GDK locale fallback operations.
If the application-locales section is omitted from the application configuration file, then the GDK assumes that the common locales, which can be returned by the OraLocaleInfo.getCommonLocales
method, are supported by the application.
The character set or character encoding of an HTML page is important to a browser and an Internet application. The browser needs to interpret the information so it can use the correct fonts and character set mapping tables for displaying pages. The Internet applications need to know so they can safely process input data from an HTML form based on the specified encoding.
The page encoding can be translated as the character set used for the locale served by an Internet application. In order to correctly specify the page encoding for HTML pages without using the GDK framework, Internet applications must:
Determine the desired page input data character set encoding for a given locale.
Specify the corresponding encoding name for each HTTP request and HTTP response.
Applications using the GDK framework can ignore these steps. No application code change is required. The character set information is specified in the GDK application configuration file. At runtime, the GDK automatically sets the character sets for the request and response objects. The GDK framework does not support the scenario where the incoming character set is different from that of the outgoing character set.
The GDK application framework supports the following scenarios for setting the character sets of the HTML pages:
A single local character set is dedicated to the whole application. This is appropriate for a monolingual Internet application. Depending on the properties of the character set, it may be able to support more than one language. For example, most Western European languages can be served by ISO-8859-1.
Unicode UTF-8 is used for all contents regardless of the language. This is appropriate for a multilingual application that uses Unicode for deployment.
The native character set for each language is used. For example, English contents are represented in ISO-8859-1, and Japanese contents are represented in Shift_JIS. This is appropriate for a multilingual Internet application that uses a default character set mapping for each locale. This is useful for applications that need to support different character sets based on the user locales. For example, for mobile applications that lack Unicode fonts or Internet browsers that cannot fully support Unicode, the character sets must be determined for each request.
The character set information is specified in the GDK application configuration file. The following is an example of setting UTF-8 as the character set for all the application pages.
<page-charset>UTF-8</page-charset>
The page character set information is used by the ServletRequestWrapper
class, which sets the proper character set for the request object. It is also used by the ContentType
HTTP header specified in the ServletResponseWrapper
class for output when instantiated. If page-charset
is set to AUTO-CHARSET
, then the character set is assumed to be the default character set for the current user locale. Set page-charset
to AUTO-CHARSET
as follows:
<page-charset>AUTO-CHARSET</page-charset>
The default mappings are derived from the LocaleMapper
class, which provides the default IANA character set for the locale name in the GDK Java API.
Table 3-3 lists the mappings between the common ISO locales and their IANA character sets.
Table 3-3 Mapping Between Common ISO Locales and IANA Character Sets
ISO Locale | IANA Character Set | NLS_LANGUAGE Value | NLS_TERRITORY Value |
---|---|---|---|
ar-SA |
WINDOWS-1256 |
ARABIC |
SAUDI ARABIA |
de-DE |
WINDOWS-1252 |
GERMAN |
GERMANY |
el |
WINDOWS-1253 |
GREEK |
GREECE |
en-GB |
WINDOWS-1252 |
ENGLISH |
UNITED KINGDOM |
en-US |
WINDOWS-1252 |
AMERICAN |
AMERICA |
es-ES |
WINDOWS-1252 |
SPANISH |
SPAIN |
fr |
WINDOWS-1252 |
FRENCH |
FRANCE |
fr-CA |
WINDOWS-1252 |
CANADIAN FRENCH |
CANADA |
it |
WINDOWS-1252 |
ITALIAN |
ITALY |
iw |
WINDOWS-1255 |
HEBREW |
ISRAEL |
ja |
SHIFT_JIS |
JAPANESE |
JAPAN |
ko |
EUC-KR |
KOREAN |
KOREA |
nl |
WINDOWS-1252 |
DUTCH |
THE NETHERLANDS |
pt |
WINDOWS-1252 |
PORTUGUESE |
PORTUGAL |
pt-BR |
WINDOWS-1252 |
BRAZILIAN PORTUGUESE |
BRAZIL |
tr |
WINDOWS-1254 |
TURKISH |
TURKEY |
zh |
GBK |
SIMPLIFIED CHINESE |
CHINA |
zh-TW |
BIG5 |
TRADITIONAL CHINESE |
TAIWAN |
The locale to character set mapping in the GDK is also customizable. To override the default mapping defined in the GDK Java API, a locale-to-character-set mapping table can be specified in the application configuration file.
<locale-charset-maps> <locale-charset> <locale>ja</locale><charset>EUC-JP</charset> </locale-charset> </locale-charset-maps>
The preceding example shows that for locale Japanese (ja
), the GDK changes the default character set from SHIFT_JIS to EUC-JP.
This section includes the following topics:
Resource bundles enable access to localized contents at runtime in Java 2 Platform, Standard Edition (J2SE). Translatable strings within Java servlets and Java Server Pages (JSPs) are externalized into Java resource bundles so these resource bundles can be translated independently into different languages. The translated resource bundles carry the same base class names as the English bundles, using the Java locale name as the suffix.
To retrieve translated data from the resource bundle, the getBundle()
method must be invoked for every request.
<% Locale user_locale=request.getLocale(); ResourceBundle rb=ResourceBundle.getBundle("resource",user_locale); %> <%= rb.getString("Welcome") %>
The GDK framework simplifies the retrieval of text strings from the resource bundles. Localizer.getMessage()
is a wrapper to the resource bundle.
<% Localizer.getMessage ("Welcome") %>
Instead of specifying the base class name as getBundle()
in the application, you can specify the resource bundle in the application configuration file. The GDK will automatically instantiate a ResourceBundle
object when a translated text string is requested.
<message-bundles> <resource-bundle name="default">resource</resource-bundle> </message-bundles>
The preceding configuration file code declares a default resource bundle whose translated contents reside in the resource Java bundle class. Multiple resource bundles can be specified in the configuration file. To access a nondefault bundle, specify the name
parameter in the getMessage
method. The message bundle mechanism uses the OraResourceBundle
GDK class for its implementation. This class provides the special locale fallback behaviors on top of the Java behaviors. The rules are as follows:
If the given locale exactly matches the locale in the available resource bundles, then it will be used.
If the resource bundle for Chinese in Singapore (zh_SG
) is not found, then it will fallback to the resource bundle for Chinese in China (zh_CN
) for Simplified Chinese translations.
If the resource bundle for Chinese in Hong Kong (zh_HK
) is not found, then it will fallback to the resource bundle for Chinese in Taiwan (zh_TW
) for Traditional Chinese translations.
If the resource bundle for Chinese in Macau (zh_MO
) is not found, then it will fallback to the resource bundle for Chinese in Taiwan (zh_TW
) for Traditional Chinese translations.
If the resource bundles for any other Chinese locale (zh_
and zh
) is not found, then it will fallback to the resource bundle for Chinese in China (zh_CN
) for Simplified Chinese translations.
The default locale, which can be obtained by the Locale.getDefault
method, will not be considered in the fallback operations.
The preceding rules provide the preferred languages for Hong Kong and Macau. The JDK fallback locale is Simplified Chinese (zh), whereas the users prefer Traditional Chinese (zh_TW).
For example, assume the default locale is ja_JP
and the resource bundle for it is available. When the resource bundle for es_MX
is requested and neither resource bundle for es
or es_MX
is provided, then the base resource bundle object that does not have the local suffix is returned.
The usage of the OraResourceBundle
class is similar to the java.util.ResourceBundle
class, but the OraResourceBundle
call does not instantiate itself. Instead, the return value of the getBundle
method is an instance of the subclass of the java.util.ResourceBundle
class.
For an application that supports only one locale, the URL that has a suffix of /index.html
typically takes the user to the starting page of the application.
In a global application, contents in different languages are usually stored separately, and it is common for them to be staged in different directories or with different file names based on the language or the country name. This information is then used to construct the URLs for localized content retrieval in the application.
The following code illustrates how to retrieve the French and Japanese versions of the index page. Their suffixes are as follows:
/fr/index.html /ja/index.html
By using the rewriteURL()
method of the ServletHelper class, the GDK framework handles the logic to locate the translated files from the corresponding language directories. The ServletHelper.rewriteURL()
method rewrites a URL based on the rules specified in the application configuration file. This method is used to determine the correct location where the localized content is staged.
The following is an example of the JSP code:
<img src="<%="ServletHelper.rewriteURL("image/welcome.jpg", request)%>"> <a href="<%="ServletHelper.rewriteURL("html/welcome.html", request)%>">
The URL rewrite definitions are defined in the GDK application configuration file:
<url-rewrite-rule fallback="yes"> <pattern>(.*)/(a-zA-Z0-9_\]+.)$</pattern> <result>$1/$A/$2</result> </url-rewrite-rule>
The pattern section defined in the rewrite rule follows the regular expression conventions. The following special variables are for use with the <result>
tag:
$L
represents the ISO 639 language code part of the current user locale
$C
represents the ISO 3166 country code
$A
represents the entire locale string, where the ISO 639 language code and ISO 3166 country code are connected with an underscore character (_
)
$1 to $9 represent the matched substrings
For example, if the current user locale is ja
, then the URL for the welcome.jpg
image file is rewritten as image/ja/welcome.jpg
, and welcome.html
is changed to html/ja/welcome.html
.
Both ServletHelper.rewriteURL()
and Localizer.getMessage()
methods perform consistent locale fallback operations in the case where the translation files for the user locale are not available. For example, if the online help files are not available for the es_MX
locale (Spanish for Mexico), but the es
(Spanish for Spain) files are available, then the methods will select the Spanish translated files as the substitute.
Java globalization functionalities and behaviors are not the same as those offered in the database. For example, J2SE supports a set of locales and character sets that are different from Oracle locales and character sets. This inconsistency can be confusing for users when their application contains data that is formatted based on 2 different conventions. For example, dates that are retrieved from the database are formatted using Oracle conventions, (such as number and date formatting and linguistic sort ordering), but the static application data is formatted using Java locale conventions. Java globalization functionalities can also be different depending on the version of the JDK that the application runs on.
The GDK Java API extends Oracle Application Server database globalization features to the middle tier. By enabling applications to perform globalization logic such as Oracle date and number formatting and linguistic sorting in the middle tier, the GDK Java API allows developers to eliminate expensive programming logic in the database, hence improving the overall application performance by reducing the database load in the database server and the unnecessary network traffic between the application tier and the database server.
The GDK Java API also offers advance globalization functionalities, such as language and character set detection, and the enumeration of common locale data for a territory or a language (for example, all time zones supported in Canada). These globalization features are not available in most programming platforms. Without the GDK Java API, developers must write business logic to handle them inside an application.
The following are the key functionalities of the GDK Java API:
Oracle locale definitions, which include languages, territories, linguistic sorts, and character sets, are exposed in the GDK Java API. The naming convention Oracle uses may also be different from other vendors. Although many of these names and definitions follow industry standards, some are specific to Oracle, and tailored to meet special customer requirements.
The Oracle locale class, OraLocaleInfo
, includes language, territory, and collator objects. It provides a method for applications to retrieve a collection of locale-related objects for a given locale. For example, a full list of the Oracle linguistic sorts available in the GDK, the local time zones defined for a given territory, or the common languages used in a particular territory.
The following are examples using the OraLocaleInfo
class:
// All Territories supported by GDK String[] avterr = OraLocaleInfo.getAvailableTerritories(); // Local TimeZones for a given Territory OraLocaleInfo oloc = OraLocaleInfo.getInstance("English", "Canada"); TimeZone[] loctz = oloc.getLocalTimeZones();
The GDK Java API provides the LocaleMapper
class. It maps equivalent locales and character sets between Java, IANA, ISO, and Oracle. A Java application may receive locale information from the client that is specified in the Oracle locale name or an IANA character set name. The Java application must be able to map to an equivalent Java locale or Java encoding before it can process the information correctly.
The following is an example of using the LocaleMapper
class.
// Mapping from Java locale to Oracle language and Oracle territory Locale locale = new Locale("it", "IT"); String oraLang = LocaleMapper.getOraLanguage(locale); String oraTerr = LocaleMapper.getOraTerritory(locale); // From Oracle language and Oracle territory to Java Locale locale = LocaleMapper.getJavaLocale("AMERICAN","AMERICA"); locale = LocaleMapper.getJavaLocale("TRADITONAL CHINESE", ""); // From IANA & Java to Oracle Character set String ocs1 = LocaleMapper.getOraCharacterSet( LocaleMapper.IANA, "ISO-8859-1"); String ocs2 = LocaleMapper.getOraCharacterSet( LocaleMapper.JAVA, "ISO8859_1");
The LocaleMapper
class can also return the most commonly used e-mail character set for a specific locale on both Microsoft Windows and UNIX platforms. This is useful when developing Java applications that need to process e-mail messages.
The GDK Java API contains a set of character set conversion class APIs that enable users to perform Oracle character set conversions. Although Java JDK is already equipped with classes that can perform conversions for many of the standard character sets, they do not support Oracle-specific character sets and Oracle user-defined character sets.
In JDK 1.4, J2SE introduced an interface for developers to extend Java character sets. The GDK Java API provides implicit support for Oracle character sets by using this plug-in feature. You can access the J2SE API to obtain behaviors specific for Oracle.
Figure 3-5 shows the GDK character set conversion tables are plugged into J2SE in the same way as the Java character set tables. With this pluggable framework of J2SE, the Oracle character set conversions can be used in the same way as other Java character set conversions.
The java.nio.charset
Java package is not available in JDK versions prior to version 1.4. You must install JDK 1.4 or later to use the Oracle character set plug-in feature.
The GDK character conversion classes support all Oracle character sets including user-defined characters sets. It can be used by Java applications to properly convert to and from Java internal character set, UTF-16.
Oracle character set names are proprietary. To avoid potential conflicts with Java's own character sets, all Oracle character set names have an X-ORACLE-
prefix for all implicit usage through Java API.
The following is an example of Oracle character set conversion:
// Converts the Chinese character "three" from UCS2 to JA16SJIS String str = "\u4e09"; byte[] barr = str.getBytes("x-oracle-JA16SJIS");
Like other Java character sets, the character set facility in java.nio.charset.Charset
is also applicable to all of the Oracle character sets. For example, to check whether the specified character set is a superset of another character set, you can use the Charset.contains
method as follows:
Charset cs1 = Charset.forName("x-oracle-US7ASCII"); Charset cs2 = Charset.forName("x-oracle-WE8WINDOWS1252"); // true if WE8WINDOWS1252 is the superset of US7ASCII, otherwise false. boolean osc = cs2.contains(cs1);
For a Java application that is using the JDBC driver to communicate with the database, the JDBC driver provides the necessary character set conversion between the application and the database. Calling the GDK character set conversion methods explicitly within the application is not required. A Java application that interprets and generates text files based on Oracle character set encoding format is an example of using Oracle character set conversion classes.
The GDK Java API provides formatting classes that support date, number, and monetary formats using Oracle conventions for Java applications in the oracle.i18n.text
package.
New locale formats introduced in Oracle Application Server, such as the short and long date, number, and monetary formats, are also provided in these format classes.
The following are examples of Oracle date, Oracle number, and Oracle monetary formatting:
// Obtain the current date and time in the default Oracle LONG format for // the locale de_DE (German_Germany) Locale locale = new Locale("de", "DE"); OraDateFormat odf = OraDateFormat.getDateTimeInstance(OraDateFormat.LONG, locale); // Obtain the numeric value 1234567.89 using the default number format // for the Locale en_IN (English_India) locale = new Locale("en", "IN"); OraNumberFormat onf = OraNumberFormat.getNumberInstance(locale); String nm = onf.format(new Double(1234567.89)); // Obtain the monetary value 1234567.89 using the default currency // format for the Locale en_US (American_America) locale = new Locale("en", "US"); onf = OraNumberFormat.getCurrencyInstance(locale); nm = onf.format(new Double(1234567.89));
Oracle provides support for binary, monolingual, and multilingual linguistic sorts in the database. In Oracle Application Server, these sorts have been expanded to provide case-insensitive and accent-insensitive sorting and searching capabilities inside the database. By using the OraCollator
class, the GDK Java API enables Java applications to sort and search for information based on the latest Oracle binary and linguistic sorting features, including case-insensitive and accent-insensitive options.
Normalization can be an important part of sorting. The composition and decomposition of characters are based on the Unicode standard, so sorting also depends on the Unicode standard. Because each version of the JDK may support a different version of the Unicode Standard, the GDK provides an OraNormalizer
class based on the Unicode 3.2 standard. It contains methods to perform composition.
The sorting order of a binary sort is based on the Oracle character set that is being used. Except for the UTFE character set, the binary sorts of all Oracle character sets are supported in the GDK Java API. The only linguistic sort that is not supported in the GDK Java API is JAPANESE, but a similar and more accurate sorting result can be achieved by using JAPANESE_M.
The following are examples of string comparisons and string sorting:
// compares strings using XGERMAN private static String s1 = "abcSS"; private static String s2 = "abc\u00DF"; String cname = "XGERMAN"; OraCollator ocol = OraCollator.getInstance(cname); int c = ocol.compare(s1, s2); // sorts strings using GENERIC_M private static String[] source = new String[] { "Hochgeschwindigkeitsdrucker", "Bildschirmfu\u00DF", "Skjermhengsel", "DIMM de Mem\u00F3ria", "M\u00F3dulo SDRAM com ECC", }; cname = "GENERIC_M"; ocol = OraCollator.getInstance(cname); List result = getCollationKeys(source, ocol); private static List getCollationKeys(String[] source, OraCollator ocol) { List karr = new ArrayList(source.length); for (int i = 0; i < source.length; ++i) { karr.add(ocol.getCollationKey(source[i])); } Collections.sort(karr); // sorting operation return karr; }
The Oracle Language and Character Set Detection Java classes in the GDK Java API provide a high performance, statistically based engine for determining the character set and language for unspecified text. It can automatically identify language and character set pairs from throughout the world. With each text, the language and character set detection engine sets up a series of probabilities, each probability corresponding to a language and character set pair. The most probable pair statistically identifies the dominant language and character set.
The purity of the text submitted affects the accuracy of the language and character set detection. Only plain text strings are accepted, so any tagging needs to be stripped before hand. The ideal case is literary text with almost no foreign words or grammatical errors. Text strings that contain a mix of languages or character sets, or nonnatural language text like addresses, phone numbers, and programming language code may yield poor results.
The LCSDetector
class can detect the language and character set of a byte array, a character array, a string, and an InputStream
class. It can take the entire input for sampling or only portions of the input for sampling, when the length or both the offset and the length are supplied. For each input, up to three potential language and character set pairs can be returned by the LCSDetector
class. They are always ranked in sequence, with the pair with the highest probability returned first.
The following are examples of using the LCSDetector
class to enable language and character set detection:
// This example detects the character set of a plain text file "foo.txt" and // then appends the detected ISO character set name to the name of the text file LCSDetector lcsd = new LCSDetector(); File oldfile = new File("foo.txt"); FileInputStream in = new FileInputStream(oldfile); lcsd.detect(in); String charset = lcsd.getResult().getIANACharacterSet(); File newfile = new File("foo."+charset+".txt"); oldfile.renameTo(newfile); // This example shows how to use the LCSDector class to detect the language and // character set of a byte array int offset = 0; LCSDetector led = new LCSDetector(); /* loop through the entire byte array */ while ( true ) { bytes_read = led.detect(byte_input, offset, 1024); if ( bytes_read == -1 ) break; offset += bytes_read; } LCSDResultSet res = led.getResult(); /* print the detection results with close ratios */ System.out.println("the best guess " ); System.out.println("Language " + res.getOraLanguage() ); System.out.println("CharacterSet " + res.getOraCharacterSet() ); int high_hit = res.getHiHitPairs(); if ( high_hit >= 2 ) { System.out.println("the second best guess " ); System.out.println("Language " + res.getOraLanguage(2) ); System.out.println("CharacterSet " +res.getOraCharacterSet(2) ); } if ( high_hit >= 3 ) { System.out.println("the third best guess "); System.out.println("Language " + res.getOraLanguage(3) ); System.out.println("CharacterSet " +res.getOraCharacterSet(3) ); }
All Oracle language names, territory names, character set names, linguistic sort names, and time zone names have been translated into 27 languages including English. They are readily available for inclusion in the user applications, and they provide consistency for the display names across user applications in different languages. OraDisplayLocaleInfo
is a utility class that provides the translations of locale and attributes. The translated names are useful for presentation in user interface text and for selection boxes. For example, a native French speaker prefers to select from a list of time zones displayed in French than in English.
The following is an example of using OraDisplayLocaleInfo
to return a list of time zones supported in Canada, using the French translation names:
OraLocaleInfo oloc = OraLocaleInfo.getInstance("CANADIAN FRENCH", "CANADA"); OraDisplayLocaleInfo odloc = OraDisplayLocaleInfo.getInstance(oloc); TimeZone[] loctzs = oloc.getLocaleTimeZones(); String [] disptz = new string [loctzs.length]; for (int i=0; i<loctzs.length; ++i) { disptz [i]= odloc.getDisplayTimeZone(loctzs[i]); ... }
You can use the GDK LocaleMapper
class to retrieve the most commonly used e-mail character set. Call LocaleMapper.getIANACharSetFromLocale
, passing in the locale object. The return value is an array of character set names. The first character set returned is the most commonly used e-mail character set.
The following is an example of sending an e-mail message containing Simplified Chinese data in GBK character set encoding:
import oracle.i18n.util.LocaleMapper; import java.util.Date; import java.util.Locale; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; /** * Email send operation sample * * javac -classpath orai18n.jar:j2ee.jar EmailSampleText.java * java -classpath .:orai18n.jar:j2ee.jar EmailSampleText */ public class EmailSampleText { public static void main(String[] args) { send("localhost", // smtp host name "your.address@your-company.com", // from email address "You", // from display email "somebody@some-company.com", // to email address "Subject test zh CN", // subject "Content ˘4E02 from Text email", // body new Locale("zh", "CN") // user locale ); } public static void send(String smtp, String fromEmail, String fromDispName, String toEmail, String subject, String content, Locale locale ) { // get the list of common email character sets final String[] charset = LocaleMapper.getIANACharSetFromLocale(LocaleMapper. EMAIL_WINDOWS, locale ); // pick the first one for the email encoding final String contentType = "text/plain; charset=" + charset[0]; try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtp); // here, set username / password if necessary Session session = Session.getDefaultInstance(props, null); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail, fromDispName, charset[0] ) ); mimeMessage.setRecipients(Message.RecipientType.TO, toEmail); mimeMessage.setSubject(MimeUtility.encodeText(subject, charset[0], "Q")); // body mimeMessage.setContent(content, contentType); mimeMessage.setHeader("Content-Type", contentType); mimeMessage.setHeader("Content-Transfer-Encoding", "8bit"); mimeMessage.setSentDate(new Date()); Transport.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); } } }
Oracle Globalization Services for Java contains the following packages:
Package oracle.i18n.lcsd
provides classes to automatically detect and recognize language and character set based on text input. Language is based on ISO, and encoding is based on IANA or Oracle character sets. It includes the following classes:
LCSDetector
: This class contains methods to automatically detect and recognize language and character set based on text input.
LCSDResultSet
: This class stores the result generated by LCSDetector
. Methods in this class can be used to retrieve specific information from the result.
Package oracle.i18n.net
provides Internet-related data conversions for globalization. It includes the following classes:
CharEntityReference
: A utility class to escape or unescape a string into character reference or entity reference form.
CharEntityReference.Form
: A form parameter class that specifies the escaped form.
Package oracle.i18n.Servlet
enables JSP and JavaServlet to have automatic locale support and also returns the localized contents to the application. It includes the following classes:
ApplicationContext
: An application context class that governs application scope operation in the framework.
Localizer
: An all-in-one object class that enables access to the most commonly used globalization information.
ServletHelper
: A delegate class that bridges between Java servlets and globalization objects.
Package oracle.i18n.text
provides general text data globalization support. It includes the following classes:
OraCollationKey
: A class which represents a String
under certain rules of a specific OraCollator
object.
OraCollator
: A class to perform locale-sensitive string comparison, including linguistic collation and binary sorting.
OraDateFormat
: An abstract class to do formatting and parsing between datetime and string locale. It supports Oracle datetime formatting behavior.
OraDecimalFormat
: A concrete class to do formatting and parsing between number and string locale. It supports Oracle number formatting behavior.
OraDecimalFormatSymbol
: A class to maintain Oracle format symbols used by Oracle number and currency formatting.
OraNumberFormat
: An abstract class to do formatting and parsing between number and string locale. It supports Oracle number formatting behavior.
OraSimpleDateFormat
: A concrete class to do formatting and parsing between datetime and string locale. It supports Oracle datetime formatting behavior.
Package oracle.i18n.util
provides general utilities for globalization support. It includes the following classes:
LocaleMapper
: This class provides mappings between Oracle locale elements and the equivalent locale elements of other vendors and standards.
OraDisplayLocaleInfo
: A translation utility class that provides the translations of locale and attributes.
OraLocaleInfo
: An Oracle locale class that includes the language, territory, and collator objects.
OraSQLUtil
: An Oracle SQL utility class that includes some useful methods of dealing with SQL.
The GDK for PL/SQL includes the following PL/SQL packages:
UTL_I18N
UTL_LMS
UTL_I18N
is a set of PL/SQL services that help developers to build global applications. The UTL_I18N
PL/SQL package provides the following functions:
String conversion functions for various datatypes
Escape and unescape sequences for predefined characters and multibyte characters used by HTML and XML documents
Functions that map between Oracle, IANA, ISO, and e-mail application character sets, languages, and territories
A function that returns the Oracle character set name from an Oracle language name
UTL_LMS
retrieves and formats error messages in different languages.
See Also: PL/SQL Packages and Types Reference |