Oracle8i National Language Support Guide Release 2 (8.1.6) Part Number A76966-01 |
|
This chapter covers NLS issues with the use of Java. It contains:
Java support is included in all tiers of a multi-tier computing environment in order to enable users to develop and deploy Java programs. You can run Java classes as Java stored procedures, Java CORBA objects, and Enterprise Java Beans (EJB) on the Java Virtual Machine (VM) of the database server. Users are able to develop a Java class, load it into the database, and package it as a stored procedure callable from SQL. Users can also develop a standard Java CORBA object or EJB, load the related classes into the database and publish them as a named object callable from any CORBA or EJB client.
The JDBC driver and SQLJ translator are also provided as programmatic interfaces enabling Java programs to access the Oracle8i database. Users can write a Java application using JDBC or SQLJ programs with embedded SQL statements to access the database. Globalization support is provided across all these Java components to ensure that they function properly across databases of different character sets and language environments, and that they enable the development and deployment of multilingual Java applications for Oracle8i.
This chapter examines the NLS support for individual Java components. Typical database and client configurations are discussed for multilingual application deployment, and how the Java components are used in the midst of them. Finally, the design and implementation of a demo application are explored to demonstrate how Oracle's Java support is used to make the application run in a multilingual environment.
Java components provide NLS support and use Unicode as the multilingual character set of choice. The following are Oracle8i's Java components:
This section describes the following:
Oracle JDBC drivers provide globalization support by allowing users to retrieve data from or insert data into a database in any character set that Oracle supports. Because Java strings are UCS2 encoded (16-bit Unicode) for JDBC programs, the target character set on the client is always UCS2. Character set conversion is required to convert data from the database character set (Db Charset) to UCS2. This applies to CHAR, LONG, CLOB, and VARCHAR2 data types; RAW data is not converted.
Following are a few examples of commonly used Java methods for JDBC that rely heavily on NLS character set conversion:
java.sql.ResultSet
's methods getString()
and getUnicodeStream()
return values from the database as Java strings and as a stream of Unicode characters, respectively.
oracle.sql.CLOB
's method getCharacterStream()
returns the contents of a CLOB
as a Unicode stream.
oracle.sql.CHAR
's methods getString()
, toString()
, and getStringWithReplacement().
The techniques that Oracle's drivers use to perform character set conversion for Java applications depend on the character set the database uses. The simplest case is where the database uses a US7ASCII or WE8ISO8859P1 character set. In this case, the driver converts the data directly from the database character set to UCS2,which is used in Java applications.
If you are working with databases that employ a non-US7ASCII or non-WE8ISO8859P1 character set (for example, Japanese or Korean), then the driver converts the data, first to UTF8, then to UCS2.
Figure 6-1 presents a graphical view of how data is converted in JDBC drivers.
The JDBC Class Library is a Java layer that implements the JDBC interface. Java applications, applets and stored procedures interact with this layer. The library always accepts US7ASCII, UTF8 or WE8ISO8859P1 encoded string data from the input stream of the JDBC drivers. It also accepts UCS2 for the JDBC server-side driver. The JDBC Class Library converts the input stream to UCS2 before passing it to the client applications. If the input stream is in UTF8, the JDBC Class Library converts the UTF8 encoded string to UCS2 by using the bit-wise operation defined in the UTF8-to-UCS2 conversion algorithm. If the input stream is in US7ASCII or WE8ISO8859P1, it converts the input string to UCS2 by casting the bytes to Java characters. This is based on the first 128 and 256 characters of UCS2 corresponding to the US7ASCII and WE8ISO8859P1 character sets, respectively. Treating WE8ISO8859P1 and US7ASCII separately improves the performance for commonly used single-byte clients by eliminating the bit-wise conversion to UTF8.
At database connection time, the JDBC Class Library sets the server NLS_LANGUAGE and NLS_TERRITORY parameters to correspond to the locale of the Java VM that runs the JDBC driver. This operation is performed on the JDBC OCI and JDBC Thin drivers only, and ensures that the server and the Java client communicate in the same language. As a result, Oracle error messages returned from the server are in the same language as the client locale.
In the case of a JDBC OCI driver installation, there is a client-side character set as well as a database character set. The client character set is determined at client-installation time by the value of the NLS_LANG environment variable. The database character set is determined at database creation. The character set used by the client can be different from the character set used by the database on the server. So, when performing character set conversion, the JDBC OCI driver has to take three factors into consideration:
The JDBC OCI driver transfers the data from the server to the client in the character set of the database. Depending on the value of the NLS_LANG environment variable, the driver handles character set conversions in one of two ways.
Notes:
If your applications or applets use the JDBC Thin driver, then there is no Oracle client installation. Because of this, the OCI client conversion routines in C are not available. In this case, the client conversion routines are different from the JDBC OCI driver.
If the database character set is US7ASCII or WE8ISO8859P1, the data is transferred to the client without any conversion. The driver then converts the character set to UCS2 in Java.
If the database character set is something other than US7ASCII or WE8ISO8859P1, then the server first translates the data to UTF8 before transferring it to the client. On the client, the JDBC Thin driver converts the data to UCS2 in Java.
For Java classes running in the Java VM of the Oracle8i Server, the JDBC Server driver is used to talk to the SQL engine or the PL/SQL engine for SQL processing. Because the JDBC Server driver is running in the same address space as the Oracle server process, it makes a local function call to the SQL engine or the PL/SQL engine. Data sent to or returned from the SQL engine or the PL/SQL engine will be encoded in the database character set. If the database character set is US7ASCII, WE8ISO8859P1, or UTF8, no conversion is performed in the JDBC Server driver, and the data is passed to or from the JDBC Class Library as is. Otherwise, the JDBC Server driver converts the data from the database character set to UCS2 before passing them to and from the class library. The class library does not need to do any conversion in this case.
The oracle.sql.CHAR
class has special functionality for NLS conversion of character data. A key attribute of the oracle.sql.CHAR
class, and a parameter always passed in when an oracle.sql.CHAR
object is constructed, is the NLS character set used in presenting the character data. Without a known character set, the bytes of data in the oracle.sql.CHAR
object are meaningless.
JDBC constructs and populates oracle.sql.CHAR
objects after character data has been read from the database.
The oracle.sql.CHAR
class provides the following methods for converting character data to strings:
getString()
: converts the sequence of characters represented by the oracle.sql.CHAR
object to a string, returning a Java String
object. If the character set is not recognized (that is, if you entered an invalid OracleID
), then getString()
throws a SQLException
.
toString()
: identical to getString()
, but if the character set is not recognized (that is, if you entered an invalid OracleID
), then toString()
returns a hexadecimal representation of the oracle.sql.CHAR
data and does not throw a SQLException
.
getStringWithReplacement()
: identical to getString()
, except a default replacement character replaces characters that have no Unicode representation in the character set of this oracle.sql.CHAR
object. This default character varies from character set to character set, but is often a question mark.
Additionally, you might want to construct an oracle.sql.CHAR
object yourself (to pass into a prepared statement, for example). When you construct an oracle.sql.CHAR
object, you must provide character set information to the oracle.sql.CHAR
object by way of an instance of the oracle.sql.CharacterSet
class. Each instance of the CharacterSet
class represents one of the NLS character sets that Oracle supports.
Follow these general steps to construct an oracle.sql.CHAR
object:
CharacterSet
instance by calling the static CharacterSet.make()
method. This method is a factory for the character set class. It takes as input an integer OracleId
, which corresponds to a character set that Oracle supports. For example:
int OracleId = CharacterSet.JA16SJIS_CHARSET; // this is character set 832 ... CharacterSet mycharset = CharacterSet.make(OracleId);
Each character set that Oracle supports has a unique predefined OracleId
. The OracleId
can always be referenced as a character set <Oracle charset name>_CHARSET where <Oracle charset name> is the Oracle character set.
oracle.sql.CHAR
object. Pass to the constructor a string (or the bytes that represent the string) and the CharacterSet
object that indicates how to interpret the bytes based on the character set. For example:
String mystring = "teststring"; ... oracle.sql.CHAR mychar = new oracle.sql.CHAR(teststring, mycharset);
The oracle.sql.CHAR
class has multiple constructors: they can take a string, a byte array, or an object as input along with the CharacterSet
object. In the case of a string, the string is converted to the character set indicated by the CharacterSet
object before being placed into the oracle.sql.CHAR
object.
Refer to the oracle.sql.CHAR
class Javadoc for more information.
The server (database) and the client (or application running on the client) can use different character sets. When you use the methods of this class to transfer data between the server and the client, the JDBC drivers must convert the data from the server character set to the client character set (or vice versa).
In Oracle8i, JDBC drivers support Oracle object types. Oracle objects are always sent from database to client as an object represented in the database character set. That means the data conversion path in Figure 6-1, "Data Conversion in JDBC Drivers", does not apply to Oracle object access. Instead, the oracle.sql.CHAR class is used for passing string data from the database to the client. An example of an object type created by SQL:
CREATE TYPE PERSON_TYPE AS OBJECT (NAME VARCHAR2(30), AGE NUMBER); CREATE TABLE EMPLOYEES (ID NUMBER, PERSON PERSON_TYPE) ;
The Java class corresponding to this object type can be constructed as follows:
public class person implement SqlData { oracle.sql.CHAR name; oracle.sql.NUMBER age; // SqlData interfaces getSqlType() {...} writeSql(SqlOutput stream) {...} readSql(SqlInput stream, String sqltype) {...} }
The oracle.sql.CHAR class is used here to map to the NAME attributes of the Oracle object type which is of VARCHAR type. JDBC populates this class with the byte representation of the VARCHAR data in the database and the character set object corresponding to the database character set. The following code retrieves a person object from the people table,
TypeMap map = ((OracleConnection)conn).getTypeMap(); map.put("PERSON_TYPE", Class.forName("person")); conn.setTypeMap(map); . . . . . . ResultSet rs = stmt.executeQuery("SELECT PERSON FROM EMPLOYEES"); rs.next(); person p = (person) rs.getObject(1); oracle.sql.CHAR sql_name = p.name; String java_name = sql_name.getString();
The getString() method of the oracle.sql.CHAR class converts the byte array from the database character set to UCS2 by calling Oracle's Java data conversion classes and return a Java string. For the rs.getObject(1) call to work, the SqlData interface has to be implemented in the class person, and the Typemap map has to be set up to indicate the mapping of the object type PERSON_TYPE to the Java class.
There is a limit on the maximum sizes for CHAR and VARCHAR2 datatypes when used in bind calls. This limitation is necessary to avoid data corruption. Data corruption occurs only with binds (not for defines) and it affects only CHAR and VARCHAR2 datatypes if you are connected to a multibyte character set database.
The maximum bind lengths are limited in the following way:
CHARs and VARCHAR2s experience character set conversions that can result in an increase in the length of the data in bytes. The ratio between data sizes before and after a conversion is called the NLS Ratio. After conversion, the bind values should not be greater than 4 Kbytes.
Driver | Datatype | Old Max Bind Length (bytes) | New Restricted Max Bind Length (bytes) |
---|---|---|---|
Thin and OCI |
CHAR |
2000 |
min(2000,4000 / NLS_Ratio) |
VARCHAR2 |
4000 |
(4000 / NLS_Ratio) |
For example, when connecting to an Oracle8 server, you cannot bind more than:
OR
Table 6-2 contains examples of the NLS Ratio and maximum bind values for some common server character sets.
Server Character Set | NLS Ratio |
Maximum Bind Value on Oracle8 Server (in bytes) |
---|---|---|
WE8DEC |
1 |
4000 |
US7ASCII |
1 |
4000 |
ISO 8859-1 through 10 |
1 |
4000 |
JA16SJIS |
2 |
2000 |
JA16EUC |
3 |
1333 |
Oracle JDBC drivers perform character set conversions as appropriate when character data is inserted into or retrieved from the database, i.e., the drivers convert Unicode characters used by Java clients to Oracle database character set characters, and vice versa. Character data making a round trip from the Java Unicode character set to the database character set and back to Java can suffer some loss of information. This happens when multiple Unicode characters are mapped to a single character in the database character set. An example would be the Unicode full-width tilde character (0xFF5E) and its mapping to Oracle's JA16SJIS character set. The round trip conversion for this Unicode character results in the Unicode character 0x301C, which is a wave dash (a character commonly used in Japan to indicate range), not a tilde.
This issue is not a bug in Oracle's JDBC, but rather is an unfortunate side effect of the ambiguity in character mapping specification on different operating systems. Fortunately, this problem affects only a small number of characters in a small number of Oracle character sets such as JA16SJIS, JA16EUC, ZHT16BIG5, and KO16KS5601. The workaround is to avoid making a full round-trip with these characters.
SQLJ is a SQL-to-Java translator that translates embedded SQL statements in a Java program into the corresponding JDBC calls irrespective of which JDBC driver is used. It also provides a callable interface that the Oracle8i database server uses to transparently translate the embedded SQL in server-side Java programs. SQLJ by itself is a Java application that reads the SQLJ programs (Java programs containing embedded SQL statements) and generates the corresponding Java program files with JDBC calls. There is an option to specify a checker to check the embedded SQL statements against the database at translation time. The javac compiler is then used to compile the generated Java program files to regular Java class files.
Figure 6-3 presents a graphical view of how the SQLJ translator works.
SQLJ enables multilingual Java application development by allowing SQLJ files encoded in different encoding schemes (those supported by the JDK). In the diagram above, a UCS2 encoded SQLJ program is being passed to the SQLJ translator and the Java program output is also encoded in UCS2. SQLJ preserves the encoding of the source in the target. To specify the encoding of the source, use the -encoding option as follows:
sqlj -encoding Unicode <source file>
Unicode notation \uXXXX (which is referred to as a Unicode escape sequence) can be used in embedded SQL statements for characters that cannot be represented in the encoding of the SQLJ program file. This enables you to specify multilingual object names in the SQL statement without using a UCS2 encoded SQLJ file. The following SQLJ code shows the usage of Unicode escape sequences in embedded SQL as well as in a string literal.
int empno = 12345; #sql {insert into E\u0063\u0064 (ENAME, EMPNO) values ('Joe', :empno)}; String name ename = "\ua0a1\ua0a2"; double raise = 0.1; #sql { update EMP set SAL = :(getNewSal(raise, ename)) where ENAME = :ename;
See "Multilingual Demo Applications in SQLJ" for an example of SQLJ usage for a multilingual Java application.
The Oracle8i Java VM base is integrated into the database server to enable the running of Java classes stored in the database. Oracle8i allows user to store Java class files, Java or SQLJ source files and Java resource files into the database, to publish the Java entry points to SQL so that it can be called from SQL or PL/SQL, and to run the Java byte code.
In addition to the engine that interprets Java byte code, the Oracle Java VM includes the core run-time classes of the JDK. The components of the Java VM are depicted in Figure 6-4.
The Java VM provides an embedded Java class loader that locates, loads, and initializes locally stored Java classes in the database, and a byte code compiler which translates standard Java programs into standard Java .class binary representation. A library manager is also included to manage Java program, class, and resource files as schema objects known as library units. It not only loads and manages these Java files in the database, but also maps Java name space to library units. For example:
public class Greeting { public String Hello(String name) { return ("Hello" + name + "!"); } }
After the preceding Java code is compiled, it is loaded into the database as follows:
loadjava Greeting.class
As a result, a library unit called Greeting, is created as a schema object in the database. If the class name contains characters that cannot be represented in the database character set, a US7ASCII library unit name is generated and mapped to the real class name stored in a RAW column so that the class loader can find the library unit corresponding to the real class name when the real class name is referenced in a Java program running in the server. In other words, the library manager and the class loader support class names or method names outside the namespace of the database character set.
A Java stored procedure or function requires that the library unit of the Java classes implementing it already be present in the database. Using the Greeting library unit example in the previous section, the following call specification DDL publishes the method Greeting.Hello() as a Java stored function:
CREATE FUNCTION MYHELLO(NAME VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'Greeting.Hello(java.lang.String) return java.lang.String';
The DDL maps the Java methods, parameter types and return types to the SQL counterparts. To the users, the Java stored function has the same calling syntax as any other PL/SQL stored functions. Users can call the Java stored procedures the same way they call any PL/SQL stored procedures. Figure 6-5 depicts the runtime environment of a stored function.
The Java entry point, Greeting.Hello(), is called by invoking the proxy PL/SQL MYHELLO() from the client. The server process serving the client runs as a normal PL/SQL stored function; when the PL/SQL engine finds that it is a call specification of the Java method, it calls the Java VM, and passes the method name of the Java stored function and the argument to the Java VM for execution. The Java VM takes control, calls the SQL to Java using code to convert the VARCHAR2 argument from the database character set to UCS2, loads the class Greeting, and runs the method Hello() with the converted argument. The string returned by Hello() is then converted back to the database character set and returned as a VARCHAR2
string to the caller.
The globalization support that enables deployment and development of internationalized Java stored procedures includes:
Visigenic's CORBA Object Request Broker (ORB) is integrated into the database server to make it a Java CORBA object and EJB server running the IIOP protocol. CORBA support also includes a set of supporting services that enables the deployment of CORBA objects to the database. For more information regarding Oracle's CORBA support, see Oracle8 Database Programming with Java.
The CORBA ORB is written in Java and includes an IIOP interpreter and the object adapter. The IIOP interpreter processes the IIOP message by invoking the object adapter to look for the CORBA object being activated and load it into the memory, and running the object method specified in the message.
A couple of CORBA objects are predefined. The LoginServer object is used for explicit session log in, and the PublishContext object is to used to resolve a published CORBA object name to the corresponding PublishedObject.
CORBA objects implemented in Java in Oracle8i are required to be loaded and then published before the client can reference it. Publish is a Java written utility that publishes a CORBA object to the ORB by creating an instance of PublishedObject which represents and activates the CORBA object, and binding the input (CosNaming) name to the published object.
Oracle8i implements the CosNaming standard for specifying CORBA object names. CosNaming provides a directory-like structure that is a context for binding names to CORBA objects. A new JNDI URL, "sess_iiop:" is created, and indicates a session based IIOP connection for a CORBA object. A name for a CORBA object in the local database can be published as:
sess_iiop://local:2222:ORCL/Demo/MyGreeting
where 2222 is the port number for receiving IIOP requests, ORCL is the database instance identifier and /Demo/MyGreeting is the name of the published object. The namespace for CORBA objects in Oracle8i is limited to US7ASCII characters.
Figure 6-6 presents a graphical view of the components in a CORBA environment:
The CORBA objects for Oracle8i can only be written in Java and they run on the Java VM of the database. The CORBA client can be written in any language the standard supports. An interface definition language (IDL) file that identifies the CORBA objects and their interfaces will be compiled with the idl2java translator to generate the stub for the client and the skeleton code for the CORBA server objects. CORBA object programmers are required to program the implementation classes of the CORBA objects defined in the IDL in Java by extending the skeleton classes generated and load them to the database together with the skeleton code.
Module Demo { interface Greeting { wstring Hello(string str); }; }; >idl2java Greeting.IDL Creating: Demo/Greeting.java Demo/GreetingHolder.java Demo/GreetingHelper.java Demo/_GreetingImpBase.java
public class GreetingImpl extends _GreetingImplBase implements ActivatableObject { public GreetingImpl (String name) { super(name); } public GreetingImpl() { super(); } public org.omg.CORBA.Object _intializeAuroraObject() { return this } public String Hello(String str) { return "Hello" + str; } }
In the above code, the CORBA object Greeting has been implemented with a method called Hello(). The CORBA standard defines the wstring data type to pass multibyte strings via CORBA/IIOP, and the Visigenic ORB implements the wstring data type as a Unicode string. If the string data type is specified instead, the parameter passed into the Hello() method is assumed to be a single byte. The wstring data type enables the development of multilingual CORBA objects. The implementation class for Greeting extends the skeleton class
_GreetingImplBase generated by idl2java.
Once the CORBA object has been implemented, the below example shows the steps involved in loading the Java object implementation classes into the database and publishing the Java CORBA object using the CosNaming convention.
loadjava -user scott/tiger -grant public Greeting.jar publish -user scott -password tiger -service sess_iiop://local:2222:orcl/Demo/MyGreeting Demo.GreetingImpl Demo.GreetingHelper
Assume that all Java classes (implementation and helper classes) required to implement the Greeting object are in the Greeting.jar file. They are loaded to the database as public, and the implementation class is published to the database. The name of the published object is /Demo/MyGreeting, and it is used in the client code to reference this CORBA object.
Clients accessing a CORBA object in the database require an ORB and authentication from the database where the object is stored. The following is a excerpt of a client code in Java accessing the Greeting object. The ORB is initialized when the CORBA object is first activated via Oracle's implementation of JNDI.
import java.util.Hashtable; import javax.naming.*; import oracle.aurora.jndi.sess_iiop.ServiceCtx; public class Client { public static void main(String args[]) throws Exception { Hashtable environment = new Hashtable(); environment.put(javax.naming.Context.URL_PKG_PREFIXES, "oracle.aurora.jndi"); environment.put(Context.SECURITY_PRINCIPAL, "scott"); environment.put(Context.SECURITY_CREDENTIALS, "tiger"); environment.put(Context.SECURITY_AUTHENTICATION,
ServiceCtx.NON_SSL_CREDENTIAL); Context ic = new InitialContext(environment); Greeting greet = (Greeting) ic.lookup("sess_iiop://local:2222:ORCL/Demo/MyGreeting"); System.out.println(greet.Hello(arg[0])); } }
The database is a secure environment, so Java clients must be authenticated before they can access CORBA objects, and the locale of the Java VM running the CORBA object is initialized when the session running the object is authenticated. To access a CORBA object, users can use explicit or implicit authentication:
In addition to CORBA objects, Oracle provides tools and an environment for developing and deploying EJBs in the Oracle8i server. An EJB is called using the IIOP protocol provided for CORBA support, and hence shares a lot of similarities with the CORBA object. An EJB is defined in the EJB descriptor, which specifies the home interface, remote interface, home name and allowed identities of the EJB among other things. For basic concepts about EJBs, refer to Oracle8i Enterprise JavaBeans and CORBA Developer's Guide. The following shows the EJB descriptor for GreetingBean, which is functionally equivalent to the CORBA object Greeting described earlier.
SessionBean GreetingServer.GreetingBean { BeanHomeName = "Demo/MyGreeting"; RemoteInterfaceClassName = hello.Greeting; HomeInterfaceClassName = hello.GreetingHome; AllowedIdentities = { PUBLIC }; RunAsMode = CLIENT_IDENTITY; TransactionAttribute = TX_SUPPORTS; }
An EJB descriptor can be in any encoding supported by the JDK. However, only the AllowedIdentities field can be non-US7ASCII. There are two ways you can specify non-US7ASCII AllowedIdentities.
The implementation class for the EJB is in GreetingBean.java package GreetingServer;
import javax.ejb.SessionBean; import javax.ejb.CreateException; import javax.ejb.SessionContext; import java.rmi.RemoteException; public class GreetingBean implements SessionBean { // Methods of the Greeting interface public String Hello (String str) throws RemoteException { return "Hello" + str; } // Methods of the SessionBean public void ejbCreate () throws RemoteException, CreateException {} public void ejbRemove() {} public void setSessionContext (SessionContext ctx) {} public void ejbActivate () {} public void ejbPassivate () {} }
Note that all strings passed to the EJB as arguments and returned from the EJB as function values are UCS2 encoded Java strings.
An EJB resembles a CORBA object in that it is required to be published before being referenced. The EJB Home name specified in the EJB descriptor will be used to publish. For example:
deployejb -republish -temp temp -u scott -p tiger -encoding Unicode -s sess_iiop://local:2222:ORCL -descriptor Greeting.ejb server.jar
Because deployejb uses IIOP to connect to Oracle, the service name (-s) for the IIOP service of the database server has to be specified. Also, server.jar should contain the class files for the home interface object, remote interface object, and the bean implementation object of the EJB Greeting. Note that -encoding is required if the EJB descriptor file Greeting.ejb is in different encoding from the default encoding of the Java VM. In this example, the Greeting.ejb is a Unicode text file.
An EJB client is like a CORBA client in that it can be a Java program using Oracle's JNDI interface to authenticate a session and look for the EJB object in the database server. To look for the corresponding EJB object, the EJB client looks for the home interface object whose name is specified in the EJB descriptor and calls the create() method of this home interface object to create the EJB instance in the database server. Once the instance of the EJB is created, you can call the methods within it.
The following code shows how the EJB client calls the Hello() method of the EJB called "Demo/Greeting". It is functionally equivalent to the code of the CORBA Client in the previous section, but uses the explicit authentication mechanism.
import Demo.Greeting; //Remote interface object import Demo.GreetingHome; //Home interface object import javax.naming.*; import java.util.Hashtable; import oracle.aurora.jndi.sess_iiop.ServiceCtx; import oracle.aurora.client.*; public class Client { public static void main (String[] args) throws Exception { Hashtable environment = new Hashtable (); environment.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi"); Context ic = new InitialContext (environment); // Login to the 8i server LoginServer lserver = (LoginServer) ic.lookup ("sess_iiop://local:2222:ORCL/etc/login"); Login li = new Login (lserver) li.authenticate (username, password, null); // Activate a Greeting instance in the 8i server // This creates a first session in the server GreetingHome greetingHome = (GreetingHome) ic.lookup ("sess_iiop://local:2222:ORCL/Demo/MyGreeting"); Greeting greet = greetingHome.create (); System.out.println (greet.Hello (arg[0])); } }
Similar to the implicit authentication mechanism, the explicit authentication protocol, namely the li.authenticate() call, will automatically pass the default Java locale of the client to the LoginServer object in the database server. This Java locale will be used to initialize the Java locale of the server Java VM on which the EJB runs. In addition, the NLS_LANGUAGE and NLS_TERRITORY session parameters will be set to reflect this Java VM locale. This is to preserve the locale settings from EJB client to EJB server so that server uses the same language as the client.
To develop and deploy multilingual Java applications for Oracle8i, the database configurations and client environments for the targeted systems have to be determined first.
To choose a database character set for multilingual applications, the following should be considered.
To use a UTF8 database, consider the following design issues:
VARCHAR
(30) in the data dictionary, the strictest limit for the length of identifier names is 10 Unicode characters in any client character set.
For each Oracle8i session, a separate Java VM instance is created in the server for running the Java object, and Oracle8i Java support ensures that the locale of the Java VM instance is the same as that of the client Java VM. For non-Java clients, the default locale of the Java VM instance will be the best matched Java locale corresponding to the NLS_LANGUAGE and NLS_TERRITORY session parameters propagated from the client NLS_LANG environment variable.
Java objects in the database such as Java stored procedures, Java CORBA, and EJB objects are server objects which are accessible from clients of different language preferences, and therefore, should be internationalized in such a way that they are sensitive to the Java VM locale. For example, with JDK internationalization support, all localizable strings or objects from a Java stored procedure, Java CORBA object, or EJB should be externalized to resource bundles and make the resource bundles as part of the procedure, object, or EJB. With the use of resource bundles, any messages gotten back from the Java server objects will be in the language of the client locale. In addition to the resource bundles, all Java locale-sensitive classes such as date and time formats can be used with the assumption that they will reflect the locale of the calling client.
All Java server objects access the database with the JDBC Server driver and should use either a Java string or oracle.sql.CHAR to represent string data to and from the database. Java strings are always encoded in UCS2, and the required conversion from the database character set to UCS2 is transparently done as described previously. oracle.sql.CHAR stores the database data in byte array and tags it with a character set ID. It should be used when no string manipulation is required on the data. For example, oracle.sql.CHAR is the best choice for transferring string data from one table to another in the database.
When developing Java CORBA objects, the wstring data type should be used in the IDL as described in "Java CORBA Object" to ensure Unicode data is being passed from client to server.
Clients (or middle tiers) can be of different language preferences, database access mechanisms, and Java runtime environments. The following are several commonly used client configurations.
This section contains a simple bookstore application written in SQLJ to demonstrate a database storing book information of different languages, and how SQLJ and JDBC are used to access the book information from the database. It also demonstrates the use of internationalized Java stored procedures to accomplish transactional tasks in the database server. The demo program consists of the following components:
UTF8 is used as the database character set to store book information, such as names and authors, in languages around the world. The following tables in Figure 6-7 are defined for storing the book and inventory information of the store.
In addition, indexes are built with the NAME and AUTHOR columns of the BOOK table to speed up searching for books. A sequence BOOKSEQ will be created to generate a unique Book ID.
The Java class called Book is created to implement the methods Book.remove() and Book.add() that perform the tasks of removing books from and adding books to the inventory respectively. They are defined as per the following code. In this class, only the remove() method and the constructor are shown. The resource bundle BookRes.class is used to store localizable messages. The remove() method returns a message gotten from the resource bundle according to the current Java VM locale. There is no JDBC connection required to access the database since the stored procedure is already running in the context of a database session.
import java.sql.*; import java.util.*; import sqlj.runtime.ref.DefaultContext; /* The book class implementation the transaction logics of the Java stored procedures.*/ public class Book { static ResourceBundle rb; static int q, id; static DefaultContext ctx; public Book() { try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); DefaultContext.setDefaultContext(ctx); rb = java.util.ResourceBundle.getBundle("BookRes"); } catch (Exception e) { System.out.println("Transaction failed: " + e.getMessage()); } } public static String Remove(int id, int quantity, String location) throws SQLException { rb = ResourceBundle.getBundle("BookRes"); try { #sql {SELECT QUANTITY INTO :q FROM INVENTORY WHERE ID = :id AND LOCATION = :location}; if (id == 1) return rb.getString ("NotEnough"); } catch (Exception e) { return rb.getString ("NotEnough"); } if ((q - quantity) == 0) { #sql {DELETE FROM INVENTORY WHERE ID = :id AND LOCATION = :location}; try { #sql {SELECT SUM(QUANTITY) INTO :q FROM INVENTORY WHERE ID = :id}; } catch (Exception e) { #sql { DELETE FROM BOOK WHERE ID = :id }; return rb.getString("RemoveBook"); } return rb.getString("RemoveInventory"); } else { if ((q-quantity) < 0) return rb.getString ("NotEnough"); #sql { UPDATE INVENTORY SET QUANTITY = :(q-quantity) WHERE ID = :id and LOCATION = :location }; return rb.getString("DecreaseInventory"); } } public static String Add( String bname, String author, String location, double price, int quantity, String publishdate ) throws SQLException { rb = ResourceBundle.getBundle("BookRes"); try { #sql { SELECT ID into :id FROM BOOK WHERE NAME = :bname AND AUTHOR = :author }; } catch (Exception e) { #sql { SELECT BOOKSEQ.NEXTVAL INTO :id FROM DUAL }; #sql { INSERT INTO BOOK VALUES (:id, :bname, TO_DATE(:publishdate,'YYYY-MM-DD'), :author, :price) }; #sql { INSERT INTO INVENTORY VALUES (:id, :location, :quantity) }; return rb.getString("AddBook"); } try { #sql { SELECT QUANTITY INTO :q FROM INVENTORY WHERE ID = :id AND LOCATION = :location }; } catch (Exception e) { #sql { INSERT INTO INVENTORY VALUES (:id, :location, :quantity) }; return rb.getString("AddInventory"); } #sql { UPDATE INVENTORY SET QUANTITY = :(q + quantity) WHERE ID = :id AND LOCATION = :location }; return rb.getString("IncreaseInventory"); } }
Once the methods Book.remove() and Book.add() are defined, they are in turn published as Java stored functions in the database called REMOVEBOOK() and ADDBOOK() as follows:
CREATE FUNCTION REMOVEBOOK (ID NUMBER, QUANTITY NUMBER, LOCATION VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'Book.remove(int, int, java.lang.String) return java.lang.String'; CREATE FUNCTION ADDBOOK (NAME VARCHAR2, AUTHOR VARCHAR2, LOCATION VARCHAR2, PRICE NUMBER, QUANTITY NUMBER, PUBLISH_DATE DATE) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'Book.add(java.lang.String, java.lang.String, java.lang.String, double, int, java.sql.Date) return java.lang.String';
Note that the Java string returned will first be converted to a VARCHAR2 string, which is encoded in the database character set, before they are passed back to the client. If the database character is not UTF8, any Unicode characters in the Java strings that cannot be represented in the database character set will become "?". Similarly, the VARCHAR2 strings, which are encoded in the database character set, are converted to Java strings before being passed to the Java methods.
The SQLJ client is a GUI Java application using either a JDBC Thin or JDBC OCI driver. It connects the client to a database, displays a list of books given a searching criterion, removes selected books from the inventory, and adds new books to the inventory. A class called BookDB is created to accomplish these tasks, and it is defined in the following code.
A BookDB object is created when the demo program starts up with the user name, password and the location of the database, and the methods are called from the GUI portion of the applications. The methods removeBook() and addBook() call the corresponding Java stored functions in the database and return the status of the transaction. The methods searchByName() and searchByAuthor() list books by name and author respectively, and store the results in the iterator books (the BookRecs class is generated by SQLJ) inside the BookDB object. The GUI code in turn calls the getNextBook() function to retrieve the list of books from the iterator object until a NULL is returned. The getNextBook() function simply fetches the next row from the iterator.
package sqlj.bookstore; import java.sql.*; import sqlj.bookstore.BookDescription; import sqlj.runtime.ref.DefaultContext; import java.util.Locale; /*The iterator used for a book description when communicating with the server*/ #sql iterator BooksRecs( int ID, String NAME, String AUTHOR, Date PUBLISH_DATE, String LOCATION, int QUANTITY, double PRICE); /*This is the class used for connection to the server.*/ class BookDb { static public final String DRIVER = "oracle.jdbc.driver.OracleDriver"; static public final String URL_PREFIX = "jdbc:oracle:thin:@"; private DefaultContext m_ctx = null; private String msg; private BooksRecs books; /*Constructor - registers the driver*/ BookDb() { try { DriverManager.registerDriver ((Driver) (Class.forName(DRIVER).newInstance())); } catch (Exception e) { System.exit(1); } } /*Connect to the database.*/ DefaultContext connect(String id, String pwd, String userUrl) throws SQLException { String url = new String(URL_PREFIX); url = url.concat(userUrl); Connection conn = null; if (m_ctx != null) return m_ctx; try { conn = DriverManager.getConnection(url, id, pwd); } catch (SQLException e) { throw(e); } if (m_ctx == null) { try { m_ctx = new DefaultContext(conn); } catch (SQLException e) { throw(e); } } return m_ctx; } /*Add a new book to the database.*/ public String addBook(BookDescription book) { String name = book.getTitle(); String author = book.getAuthor(); String date = book.getPublishDateString(); String location = book.getLocation(); int quantity = book.getQuantity(); double price = book.getPrice(); try { #sql [m_ctx] msg = {VALUE ( ADDBOOK ( :name, :author, :location, :price, :quantity, :date))}; #sql [m_ctx] {COMMIT}; } catch (SQLException e) { return (e.getMessage()); } return msg; } /*Remove a book.*/ public String removeBook(int id, int quantity, String location) { try { #sql [m_ctx] msg = {VALUE ( REMOVEBOOK ( :id, :quantity, :location))}; #sql [m_ctx] {COMMIT}; } catch (SQLException e) { return (e.getMessage()); } return msg; } /*Search books by the given author.*/ public void searchByAuthor(String author) { String key = "%" + author + "%"; books = null; System.gc(); try { #sql [m_ctx] books = { SELECT BOOK.ID, NAME, AUTHOR, PUBLISH_DATE, LOCATION, QUANTITY, PRICE FROM BOOK, INVENTORY WHERE BOOK.ID = INVENTORY.ID AND AUTHOR LIKE :key ORDER BY BOOK.ID}; } catch (SQLException e) {} } /*Search books with the given title.*/ public void searchByTitle(String title) { String key = "%" + title + "%"; books = null; System.gc(); try { #sql [m_ctx] books = { SELECT BOOK.ID, NAME, AUTHOR, PUBLISH_DATE, LOCATION, QUANTITY, PRICE FROM BOOK, INVENTORY WHERE BOOK.ID = INVENTORY.ID AND NAME LIKE :key ORDER BY BOOK.ID}; } catch (SQLException e) {} } /*Returns the next BookDescription from the last search, null if at the end of the result list.*/ public BookDescription getNextBook() { BookDescription book = null; try { if (books.next()) { book = new BookDescription(books.ID(), books.AUTHOR(), books.NAME(), books.PUBLISH_DATE(), books.PRICE(), books.LOCATION(), books.QUANTITY()); } } catch (SQLException e) {} return book; } }
Oracle8i provides the infrastructure for a multi-tier computing environment to develop and deploy Java applications. JDBC and SQLJ are Java programmatic interfaces for database access used in clients, middle-tiers and servers. The Java VM, CORBA ORB, and EJB container bundled with the Oracle8i server provide a run-time environment for Java stored procedures, Java CORBA objects, and EJBs running in the server. Additionally, the CORBA ORB of Oracle8i can also be used as a middle tier to other CORBA servers.
The internationalization support in JDBC, SQLJ, Java VM, CORBA ORB, and EJBs and all the supporting services enables the development and deployment of multilingual Java applications for Oracle8i. The transparent conversions from a database character set to Unicode enables Java program to manipulate string data from the database in terms of Java strings. The locale of the clients are always preserved in the Java VM of the database server, and that enables the development of locale-sensitive Java stored procedures, Java CORBA objects, and EJBs by leveraging the current internationalization support of the JDK.
|
![]() Copyright © 1996-2000, Oracle Corporation. All Rights Reserved. |
|