AS400 Developer Kit for Java (Rzaha)

206
AS/400 Developer Kit for Java

Transcript of AS400 Developer Kit for Java (Rzaha)

Page 1: AS400 Developer Kit for Java (Rzaha)

AS/400 Developer Kit for Java

���

Page 2: AS400 Developer Kit for Java (Rzaha)
Page 3: AS400 Developer Kit for Java (Rzaha)

AS/400 Developer Kit for Java

���

Page 4: AS400 Developer Kit for Java (Rzaha)

© Copyright International Business Machines Corporation 1998, 1999. All rights reserved.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.

Page 5: AS400 Developer Kit for Java (Rzaha)

Contents

Chapter 1. AS/400 Developer Kit for Java 1Print this topic. . . . . . . . . . . . . . 2What’s new in V4R5 for AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . . 3

How to see what’s new or changed: . . . . . 3What’s new in V4R5 for Java Development Kit(JDK) 1.1.8 . . . . . . . . . . . . . . 3What’s new in V4R5 for Java 2 SoftwareDevelopment Kit (J2SDK), Standard Edition,version 1.2 . . . . . . . . . . . . . . 4

Chapter 2. Getting started with theAS/400 Developer Kit for Java . . . . . 7Installing the AS/400 Developer Kit for Java. . . . 7

Support for multiple Java Development Kits(JDKs) . . . . . . . . . . . . . . . 8

Configuring AS/400 for the AS/400 Developer Kitfor Java . . . . . . . . . . . . . . . . 9Running your first Hello World Java program . . . 10Creating, compiling, and running a Hello WorldJava program . . . . . . . . . . . . . . 10Creating and running Java programs with theAS/400 Developer Kit for Java . . . . . . . . 11

Java classpath . . . . . . . . . . . . 12Selecting which mode to use when running aJava program . . . . . . . . . . . . . 15

Creating and editing Java source files. . . . . . 16Downloading and installing Java packages onAS/400 . . . . . . . . . . . . . . . . 17Release to release compatibility . . . . . . . . 19

Chapter 3. AS/400 Developer Kit forJava concepts . . . . . . . . . . . 21Java transformer. . . . . . . . . . . . . 23AS/400 Developer Kit for Java advanced garbagecollection . . . . . . . . . . . . . . . 24

Java garbage collection . . . . . . . . . 24AS/400 Java runtime environment. . . . . . 25

AS/400 Developer Kit for Java Remote AbstractWindow Toolkit . . . . . . . . . . . . . 26AS/400 Developer Kit for Java Class Broker for Java 26Just-In-Time compiler . . . . . . . . . . . 27

Comparison of Just-In-Time compiler and directexecution . . . . . . . . . . . . . . 27

Comparison of Integrated Language Environmentand Java . . . . . . . . . . . . . . . 27Running Java in a batch job . . . . . . . . . 28Java classes, packages, and directories . . . . . 29Java system properties. . . . . . . . . . . 30

Java system properties for Java Development Kit(JDK) 1.1.8. . . . . . . . . . . . . . 30Java system properties for Java 2 SoftwareDevelopment Kit (J2SDK), Standard Edition,version 1.2. . . . . . . . . . . . . . 34

Files in the integrated file system . . . . . . . 40

Java file authorities in the integrated file system . . 41Java character encodings . . . . . . . . . . 41

File.encoding values and AS/400 CCSID . . . 42Java Naming and Directory Interface . . . . . . 47Java Virtual Machine Debug Interface . . . . . 48Limitations, restrictions, and unique behaviors . . 48The Java platform . . . . . . . . . . . . 49

Java applications and applets . . . . . . . 50Java virtual machine . . . . . . . . . . 50Java class files . . . . . . . . . . . . 51Java ZIP files . . . . . . . . . . . . . 51Java JAR files. . . . . . . . . . . . . 51Java interpreter . . . . . . . . . . . . 52Java threads . . . . . . . . . . . . . 52

Sun Microsystems, Inc. Java Development Kit . . . 53Java packages . . . . . . . . . . . . 54Java tools . . . . . . . . . . . . . . 55Native methods and the Java Native Interface . . 55

Chapter 4. Commands and tools for theAS/400 Developer Kit for Java. . . . . 57Java tools that are supported by the AS/400Developer Kit for Java . . . . . . . . . . . 57

Java ajar tool . . . . . . . . . . . . . 58Java appletviewer tool . . . . . . . . . . 58Running the Java appletviewer tool with RemoteAbstract Window Toolkit . . . . . . . . . 59Java extcheck tool . . . . . . . . . . . 59Java jar tool . . . . . . . . . . . . . 59Java jarsigner tool . . . . . . . . . . . 60Java javac tool . . . . . . . . . . . . 60Java javadoc tool . . . . . . . . . . . 60Java javah tool . . . . . . . . . . . . 61Java javakey tool . . . . . . . . . . . 61Java javap tool . . . . . . . . . . . . 62Java keytool . . . . . . . . . . . . . 62Java native2ascii tool . . . . . . . . . . 63Java policytool . . . . . . . . . . . . 63Java rmic tool . . . . . . . . . . . . 63Java rmid tool . . . . . . . . . . . . 64Java rmiregistry tool . . . . . . . . . . 64Java serialver tool . . . . . . . . . . . 64Java tnameserv tool. . . . . . . . . . . 64Java command in Qshell . . . . . . . . . 65

CL commands that are supported by Java . . . . 66Create Java Program (CRTJVAPGM) command 66Change Java Program (CHGJVAPGM) command 75JAVA command . . . . . . . . . . . . 79Run Java (RUNJVA) command . . . . . . . 79Delete Java Program (DLTJVAPGM) command . 85Dump Java Virtual Machine (DMPJVM)command . . . . . . . . . . . . . . 86Display Java Program (DSPJVAPGM) command 89

Operations Navigator commands that are supportedby Java . . . . . . . . . . . . . . . . 93

© Copyright IBM Corp. 1998, 1999 iii

Page 6: AS400 Developer Kit for Java (Rzaha)

Chapter 5. Using Java with otherprogramming languages . . . . . . . 95Using the Java Native Interface for native methods 96

Java native methods and threads considerations 98Strings in native methods. . . . . . . . . 99Examples: Using the Java Native Interface fornative methods . . . . . . . . . . . . 101

Using java.lang.Runtime.exec() . . . . . . . 105Example: Calling another Java program withjava.lang.Runtime.exec() . . . . . . . . . 106Example: Calling a CL program withjava.lang.Runtime.exec() . . . . . . . . . 107Example: Calling a CL command withjava.lang.Runtime.exec() . . . . . . . . . 107

Interprocess communication examples . . . . . 108Using sockets for interprocess communication 108Using input and output streams for interprocesscommunication . . . . . . . . . . . . 111Calling Java from other languages . . . . . 113

Java Invocation API . . . . . . . . . . . 114Invocation API functions . . . . . . . . 115Support for multiple Java virtual machines . . 117Example: Java Invocation API . . . . . . . 117

Chapter 6. Accessing your AS/400database with the AS/400 DeveloperKit for Java JDBC driver . . . . . . 121Registering the AS/400 Developer Kit for JavaJDBC driver before using JDBC . . . . . . . 122Connecting to an AS/400 database using theAS/400 Developer Kit for Java JDBC driver . . . 123

Examples: Connecting to an AS/400 databaseusing the AS/400 Developer Kit for Java JDBCdriver . . . . . . . . . . . . . . . 123

Creating a JDBC application . . . . . . . . 124Example: Creating a JDBC application . . . . 124

Statement interface for AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . 126

Example: Statement interface for AS/400Developer Kit for Java . . . . . . . . . 126

PreparedStatement interface for AS/400 DeveloperKit for Java . . . . . . . . . . . . . . 127

Example: PreparedStatement interface forAS/400 Developer Kit for Java . . . . . . 127

CallableStatement interface for AS/400 DeveloperKit for Java . . . . . . . . . . . . . . 128

Example: CallableStatement interface for AS/400Developer Kit for Java . . . . . . . . . 128

ResultSet interface for AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . 128

Example: ResultSet interface for AS/400Developer Kit for Java . . . . . . . . . 129

DatabaseMetaData interface for AS/400 DeveloperKit for Java . . . . . . . . . . . . . . 129

Example: DatabaseMetaData interface forAS/400 Developer Kit for Java . . . . . . 130

Blob interface for the AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . 130Clob interface for the AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . 131

Chapter 7. Accessing databases usingAS/400 Developer Kit for Java DB2SQLJ support . . . . . . . . . . . 133SQLJ tools . . . . . . . . . . . . . . 133DB2 SQLJ restrictions. . . . . . . . . . . 133Embedding SQL statements in your Javaapplication . . . . . . . . . . . . . . 134Compiling and running SQLJ programs . . . . 135

Host variables in Structured Query Languagefor Java . . . . . . . . . . . . . . 136Structured Query Language for Java profiles 136

The structured query language for Java (SQLJ)translator (sqlj) . . . . . . . . . . . . . 139Precompiling SQL statements in a profile using theDB2 SQLJ profile customizer, db2profc . . . . . 139Printing the contents of DB2 SQLJ profiles(db2profp and profp) . . . . . . . . . . . 143The SQLJ profile auditor installer (profdb). . . . 143Converting a serialized profile instance to Javaclass format using the SQLJ profile conversion tool(profconv) . . . . . . . . . . . . . . 144

Chapter 8. Running your Javaapplication on a host that does nothave a graphical user interface. . . . 145Setting up the Remote Abstract Window Toolkit forJava on a remote display . . . . . . . . . 145

Example: Setting up the Remote AbstractWindow Toolkit for Java on a Windows remotedisplay . . . . . . . . . . . . . . 146Making the Remote Abstract Window Toolkitfor Java class files accessible to the remotedisplay . . . . . . . . . . . . . . 147Adding RAWTGui.zip or RAWTGui.jar to theCLASSPATH of the remote display . . . . . 147Starting the Remote Abstract Window Toolkitfor Java on a remote display . . . . . . . 148Running a Java program using Remote AbstractWindow Toolkit . . . . . . . . . . . 149Printing with the Remote Abstract WindowToolkit. . . . . . . . . . . . . . . 151Remote Abstract Window Toolkit properties . . 151Remote Abstract Window ToolkitSecurityManager restrictions . . . . . . . 152

Setting up the Class Broker for Java on a remotedisplay . . . . . . . . . . . . . . . 152

Installing Class Broker for Java on AS/400 . . 153Installing Class Broker for Java on Windows orUNIX . . . . . . . . . . . . . . . 153Package content of cbj_1.1.jar . . . . . . . 154

Chapter 9. Java security. . . . . . . 157Java security model . . . . . . . . . . . 157Making a Java application secure with securesockets layer . . . . . . . . . . . . . 158

Preparing AS/400 for secure sockets layersupport . . . . . . . . . . . . . . 158Choosing a digital certificate to use . . . . . 160Using the digital certificate when you run yourJava application . . . . . . . . . . . 160

iv AS/400 Developer Kit for Java

Page 7: AS400 Developer Kit for Java (Rzaha)

Modifying your Java code to use socketfactories . . . . . . . . . . . . . . 162Modifying your Java code to use secure socketslayer . . . . . . . . . . . . . . . 165

Chapter 10. Creating aninternationalized Java program. . . . 169Java locales . . . . . . . . . . . . . . 169Example: Internationalization of dates using thejava.util.DateFormat class . . . . . . . . . 171Example: Internationalization of numeric displayusing the java.util.NumberFormat class. . . . . 171Example: Internationalization of locale-specific datausing the java.util.ResourceBundle class . . . . 172

Chapter 11. Tuning Java programperformance with the AS/400Developer Kit for Java . . . . . . . 175Java runtime performance considerations . . . . 176Java transformation performance considerations 176Java garbage collection performance considerations 177Java Native Method Invocation performanceconsiderations . . . . . . . . . . . . . 177Java method inlining performance considerations 177Java exception performance considerations . . . 178Java event trace performance tools . . . . . . 178Java call trace performance tools . . . . . . . 178Java profiling performance tools . . . . . . . 179

Collecting Java performance data. . . . . . 179

Performance Data Collector tool . . . . . . . 180Java Performance Data Converter tool . . . . 181Running the Java Performance Data Converter 181

Chapter 12. Debugging programsusing the AS/400 Developer Kit forJava . . . . . . . . . . . . . . . 183Debugging a Java program . . . . . . . . . 183

Debugging Java programs by using the *DEBUGoption . . . . . . . . . . . . . . . 184Initial debugging displays for Java programs 184Setting breakpoints . . . . . . . . . . 185Stepping through Java programs to debug. . . 186

Debugging Java and native method programs . . 188Debugging a Java program from another display 188

QIBM_CHILD_JOB_SNDINQMSG environmentvariable . . . . . . . . . . . . . . 189

Debugging servlets . . . . . . . . . . . 190

Chapter 13. Troubleshooting theAS/400 Developer Kit for Java . . . . 191Finding job logs for Java problem analysis. . . . 191Collecting data for Java problem analysis . . . . 192Getting support for the AS/400 Developer Kit forJava . . . . . . . . . . . . . . . . 193

Chapter 14. Code examples for theAS/400 Developer Kit for Java . . . . 195

Contents v

Page 8: AS400 Developer Kit for Java (Rzaha)

vi AS/400 Developer Kit for Java

Page 9: AS400 Developer Kit for Java (Rzaha)

Chapter 1. AS/400 Developer Kit for Java

What it is:

The AS/400 Developer Kit for Java is optimized for use in an AS/400 serverenvironment. It utilizes the compatibility of Java programming and user interfaces,so you can develop your own applications for the AS/400 system.

The AS/400 Developer Kit for Java allows you to create and run Java programs onAS/400. The AS/400 Developer Kit for Java is a compatible implementation of theSun Microsystems, Inc. Java Technology, so we assume that you are familiar withtheir Java Development Kit (JDK) documentation. To make it easier for you towork with their information and ours, we provide links to Sun Microsystems,Inc.’s information.

If for any reason our links to Sun Microsystems, Inc. Java Development Kitdocumentation do not work, refer to their HTML reference documentation for theinformation that you need. You can find this information on the World Wide Web

at The Source for Java Technology java.sun.com.

How to use these pages:

Select any of these topics for more details on how to use the AS/400 Developer Kitfor Java:v Print this topic provides details on how to download a printable PDF file or a

zipped package of AS/400 Developer Kit for Java HTML files.v What’s new in V4R5 highlights the latest product and information updates.v Getting started gives information about installation, configuration, how to create

and run simple Hello World Java programs, downloading and installing, andrelease to release compatibility.

v Concepts introduces the specific concepts that you should be familiar with whenusing the AS/400 Developer Kit for Java. Also provides very basic Javadefinitions for those who are looking for general details.

v Commands and tools provides details on how to use the Java commands andJava tools.

v Other programming languages shows you how to call code that was written inlanguages other than Java by using Java Native Interface (JNI),java.lang.Runtime.exec(), interprocess communication, and the Java InvocationAPI.

v JDBC driver explains how the AS/400 Developer Kit for Java JDBC driverallows Java programs to access AS/400 database files.

v SQLJ support explains how the AS/400 Developer Kit for Java allows you to useSQL statements that are embedded in your Java application.

© Copyright IBM Corp. 1998, 1999 1

Page 10: AS400 Developer Kit for Java (Rzaha)

v Running on a host without a GUI contains information about how to set up andrun Java programs with the Remote Abstract Window Toolkit (AWT) or ClassBroker for Java.

v Security provides details on adopted authority and explains how you can useSSL to make socket streams secure in your Java application.

v Internationalization gives instructions on how to customize a Java program for aspecific region of the world.

v Performance provides information about how to tune your Java performance.v Debugging explains how to debug Java programs.v Troubleshooting shows you how to find job logs and collect data for Java

program analysis. This topic also provides information about programtemporary fixes (PTFs) and getting support for the AS/400 Developer Kit forJava.

v Code examples links directly to all of the code examples in this information.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Print this topicYou can view or download a PDF version of this document for viewing orprinting. You must have Adobe(R) Acrobat(R) Reader installed to view PDF files.

You can download a copy from Adobe .

To view or download the PDF version, select AS/400 Developer Kit for Java (about943 KB or 176 pages).

To save a PDF on your workstation for viewing or printing:1. Open the PDF in your browser (click the link above).2. In the menu of your browser, click File.3. Click Save As...

4. Navigate to the directory in which you would like to save the PDF.5. Click Save.

Download a zipped package of this document

To download a zipped package of the AS/400 Developer Kit for Java HTML filesto your workstation:1. Ensure your hard drive has at least 5.0 MB of storage space:2. Create a new directory on your hard drive.3. Download the package. The package size is about 412 KB.

a. Select the Save to disk option.b. Select a temporary directory as the destination for the download.c. Click OK.

4. Unzip the package into the directory you created in step 2.5. Open devkit.htm with your browser to view the reference.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

2 AS/400 Developer Kit for Java

Page 11: AS400 Developer Kit for Java (Rzaha)

What’s new in V4R5 for AS/400 Developer Kit for Java

This topic highlights changes to the AS/400 Developer Kit for Java in V4R5.We highlight Java Development Kit (JDK) 1.1.8 and Java 2 Software Development

Kit (J2SDK), Standard Edition, version 1.2 changes. If you are already familiarwith this information, you can link to the version of your choice for new updates:v Java Development Kit (JDK) 1.1.8v Java 2 Software Development Kit (J2SDK), Standard Edition, version 1.2

How to see where you are in our information:

The small links at the top of each page show you where you are in ourinformation. These links are displayed in a directory structure format. To see whereyou are, read through the links. For example, if you look at the top of this page,you see:

AS/400 Developer Kit for Java \ What’s new

These links tell you that you are in the “What’s new” information under the“AS/400 Developer Kit for Java” topic.

How to see what’s new or changed:To help you see where technical changes have been made, this information uses:

v The image to mark where new or changed information begins.

v The image to mark where new or changed information ends.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

What’s new in V4R5 for Java Development Kit (JDK) 1.1.8This topic highlights changes to the AS/400 Developer Kit for Java in V4R5 for theJava Development Kit (JDK) 1.1.8.

Getting started:

v See multiple JDK support for information on each JDK that IBM supports.v See Java classpath for details on how to properly set your classpath for JDK 1.1.x

or J2SDK.

Tools and commands:

v The Java ajar tool was added to the list of Java tools that are supported by theAS/400 Developer Kit for Java.

v See the Java appletviewer tool for new details about how to run theappletviewer tool with Remote Abstract Window Toolkit.

v The new Dump Java Virtual Machine (DMPJVM) command was added to dumpinformation about the Java virtual machine for a job that you specify.

v The TGTRLS parameter was added to the Create Java Program (CRTJVAPGM)command.

v The SUBTREE parameter was added to the Change Java Program(CHGJVAPGM) command.

Chapter 1. AS/400 Developer Kit for Java 3

Page 12: AS400 Developer Kit for Java (Rzaha)

v The JIT option was added to the OPTIMIZE parameter and the INTERPRETparameter of the Run Java (RUNJVA) command.

v A display example with descriptions of each field was added to the Display JavaProgram (DSPJVAPGM) command.

Running on a host without a GUI:

v

See the setting up the Remote Abstract Window Toolkit topic for updates.v

If you want to run your Java application on a host that does not have agraphical user interface (GUI), such as an AS/400 system, you can use either theRemote Abstract Window Toolkit (AWT) or the Class Broker for Java (CBJ). Youcan use the CBJ for high performance GUI services. Since Remote AWT is notrecommended for complex graphics or highly-interactive operations, you can usethe CBJ instead, which was designed for these environments. To use CBJ, seesetting up Class Broker for Java.

Debugging:

v Added details about how to debug servlets.

Code examples:

v More code examples were added.

Print this topic:

v See print this topic for a PDF of the AS/400 Developer Kit for Java information.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

What’s new in V4R5 for Java 2 Software Development Kit(J2SDK), Standard Edition, version 1.2

This topic highlights changes to the AS/400 Developer Kit for Java in V4R5 for theJava 2 Software Development Kit (J2SDK), Standard Edition, version 1.2.

Note: In this section, we only discuss changes that are unique or interesting in theJ2SDK, version 1.2. The general information on updates from the What’s new forJava Development Kit (JDK) 1.1.8 topic also apply to J2SDK, version 1.2.

Getting started:

v See multiple JDK support for information on each JDK that IBM supports.v See Java classpath for details on how to properly set your classpath for JDK 1.1.x

or J2SDK.v The selecting which mode to use when running a Java program topic was added

to explain the difference between running a Java program with interpreted,direct execution, or Just-In-Time compile.

v For information about the Java extensions framework, see downloading andinstalling Java packages on AS/400 and installing extensions for the AS/400Developer Kit for Java.

Concepts:

v See Class Broker for Java for overview information on how to run Javaapplications on a host that does not have a graphical user interface (GUI).

v Support for a Just-In-Time compiler that improves performance by compilingcode as you need it was added.

4 AS/400 Developer Kit for Java

Page 13: AS400 Developer Kit for Java (Rzaha)

v New system properties for J2SDK were added.v Support for the Java Virtual Machine Debug Interface was added.

Commands and tools:

v See the Java appletviewer tool for new details about how to run theappletviewer tool with Remote Abstract Window Toolkit.

v The Java extcheck tool, Java jarsigner tool, Java keytool, Java policytool, Javarmid tool, and the Java tnameserv tool were added to the list of Java tools thatare supported by the AS/400 Developer Kit for Java.

v The Java javakey tool is now obsolete in J2SDK, version 1.2.

Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support

v The accessing databases using AS/400 Developer Kit for Java DB2 SQLJ supportinformation has been revised.

v The SQLJ translator tool allows you to generate SQLJ profiles from your Javasource code.

v The DB2 SQLJ profile customizer allows you to customize SQLJ profiles.v The DB2 SQLJ profile printer tool allows you to print SQLJ profiles.v The SQLJ profile auditor installer tool allows you to install SQLJ profile autitors

over your SQLJ profiles.v The SQLJ profile conversion tool allows you to convert a serialized profile

instance to Java class format.v Embedding SQL Statements in your Java application shows you how you can

embed SQL statements into your Java source code.v Compiling and running SQLJ Programs shows you how to compile and run

your SQLJ programs.

Running on a host without a GUI:

v

See the setting up the Remote Abstract Window Toolkit topic for updates.v

If you want to run your Java application on a host that does not have agraphical user interface (GUI), such as an AS/400 system, you can use either theRemote Abstract Window Toolkit (AWT) or the Class Broker for Java (CBJ). Youcan use the CBJ for high performance GUI services. Since Remote AWT is notrecommended for complex graphics or highly-interactive operations, you can usethe CBJ instead, which was designed for these environments. To use CBJ, seesetting up Class Broker for Java.

Debugging:

v Added details about how to debug servlets.

Code examples:

v More code examples were added.

Print this topic:

v See print this topic for a PDF of the AS/400 Developer Kit for Java information.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 1. AS/400 Developer Kit for Java 5

Page 14: AS400 Developer Kit for Java (Rzaha)

6 AS/400 Developer Kit for Java

Page 15: AS400 Developer Kit for Java (Rzaha)

Chapter 2. Getting started with the AS/400 Developer Kit forJava

If you have not yet used the AS/400 Developer Kit for Java, follow these steps toinstall it, configure it, and practice running a simple Hello World Java program.1. If you are already familiar with the AS/400 Developer Kit for Java information,

see what’s new for links to the latest product updates and information.2. Install the AS/400 Developer Kit for Java.3. Configure your system.4. If you are new to this information and have not yet used the AS/400 Developer

Kit for Java, see Running your first Hello World Java program. This topicillustrates two methods of running a simple Hello World Java program with theAS/400 Developer Kit for Java. It is a convenient way to see if you havecorrectly installed the AS/400 Developer Kit for Java.

5. Now you are ready to create, compile and run your own Hello World Javaprogram. For how-to steps, see creating, compiling, and running a Hello WorldJava program.

6. If you are interested in creating more of your own Java applications, read thesetopics:v Creating and running programs provides step-by-step instructions on how to

create and run your own Java programs.v Creating and editing Java source files shows three different ways that you

can create and edit your Java source files.v Downloading and installing Java packages on AS/400 helps you use Java

packages more effectively. It provides details about packages with graphicaluser interface (GUI), integrated file system and case sensitivity, as well as ZIPfile handling and JAR file handling.

v Release to release compatibility provides information on compatibility fromone release to another.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Installing the AS/400 Developer Kit for JavaInstalling the AS/400 Developer Kit for Java allows you to create and run Javaprograms on AS/400.

To install the AS/400 Developer Kit for Java:1. Enter the Go Licensed Program (GO LICPGM) command on the command line.2. Select option 11 (Install licensed program).3. Choose option 1 (Install) for licensed program (LP) 5769-JV1 *BASE, and select

the option that matches the Java Development Kit (JDK) that you want toinstall. If the option that you wish to install is not displayed in the list, you canadd it to the list by entering option 1 (Install) in the option field. Enter 5769JV1in the licensed program field and your option number in the product optionfield. IBM supports multiple JDKs.Note: You can install more than one option at once.

© Copyright IBM Corp. 1998, 1999 7

Page 16: AS400 Developer Kit for Java (Rzaha)

The AS/400 Developer Kit is licensed program (LP) number 5769-JV1.

Once you have installed the AS/400 Developer Kit for Java on your AS/400, youmay choose to configure your system.

See running your first Hello World Java program for information on getting startedwith the AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Support for multiple Java Development Kits (JDKs)AS/400 supports multiple Java Development Kits (JDKs) and Java 2 SDK (J2SDK),Standard Edition, version 1.2. AS/400 supports the use of multiple JDKssimultaneously, but only through multiple Java virtual machines. A single Javavirtual machine runs one specified JDK.

Find the JDK that you are using or want to use, and select the coordinating optionto install. You can install more than one JDK at one time. The java.version systemproperty determines which JDK to run. However, when you change thejava.version system property it has no effect once a Java virtual machine is up andrunning.

Option JDK java.home java.version1 1.1.6 /QIBM/ProdData/Java400/jdk116/1.1.62 1.1.7 /QIBM/ProdData/Java400/jdk117/1.1.73 1.2* /QIBM/ProdData/Java400/jdk12/1.2

4 1.1.8/QIBM/ProdData/Java400/jdk118/

1.1.8

* Version 1.2 is the same as Java 2 SDK (J2SDK), Standard Edition, version 1.2.

For example, these are the results of which options you install and the commandyou enter.

Install Enter ResultOption 1 (1.1.6) java Hello JDK 1.1.6 runs, because only

one JDK is installed and thatis your default.

Option 1 (1.1.6) java -Djava.version=1.1.7Hello

Error stating that Option 2 isnot installed.

Option 1 (1.1.6) and Option 2(1.1.7) and Option 4 (1.1.8)

java Hello JDK 1.1.8 runs, because themost recent JDK 1.1.x is thedefault.

Option 1 (1.1.6) and Option 2(1.1.7) and Option 4 (1.1.8)

java -Djava.version=1.1.7Hello

JDK 1.1.7 runs.

8 AS/400 Developer Kit for Java

Page 17: AS400 Developer Kit for Java (Rzaha)

Option 1 (1.1.6), Option 2(1.1.7), and Option 3 (1.2)

java -Djava.version=1.2Hello

J2SDK, Standard Edition,version 1.2 runs. If you didnot specify java.version, thelatest 1.1.x (for example, JDK1.1.7) is the default. For moredetails on the java.versionproperty, see Java systemproperties.

Option 3 (1.2) java Hello J2SDK, Standard Edition,version 1.2 runs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Configuring AS/400 for the AS/400 Developer Kit for JavaOnce you have installed the AS/400 Developer Kit for Java on your AS/400, youmay choose to configure your system.

Time zone configuration

If your Java programs are sensitive to time of day, then time zone configurationmay be required.

If the Coordinated Universal Time Offset (QUTCOFFSET) system value is set to itsdefault (+00:00), then Java uses the AS/400 time as the current time. The defaultvalue of the user.timezone Java system property setting is UTC.

A QUTCOFFSET system value and an updated locale are required for any of these:v If QUTCOFFSET is not set to its default value, thus sensitive to time zone.v If your Java code expects the user.timezone system property to default to a value

other than UTC.v If you specify the user.timezone Java system property when running the java

command.

The LC_TOD category of the locale contains the tname field, which must be set tothe same value that matches your time zone. For details on how to create a localeand format the tname field, see the AS/400 International Application Development,

SC41-5603 book.

System property configuration

Java system properties determine the environment in which the Java programs run.They are similar to system values or environment variables in OS/400. A numberof properties are set when the Java virtual machine starts. You can choose to usethe system property default values or you can specify your own set of defaultproperty values by doing either of these steps:1. Provide a file in /QIBM/UserData/Java400, named SystemDefault.properties.

The property values that you specify in this file override the system defaultsthat IBM provides. This file sets the default system properties for all Javavirtual machines that run on your AS/400 system.

2. Or, place a SystemDefault.properties file in your own user.home path. This fileand the properties that it contains override those in

Chapter 2. Getting started with the AS/400 Developer Kit for Java 9

Page 18: AS400 Developer Kit for Java (Rzaha)

/QIBM/UserData/Java400/SystemDefault.properties. This file sets the defaultsystem properties for all Java virtual machines that run for you.

See running your first Hello World Java program for information on getting startedwith the AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Running your first Hello World Java programYou can get your Hello World Java program up and running in either of theseways:1. You can simply run the Hello World Java program that was shipped with the

AS/400 Developer Kit for Java in the com.ibm.as400.system package.To run the program that is included:a. Check that the AS/400 Developer Kit for Java is installed by entering the

Go Licensed Program (GO LICPGM) command. Then, select option 10(Displayed installed licensed programs). Verify that licensed program5769-JV1 *BASE and at least one of the options are listed as installed.

b. Enter java com.ibm.as400.system.Hello on the AS/400 Main Menucommand line. Press Enter to run the Hello World Java program.

c. If the AS/400 Developer Kit for Java was installed correctly, Hello Worldappears in the Java Shell Display. Press F3 (Exit) or F12 (Exit) to return tothe command entry display.

d. If the Hello World class does not run, check to see that the installation wascompleted successfully, or see getting support for the AS/400 Developer Kitfor Java for service information.

2. You can also run your own Hello Java program. For more information abouthow to create your own Hello Java program, see creating, compiling, andrunning a Hello World Java program.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Creating, compiling, and running a Hello World Java programCreating the simple, Hello World Java program is a great place to start whenbecoming familiar with the AS/400 Developer Kit for Java.

To create, compile, and run your own Hello World Java program:1. Create the source file as an American National Standard Code for Information

Interchange (ASCII) text file in the integrated file system.a. Name your text file Hello.java. For more information about how you can

create and edit your file, see creating and editing Java source files.b. Make sure that your file contains this source code:

class Hello {public static void main (String args[]) {

System.out.println(“Hello World”);}

}

2. Compile the source file.

10 AS/400 Developer Kit for Java

Page 19: AS400 Developer Kit for Java (Rzaha)

a. Enter the Work with Environment Variable (WRKENVVAR) command tocheck the CLASSPATH environment variable. If the CLASSPATH variabledoes not exist, add it and set it to ’.’ (the current directory). If theCLASSPATH variable does exist, make sure that the ’.’ is at the beginning ofthe path name list. For details about the CLASSPATH environment variable,see Java classpath.

b. Enter the Start Qshell (STRQSH) command to start the Qshell Interpreter.c. Use the change directory (cd) command to change the current directory to

the integrated file system directory that contains the Hello.java file.d. Enter javac followed by the name of the file as you have it saved on your

disk. For example, enter javac Hello.java.3. Run the class file.

a. Enter java followed by Hello to run your Hello.class with the Java virtualmachine. For example, enter java Hello.

b. “Hello World” prints to your screen if everything was entered correctly.c. Press F3 (Exit) or F12 (Disconnect) to return to the command entry display.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Creating and running Java programs with the AS/400 Developer Kit forJava

You can create Java application and applet programs by using the AS/400Developer Kit for Java. You can also use Sun Microsystems, Inc. Java DevelopmentKit (JDK) that is available on a workstation.

To create a Java program:1. Create a source code file by using an editor that supports American National

Standard Code for Information Interchange (ASCII) text files.2. Compile the source file into a class file by using the Java compiler tool, which

is javac.Note: Java class files are portable across platforms, so the Java source file cancompile on a workstation that also has a javac. After the source files arecompiled, the class files are transferred to the integrated file system.

3. Set the file authorities on the class file in the integrated file system.4. Optimize the Java program by using the Create Java Program (CRTJVAPGM)

command.Note: This step is optional.

To run a Java program:1. Ensure that your Java classpath is set up correctly.2. Use the Run Java (RUNJVA) command or JAVA command on AS/400, or the

java command in Qshell to run the Java program. Then, select which modeyou want to use to run your Java program. You can either set the mode bysetting a system property with the Java command, or by setting theenvironment variable before you run the Java command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 2. Getting started with the AS/400 Developer Kit for Java 11

Page 20: AS400 Developer Kit for Java (Rzaha)

Java classpathThe Java virtual machine uses the Java classpath to find classes during runtime.Java commands and tools also use the classpath to locate classes. The defaultsystem classpath, the CLASSPATH environment variable, and the classpathcommand parameter all determine what directories are searched when looking fora particular class.

Note: In In Java 2 Software Development Kit (J2SDK), Standard Edition,version 1.2, the java.ext.dirs property determines the classpath for the extensionsthat will be loaded. See Installing extensions for the AS/400 Developer Kit for Java

for more information.

The default system classpath is system-defined and you cannot change it. OnAS/400, the default classpath specifies where to find the classes that are part of theAS/400 Developer Kit, the Remote Abstract Window Toolkit (AWT), and othersystem classes.

To find any other classes on the system, you must specify the classpath to searchby using the CLASSPATH environment variable or the classpath parameter. Theclasspath parameter that is used on a tool or command overrides the value that isspecified in the CLASSPATH environment variable.

You can work with the CLASSPATH environment variable using the Work withEnvironment Variable (WRKENVVAR) command. From the WRKENVVAR display,you can add or change the CLASSPATH environment variable. The AddEnvironment Variable (ADDENVVAR) command and Change EnvironmentVariable (CHGENVVAR) command either add or change the CLASSPATHenvironment variable.

The value of the CLASSPATH environment variable is a list of path names,separated by colons(:), which are searched to find a particular class. A path name isa sequence of zero or more directory names. These directory names are followedby the name of the directory, the ZIP file, or the JAR file that is to be searched inthe integrated file system. The components of the path name are separated by theslash (/) character. Use a period (.) to indicate the current working directory.

You can set the CLASSPATH variable in the Qshell environment by using theexport utility that is available using the Qshell Interpreter.

These commands add the CLASSPATH variable to your environment and set it tothe value “ .:/myclasses.zip:/Product/classes.”

v This command sets the CLASSPATH variable in the Qshell environment:export -s CLASSPATH=.:/myclasses.zip:/Product/classes

v This command sets the CLASSPATH variable from the command line:ADDENVVAR ENVVAR(CLASSPATH) VALUE(“.:/myclasses.zip:/Product/classes”)

J2SDK searches for classes differently than JDK 1.1.x. JDK 1.1.x searches the systemclasspath first, then any user-specified classpaths. J2SDK searches the bootstrapclasspath first, then the extension directories, then the classpath.

So, the search order for JDK 1.1.x, using the example code above, is:1. The default system classpath,2. The current working directory,

12 AS/400 Developer Kit for Java

Page 21: AS400 Developer Kit for Java (Rzaha)

3. The myclasses.zip file that is located in the “root” (/) file system,4. The classes directory in the Product directory in the “root” (/) file system.

The search order for J2SDK, using the example code above, is:1. The bootstrap classpath, which is in the sun.boot.class.path property,2. The extension directories, which is in the java.ext.dirs property,3. The default system classpath,4. The current working directory,5. The myclasses.zip file that is located in the “root” (/) file system,

6. The classes directory in the Product directory in the “root” (/) file system.

When entering the Qshell environment, the CLASSPATH variable is set to theenvironment variable. The classpath parameter specifies a list of path names. It hasthe same syntax as the CLASSPATH environment variable. A classpath parameteris available on these tools and commands:v java command in Qshellv javac toolv javah toolv javap toolv javadoc toolv rmic toolv Run Java (RUNJVA) command

For more information about the above commands, see commands and tools. If youuse the classpath parameter with any of these command or tools, it ignores theCLASSPATH environment variable.

You can override the CLASSPATH environment variable by using thejava.class.path property. You can change the java.class.path property, as well asother properties, by using the SystemDefault.properties file. The values in theSystemDefault.properties files override the CLASSPATH environment variable. Forinformation on the SystemDefault.properties file, see The SystemDefault.propertiesfile.

In JDK 1.1.x, the os400.class.path.system property also affects what is searchedwhen looking for classes. This property can contain one of three values: PRE,POST, or NONE. By default, this property is set to PRE, which causes the defaultsystem classpath to be searched before the path. The CLASSPATH environmentvariable or the classpath parameter specify this path. If you set theos400.class.path.system property to POST, the default system classpath is searchedafter any user-specified classpath. If the value NONE is used, the default classpath

is not searched at all and only the user-specified classpath is searched.

Note: Use caution when specifying NONE or POST because unpredictable resultsoccur if a system class cannot be found or is incorrectly replaced by a user-definedclass. Therefore, you should allow the system default classpath to be searchedbefore any user-specified classpath.

See Java system properties for information about how to determine theenvironment in which Java programs run.

Chapter 2. Getting started with the AS/400 Developer Kit for Java 13

Page 22: AS400 Developer Kit for Java (Rzaha)

For more information, see the OS/400 Program and CL Command APIs, SC41-5870

book or the OS/400 Integrated File System Introduction.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

SystemDefault.properties fileThe SystemDefault.properties file is a standard Java properties file. You can

specify default properties in a SystemDefault.properties file. TheSystemDefault.properties file that is in your home directory takes priority over theSystemDefault.properties file that is in the /QIBM/UserData/Java400 directory.

You can specify the values of properties in the SystemDefault.properties file justlike you do in any Java properties file.

Example: SystemDefault.properties file#Comments start with pound sign#this means always run with JDK 1.2java.version=1.2#set my special propertymyown.propname=6

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Installing extensions for the AS/400 Developer Kit for JavaExtensions are packages of Java classes that you can use to extend the

functionality of the core platform. Extensions are packaged in one or more ZIP filesor JAR files, and are loaded into the Java virtual machine by an extension classloader.

The extension mechanism allows the Java virtual machine to use the extensionclasses in the same way that the virtual machine uses the system classes. Theextension mechanism also provides a way for you to retreive extensions fromspecified uniform resource locators (URLs) when they are not already installed inthe Java Development Kit (JDK) or Java 2 Runtime Environment, Standard Edition,version 1.2.

The JAR files of an installed extension are located in theQIBM/ProdData/Java400/ext directory. If you would like to install an extension,enter this command:ADDLNKOBJ('/QIBM/ProdData/Java400/ext/extensionToInstall.jar')

NEWLNK('/QIBM/UserData/Java400/ext/extensionToInstall.jar')LNKTYPE(*SYMBOLIC)

Where extensionToInstall.jar is the name of the zip or JAR file that contains theextension that you wish to install.

When you create a link to an extension by using the Add Link Object(ADDLNKOBJ) command, the list of files that the extension class loader searcheschanges for every Java virtual machine that is running on AS/400. If you do not want

14 AS/400 Developer Kit for Java

Page 23: AS400 Developer Kit for Java (Rzaha)

to impact the extension class loaders for other Java virtual machines on AS/400,but you still wish to create a link to an extension, follow these steps:1. Create a directory to install the extensions.

Use either the Make Directory (MKDIR) command from the AS/400 commandline or the mkdir command from the Qshell Interpreter.

2. Install the extensions to the new directory using the ADDLNKOBJ command.3. Add the new directory to the java.ext.dirs property.

You can add the new directory to the java.ext.dirs property by using the PROPfield of the JAVA command from the AS/400 command line.

If the name of your new directory is “/home/username/ext,” and the name ofyour Java program is “Hello,” then the commands that you enter should look likethis:MKDIR DIR('/home/username/ext')ADDLNKOBJ('/QIBM/ProdData/Java400/ext/extensionToInstall.jar')NEWLNK('/home/username/ext/extensionToInstall.jar')LNKTYPE(*SYMBOLIC)JAVA Hello PROP((java.ext.dirs '/home/username/ext'))

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Selecting which mode to use when running a Java program

When you run a Java program, you can select which mode you would like touse. You can choose either interpreted, direct execution, or Just-In-Time (JIT)compile.

Interpreted:

If you choose to run your Java program in the interpreted mode, the code isverified and a Java program object is created to hold the pre-verified form of theprogram. Each bytecode is interpreted at runtime.

For information on running your Java program in the interpreted mode, see theRun Java (RUNJVA) command.

Direct Execution:

If you choose to run your Java program using direct execution, the code is verifiedand a Java program object is created to hold the pre-verified form of the program.Machine instructions for a method are generated during the first call to thatmethod, and saved for use the next time that the program runs. One copy is alsoshared for the entire system.

For information on running your Java program using direct execution, see the RunJava (RUNJVA) command.

Just-In-Time (JIT) compile:

If you choose to run your Java program using the Just-In-Time compiler, the codeis verified and an associated Java program is created to hold the pre-verified form

Chapter 2. Getting started with the AS/400 Developer Kit for Java 15

Page 24: AS400 Developer Kit for Java (Rzaha)

of the program. Machine instructions for a method are generated during the firstcall to that method, and saved for the duration of the Java virtual machine run.

To use the JIT compiler, you need to set the compiler value to jitc. You can set thevalue by adding an environment variable or setting the java.compiler systemproperty. Select one method from the list below to set the compiler value:v Add the environment variable by entering the Add Environment Variable

(ADDENVVAR) command on the AS/400 command line. Then, run your Javaprogram using the Run Java (RUNJVA) command or JAVA command. Forexample, enterADDENVVAR ENVVAR (JAVA_COMPILER) VALUE(jitc)JAVA CLASS(Test)

v Set the java.compiler system property on the AS/400 command line. Forexample, enter JAVA CLASS(Test) PROP((java.compiler jitc))

v Set the java.compiler system property on the Qshell Interpreter command line.For example, enter java -Djava.compiler=jitc Test

Once you set this value, the JIT compiler optimizes all of the Java code beforerunning it.

Just-In-Time (JIT) compile and Direct Execution:

The most common way to use the Just-In-Time (JIT) compiler, is with the jit_deoption. When running with this option, programs that have already beenoptimized with direct execution, run in direct execution mode. Programs that havenot been optimized for direct optimization, run in JIT mode.

To use JIT and direct execution together, you need to set the compiler value tojitc-de. You can set the value by adding an environment variable or setting thejava.compiler system property. Select one method from the list below to set thecompiler value:v Add the environment variable by entering the Add Environment Variable

(ADDENVVAR) command on the AS/400 command line. Then, run your Javaprogram using the Run Java (RUNJVA) command or JAVA command. Forexample, enterADDENVVAR ENVVAR (JAVA_COMPILER) VALUE(jitc_de)JAVA CLASS(Test)

v Set the java.compiler system property on the AS/400 command line. Forexample, enter JAVA CLASS(Test) PROP((java.compiler jitc_de))

v Set the java.compiler system property on the Qshell Interpreter command line.For example, enter java -Djava.compiler=jitc_de Test

Once this value is set, the Java program for the class file that was created as directexecution is used. If the Java program was not created as direct execution, the classfile is optimized by the JIT prior to running. For more information, see the

comparison of Just-In-Time compiler and direct execution.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Creating and editing Java source filesWith Client Access:

16 AS/400 Developer Kit for Java

Page 25: AS400 Developer Kit for Java (Rzaha)

Java source files are American National Standard Code for Information Interchange(ASCII) text files in the integrated file system on AS/400.

You can create and edit a Java source file with Client Access and aworkstation-based editor.

On a workstation:

You can create a Java source file on a workstation. Then, transfer the file to theintegrated file system by using file transfer protocol (FTP).

To create and edit Java source files on a workstation:1. Create the ASCII file on the workstation by using the editor of your choice.2. Connect to AS/400 with FTP.3. Transfer the source file to your directory in the integrated file system as a

binary file, so that the file remains in ASCII format.

With Source Entry Utility:

You can create a Java source file as a text file by using source entry utility (SEU).

To create a Java source file as a text file by using SEU:1. Create a source file member by using SEU.2. Use the Copy To Stream File (CPYTOSTMF) command to copy the source file

member to an integrated file system stream file, while converting the data toASCII.

If you need to make changes to the source code, change the database member byusing SEU and copy the file again.

For information on storing files, see files in the integrated file system.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Downloading and installing Java packages on AS/400To download, install, and use Java packages more effectively on AS/400, see thefollowing:v Packages with graphical user interfaces (page 17)v Case sensitivity and integrated file system (page 17)v ZIP file handling and JAR file handling (page 18)v Java extensions framework (page 19)

Packages with graphical user interfaces:

Java programs used with graphical user interface (GUI) require the use of apresentation device with graphical display capabilities. For example, you can use apersonal computer, technical workstation, or network computer. AS/400 provides aRemote Abstract Window Toolkit (AWT) capability. This capability runsapplications on AS/400 by using a full range of graphical capabilities on theappropriate Transmission Control Protocol/Internet Protocol (TCP/IP) attacheddisplay device. For more specific installation, setup, and overall use information,see setting up the Remote Abstract Window Toolkit.

Chapter 2. Getting started with the AS/400 Developer Kit for Java 17

Page 26: AS400 Developer Kit for Java (Rzaha)

Case sensitivity and integrated file system:

Integrated file system provides file systems, which are both case-sensitive andthose that are not with regard to file names. QOpenSys is an example of acase-sensitive file system within the integrated file system. Root, ’/’, is an exampleof a case-insensitive file system. For more information about the integrated filesystem, see the “File Systems” information in the OS/400 Integrated File SystemIntroduction.

ZIP file handling and JAR file handling:

ZIP files and JAR files contain a set of Java classes. When you use the Create JavaProgram (CRTJVAPGM) command on one of these files, the classes are verified,converted to an internal machine form, and if specified, transformed to AS/400machine code. You can treat ZIP files and JAR files like any other individual classfile. When an internal machine form is associated with one of these files, it remainsassociated with the file. The internal machine form is used on future runs in placeof the class file to improve performance. If you are unsure whether a current Javaprogram is associated your class file or JAR file, use the Display Java Program(DSPJVAPGM) command to display information about your Java program onAS/400.

In previous releases of the AS/400 Developer Kit for Java, you had to recreate aJava program if you changed the JAR file or ZIP file in any way, because theattached Java program would become unusable. This is no longer true. In manycases, if you change a JAR file or ZIP file, the Java program is still valid and youdo not have to recreate it. If partial changes are made, such as when a single classfile is updated within a JAR file, you only need to recreate the affected class filesthat are within the JAR file.

Java programs remain attached to the JAR file after most typical changes to theJAR file. For example, these Java programs remain attached to the JAR file when:v Changing or recreating a JAR file by using the ajar tool.v Changing or recreating a JAR file by using the jar tool.v Replacing a JAR file by using the 0S/400 COPY command or the Qshell cp

utility.Note: Java programs do not remain intact with the COPY command, however,Java programs do remain intact with the move object (MOV) command.Anytime you copy a JAR file, you need to run the CRTJVAPGM commandagainst the resulting JAR file for performance and space. Or, let the Javaprograms be created automatically, as needed, when the application runs.

If you access a JAR file in the integrated file system through Client Access or froma mapped drive on a personal computer (PC), these Java programs remainattached to the JAR file when:v Dragging and dropping another JAR file onto the existing integrated file system

JAR file.v Changing or recreating the integrated file system JAR file by using the jar tool.v Replacing the integrated file system JAR file by using the PC copy command.

When a jar file is changed or replaced, the Java program that is attached to it is nolonger current.

18 AS/400 Developer Kit for Java

Page 27: AS400 Developer Kit for Java (Rzaha)

There is one exception in which Java programs do not remain attached to the JARfile. The attached Java programs are destroyed if you use file transfer protocol(FTP) to replace the JAR file. For example, this occurs if you use the FTP putcommand to replace the JAR file.

See runtime performance for more detailed information about the performancecharacteristics of JAR files.

Java extensions framework:

In Java 2 SDK, Standard Edition, version 1.2, extensions are packages of Javaclasses that you can use to extend the functionality of the core platform. Anextension or application is packaged in one or more JAR files. The extensionmechanism allows the Java virtual machine to use the extension classes in thesame way that the virtual machine uses the system classes. The extensionmechanism also provides a way for you to retreive extensions from specified URLswhen they are not already installed in the Java Development Kit (JDK) or Java 2Runtime Environment, Standard Edition, version 1.2.

See Installing extensions for the AS/400 Developer Kit for Java for information oninstalling extensions.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Release to release compatibilityAs with all Java programs, your class files are portable to previous and futurereleases of AS/400 or other compatible Java machines, subject to any limitationsthat Sun Microsystems, Inc. introduces. However, the Java programs are currentlynot portable between releases of AS/400, so you should run the Create JavaProgram (CRTJVAPGM) command to optimize the class file, ZIP file, or JAR filewhen you move the program to another AS/400 from a different release.

The Java programs that may be attached to the class file, ZIP file, or JAR file arenot upward compatible from releases prior to V4R4. You should run theCRTJVAPGM command on V4R4 for the best optimization when using a class file,ZIP file, or JAR file with an attached Java program from a release prior to V4R4.Use the Display Java Program (DSPJVAPGM) command to determine if you havean attached Java program. Regardless, you should still run the CRTJVAPGMcommand even if there is not an attached Java program from a previous release. Ineither case, implicit creation occurs if you do not explicitly run the CRTJVAPGMcommand, but an an explicit creation by using the CRTJVAPGM commandproduces better code and uses less disk space.

If you have Java programs that were created at optimization level 40, prior to theinstallation of Java 2 Software Development Kit (J2SDK), Standard Edition, version1.2, you should recreate them by using the CRTJVAPGM command. You need torecreate them because of changes made in the base J2SDK classes.

Note: If you create Java programs that use unique J2SDK, version 1.2 features, theyare not portable to versions prior to J2SDK, version 1.2. If your Java programs donot use unique features, they are portable to prior versions.

See runtime performance for more detailed performance information.

Chapter 2. Getting started with the AS/400 Developer Kit for Java 19

Page 28: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

20 AS/400 Developer Kit for Java

Page 29: AS400 Developer Kit for Java (Rzaha)

Chapter 3. AS/400 Developer Kit for Java concepts

The AS/400 Developer Kit for Java concepts introduce what you should befamiliar with when using the AS/400 Developer Kit for Java. This information isspecific to AS/400.

The basic Java concepts provide Java definitions for those of you who are lookingfor basic details. This is general Java information, and is not specific to the AS/400.It is only provided here as a quick reference. Reference information is alsoavailable for Sun Microsystems Inc. Java Development Kit (JDK).

AS/400 Developer Kit for Java concepts:

The AS/400 Developer Kit for Java is optimized for use in an AS/400 serverenvironment. It utilizes the compatibility of Java programming and user interfaces,so you can develop your own applications for AS/400.

The AS/400 Developer Kit for Java allows you to create and run Java programs onAS/400. The AS/400 Developer Kit for Java is a compatible implementation of theSun Microsystems, Inc. Java Technology, so we assume that you are familiar withtheir Java Development Kit (JDK) documentation, and often provide links to thisinformation.

Unique aspects of the AS/400 Developer Kit for Java design include:v The integration of critical Java virtual machine components below the

Technology Independent Machine Interface (TIMI).v A Java transformer for conversion of Java bytecodes to RISC machine

instructions.v Advanced, scalable implementations of garbage collection, object allocation, and

synchronization.v The Remote Abstract Window Toolkit implementation that supports the java.awt

APIs.v The Class Broker for Java that you can use for high performance graphical user

interface (GUI) services.v A Just-In-Time compiler that improves performance by compiling code as you

need it.

The AS/400 Developer Kit for Java is not an integrated language environment(ILE) language. It introduces a new language environment on AS/400 that is builton Java, American National Standard Code for Information Interchange (ASCII),integrated file system, and other industry standards.

The AS/400 Developer Kit for Java supports the common JDK tools, such as javac,javadoc, and jar. There are also CL commands and Operations Navigator interfacesto the AS/400 Developer Kit for Java.

For definitions of specific AS/400 Developer Kit for Java concepts and details, clickon any of these links:v Running Java in a batch job explains how Java programs run in a batch job by

using the Submit Job (SBMJOB) command.

© Copyright IBM Corp. 1998, 1999 21

Page 30: AS400 Developer Kit for Java (Rzaha)

v Java classes, packages, and directories provides definitions of each and how theyrelate to one another.

v Java system properties shows the system properties along with their descriptionsand system default values.

v Files in the integrated file system lists where you can store source files inintegrated file systems.

v Java file authorities in the integrated file system shows you how to set Java fileauthorities.

v Java character encodings explains how the Java virtual machine converts data toother encodings.

v Java Naming and Directory Interface tells you how to run JNDI.v Java Virtual Machine Debug Interface explains what JVMDI is and why you

would use it.v Limitations, restrictions, and unique behaviors lists any known limitations.

Basic Java concepts:

Java is a full-function, object-oriented programming language that you can use todevelop applications and applets. Object-oriented programming uses objects andclasses in a program to represent entities and classifications of entities in the realworld. The class defines the attributes and behavior common to all objects of thatclass. An object is an instance of a class—the specific example of the more generalconceptual model. Object-oriented programming enables programmers to designapplications that use classes and objects that parallel those that are found in thereal world.

Not only can you use Java technology for programming applets or writingapplications, but you can use servlets to bring Java to your servers. Servlets areprotocol and platform-independent server side components that are written in Javato dynamically extend Java enabled servers. See the IBM WebSphere Application

Server homepage for more specific servlet information.

Syntactically, the Java language is similar to C++. But it was designed to besimpler to learn and simpler to use. One of the simplifications in Java was theelimination of pointers in the language. In a language like C++, pointers are oftenthe source of errors in a program, because of incorrect memory references. Javaallows references to objects, but the programmer cannot manipulate or directlychange references.

Java is simpler than C++ in other ways. There are no multiple inheritance ofimplementation, templates, operator overloading, or header files. Thesesimplifications add to the versatility of the language by making it easier forprogrammers to use and by reducing the risk of programming errors.

Java also relieves the programmer of having to manage memory. A component ofthe Java virtual machine, called the garbage collector, frees up memory that isallocated to an object once that object is no longer in use. The garbage collectorkeeps track of which objects are active in a program. When the program no longerrefers to the object, the garbage collector automatically frees up the object’smemory for reuse within the program.

The garbage collector runs in parallel with the user-written program. Javaincorporates multithreading into its runtime and provides the language constructsthat allow a programmer to write multithreaded code. Threads allow parallel,

22 AS/400 Developer Kit for Java

Page 31: AS400 Developer Kit for Java (Rzaha)

concurrent running of code within a program. The ability to create and run threadsis not inherent in other programming languages. Java provides the power ofthreads as part of the base language.

Java is an ideal language for network computing. You can develop both appletsand applications that run in a distributed environment. Java programs are portablebetween platforms and do not require any modification or recompilation to run ondifferent hardware or operating system configurations.

For more detailed information about the basic Java platform or Sun Microsystems,Inc. Java Development Kit, see these topics for background information:v The Java platform compares how the Java environment differs from traditional

programming languages.v Sun Microsystems, Inc. Java Development Kit provides information and details

about the Java Development Kit.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java transformerThe Java transformer is an IBM Operating System/400 (OS/400) component thatpreprocesses class files to prepare them to run using the AS/400 Java virtualmachine. The Java transformer creates an optimized program object that ispersistent and is associated with the class file. In the default case, the programobject contains a compiled, 64-bit RISC machine instruction version of the class.The Java interpreter does not interpret the optimized program object at runtime.Instead, it directly runs when the class file is loaded.

You do not need to do anything to start the Java transformer. It runs automaticallythe first time that the class file runs on the system, unless you explicitly requestthat the class file run in interpreted mode.

You can use the Create Java Program (CRTJVAPGM) command to explicitly startthe Java transformer. The CRTJVAPGM command optimizes the class file or JARfile while the command runs, so nothing needs to be done while the program isrunning. This improves the speed of the program the first time that it runs. Usingthe CRTJVAPGM command, instead of relying on default optimization, ensures thebest optimization possible and also better utilizes space for the Java programs thatare associated with the class file or JAR file.

Using the CRTJVAPGM command on a class file, JAR file, or ZIP file causes all theclasses in the file to be optimized, and the resulting Java program object will bepersistent. This results in better runtime performance. You can also change theoptimization level or select an optimization level other than the default of 10 byusing the CRTJVAPGM command or the Change Java Program (CHGJVAPGM)command. At optimization level 40, interclass binding is performed between theclasses within a JAR file, and in some cases, the classes are inlined. Interclassbinding improves the call speed. Inlining removes the call entirely. In some cases,you can inline methods between classes within the JAR file or ZIP file. SpecifyingOPTIMIZE(*INTERPRET) on the CRTJVAPGM command causes any classes that arespecified on the command to be verified and prepared to run in interpreted mode.

The Run Java (RUNJVA) command can also specify OPTIMIZE(*INTERPRET). Thisparameter specifies that any classes running under the Java virtual machine are

Chapter 3. AS/400 Developer Kit for Java concepts 23

Page 32: AS400 Developer Kit for Java (Rzaha)

interpreted, regardless of the optimization level of the associated program object.This is useful when debugging a class that was transformed with an optimizationlevel of 40. To force interpretation, use INTERPRET(*YES).

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

AS/400 Developer Kit for Java advanced garbage collectionThe AS/400 Developer Kit for Java implements an advanced garbage collectoralgorithm. This algorithm allows the discovery and collection of unreachableobjects without significant pauses in the operation of the Java program. Aconcurrent collector cooperatively discovers the references to objects under therunning threads, instead of a single thread.

Many garbage collectors are “stop-the-world”. This means that at the point wherea collection cycle occurs, all threads, except the thread that does garbage collection,stop while the garbage collector does its work. When this happens, Java programsexperience a pause, and any multiple processor capability of the platform iswasted relative to Java, while the collector does its work. The AS/400 algorithmnever stops the program threads. It allows those threads to continue operationwhile the garbage collector completes its task. This prevents the pauses, and allowsall processors to be used during garbage collection.

Garbage collection occurs automatically based on parameters that you specifywhen you start the Java virtual machine. Garbage collection can also be startedexplicitly under the control of the Java program by using thejava.lang.Runtime.gc() method.

For a basic concept definition, see Java garbage collection.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java garbage collectionGarbage collection is the process of freeing storage that is used by objects that areno longer referred to by a program. With garbage collection, programmers nolonger have to write error prone code to explicitly “free” or “delete” their objects.This code frequently results in “memory leak” program errors. The garbagecollector automatically detects an object or group of objects that the user programcan no longer reach. It does this because there are no references to that object inany program structure. Once the object has been collected, you can allocate thespace for other uses.

The Java runtime environment includes a garbage collector that frees memory thatis no longer in use. The garbage collector runs automatically, as needed.

The garbage collector can also be started explicitly under the control of the Javaprogram using the java.lang.Runtime.gc() method.

See AS/400 Developer Kit for Java advanced garbage collection for AS/400Developer Kit for Java specifics.

24 AS/400 Developer Kit for Java

Page 33: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

AS/400 Java runtime environmentThe Java runtime environment starts whenever you enter the Run Java (RUNJVA)command or JAVA command on the AS/400 command line. Because the Javaenvironment is multithreaded, it is necessary to run the Java virtual machine in ajob that supports threads, such as a batch immediate (BCI) job. Once the Javavirtual machine starts, additional threads may start in which the garbage collectorruns. The typical Java environment looks like this:

It is also possible to start the Java runtime environment by using the javacommand in Qshell from the Qshell Interpreter. In this environment, the QshellInterpreter is running in a BCI job that is associated with an interactive job. TheJava runtime environment starts in the job that is running the Qshell Interpreter.

When the Java runtime environment starts from an interactive job, the Java ShellDisplay is shown. This display provides an input line for entering data into theSystem.in stream, as well as displaying data that is written to the System.outstream and System.err stream.

Chapter 3. AS/400 Developer Kit for Java concepts 25

Page 34: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

AS/400 Developer Kit for Java Remote Abstract Window ToolkitThe Remote Abstract Window Toolkit is an implementation of the AbstractWindow Toolkit (AWT). It allows Java applications to run, without any changes, ona host that does not have a graphical user interface (GUI). AS/400 does notsupport locally-attached graphic terminals; therefore Remote AWT is necessary toallow graphical Java applications to run on AS/400.

You use Remote AWT with install and administration interfaces of serverapplications. These interfaces typically have a minimum of complex graphics andhighly-interactive content. Remote AWT distributes AWT processing betweenAS/400 and a workstation. Responsiveness of graphic-intensive andhighly-interactive operations might not be as fast as AWT implementations onplatforms with locally-attached graphic terminals.

Since AS/400 Developer Kit for Java Remote AWT is not recommended forcomplex graphics or highly-interactive operations, you can use the Class Broker forJava instead, which was designed for these environments.

For information on how to set up Remote AWT, see Setting up the RemoteAbstract Window Toolkit for Java on a remote display.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

AS/400 Developer Kit for Java Class Broker for Java

Class Broker for Java (CBJ) is a general-purpose framework for writingclient/server applications in Java. Typically, a client/server application consists ofboth a client object and a server object. The server and client are responsible for allcommunication between the two objects. This communication is oftenaccomplished by Remote Method Invocation (RMI) or by a socket connection. RMIis not very easy or flexible to use and there is a considerable learning curve whentrying to use sockets effectively.

CBJ is easy to use, flexible, and hides the complexity of socket connections. Exceptfor a few calls to the CBJ classes to initialize the application, a brokeredclient/server application appears to be a local application. CBJ handles allcommunication and resource loading between the client and server. The fact thatsome of the objects of the program are running on the client and some are runningon the server is almost transparent. CBJ creates client and server proxies using theCBJ runtime. Once the broker creates the proxy objects, the client communicateswith the remote server by calling methods on the proxy of the server. Likewise, theserver object communicates with the client by calling methods on the proxy of theclient. Thus, both the client and server sides of the application appear as if they arecalling methods of local objects.

For information about using Class Broker for Java, see setting up Class Broker for

Java .

26 AS/400 Developer Kit for Java

Page 35: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Just-In-Time compiler

A Just-In-Time (JIT) compiler is a platform-specific compiler that generatesmachine instructions for each method upon the first call to that method. Toimprove performance, the JIT compiler compiles code as you need it.

To understand the difference between the JIT compiler and direct execution, see

comparison of the JIT compiler and direct execution.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Comparison of Just-In-Time compiler and direct execution

If you are trying to decide whether to use the Just-In-Time compiler or directexecution mode to run your Java program, this table provides additionalinformation to help you make the best choice for your situation.

Just-In-Time compiler Direct executionProvides an automatic compile of anymethod when needed. This method is muchfaster than direct execution.

You compile an entire class or JAR file usingthe Create Java Program (CRTJVAPGM)command or the files are compiledautomatically at runtime.

Used for development of small or low usageapplications, and highly dynamicapplications in which the code is generatedor loaded at runtime. JIT may be your onlychoice for optimized code, other thaninterpretation, which is often much slower.

Used for relatively large applications. Directexecution code, at optimization level 40, istypically faster than JIT. Most ready todeploy server applications use directexecution at optimization level 40, becausethey are likely to be in use by multiple usersat any given time, and the cost of using JITover and over is too much overhead.

Optimizations are limited to those that canbe performed rapidly at runtime.

More complex optimizations are possible,since optimization is not performed atruntime.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Comparison of Integrated Language Environment and JavaThe Java environment on AS/400 is separate from the integrated languageenvironment (ILE). Java is not an ILE language, and it cannot bind to ILE objectmodules to create programs or service programs on AS/400.

ILE JavaMembers that are part of the library or filestructure on AS/400 store source codes.

Stream files in the integrated file systemcontain source code.

Chapter 3. AS/400 Developer Kit for Java concepts 27

Page 36: AS400 Developer Kit for Java (Rzaha)

ILE JavaSource entry utility (SEU) edits extendedbinary-coded decimal interchange code(EBCDIC) source files.

American National Standard Code forInformation Interchange (ASCII) source filesare usually edited using a workstation editor.

Source files compile into object codemodules, which are stored in libraries onAS/400.

Source code compiles into class files, whichthe integrated file system stores.

Object modules are statically bound togetherin programs or service programs.

Classes are dynamically loaded, as needed, atruntime.

You can directly call to functions that arewritten in other ILE programming languages.

Java Native Interface must be used to callother languages from Java.

ILE languages are always compiled and runas machine instructions.

Java programs can be interpreted orcompiled.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Running Java in a batch jobJava programs run in a batch job by using the Submit Job (SBMJOB) command. Inthis mode, the Java Qshell Command Entry display is not available to handle theSystem.in, System.out, nor System.err streams.

You may redirect these streams to other files. Default handling sends theSystem.out and System.err streams to a spooled file. The batch job, which results inan input and output exception for read requests from System.in, owns the spooledfile. You can redirect System.in, System.out, and System.err within your Javaprogram. You can also use the os400.stdin, os400.stdout, and os400.stderr systemproperties to redirect System.in, System.out, and System.err.

Note: SBMJOB sets the Current Working Directory (CWD) to the HOME directorythat is specified in the user profile.

Example: Running Java in a Batch Job

SBMJOB CMD(JAVA Hello OPTION(*VERBOSE)) CPYENVVAR(*YES)

Running the JAVA command in the above example will spawn a second job.Therefore, the subsystem that the batch job runs in must be capable of runningmore than one job.

You can verify that your batch job is capable of running more than one job byfollowing these steps:1. On the CL command line, enter DSPSBSD(MYSBSD), where MYSBSD is the

subsystem description of your batch job.2. Choose option 6, Job queue entries.3. Look at the Max Active field for your job queue.

If the Max Active field is less than or equal to 1, and it is not *NOMAX,enter the following on the CL command line:

CHGJOBQE SBSD(MYSBSD) JOBQ(MYJOBQ) MAXACT(*NOMAX)Where:v MYSBSD is your subsystem description, andv MYJOBQ is your job queue.

28 AS/400 Developer Kit for Java

Page 37: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java classes, packages, and directoriesEach Java class is part of a package. The first statement in a Java source fileindicates which class is in what package. If the source file does not contain apackage statement, the class is part of an unnamed default package.

The package name relates to the directory structure in which the class resides. Theintegrated file system supports Java classes in a hierarchical file structure that issimilar to what you find on most PC and UNIX systems. You must store a Javaclass in a directory with a relative directory path that matches the package namefor that class. For example, consider these Java class:package classes.geometry;import java.awt.Dimension;public class Shape {Dimension metrics;

// The implementation for the Shape class would be coded here ...}

The package statement in the code above indicates that the Shape class is part ofthe “classes.geometry” package. For the Java runtime to find the Shape class, storethe Shape class in the relative directory structure “classes/geometry”.

Note: The package name corresponds to the relative directory name in which theclass is stored. The Java virtual machine class loader finds the class by appendingthe relative path name to each directory that is specified in the classpath. The Javavirtual machine class loader can also find the class by searching the ZIP files orJAR files that are specified in the classpath.

For example, if the Shape class was stored in the /Product/classes/geometrydirectory in the “root” (/) file system, /Product would need to be specified in theclasspath.

Chapter 3. AS/400 Developer Kit for Java concepts 29

Page 38: AS400 Developer Kit for Java (Rzaha)

Note: Multiple versions of the Shape class can exist in the directory structure. Touse the “beta” version of the Shape class, place /Beta/myclasses in theCLASSPATH before any other directories or ZIP files that contain the Shape class.

The Java compiler uses the Java classpath, package name, and directory structureto find packages and classes when compiling Java source code.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java system propertiesJava system properties determine the environment in which the Java programs run.They are similar to system values or environment variables in OS/400. A numberof properties are set when the Java virtual machine starts.

To view the system properties that this release supports, link to the version of yourchoice for detailed information:v Java Development Kit (JDK) 1.1.8v Java 2 Software Development Kit (J2SDK), Standard Edition, version 1.2

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java system properties for Java Development Kit (JDK) 1.1.8Java system properties determine the environment in which the Java programs run.They are similar to system values or environment variables in OS/400. A numberof properties are set when the Java virtual machine starts.

30 AS/400 Developer Kit for Java

Page 39: AS400 Developer Kit for Java (Rzaha)

The system properties are set to these system default values in JDK 1.1.8.

System properties System default valuesawt.toolkit com.ibm.rawt.client.CToolkitfile.encoding.pkg sun.iofile.separator / (forward slash)java.class.version 45.3java.home See Multiple JDK support for details.java.vendor IBM Corporationjava.vendor.url http://www.ibm.comline.separator \nos.arch PowerPCos.name OS/400os400.class.path.rawt 0os400.class.path.security.check

20Valid values:0—No security check10—equivalent to RUNJVACHKPATH(*IGNORE)20—equivalent to RUNJVACHKPATH(*WARN)30—equivalent to RUNJVACHKPATH(*SECURE)

os400.class.path.tools 0os400.create.type

directValid values:interpret—equivalent to RUNJVAOPTIMIZE(*INTERPRET) andINTERPRET(*OPTIMIZE), orINTERPRET(*YES)direct—Otherwise

os400.defineClass.optLevel 20os400.enbpfrcol

0Valid values:0—equivalent to CRTJVAPGMENBPFRCOL(*NONE)1—equivalent to CRTJVAPGMENBPFRCOL(*ENTRYEXIT)7—equivalent to CRTJVAPGMENBPFRCOL(*FULL)

os400.interpret

0Valid values:0—equivalent to CRTJVAPGMINTERPRET(*NO)1—equivalent to CRTJVAPGMINTERPRET(*YES)

Chapter 3. AS/400 Developer Kit for Java concepts 31

Page 40: AS400 Developer Kit for Java (Rzaha)

System properties System default valuesos400.optimization

10Valid values:0—equivalent to CRTJVAPGMOPTIMIZE(*INTERPRET)10—equivalent to CRTJVAPGMOPTIMIZE(10)20—equivalent to CRTJVAPGMOPTIMIZE(20)30—equivalent to CRTJVAPGMOPTIMIZE(30)40—equivalent to CRTJVAPGMOPTIMIZE(40)

os400.run.mode

program_create_typeValid values:interpret—equivalent to RUNJVAOPTIMIZE(*INTERPRET) andINTERPRET(*OPTIMIZE), orINTERPRET(*YES)program_create_type—Otherwise

os400.stdin.allowed 0os400.verify.checks.disable 65535 This system property value is a string

that represents the sum of one or morenumeric values. For a list of these values, seeos400.verify.checks.disable numeric values.

path.separator : (colon)

This set of system properties are set based on additional system information.

System properties Descriptionfile.encoding Maps the OS/400 job CCSID to the

corresponding ISO ASCII CCSID. Also, setsthe file.encoding value to the Java value thatrepresents the ISO ASCII coded character setidentifier (CCSID). See file.encoding valuesand AS/400 CCSID for a table that shows therelationship between possible file.encodingvalues and the closest matching AS/400coded character set identifier (CCSID).

java.class.path Path used to locate classes. Defaults to thedefault system classpath followed by theuser-specified classpath. You can change thecontruction of the java.class.path systemproperty by using the os400.class.path.systemsystem property.

java.version Determines which Java Development Kit(JDK) to run.

If you specify a JDK that is not installed, anerror message results. If you do not specify aJDK, the most recent JDK is the default. Ifonly one JDK is installed, that is yourdefault. See Multiple JDK support for versiondetails.

32 AS/400 Developer Kit for Java

Page 41: AS400 Developer Kit for Java (Rzaha)

System properties Descriptionos.version Obtains the OS/400 release level from the

Retrieve Product Information applicationprogram interface (API).

os400.CertificateContainer Directs Java secure sockets layer (SSL)support to use the specified certificatecontainer for the Java program that wasstarted and the property that was specified.If you specify the os400.secureApplicationsystem property, this system property isignored. For example, enter-Dos400.certificateContainer=/home/username/mykeyfile.kor any other keyfile in the integrated filesystem.

os400.CertificateLabel You can specify this system property inconjunction with theos400.CertificateContainer system property.This property lets you select which certificatein the specified container you want securesockets layer (SSL) to use. For example,enter-Dos400.certificateLabel=myCert,where myCert is the label name that youassign to the certificate through the DigitalCertificate Manager (DCM) when you createor import the certificate.

os400.child.stdio.convert Allows control of the data conversion forstdin, stdout, and stderr in Java. Dataconversion occurs by default in the Javavirtual machine to convert ASCII data to orfrom EBCDIC. You can turn theseconversions on or off with this property,which effects any child processes that werestarted by this process by using theruntime.exec() method. See default values.

os400.class.path.system PRE (this causes the os400 default systemclasspath to be prepended onto theuser-specified portion of the classpath whenconstructing the java.class.path systemproperty). Other values are POST (the systemdefault class is appended to theuser-specified portion of the classpath) andNONE (only the user-specified classpath isused). The default is PRE. The property isnot case sensitive. For example, you canspecify NONE, none, noNe. However, theproperty name is case sensitive. For example,you cannot specifyOS400.CLASS.PATH.SYSTEM. To avoidpotential problems, you should not changethis system property.

os400.file.io.mode Converts the CCSID of the file if it ifdifferent than the file.encoding value whenyou specify TEXT, rather than the default,which is BINARY.

os400.secureApplication Associates the Java program that starts whenuse use this system property(os400.secureApplication) with the registeredsecure application name. You can viewregistered secure application names by usingthe Digital Certificate Manager (DCM).

Chapter 3. AS/400 Developer Kit for Java concepts 33

Page 42: AS400 Developer Kit for Java (Rzaha)

System properties Descriptionos400.stderr Allows mapping stderr to a file or socket.

See default values.os400.stdin Allows mapping stdin to a file or socket. See

default values.os400.stdio.convert Allows control of the data conversion for

stdin, stdout, and stderr in Java. Dataconversion occurs by default in the Javavirtual machine to convert ASCII data to orfrom EBCDIC. You can turn theseconversions on or off with this property,which effects the current Java program. Seedefault values.

os400.stdout Allows mapping stdout to a file or socket.See default values.

user.dir Current working directory using the getcwdAPI.

user.home Retrieves the initial working directory byusing the Get API (getpwnam). You can placea SystemDefault.properties file in youruser.home path to override the defaultproperites in/QIBM/UserData/Java400/SystemDefault.properties.See configuring AS/400 for details on how tospecify your own set of default propertyvalues.

user.language The Java virtual machine uses this systemproperty to read the job LANGID value anduses this value to find the correspondinglanguage.

user.name The Java virtual machine uses this systemproperty to retrieve the effective user profilename from the Security section(Security.UserName) of the TrustedComputing Base (TCB).

user.region The Java virtual machine uses this systemproperty to read the job CNTRYID value anduses this value to determine the user region.

user.timezone The Java virtual machine uses this systemproperty to obtain the time zone name byusing the QlgRetrieveLocalInformation API.If no time zone information is available,user.timezone is set to Univeral TimeCoordinate (UTC).

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java system properties for Java 2 Software Development Kit(J2SDK), Standard Edition, version 1.2

Java system properties determine the environment in which the Java programs run.They are similar to system values or environment variables in OS/400. A numberof properties are set when the Java virtual machine starts.

The system properties are set to these system default values in Java 2 SoftwareDevelopment Kit (J2SDK), Standard Edition, version 1.2.

34 AS/400 Developer Kit for Java

Page 43: AS400 Developer Kit for Java (Rzaha)

System properties System default valuesawt.toolkit com.ibm.rawt.client.CToolkitfile.encoding.pkg sun.iofile.separator / (forward slash)java.class.version 46.0java.ext.dirs

/QIBM/ProdData/Java400/jdk12/lib/ext:/QIBM/ProdData/java.home See Multiple JDK support for details.java.library.path OS/400 library listjava.policy

/QIBM/ProdData/Java400/jdk12/lib/security/java.policyjava.specification.name Java Language Specificationjava.specification.vendor Sun Microsystems, Inc.java.specification.version 1.2java.sys.class.path Class_Path_Sysjava.use.policy truejava.vendor IBM Corporationjava.vendor.url http://www.ibm.comjava.vm.name AS/400 Developer Kit for Javajava.vm.specification.name Java Virtual Machine Specificationjava.vm.specification.vendor Sun Microsystems, Inc.java.vm.specification.version 1.2java.vm.vendor IBM Corporationjava.vm.version OS400_JVM_12line.separator \nos.arch PowerPCos.name OS/400os400.class.path.rawt 0os400.class.path.security.check

20Valid values:0—No security check10—equivalent to RUNJVACHKPATH(*IGNORE)20—equivalent to RUNJVACHKPATH(*WARN)30—equivalent to RUNJVACHKPATH(*SECURE)

os400.class.path.tools 0os400.create.type

directValid values:interpret—equivalent to RUNJVAOPTIMIZE(*INTERPRET) andINTERPRET(*OPTIMIZE), orINTERPRET(*YES)direct—Otherwise

os400.defineClass.optLevel 20

Chapter 3. AS/400 Developer Kit for Java concepts 35

Page 44: AS400 Developer Kit for Java (Rzaha)

System properties System default valuesos400.enbpfrcol

0Valid values:0—equivalent to CRTJVAPGMENBPFRCOL(*NONE)1—equivalent to CRTJVAPGMENBPFRCOL(*ENTRYEXIT)7—equivalent to CRTJVAPGMENBPFRCOL(*FULL)

os400.interpret

0Valid values:0—equivalent to CRTJVAPGMINTERPRET(*NO)1—equivalent to CRTJVAPGMINTERPRET(*YES)

os400.optimization

10Valid values:0—equivalent to CRTJVAPGMOPTIMIZE(*INTERPRET)10—equivalent to CRTJVAPGMOPTIMIZE(10)20—equivalent to CRTJVAPGMOPTIMIZE(20)30—equivalent to CRTJVAPGMOPTIMIZE(30)40—equivalent to CRTJVAPGMOPTIMIZE(40)

os400.run.mode

program_create_typeValid values:interpret—equivalent to RUNJVAOPTIMIZE(*INTERPRET) andINTERPRET(*OPTIMIZE), orINTERPRET(*YES)program_create_type—Otherwise

os400.stdin.allowed 0os400.verify.checks.disable 65535 This system property value is a string

that represents the sum of one or morenumeric values. For a list of these values, seeos400.verify.checks.disable numeric values.

path.separator : (colon)

36 AS/400 Developer Kit for Java

Page 45: AS400 Developer Kit for Java (Rzaha)

This set of system properties are set based on additional system information.

System properties Descriptionfile.encoding Maps the OS/400 job CCSID to the

corresponding ISO ASCII CCSID. Also, setsthe file.encoding value to the Java value thatrepresents the ISO ASCII coded character setidentifier (CCSID). See file.encoding valuesand AS/400 CCSID for a table that shows therelationship between possible file.encodingvalues and the closest matching AS/400coded character set identifier (CCSID).

java.class.path Path used to locate classes. Defaults to theuser-specified classpath.

java.compiler Specifies whether code is compiled with theJust-In-Time (JIT) compiler (jitc) or with boththe JIT compiler and direct execution(jitc_de).

java.version Determines which Java Development Kit(JDK) to run.

If you specify a JDK that is not installed, anerror message results. If you do not specify aJDK, the most recent JDK is the default. Ifonly one JDK is installed, that is yourdefault. See Multiple JDK support for versiondetails.

os.version Obtains the OS/400 release level from theRetrieve Product Information applicationprogram interface (API).

os400.CertificateContainer Directs Java secure sockets layer (SSL)support to use the specified certificatecontainer for the Java program that wasstarted and the property that was specified.If you specify the os400.secureApplicationsystem property, this system property isignored. For example, enter-Dos400.certificateContainer=/home/username/mykeyfile.kor any other keyfile in the integrated filesystem.

os400.CertificateLabel You can specify this system property inconjunction with theos400.CertificateContainer system property.This property lets you select which certificatein the specified container you want securesockets layer (SSL) to use. For example,enter-Dos400.certificateLabel=myCert,where myCert is the label name that youassign to the certificate through the DigitalCertificate Manager (DCM) when you createor import the certificate.

os400.child.stdio.convert Allows control of the data conversion forstdin, stdout, and stderr in Java. Dataconversion occurs by default in the Javavirtual machine to convert ASCII data to orfrom EBCDIC. You can turn theseconversions on or off with this property,which effects any child processes that werestarted by this process by using theruntime.exec() method. See default values.

Chapter 3. AS/400 Developer Kit for Java concepts 37

Page 46: AS400 Developer Kit for Java (Rzaha)

System properties Descriptionos400.class.path.system This system property is ignored in version

1.2.os400.file.io.mode Converts the CCSID of the file if it if

different than the file.encoding value whenyou specify TEXT, rather than the default,which is BINARY.

os400.secureApplication Associates the Java program that starts whenuse use this system property(os400.secureApplication) with the registeredsecure application name. You can viewregistered secure application names by usingthe Digital Certificate Manager (DCM).

os400.stderr Allows mapping stderr to a file or socket.See default values.

os400.stdin Allows mapping stdin to a file or socket. Seedefault values.

os400.stdin.allowed Specifies whether stdin is allowed (1) or notallowed (0). If the caller is running a batchjob, stdin should not be allowed. The default0.

os400.stdio.convert Allows control of the data conversion forstdin, stdout, and stderr in Java. Dataconversion occurs by default in the Javavirtual machine to convert ASCII data to orfrom EBCDIC. You can turn theseconversions on or off with this property,which effects the current Java program. Seedefault values.

os400.stdout Allows mapping stdout to a file or socket.See default values.

user.dir Current working directory using the getcwdAPI.

user.home Retrieves the initial working directory byusing the Get API (getpwnam). You can placea SystemDefault.properties file in youruser.home path to override the defaultproperites in/QIBM/UserData/Java400/SystemDefault.properties.See configuring AS/400 for details on how tospecify your own set of default propertyvalues.

user.language The Java virtual machine uses this systemproperty to read the job LANGID value anduses this value to find the correspondinglanguage.

user.name The Java virtual machine uses this systemproperty to retrieve the effective user profilename from the Security section(Security.UserName) of the TrustedComputing Base (TCB).

user.region The Java virtual machine uses this systemproperty to read the job CNTRYID value anduses this value to determine the user region.

38 AS/400 Developer Kit for Java

Page 47: AS400 Developer Kit for Java (Rzaha)

System properties Descriptionuser.timezone The Java virtual machine uses this system

property to obtain the time zone name byusing the QlgRetrieveLocalInformation API.If no time zone information is available,user.timezone is set to Univeral TimeCoordinate (UTC).

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

os400.stdio.convert and os400.child.stdio.convert systemproperty valuesThis table shows the system values for both the os400.stdio.convert andos400.child.stdio.convert system properties.

Value Description

N (default) No stdio conversion is performed during read or write.

Y All stdio converts to or from the file.encoding value to job CCSIDduring read or write.

1 Only stdin data converts from job CCSID to file.encoding during read.

2 Only stdout data converts from file.encoding to job CCSID duringwrite.

3 Both stdin and stdout conversions are performed.

4 Only stderr data converts from file.encoding to job CCSID duringwrite.

5 Both stdin and stderr conversions are performed.

6 Both stdout and stderr conversions are performed.

7 All stdio conversions are performed.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

os400.stdin, os400.stdout, and os400.stderr system propertyvaluesThis table shows the system values for os400.stdin, os400.stdout, and os400.stderrsystem properties.

Value Example name Description Example

File SomeFileName SomeFileName is anabsolute path or a pathrelative to the currentdirectory.

file:/QIBM/UserData/Java400/Output.file

Port HostName Port address port:myhost:2000

Port TCPAddress Port address port:1.1.11.111:2000

Chapter 3. AS/400 Developer Kit for Java concepts 39

Page 48: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

os400.verify.checks.disable numeric valuesThe os400.verify.checks.disable system property value is a string that represents thesum of one or more numeric values from this list:

Value Description

1

Bypass access checks for local classes:Indicates that you want the Java virtualmachine to bypass access checks on privateand protected fields and methods for classesthat are loaded from the local file system. Itis helpful when transferring applications,which contain inner classes that refer toprivate and protected methods and fields oftheir enclosing classes.

2 Suppress NoClassDefFoundError duringearly load: Indicates that you want the Javavirtual machine to ignoreNoClassDefFoundErrors, which occurduring early verification checks fortypecasting and field or method access.

4 Allow LocalVariableTable checking to bebypassed: Indicates that if you encounter anerror in the LocalVariableTable of a class, theclass operates as if the LocalVariableTabledoes not exist. Otherwise errors in theLocaleVariableTable result in aClassFormatError.

7 Value used at runtime.

You can indicate the value in decimal, hexadecimal, or octal format. It ignoresvalues that are less than zero. For example, to select the first two values from thelist, use this AS/400 command syntax:JAVA CLASS(Hello) PROP((os400.verify.checks.disable 3))

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Files in the integrated file systemThe integrated file system stores Java-related class files, source files, ZIP files, andJAR files in a hierarchical file structure. You can also store source files in theintegrated file system. You may store the files in the these integrated file systems:v “root” (/) file systemv open systems file system (QOpenSys)v user-defined file systemv library file system (QSYS.LIB)v OS/2 Warp Server for AS/400 file system (QLANSrv)v optical file system (QOPT)

40 AS/400 Developer Kit for Java

Page 49: AS400 Developer Kit for Java (Rzaha)

Note: Other integrated file systems are not supported, because they are not threadsafe.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java file authorities in the integrated file systemTo run or debug a Java program, the class file, JAR file, or ZIP file needs to haveread authority (*R). Any directories need read and execute authorities (*RX).

To use the Create Java Program (CRTJVAPGM) command to optimize a program,the class file, JAR file, or ZIP file must have read authority (*R), and the directorymust have execute authority (*X). If you use a pattern in the class file name, thedirectory must have read and execute authority (*RX).

To delete a Java program by using the Delete Java Program (DLTJVAPGM)command, you must have read and write authority (*RW) to the class file, and thedirectory must have execute authority (*X). If you use a pattern in the class filename, the directory must have read and execute authority (*RX).

To display a Java program by using the Display Java Program (DSPJVAPGM)command, you need no special authority on the class file or directory.

Note: Files and directories that do not have execute authority (*X) always appearto have execute authority (*X) to a user with QSECOFR authority. Different userscan get different results in certain situations, even though both users appear tohave the same access to the same files. This is important to know when runningshell scripts using the Qshell Interpreter or java.Runtime.exec().

For example, one user writes a Java program that uses java.Runtime.exec() to call ashell script, then tests it using a userid with QSECOFR authority. If the file modeof the shell script has read and write authority (*RW), the integrated file systemallows the userid with QSECOFR authority to run it. However, a non-QSECOFRauthority user could try to run the same Java program, and the integrated filesystem would tell the java.Runtime.exec() code that the shell script is notexecutable, because *X is missing. In this case, java.Runtime.exec() throws an inputand output exception.

For more information, see the OS/400 Program and CL Command APIs, SC41-5870

book or the OS/400 Integrated File System Introduction.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java character encodingsInternally, the Java virtual machine always operates with data in Unicode.However, as data transfers to or from the Java virtual machine, the Java virtualmachine converts the data to other encodings.

You store Java program files in the integrated file system. You encode the characteror text program files in the integrated file system in the code page that is specifiedby the Java system property “file.encoding.” This includes Java source code files

Chapter 3. AS/400 Developer Kit for Java concepts 41

Page 50: AS400 Developer Kit for Java (Rzaha)

(.java), Java .property files, and any character data user program files. For moreinformation, see the file.encoding values and AS/400 CCSID table or the defaultfile.encoding values table.

Program data input or output that uses any stream class, other than these four:java.io.InputStreamReader, java.io.FileReader, java.io.OutputStreamWriter, orjava.io.FileWriter, is considered binary data and performs no character code pageconversion. Program data input or output that uses the above four stream classesis considered as character data, and performs an appropriate character code pageconversion. Character code page conversion depends on the source or target of thedata.

Character data that is written to a Transmission Control Protocol/Internet Protocol(TCP/IP) socket that uses an OutputStreamReader converts to the code page that isspecified by the file.encoding system property. Character data that is read from aTCP/IP socket that uses an InputStreamReader converts from the code page that isspecified by the file.encoding system property.

Character data that is written to the System.out and System.err streams isconverted to the code page that is specified by the AS/400 job CCSID. Data that isread from the System.in stream is converted from the code page that is specifiedby the AS/400 job coded character set identifier (CCSID).

If System.in has been redirected to another stream, the conversion is handleddifferently. System.in can be redirected by using the java.lang.System.SetIn()method if you want to supply the input to your program from the output ofanother Java program. In this case, conversion from an AS/400 CCSID is notappropriate, because both the source and target programs are Java. The data isconverted from the code page that is specified by the Java file.encoding systemproperty. Similarly, data to a redirected System.out or and System.err is convertedto the code page that is specified by the Java file.encoding system property.

Data to or from the DB2/400 database, through the JDBC APIs, converts to or fromthe CCSID of the AS/400 database.

Data that is transferred to or from other programs through Java Native Interfacedoes not get converted.

For more information about internationalization, see the AS/400 National

Language Support, SC41-5101 book or the AS/400 International Application

Development, SC41-5603 book.

You can also see Internationalization by Sun Microsystems, Inc. for moreinformation.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

File.encoding values and AS/400 CCSIDThis table shows the relation between possible file.encoding values and the closestmatching AS/400 coded character set identifier (CCSID).

42 AS/400 Developer Kit for Java

Page 51: AS400 Developer Kit for Java (Rzaha)

file.encoding CCSID DescriptionBig5 950 8-bit ASCII T-Chinese BIG-5CNS11643 964 Chinese National Character

Set for traditional ChineseCp037 037 IBM EBCDIC US, Canada,

Netherlands,...Cp273 273 IBM EBCDIC Germany,

AustriaCp277 277 IBM EBCDIC Denmark,

NorwayCp278 278 IBM EBCDIC Finland,

SwedenCp280 280 IBM EBCDIC ItalyCp284 284 IBM EBCDIC Spanish, Latin

AmericaCp285 285 IBM EBCDIC UKCp297 297 IBM EBCDIC FranceCp420 420 IBM EBCDIC ArabicCp424 424 IBM EBCDIC HebrewCp437 437 8-bit ASCII US PCCp500 500 IBM EBCDIC InternationalCp737 737 8-bit ASCII Greek MS-DOSCp775 775 8-bit ASCII Baltic MS-DOSCp838 838 IBM EBCDIC ThailandCp850 850 8-bit ASCII Latin-1

MultinationalCp852 852 8-bit ASCII Latin-2Cp855 855 8-bit ASCII CyrillicCp856 856 8-bit ASCII HebrewCp857 857 8-bit ASCII Latin-5Cp860 860 8-bit ASCII PortugalCp861 861 8-bit ASCII IcelandCp862 862 8-bit ASCII HebrewCp863 863 8-bit ASCII CanadaCp864 864 8-bit ASCII ArabicCp865 865 8-bit ASCII Denmark,

NorwayCp866 866 8-bit ASCII CyrillicCp868 868 8-bit ASCII UrduCp869 869 8-bit ASCII GreekCp870 870 IBM EBCDIC Latin-2Cp871 871 IBM EBCDIC IcelandCp874 874 8-bit ASCII ThailandCp875 875 IBM EBCDIC GreekCp918 918 IBM EBCDIC UrduCp921 921 8-bit ASCII BalticCp922 922 8-bit ASCII EstoniaCp930 930 IBM EBCDIC Japanese

Extended KatakanaCp933 933 IBM EBCDIC KoreanCp935 935 IBM EBCDIC Simplified

ChineseCp937 937 IBM EBCDIC Traditional

ChineseCp939 939 IBM EBCDIC Japanese

Extended Latin

Chapter 3. AS/400 Developer Kit for Java concepts 43

Page 52: AS400 Developer Kit for Java (Rzaha)

file.encoding CCSID DescriptionCp942 942 8-bit ASCII JapaneseCp943 943 Japanese PC data mixed for

open envCp948 948 8-bit ASCII IBM Traditional

ChineseCp949 949 8-bit ASCII Korean KSC5601Cp950 950 8-bit ASCII T-Chinese BIG-5Cp964 964 EUC Traditional ChineseCp970 970 EUC KoreanCp1006 1006 ISO 8-bit UrduCp1025 1025 IBM EBCDIC CyrillicCp1026 1026 IBM EBCDIC TurkeyCp1046 1046 8-bit ASCII ArabicCp1097 1097 IBM EBCDIC FarsiCp1098 1098 8-bit ASCII FarsiCp1112 1112 IBM EBCDIC BalticCp1122 1122 IBM EBCDIC EstoniaCp1123 1123 IBM EBCDIC UkraineCp1124 1124 ISO 8-bit UkraineCp1250 1250 MS-Win Latin-2Cp1251 1251 MS-Win CyrillicCp1252 1252 MS-Win Latin-1Cp1253 1253 MS-Win GreekCp1254 1254 MS-Win TurkishCp1255 1255 MS-Win HebrewCp1256 1256 MS-Win ArabicCp1257 1257 MS-Win BalticCp1258 1251 MS-Win RussianCp1381 1381 8-bit ASCII S-Chinese GBCp1383 1383 EUC Simplified ChineseCp33722 33722 EUC JapaneseEUC_CN 1383 EUC for Simplified ChineseEUC_JP 33722 EUC for JapaneseEUC_KR 970 EUC for KoreanEUC_TW 964 EUC for Traditional ChineseGB2312 1381 8-bit ASCII S-Chinese GBGBK 1386 New simplified Chinese 8-bit

ASCII 9ISO2022CN_CNS None Available 7-bit ASCII for Traditional

ChineseISO2022CN_GB None Available 7-bit ASCII for Simplified

ChineseISO2022JP 5054 7-bit ASCII for JapaneseISO2022KR 25546 7-bit ASCII for KoreanISO8859_1 819 ISO 8859-1 ISO Latin-1ISO8859_2 912 ISO 8859-2 ISO Latin-2ISO8859_3 913 ISO 8859-3 ISO Latin-3ISO8859_4 914 ISO 8859-4 ISO Latin-4ISO8859_5 915 ISO 8859-5 ISO Latin-5ISO8859_6 1089 ISO 8859-6 ISO Latin-6

(Arabic)ISO8859_7 813 ISO 8859-7 ISO Latin-7

(Greek/Latin)ISO8859_8 916 ISO 8859-8 ISO Latin-8

(Hebrew)

44 AS/400 Developer Kit for Java

Page 53: AS400 Developer Kit for Java (Rzaha)

file.encoding CCSID DescriptionISO8859_9 920 ISO 8859-9 ISO Latin-9

(ECMA-128, Turkey)JIS0201 897 Japanese industry standard

X0201JIS0208 952 Japanese industry standard

X0208JIS0212 953 Japanese industry standard

X0212Johab None Available Korean composition Hangul

encoding (full)K018_R CyrillicKSC5601 949 8-bit ASCII KoreanMS874 874 MS-Win ThailandSJIS 932 8-bit ASCII JapaneseTIS620 874 Thai industry standard 620UTF8 1208 UTF-8 (IBM CCSID 1208,

which is not yet available onAS/400)

Unicode 13488 UNICODE, UCS-2UnicodeBig 13488 Same as UnicodeUnicodeBigUnmarked Unicode with no byte-order

markUnicodeLittle Unicode with little-endian

byte orderUnicodeLittleUnmarked UnicodeLittle with no

byte-order mark

For default values, see Default file.encoding values.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Default file.encoding valuesThis table shows how the file.encoding value is set based on the AS/400 codedcharacter set identifier (CCSID) when the Java virtual machine starts.

AS/400 CCSID CorrespondingASCII CCSID

Default file.encoding Description

37 ISO8859_1 English for USA,Canada, NewZealand, andAustralia; Portuguesefor Portugal andBrazil; and Dutch forNetherlands

256 ISO8859_1 International #1273 ISO8859_1 German/Germany,

German/Austria277 ISO8859_1 Danish/Denmark,

Norwegian/Norway,Norwegian/Norway,NY

278 ISO8859_1 Finnish/Finland280 ISO8859_1 Italian/Italy

Chapter 3. AS/400 Developer Kit for Java concepts 45

Page 54: AS400 Developer Kit for Java (Rzaha)

AS/400 CCSID CorrespondingASCII CCSID

Default file.encoding Description

284 ISO8859_1 Catalan/Spain,Spanish/Spain

285 ISO8859_1 English/Great Britain,English/Ireland

290 Cp942 SBCS portion ofJapanese EBCDICmixed (CCSID 5026)

297 ISO8859_1 French/France420 ISO8859_6 Arabic/Egypt423 ISO8859_7 Greece424 ISO8859_8 Hebrew/Israel500 ISO8859_1 German/Switzerland,

French/Belgium,French/Canada,French/Switzerland

833 Cp949 SBCS portion ofKorean EBCDICmixed (CCSID 933)

836 Cp1381 SBCS portion ofS-Chinese EBCDICmixed (CCSID 935).

838 Cp874 Thai870 ISO8859_2 Czech/Czech

Republic,Croatian/Croatia,Hungarian/Hungary,Polish/Poland

871 ISO8859_1 Icelandic/Iceland875 ISO8859_7 Greek/Greece880 ISO8859_5 Bulgaria (ISO 8859_5)905 ISO8859_9 Turkey extended918 Cp868 Urdu930 Cp942 Japanese EBCDIC

mixed (very close toCCSID 5026)

933 Cp970 Korean/Korea935 Cp1381 Simplified

Chinese/China937 Cp950 Traditional

Chinese/Taiwan939 Cp942 Japanese EBCDIC

Mixed (very close toCCSID 5035)

1025 ISO8859_5 Belorussian/Belarus,Bulgarian/Bulgaria,Macedonian/Macedonia,Russian/Russia

1026 ISO8859_9 Turkish/Turkey1027 Cp942 SBCS portion of

Japanese EBCDICmixed (CCSID 5035)

1097 Cp1098 Farsi1112 Cp921 Lithuanian/Lithuania,

Latvian/Latvia, Baltic1122 Cp922 Estonian/Estonia1123 Cp1123 Ukrainian/Ukraine

46 AS/400 Developer Kit for Java

Page 55: AS400 Developer Kit for Java (Rzaha)

AS/400 CCSID CorrespondingASCII CCSID

Default file.encoding Description

1130 ISO8859_1 Vietnamese. There isno Vietnameselanguage support inJDK 1.1.4, sofile.encoding is set to8859_1.

1132 ISO8859_1 Lao. There is no Laolanguage support inJDK 1.1.4, sofile.encoding is set to8859_1.

1388 Cp1381 Simplified ChineseEBCDIC mixed (GBKis included)

5026 Cp942 Japanese EBCDICmixed CCSID(Extended Katakana)

5035 Cp942 Japanese EBCDICmixed CCSID(Extended Latin)

8612 Cp864 Arabic (base shapesonly) (or ASCII 420and 8859_6)

9030 Cp874 Thai (host extendedSBCS)

13124 Cp1381 SBCS portion ofSimplified ChineseEBCDIC mixed (GBKis included)

28709 Cp948 SBCS portion ofTraditional ChineseEBCDIC mixed(CCSID 937)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java Naming and Directory InterfaceThe Java Naming and Directory Interface (JNDI) is part of JavaSoft’s platformapplication program interfaces (API). With JNDI you can connect seamlessly tomultiple naming and directory services. You can build powerful and portabledirectory-enabled Java applications by using this interface.

JavaSoft developed the JNDI specification with leading industry partners,including IBM, SunSoft, Novell, Netscape, and Hewlett-Packard Co.

If you would like to run JNDI, add this to your classpath:/QIBM/ProdData/Java400/ext/ibmjndi.jar:/QIBM/ProdData/Java400/ext/jndi.jar

For more information about JNDI, see Java Naming and Directory interface by Sun

Microsystems, Inc. For IBM-specific information, see the DSSeries LDAP V3Client for Java Programming Guide.

Chapter 3. AS/400 Developer Kit for Java concepts 47

Page 56: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java Virtual Machine Debug Interface

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the Java Virtual MachineDebug Interface (JVMDI) is part of Sun Microsystems, Inc. platform applicationprogram interfaces (APIs). JVMDI allows anyone to write a Java debugger forAS/400 in AS/400 C code. The debugger does not need to know the internalstructure of the Java virtual machine, and cannot harm the Java virtual machinesince it uses JVMDI interfaces.

The debugger runs in the same multi-thread capable job as the Java virtualmachine. The debugger uses Java Native Interface (JNI) Invocation APIs to create aJava virtual machine. It then places a hook at the beginning of a user class mainmethod and calls the main method. When the main method begins, the hook is hitand debugging begins. Typical debug facilities are available, such as settingbreakpoints, stepping, displaying variables, and changing variables.

The debugger handles communication between the job where the Java virtualmachine is running and a job handling the user interface. This user interface iseither on your AS/400 or another system.

A service program, called QJVAJVMDI that resides in the QSYS library, supportsthe JVMDI functions.

For more information about JVMDI, see Java Virtual Machine Debugger Interface

by Sun Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Limitations, restrictions, and unique behaviorsWhen using the AS/400 Developer Kit for Java, you may notice that there aresome limitations in how it is used. This list identifies any known limitations,restrictions, or unique behaviors.v When a class is loaded and its superclasses are not found, the error indicates

that the original class was not found. For example, if class B extends class A,and class A is not found when loading class B, the error indicates that class Bwas not found, even though it is actually class A that was not found. When yousee an error that indicates that a class was not found, check to make sure thatthe class and all of its superclasses are in the CLASSPATH. This also applies tointerfaces that are implemented by the class being loaded.

v The garbage collection heap is limited to 132,800 MB.

v The number of constructed objects is limited to 256 million.v The java.net backlog parameter on AS/400 may behave differently than on other

platforms. For example:– Listen backlogs 0, 1

- Listen(0) means to allow one pending connection; it does not disable asocket.

48 AS/400 Developer Kit for Java

Page 57: AS400 Developer Kit for Java (Rzaha)

- Listen(1) means to allow one pending comment, and means the same asListen(0).

– Listen backlogs > 1- This allows many pending requests to remain on the listen queue. If a new

connection request arrives and the queue is at the limit, then it deletes oneof the pending requests.

v On other platforms that support JDK 1.1.6, the DecimalFormat class mayincorrectly format numeric input. This was fixed in the version of JDK 1.1.6 thatis used on AS/400.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

The Java platformThe Java platform is the environment for developing and managing Java appletsand applications. It consists of three primary components: the Java language, theJava packages, and the Java virtual machine. The Java language and packages aresimilar to C++ and its class libraries. The Java packages contain classes, which areavailable in any compliant Java implementation. The application program interface(API) should be the same on any system that supports Java.

Java differs from a traditional language, like C++, in how it compiles and runs. Ina traditional programming environment, you write and compile source code of aprogram into object code for a specific hardware and operating system. The objectcode binds to other object code modules to create a running program. Theexecutable code is specific for a particular set of computer hardware and does notrun on other systems without modification. This graphic illustrates the traditionallanguage deployment environment.

The Java environment differs from other programming environments in that theJava compiler does not generate machine code for a hardware-specific instructionset. Instead, the Java compiler converts Java source code into Java virtual machineinstructions, which Java class files store. You can use either ZIP files or JAR files tostore class files. The class file does not target a specific hardware platform, butinstead targets the Java virtual machine architecture.

This graphic shows the Java environment, as explained above.

Chapter 3. AS/400 Developer Kit for Java concepts 49

Page 58: AS400 Developer Kit for Java (Rzaha)

You can embed the Java virtual machine within a web browser or an operatingsystem such as IBM Operating System/400 (OS/400). The Java virtual machineconsists of the Java interpreter and runtime. The interpreter performs the task ofinterpreting the class file and running the Java instructions on a particularhardware platform. The Java virtual machine is what allows Java code to bewritten and compiled once, and run on any platform.

Java is a “multithreaded” programming language, thus more than one thread maybe running within the Java virtual machine at one time. Java threads provide away for a Java program to perform multiple tasks at the same time.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java applications and appletsYou can write Java programs in two forms: applications and applets.

Applications are stand-alone programs that do not require the use of a browser.Java applications run by starting the Java interpreter from the command line andby specifying the file that contains the compiled application. Applications usuallyreside on the system on which they are deployed. Applications access resources onthe system, and the Java “sandbox” security model does not restrict applications.

A Java applet is a small computer program that you write in Java and run insideof a Java-compatible browser or appletviewer. A Hypertext Markup Language(HTML) web document can include a reference to the system on which the appletresides. At runtime, the server downloads the applet from the server onto thetarget system. On the target system, the applet is restricted from accessing localsystem resources unless authorization has been explicitly granted.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java virtual machineThe Java virtual machine is a runtime environment that you can add into a webbrowser or any operating system, such as IBM Operating System/400 (OS/400).The Java virtual machine runs instructions that a Java compiler generates. Itconsists of a bytecode interpreter and runtime that allow Java class files to run onany platform, regardless of the platform on which they were originally developed.

50 AS/400 Developer Kit for Java

Page 59: AS400 Developer Kit for Java (Rzaha)

The class loader and security manager, which is part of the Java runtime, insulatecode that comes from another platform. They also can restrict which systemresources each class that is loaded accesses.

Note: Java applications are not restricted; only applets are restricted. Applicationscan freely access system resources and use native methods. Most AS/400Developer Kit for Java programs are applications.

You can use the Create Java Program (CRTJVAPGM) command to ensure that thecode meets the safety requirements that the Java runtime imposes to verify thebytecodes. This includes enforcing type restrictions, checking data conversions,ensuring that parameter stack overflows or underflows will not occur, andchecking for access violations. However, you do not need to explicitly verify thebytecodes. If you do not use the CRTJVAPGM command in advance, then thechecks occur during the first use of a class. Once the bytecodes are verified, theinterpreter decodes the bytecodes and runs the machine instructions that areneeded to carry out the desired operations.

Note: The Java interpreter is only used if you specify OPTIMIZE(*INTERPRET) orINTERPRET(*YES).

In addition to loading and running the bytecodes, the Java virtual machineincludes a garbage collector that manages memory. Garbage collection runs at thesame time as the loading and interpretation of the bytecodes.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java class filesJava class files are stream files that are produced when a source file is compiled bythe Java compiler. The class file contains tables that describe each field and methodof the class. The file also contains the bytecodes for each method, static data, anddescriptions that are used to represent Java objects.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java ZIP filesA ZIP file is a single file that contains many class files, which may be individuallyextracted. The contents of a ZIP file may be either compressed or not compressed.ZIP files are an especially useful way to store classes on systems that do notsupport long file names.

To combine many files into one, see Java JAR files.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java JAR filesA Java ARchive (JAR) file is a file format, that is based on the ZIP file format,which combines many files into one. You can use JAR as a general archiving tool,but its main purpose is to download Java applets and their components (.classfiles, images, and sounds). Java applets download into a browser in a single

Chapter 3. AS/400 Developer Kit for Java concepts 51

Page 60: AS400 Developer Kit for Java (Rzaha)

Hypertext Transfer Protocol (HTTP) transaction rather than by opening a newconnection for each piece. This method of downloading improves the speed atwhich an applet loads on a web page and begins functioning.

JAR is the only archive format that is cross-platform. JAR is also the only formatthat handles audio files and image files, as well as class files. JAR is an openstandard, fully extendable format that is written in Java.

The JAR format also supports compression, which reduces the size of the file anddecreases download time. Additionally, an applet author may digitally signindividual entries in a JAR file to authenticate their origin.

To update classes in JAR files, see the Java ajar tool.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java interpreterThe Java interpreter is the part of the Java virtual machine that interprets Java classfiles for a particular hardware platform. The Java interpreter decodes eachbytecode and runs a series of machine instructions for that bytecode.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java threadsA thread is a single independent stream that runs within a program. Java is amultithreaded programming language, so more than one thread may be runningwithin the Java virtual machine at one time. Java threads provide a way for a Javaprogram to perform multiple tasks at the same time. A thread is essentially a flowof control in a program.

Threads are a modern programming construct that are used to support concurrentprograms and to improve the performance and scalability of applications. Mostprogramming languages support threads through the use of add-in programminglibraries. Java supports threads as built-in application program interfaces (API).

Note: The use of threads provides the support to increase the interactivity,meaning a shorter wait at the keyboard because more things are running inparallel. But, the program is not necessarily more interactive just because it hasthreads.

Threads are the mechanism for waiting on long running interactions, while stillallowing the program to handle other work. Threads are the ability to supportmultiple flows through the same code stream. They are sometimes called“lightweight processes”. The Java language includes direct support for threads.But, by design, it does not support asynchronous non-blocking input and outputwith interrupts or multiple wait.

Threads allow the development of parallel programs that scale well in anenvironment where a machine has multiple processors. If properly constructed,they also provide a model for handling multiple transactions and users.

52 AS/400 Developer Kit for Java

Page 61: AS400 Developer Kit for Java (Rzaha)

You can use threads in a Java program for a number of situations. Some programsmust be able to engage in multiple activities and still be able to respond toadditional input from the user. For example, a Web browser should be able torespond to user input while playing a sound.

Threads can also use asynchronous methods. When you call a second method, youdo not have to wait for the first method to complete before the second methodcontinues with its own activity.

There are also many reasons not to use threads. If a program uses inherentlysequential logic, one thread can accomplish the entire sequence. Using multiplethreads in such a case results in a complex program with no benefits. There isconsiderable work in creating and starting a thread. If an operation involves only afew statements, it is faster to handle it in a single thread. This can be true evenwhen the operation is conceptually asynchronous. When multiple threads shareobjects, the objects must synchronize to coordinate thread access and maintainconsistency. Synchronization adds complexity to a program, is difficult to tune foroptimal performance, and can be a source of programming errors.

For more threads information, see Developing multithreaded applications .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Sun Microsystems, Inc. Java Development KitThe Java Development Kit (JDK) is software that is distributed by SunMicrosystems, Inc. for Java developers. It includes the Java interpreter, Java classes,and Java development tools: compiler, debugger, disassembler, appletviewer, stubfile generator, and documentation generator.

The JDK enables programmers to write applications that are developed once andrun anywhere on any Java virtual machine. Java applications that are developedwith the JDK on one system can be used on another system without changing orrecompiling the code. The Java class files are portable to any standard Java virtualmachine.

To find more information about the current JDK, check the version of the AS/400Developer Kit for Java on your AS/400.

You can check the version of the default AS/400 Developer Kit for Java Javavirtual machine on your AS/400 by entering either of the following:v java -version on the Qshell command prompt.v RUNJVA CLASS(*VERSION) on the CL command line.

Then, look for the same version of Sun Microsystems, Inc. JDK at The Source for

Java Technology java.sun.com for specific documentation. The AS/400Developer Kit for Java is a compatible implementation of the Sun Microsystems,Inc. Java Technology, so you should be familiar with their JDK documentation.

See Support for multiple Java Development Kits (JDKs) for more information aboutusing different Java virtual machines.

Chapter 3. AS/400 Developer Kit for Java concepts 53

Page 62: AS400 Developer Kit for Java (Rzaha)

For more specific details on Sun Microsystems, Inc. Java Development Kit, seethese topics:v Java packages lists the packages that are available as part of Sun Microsystems,

Inc. JDK.v Java tools is a reference table that lists the tools that Sun Microsystems, Inc. JDK

supplies.v Native methods and the Java Native Interface defines what a native method is

and what they do. This topic also briefly explains the Java Native Interface.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java packagesA Java package is a way of grouping related classes and interfaces in Java. Javapackages are similar to class libraries that are available in other languages.

The Java packages, which provide the Java APIs, are available as part of SunMicrosystems, Inc. Java Development Kit (JDK).

Package Contentsjava.applet Applet classesjava.awt Graphics, window, and graphical user

interface (GUI) classesjava.awt.datatransfer Data transfer classesjava.awt.event Event processing classes and interfacesjava.awt.image Image processing classesjava.awt.peer GUI interfaces for platform independencejava.beans JavaBeans component model APIjava.io Input and output classesjava.lang Core language classesjava.lang.reflect Reflection API classesjava.math Arbitrary precision arithmeticjava.net Networking classesjava.rmi Remote Method Invocation classesjava.rmi.dgc RMI-related classesjava.rmi.registry RMI-related classesjava.rmi.server RMI-related classesjava.security Security classesjava.security.acl Security-related classesjava.security.interfaces Security-related classesjava.sql JDBC SQL API for database classesjava.text Internationalization classesjava.util Data typesjava.util.zip Compression and decompression classes

For more information about the Java APIs by Sun Microsystems, Inc., see the SunMicrosystems, Inc. API Users Guide.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

54 AS/400 Developer Kit for Java

Page 63: AS400 Developer Kit for Java (Rzaha)

Java toolsFor a complete list of tools that Sun Microsystems, Inc. Java Development Kitsupplies, see Tools Reference by Sun Microsystems, Inc. For more informationabout each individual tool that the AS/400 Developer Kit for Java supports, seeJava tools that are supported by the AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Native methods and the Java Native InterfaceNative methods are Java methods that start in a language other than Java. Nativemethods can access system-specific functions and APIs that are not availabledirectly in Java.

The use of native methods limits the portability of an application, because itinvolves system-specific code. Native method can either be new native codestatements or native code statements that call existing native code.

Once you decide that a native method is required, it may have to interoperate withthe Java virtual machine where it runs. The Java Native Interface (JNI) facilitatesthis interoperability in a platform-neutral way.

The JNI is a set of interfaces that permit a native method to interoperate with theJava virtual machine in numerous ways. For example, the JNI includes interfacesthat create new objects and call methods, get fields and set fields, processexceptions, and manipulate strings and arrays.

For a complete description of the JNI, refer to the Java Native Interface by Sun

Microsystems, Inc. , or The Source for Java Technology java.sun.com .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 3. AS/400 Developer Kit for Java concepts 55

Page 64: AS400 Developer Kit for Java (Rzaha)

56 AS/400 Developer Kit for Java

Page 65: AS400 Developer Kit for Java (Rzaha)

Chapter 4. Commands and tools for the AS/400 Developer Kitfor Java

When using the AS/400 Developer Kit for Java, you can either use Java tools withthe Qshell Interpreter or CL commands.

If you have prior Java programming experience, you may be more comfortableusing the Qshell Interpreter Java tools, because they are similar to the tools thatyou would use with Sun Microsystems, Inc. Java Development Kit. See QshellInterpreter for information about using the Qshell environment.

If you are an AS/400 programmer, you may want to use the CL commands forJava that are typical to the AS/400 server environment. Read on for moreinformation about using CL commands and Operations Navigator commands.

You can use any of these commands and tools with the AS/400 Developer Kit forJava:v The Qshell environment includes the Java development tools that are typically

required for program development.v The CL environment contains the CL commands for optimizing and managing

Java programs.v The Operations Navigator commands also create and run optimized Java

programs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java tools that are supported by the AS/400 Developer Kit for JavaThe AS/400 Developer Kit for Java supports these tools.v Java ajar toolv Java appletviewer toolv Java extcheck toolv Java jar toolv Java jarsigner toolv Java javac toolv Java javadoc toolv Java javah toolv Java javakey toolv Java javap toolv Java keytoolv Java native2ascii toolv Java policytoolv Java rmic toolv Java rmid toolv Java rmiregistry toolv Java serialver tool

© Copyright IBM Corp. 1998, 1999 57

Page 66: AS400 Developer Kit for Java (Rzaha)

v Java tnameserv tool

With a few exceptions, the Java tools, except the ajar tool, support the syntax andoptions that are documented by Sun Microsystems, Inc. They must all run by usingthe Qshell Interpreter.

You can start the Qshell Interpreter by using the Start Qshell (STRQSH or QSH)command. When the Qshell Interpreter is running, a QSH Command Entry displayappears. All output and messages from Java tools and programs that run underQshell appear in this display. Any input to a Java program is also read from thisdisplay. See Java command in Qshell for more details.

Note: Functions of AS/400 command entry are not available directly from withinthe Qshell. To get a command entry, press F21 (CL command entry).

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java ajar toolThe ajar tool is an alternative interface to the jar tool that you use to create andmanipulate Java ARchive (JAR) files. You can use the ajar tool to manipulate bothJAR files and ZIP files.

If you need a ZIP interface or UNZIP interface, use the ajar tool instead of the jartool.

The ajar tool lists the contents of JAR files, extracts from JAR files, creates newJAR files, and supports many of the ZIP formats just as the jar tool does.Additionally, the ajar tool supports adding and deleting files in existing JAR files.

The ajar tool is available using the Qshell Interpreter. For more details, see ajar -Alternative Java archive.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java appletviewer toolThe appletviewer tool allows you to run applets without a web browser. It iscompatible with the appletviewer tool that is supplied by Sun Microsystems, Inc.

The appletviewer tool is available using the Qshell Interpreter. You need to use

Remote Abstract Window Toolkit to run the appletviewer tool. See Runningthe Java appletviewer tool with Remote AWT for information about how to set up

Remote AWT to use the appletviewer tool.

For more information about the appletviewer tool, see the appletviewer tool bySun Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

58 AS/400 Developer Kit for Java

Page 67: AS400 Developer Kit for Java (Rzaha)

Running the Java appletviewer tool with Remote AbstractWindow Toolkit

To use the Java appletviewer tool, you need to set up the Remote AbstractWindow Toolkit for Java on a Windows remote display, and use either thesun.applet.AppletViewer class or run the appletviewer tool in the QshellInterpreter with Remote AWT properties.

For example, if you use the sun.applet.AppletViewer class and run example1.htmlout of the TicTacToe directory, the command line should look like this:JAVA CLASS(sun.applet.AppletViewer) PARM('example1.html') CLASSPATH('/TicTacToe')PROP((RmtAwtServer '1.1.11.11') (os400.class.path.rawt 1)(java version 1.2))

If you use the appletviewer tool in the Qshell Interpreter and run example1.htmlout of the TicTacToe directory, the commands should look like this:qsh “enter”cd TicTacToe “enter”Appletviewer -J-DRmtAwtServer=1.1.11.11 -J-Dos400.class.path.rawt=1 -J-Djava.version=1.2 example1.

Note: -J are runtime flags for Appletviewer. -D are properties.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java extcheck tool

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the extcheck tool detectsversion conflicts between a target JAR file and currently installed extension JARfiles. It is compatible with the keytool that is supplied by Sun Microsystems, Inc.

The extcheck tool is available using the Qshell Interpreter.

For more information about the extcheck tool, see the extcheck tool by Sun

Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java jar toolThe jar tool combines multiple files into a single Java ARchive (JAR) file. It iscompatible with the jar tool that is supplied by Sun Microsystems, Inc.

The jar tool is available using the Qshell Interpreter.

For an alternative interface to the jar tool, see the ajar tool for creating andmanipulating JAR files.

For more information about AS/400 file systems, see the OS/400 Integrated FileSystem Introduction or files in the integrated file system.

For more information about the jar tool, see the jar tool by Sun Microsystems, Inc.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 59

Page 68: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java jarsigner tool

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the jarsigner tool signsJAR files and verifies signatures on signed JAR files. The jarsigner tool accessesthe keystore, which the keytool creates and manages, when it needs to find theprivate key for signing a JAR file. In J2SDK, the jarsigner and keytool toolsreplace the javakey tool. It is compatible with the jarsigner tool that is suppliedby Sun Microsystems, Inc.

The jarsigner tool is available using the Qshell Interpreter.

For more information about the jarsigner tool, see the jarsigner tool by Sun

Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java javac toolThe javac tool compiles Java programs. It is compatible with the javac tool that issupplied by Sun Microsystems, Inc. with one exception.

-classpathDoes not override the default classpath. Instead, it is appended to thesystem default classpath. The -classpath option does override theCLASSPATH environment variable.

The javac tool is available using the Qshell Interpreter.

If you have JDK 1.1.x installed on AS/400 as your default, but you need to run the1.2 version of the java command, enter this command:javac -djava.version=1.2 <my_dir> MyProgram.java

For more information about the javac tool, see the javac tool by Sun Microsystems,Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java javadoc toolThe javadoc tool generates API documentation. It is compatible with the javadoctool that is supplied by Sun Microsystems, Inc.

The javadoc tool is available using the Qshell Interpreter.

For more information about the javadoc tool, see the javadoc tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

60 AS/400 Developer Kit for Java

Page 69: AS400 Developer Kit for Java (Rzaha)

Java javah toolThe javah tool facilitates the implementation of Java native methods. It iscompatible with the javah tool that is supplied by Sun Microsystems, Inc. with afew exceptions.

Note: Writing native methods means that your application is not 100% pure Java.It also means that your application is not directly portable across platforms. Nativemethods are, by nature, platform or system specific. Using native methods mayincrease your development and maintenance costs for your applications.

The javah tool is available using the Qshell Interpreter. It reads a Java class fileand creates a C-language header file in the current working directory. The headerfile that is written is an AS/400 Stream File (STMF). It must be copied to a filemember before it can be included in a C program on AS/400.

The javah tool is compatible with the tool that is provided by Sun Microsystems,Inc. If these options are specified; however, AS/400 ignores them.

-td The javah tool on AS/400 does not require a temporary directory.

-stubs Java on AS/400 only supports the Java Native Interface (JNI) form ofnative methods. Stubs were only required for the pre-JNI form of nativemethods.

-trace Relates to the .c stub file output, which Java on AS/400 does not support.

-v Not supported.

Note:The -jni option must always be specified. The AS/400 system does notsupport native method implementations prior to JNI.

For more information about the javah tool, see the javah tool by Sun Microsystems,Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java javakey toolUse the javakey tool for encryption key, and certificate generation andmanagement, including generation of digital signatures for applets. It is compatiblewith the javakey tool that is supplied by Sun Microsystems, Inc. in JavaDevelopment Kit (JDK) versions 1.1.x.

In Java 2 Software Development Kit (J2SDK), Standard Edition, version 1.2, thejavakey tool is obsolete. Due to bugs in JDK versions 1.1.x, code that is signedusing the 1.1.x javakey tool is recognized as unsigned in the J2SDK, version 1.2. Ifyou sign code using J2SDK, version 1.2, it is recognized as unsigned on JDK 1.1.xversions.

Note: The AS/400 secure sockets layer (SSL) support cannot access keys created bythis tool. Instead, you must use the certificate and key containers that areintegrated into the AS/400 and created or imported with the Digital CertificateManager. See making a Java application secure with the secure sockets layer formore information.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 61

Page 70: AS400 Developer Kit for Java (Rzaha)

Applet packaging and applet signing is dependent on your browser. Check yourbrowser documentation to ensure that your browser is compatible with the JavaJAR file format and javakey applet signing.

Note: The files that are created by the javakey tool contain sensitive information.Appropriate integrated file system security measures protect the public and privatekey files.

The javakey tool is available using the Qshell Interpreter.

For more information about AS/400 file systems, see the OS/400 Integrated FileSystem Introduction or files in the integrated file system.

For more information about the javakey tool, see the javakey tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java javap toolThe javap tool disassembles compiled Java files and prints out a representation ofthe Java program. This may be helpful when the original source code is no longeravailable on a system.

It is compatible with the javap tool that is supplied by Sun Microsystems, Inc. witha few exceptions.

-b This option is ignored. Backward compatibility is not required, becauseJava on AS/400 only supports Java Development Kit (JDK) 1.1.4 and later.

-p On AS/400, -p is not a valid option. You must spell out -private.

-verifyThis option is ignored. The javap tool does not do verification on AS/400.

The javap tool is available using the Qshell Interpreter.

Note:The use of the javap tool to disassemble classes may violate the licenseagreement for those classes. Consult the license agreement for the classes beforeusing the javap tool.

For more information about the javap tool, see the javap tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java keytool

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the keytool createspublic and private key pairs, self-signed certificates, and manage keystores. InJ2SDK, the jarsigner and keytool tools replace the javakey tool. It is compatiblewith the keytool that is supplied by Sun Microsystems, Inc.

The keytool is available using the Qshell Interpreter.

62 AS/400 Developer Kit for Java

Page 71: AS400 Developer Kit for Java (Rzaha)

For more information about the keytool, see the keytool by Sun Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java native2ascii toolThe native2ascii tool converts a file with native-encoded characters (characterswhich are non-Latin 1 and non-Unicode) to one with Unicode-encoded characters.It is compatible with the native2ascii tool that is supplied by Sun Microsystems,Inc.

The native2ascii tool is available using the Qshell Interpreter.

For more information about the native2ascii tool, see the native2ascii tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java policytool

In Java 2 SDK, Standard Edition, version 1.2, the policytool creates andchanges the external policy configuration files that define the Java security policyof your installation. It is compatible with the policytool that is supplied by SunMicrosystems, Inc.

The policytool is a graphical user interface (GUI) tool available using the QshellInterpreter and the Remote Abstract Window Toolkit. See AS/400 Developer Kitfor Java Remote Abstract Window Toolkit for more information.

For more information about the policytool, see the policytool by Sun

Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java rmic toolThe rmic tool generates stub files and class files for Java objects. It is compatiblewith the rmic tool that is supplied by Sun Microsystems, Inc.

The rmic tool is available using the Qshell Interpreter.

For more information about the rmic tool, see the rmic tool by Sun Microsystems,Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 63

Page 72: AS400 Developer Kit for Java (Rzaha)

Java rmid tool

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the rmid tool starts theactivation system daemon, so objects can be registered and activated in a Javavirtual machine. It is compatible with the rmid tool that is supplied by SunMicrosystems, Inc.

The rmid tool is available using the Qshell Interpreter.

For more information about the rmid tool, see the rmid tool by Sun Microsystems,

Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java rmiregistry toolThe rmiregistry tool starts a remote object registry on a specified port. It iscompatible with the rmiregistry tool that is supplied by Sun Microsystems, Inc.

The rmiregistry tool is available using the Qshell Interpreter.

For more information about the rmiregistry tool, see the rmiregistry tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java serialver toolThe serialver tool returns the version number or serialization-unique identifier forone or more classes. It is compatible with the serialver tool that is supplied bySun Microsystems, Inc.

The serialver tool is available using the Qshell Interpreter.

For more information about the serialver tool, see the serialver tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java tnameserv tool

In Java 2 SDK (J2SDK), Standard Edition, version 1.2, the tnameserv toolprovides access to the naming service. It is compatible with the tnameserv tool thatis supplied by Sun Microsystems, Inc.

The tnameserv tool is available using the Qshell Interpreter.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

64 AS/400 Developer Kit for Java

Page 73: AS400 Developer Kit for Java (Rzaha)

Java command in QshellThe java command in Qshell runs Java programs. It is compatible with the javatool that is supplied by Sun Microsystems, Inc. with a few exceptions.

The AS/400 Developer Kit for Java ignores these options of the java command inQshell.

Option Description-cs Not supported.-checksource Not supported.-debug Supported by the AS/400 internal debugger.-noasyncgc Garbage collection is always running with

the AS/400 Developer Kit for Java.-noclassgc Garbage collection is always running with

the AS/400 Developer Kit for Java.-prof AS/400 has its own performance tools.-ss Not applicable on AS/400.-oss Not applicable on AS/400.-t AS/400 uses its own trace function.-verify Always verify on AS/400.-verifyremote Always verify on AS/400.-noverify Always verify on AS/400.

On AS/400, the -classpath option does not override the default classpath. Instead,it is appended to the system default classpath. The -classpath option doesoverride the CLASSPATH environment variable.

The java command in Qshell supports new options for AS/400. These are the newoptions that are supported.

Option Description-secure Checks for public write access to directories

in the CLASSPATH.-gcfrq Specifies the garbage collection frequency.-gcpty Specifies the garbage collection priority.-opt Specifies the optimization level.-verbosegc A message is displayed for each garbage

collection sweep.

The Run Java (RUNJVA) command in the CL command reference informationdescribes these new options in detail. The CL command reference information forthe Create Java Program (CRTJVAPGM) command, Delete Java Program(DLTJVAPGM) command, and Display Java Program (DSPJVAPGM) commandcontains information about managing Java programs.

The java command in Qshell is available using the Qshell Interpreter.

For more information about the java command in Qshell, see the java tool by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 65

Page 74: AS400 Developer Kit for Java (Rzaha)

CL commands that are supported by JavaThe AS/400 Developer Kit for Java supports the these CL commands.v Create Java Program (CRTJVAPGM) command creates a Java program on

AS/400 from a Java class file, ZIP file, or JAR file.v Change Java Program (CHGJVAPGM) command changes the attributes of a Java

program.v JAVA command and Run Java (RUNJVA) command run AS/400 Java programs.v Delete Java Program (DLTJVAPGM) command deletes an AS/400 Java program

that is associated with a Java class file, ZIP file, or JAR file.

v Dump Java Virtual Machine (DMPJVM) command dumps information about

the Java virtual machine for a specified job to a spooled printer file.v Display Java Program (DSPJVAPGM) command displays information about a

Java program on AS/400.

For more information see the OS/400 Program and CL Command APIs, SC41-5870

book.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Create Java Program (CRTJVAPGM) commandPurpose:

The Create Java Program (CRTJVAPGM) command creates a Java program onAS/400 from a Java class file, or one or more Java programs from a JAR file. If thefile name ends with .jar or .zip, then it is a JAR file. The resulting Java programobject or objects become part of the class file or JAR file object, but cannot bechanged directly.The Java programs run when you start the Run Java (RUNJVA)command. You can control the size and performance of the Java program by usingthe OPTIMIZE parameter, or LICOPT parameter.

Syntax:CRTJVAPGM Command

(P)>>—CRTJVAPGM—CLSF(—.-class-file-name-.—)————————————————>

'-JAR-file-name—-'>—.———————————————.—.———————————-.———————>

| .-10————-. | | .-*YES-. |'-OPTIMIZE(—+-*INTERPRET-+—)-' '-REPLACE(—'-*NO—'—)-'

|-20————-||-30————-|'-40————-'

>—.———————————————-.—.————————————.——————>| .-*NONE———. | | .-*USER—. |'-ENBPFRCOL(—+-*ENTRYEXIT-+—)-' '-USRPRF(—'-*OWNER-'—)-'

'-*FULL———'>—.————————————-.—.————————————.—————————>

| .-*NO—. | | .-*NONE-. |'-USEADPAUT(—'-*YES-'—)-' '-SUBTREE(—'-*ALL—'—)-'

>—.————————————————-.———————————————————>| .-*OPTIMIZE———. |'-LICOPT(—'-options-string-'—)—'

66 AS/400 Developer Kit for Java

Page 75: AS400 Developer Kit for Java (Rzaha)

>—.————————————————.———————————————————-><| .-*CURRENT———-. |'-TGTRLS(—'-target-release-'—)-'

Notes: (P) All parameters preceding this point can be specified positionally.

Required parameters:

CLSF

The CLSF parameter specifies the class file name or JAR file name fromwhich you create Java programs on AS/400. One or more directory namesmay qualify the class file name.

For the class-file-name, specify the name of the class file or a pattern foridentifying the name of the class files that are used. Specify a pattern inthe last part of the name. An asterisk matches any number of characters,and a question mark matches a single character. Enclose the name inapostrophes if it is qualified or contains a pattern. An example of aqualified class file name is:'/directory1/directory2/myclassname.class'

An example of a pattern is:'/directory1/directory2/myclass*.class'

For the JAR-file-name, specify the name of the JAR file or a pattern foridentifying the name of the JAR files that are used. A file is a JAR file if itends with .jar or .zip. Specify a pattern in the last part of the name. Anasterisk matches any number of characters, and a question mark matches asingle character. Enclose the name in apostrophes if it is qualified orcontains a pattern. An example of a qualified JAR file name is:'/directory1/directory2/myappname.jar'

An example of a pattern is:'/directory1/directory2/myapp*.zip'

Optional parameters:

OPTIMIZE

The OPTIMIZE parameter for the CRTJVAPGM command specifies theoptimization level of the AS/400 Java program that attaches to the classfile object or JAR file object. If you use the OPTIMIZE(*INTERPRET)parameter, the resulting Java program is verified and converted to aninternal form. It is then interpreted when it runs. For the otheroptimization levels, the internal form includes AS/400 machineinstructions. These AS/400 machine instructions are optimized based onthe specified optimization level. The AS/400 directly runs the machineinstructions when the program runs.

When you specify OPTIMIZE(*INTERPRET), Java programs are smaller,but run slower than Java programs that are created with higheroptimization levels. As you increase the optimization level beyond 10, Javaprogram performance gradually improves, but the time that is required tocreate the Java program increases. It also makes it more difficult to debugthe Java program as you increase the optimization level.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 67

Page 76: AS400 Developer Kit for Java (Rzaha)

Typically, *INTERPRET is a good option during development and earlytesting, because quick edit, compile turnaround, and quality debugfunctions are important. As the program moves toward release, the level ofoptimization often increases.

This list shows how the optimization levels differ and what they do:

10 The Java program contains a transformed version of the class filebytecodes, but has only minimal additional compiler optimization.You can display and change variables while debugging.

20 The Java program contains a compiled version of the class filebytecodes and performs additional compiler optimization. You candisplay, but not change variables while debugging.

30 The Java program contains a compiled version of the class filebytecodes and performs more compiler optimization thanoptimization level 20. Debugging at higher optimization levels ismore difficult, because optimization reduces the ability to stop atprecise points in the code and display program variables. You candisplay, but not change variables while debugging. The values thatare presented may not be the current value of the variable.

40 The Java program contains a compiled version of the class filebytecodes and performs more compiler optimization thanoptimization level 30. In addition, it includes optimization thatdisables call and instruction tracing. Optimization level 40 includescross-class optimizations. In a small number of cases, the order inwhich static initializers are run for unrelated classes (not related byinheritance nor containment) may be different than outlined in thestatic initialization specification. In addition, it includesoptimization that disables call and instruction tracing.Note: If your Java program fails to optimize or throws anexception at optimization level 40, use optimization level 30.

*INTERPRETThe Java programs that you create are not optimized. When youstart the program, it interprets the class file bytecode. You candisplay and change variables while debugging.

REPLACE

The REPLACE parameter specifies whether a new Java program replacesan existing Java program that is associated with the class file.

*YES Forces all of the Java programs that are associated with the classfile or JAR file to be re-created for your selected optimization level.For large JAR files, this could be time consuming, but it creates thehighest performing code generation and uses the minimumamount of space on the disk.

*NO Recreates the minimum number of required Java programs that areassociated with the class file or JAR file. If classes have beenmodified, no Java program is associated with one or more classes.If the Java program is at a different optimization level than youhad specified with the OPTIMIZE parameter, new Java programsare created.

68 AS/400 Developer Kit for Java

Page 77: AS400 Developer Kit for Java (Rzaha)

ENBPFRCOL

The ENBPFRCOL parameter specifies whether or not to enable thecollection of performance data.

*NONEThe collection of performance data is not enabled. No performancedata is collected.

*ENTRYEXITThe performance data is collected for procedure entry and exit.

*FULL The performance data is collected for procedure entry and exit.Performance data is also collected before and after calls to theexternal procedures.

USRPRF

The USRPRF parameter specifies whether the authority checking that isdone while the program is running should include only the user who isrunning the program (*USER) or both the user who is running the programand the program owner (*OWNER). The user profiles of the program user,or both the program user and the program owner control which objects theprogram can use. This includes the authority that the program has for eachobject. Only the program owner or program user with QSECOFR authoritycan change the user profile attribute of an existing Java program.

Note: Integrated file system functions that the program might use, such asFile.delete(), do not recognize adopted authority. Integrated file systemfunctions only use the authority from the user who is running theprogram.

*USERThe program runs under the user profile of the program user.

*OWNERYou use the user profiles of both the program owner and programuser when processing the program. You can use the collective setsof object authority in both user profiles to find and access objectsduring program processing. Authority from the group profile ofthe owning user profile is not used.

USEADPAUT

The USEADPAUT parameter specifies whether or not you use programadopted authority from previous programs in the call stack as a source ofauthority when the program is running.

Note: Integrated file system functions that the program might use, such asFile.delete(), do not recognize adopted authority. Integrated file systemfunctions only use the authority from the user who is running theprogram.

*NO Do not use program adopted authority from previous call levelswhen the program is running. If an authorization list is specifiedfor the QUSEADPAUT system value and the user performingCRTJVAPGM is not included in that authorization list, then thevalue *NO is automatically supplied for this parameter.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 69

Page 78: AS400 Developer Kit for Java (Rzaha)

*YES Use program adopted authority from previous call levels when theprogram is running.

LICOPT

The LICOPT parameter specifies one or more licensed internal codecompile-time optimization options. Only advanced programmers, whounderstand the potential benefits and drawbacks of each selected type ofoptimization, should use this parameter. For a listing of recognized stringsfor the LICOPT parameter, see LICOPT parameter strings.

Note:You should contact your service representative for more informationon how to use these optimizations.

*OPTIMIZEThe *OPTIMIZE option uses the set of compile-time optimizations,which are implicitly associated with the optimization level that isspecified on the OPTIMIZE parameter. If you specifyOPTIMIZE(*INTERPRET), no compile-time optimizations areperformed.

’Licensed-Internal-Code-options-string’Use the selected licensed internal code compile-time optimizationoptions when creating the Java program object. Certainoptimization options may reduce your ability to debug the Javaprogram that was created.

SUBTREE

The SUBTREE parameter specifies whether or not subdirectories areprocessed when looking for files that match the CLSF keyword.

*NONEOnly the files that match the object name pattern are processed. Nosubtrees are processed. If the directory has subdirectories, neitherthe subdirectories nor the objects on the subdirectories areprocessed.

*ALL The entire subtree of the path that is specified in CLSF is processedto create Java programs for files that match the name that wasspecified on the CLSF parameter.

TGTRLS

The TGTRLS parameter specifies the release of the operating system onwhich you intend to use the object that is being created. When specifyingthe target-release, you use the VxRxMx format to specify the release. Vx isthe version. Rx is the release, and Mx is the modification level. Forexample, V4R5M0 is version 4, release 5, modification level 0. Valid valuesdepend on the current version, release, and modification level. These validvalues change with each new release.

*CURRENTThe object is used on the release of the operating system that is

70 AS/400 Developer Kit for Java

Page 79: AS400 Developer Kit for Java (Rzaha)

currently running on your system. The object can also be used on asystem that has any subsequent release of the operating systeminstalled.

target-releaseSpecify the release in the format VxRxMx. You can use the objecton a system with a specified release, or with any subsequentrelease of the operating system installed. Valid values depend onthe current version, release, and modification level. These validvalues change with each new release. To see a list of valid targetrelease levels, press the F4 key.

For more performance information, see tuning Java program performance with theAS/400 Developer Kit for Java.

See Example: Create Java Program (CRTJVAPGM) command for an example thatuses the CRTJVAPGM command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Licensed Internal Code option parameter stringsThis table shows the strings that are recognized by the Licensed Internal Codeoption (LICOPT) parameter. These strings are not case sensitive, but they areshown as mixed case for readability.

LICOPT parameter strings

String DescriptionAllFieldsVolatile If set, treats all fields as volatile.NoAllFieldsVolatile Is not set; does not treat all fields as volatile.AllowBindingToLoadedClasses Indicates that temporary class representations

that were created as a result of defineClasscalls within a running Java virtual machinemay be tightly bound to other classrepresentations within the same Java virtualmachine.

NoAllowBindingToLoadedClasses Indicates that temporary class representationsthat were created as a result of defineClasscalls within a running Java virtual machinemay not be tightly bound to other classrepresentations within the same Java virtualmachine.

AllowBindingWithinJar Indicates that class representations within aZIP file or JAR file may be tightly bound toother class representations within the sameZIP file or JAR file.

NoAllowBindingWithinJar Indicates that class representations within aZIP file or JAR file may not be tightly boundto other class representations within the sameZIP file or JAR file.

AllowInlining Tells the translator that it is permitted toinline local methods. This is the default foroptimization levels 30 and 40.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 71

Page 80: AS400 Developer Kit for Java (Rzaha)

String DescriptionNoAllowInlining Does not tell the translator that it is

permitted to inline local methods.AssumeUnknownFieldsNonvolatile When the attributes of a field in an external

class cannot be determined, this parametergenerates code by assuming that the field isnon-volatile.

NoAssumeUnknownFieldsNonvolatile When the attributes of a field in an externalclass cannot be determined, this parametergenerates code by assuming that the field isvolatile.

BindErrorHandling Specifies what action should be taken if, as aresult of honoring theAssumeUnknownFieldsNonvolatile,PreresolveExtRef, or PreLoadExtRef LicensedInternal Code option, the Java virtualmachine class loader detects that a classrepresentation contains methodrepresentations, which cannot be used in thecurrent context.

BindInit Use bound call to local init methods.NoBindInit Do not use bound call to local init methods.BindSpecial Use bound call to local special methods.NoBindSpecial Do not use bound call to local special

methods.BindStatic Use bound call to local static methods.NoBindStatic Do not use bound call to local static

methods.BindTrivialFields Bind trivial field references during program

creation.NoBindTrivialFields Resolve field references at first touch.BindVirtual Use bound call to local final virtual methods.NoBindVirtual Do not use bound call to local final virtual

methods.DeferResolveOnClass Takes a string parameter that is presumed to

be the name of a class (for example,java.lang.Integer). When you setPreresolveExtRef to optimization level 40,classes that are specified withDeferResolveOnClass are not in thepreresolve operation. This is useful if someclasses in unused paths in the code are not inthe CLASSPATH. It allows you to useoptimization level 40 regardless of this byspecifying a“DeferResolveOnClass=’somepath.someclass’”for each missing class. MultipleDeferResolveOnClass entries are allowed.

DevirtualizeFinalJDK Allows CRTJVAPGM to use knowledge ofthe standard JDK to devirtualize calls tothose JDK methods that are known to befinal methods or members of final classes. Itis the default at optimization levels 30 and40.

NoDevirtualizeFinalJDK Does not allow CRTJVAPGM to useknowledge of the standard JDK todevirtualize calls to those JDK methods thatare known to be final methods or membersof final classes.

72 AS/400 Developer Kit for Java

Page 81: AS400 Developer Kit for Java (Rzaha)

String DescriptionDevirtualizeRecursive Causes special code to be generated in the

case of some recursive methods andeliminates much of the overhead of therecursive method calls. However, additionalchecking logic is generated on initial entry tothe recursive method, so performance maynot improve in cases of shallow recursion.

NoDevirtualizeRecursive Does not cause special code to be generatedin the case of some recursive methods.

DisableIntCse Causes certain common subexpressionoptimizations to be disabled when generatingcode for certain types of integer expressions.This may improve overall optimization byexposing other optimization oppportunitiesto the Optimizing Translator.

NoDisableIntCse Causes certain common subexpressionoptimizations to not be disabled whengenerating code for certain types of integerexpressions. This generally results in betterperforming code at lower optimization levels.

DoExtBlockCSE Perform extended basic block commonsubexpression elimination.

NoDoExtBlockCSE Do not perform extended basic blockcommon subexpression elimination.

InlineArrayCopy Causes the inlining of the System.arraycopymethod in some cases of scalar arrays.

NoInlineArrayCopy Prevents the inlining of the System.arraycopymethod.

DoLocalCSE Perform local common subexpressionelimination.

NoDoLocalCSE Do not perform local common subexpressionelimination.

EnableCseForCastCheck If set, generates code for castcheck that canbe DAGed to an earlier instance of.

NoEnableCseForCastCheck

Is not set; does not generate code forcastcheck that can be DAGed to an earlierinstance of.

ErrorReporting Runtime error reporting field**: Provides theoption to fail the compile when encounteringverification or class format errors. 0=Reportall errors immediately; 0=Report all errorsimmediately; 1=Defer reporting of bytecodeverification errors; 2=Defer reporting ofbytecode verification errors and class formaterrors to runtime.

InlineInit Inline init methods for java.lang classes.NoInlineInit No inline init methods.InlineMiscFloat Inline miscellaneous float/double methods

from java.lang.Math.NoInlineMiscFloat No inline miscellaneous float/double

methods.InlineMiscInt Inline miscellaneous int/long methods from

java.lang.Math.NoInlineMiscInt No inline miscellaneous int/long methods.InlineTransFloat Inline transcendental float/double methods

from java.lang.Math.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 73

Page 82: AS400 Developer Kit for Java (Rzaha)

String DescriptionNoInlineTransFloat No inline transcendental float/double

methods.PreloadExtRef Indicates that referenced classes may be

pre-loaded (without class initialization) uponmethod entry.

NoPreloadExtRef Indicates that referenced classes may not bepre-loaded upon method entry. However, thePreresolveExtRef parameter overrides thissetting and causes referenced classes to bepre-loaded and initialized. .

PreresolveExtRef Preresolve referenced methods at methodentry.

NoPreresolveExtRef Resolve method references at first touch. Useto resolve “class not found” exceptions onprograms that run on other machines.

ShortCktAthrow If set, attempt to short-circuit athrows.NoShortCktAthrow Is not set; does not attempt to short-circuit

athrows.ShortCktExSubclasses If set, recognize some subclasses of Exception

and short-circuit them directly.NoShortCktExSubclasses Is not set; does not recognize some

subclasses of Exception and short-circuitthem directly.

The double asterisk (**) signifies that these strings require a numerical value forinput in the syntax of stringname=number (with no spaces in between).

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Create Java Program (CRTJVAPGM) commandTo create a Java program and associate it with the class file, myJavaClassFileName,use the Create Java Program (CRTJVAPGM) command. When created withOPTIMIZE(*INTERPRET), the Java program class file bytecodes are interpreted. Tostart the program, use the Run Java (RUNJVA) command.

Example 1: Create an interpreted Java programCRTJVAPGM CLSF('/projectA/team2/myJavaClassFileName.class')

OPTIMIZE(*INTERPRET)

This example is the same as Example 1; except that the program is optimized. It iscreated with OPTIMIZE(40), so the program contains compiled machineinstructions that run when the Java program starts.

Example 2: Create an optimized Java programCRTJVAPGM CLSF('/projectB/team2/myJavaclassfile.class')

OPTIMIZE(40)

See the Create Java Program (CRTJVAPGM) command for syntax diagram andparameter details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

74 AS/400 Developer Kit for Java

Page 83: AS400 Developer Kit for Java (Rzaha)

Change Java Program (CHGJVAPGM) commandPurpose:

The Change Java Program (CHGJVAPGM) command changes the attributes of aJava program, which is attached to either a Java class file or a set of Java programsthat are attached to a JAR file. A file is a JAR file if the file name ends with .jar or.zip.

You can recreate Java programs if the attributes that are specified differ from thoseof the current programs or if you specify MERGE(*YES). The CHGJVAPGMcommand does not create Java programs for class files, or classes within JAR filesthat do not have attached Java programs. A Java program is created dynamicallywhen a class is loaded without a current Java program attached. There may beclasses in a JAR file from which no Java programs have been created. You can usethe Create Java Program (CRTJVAPGM) command to create Java programs fromthese classes. The CHGJVAPGM command replaces existing Java programs only.

Syntax:CHGJVAPGM Command

(P)>>—CHGJVAPGM—CLSF(—.-class-file-name-.—)————————————————>

'-JAR-file-name—-'>—.———————————————.—.———————————————-.———>

| .-SAME———-. | | .-*SAME———. |'-OPTIMIZE(—+-*INTERPRET-+—)-' '-ENBPFRCOL(—+-*NONE———+—)-'

|-10————-| |-*ENTRYEXIT-||-20————-| '-*FULL———'

|-30————-|'-40————-'

>—.——————————-.—.————————————.———————————>| .-*RPL-. | | .-*NONE-. |'-MERGE(—'-*YES-'—)-' '-SUBTREE(—'-*ALL—'—)-'

>—.————————————————.———————————————————->| .-*SAME—————. |'-LICOPT(—+-*OPTIMIZE———+—)-'

'-options-string-'

Notes: (P) All parameters preceding this point can be specified positionally.

Required parameter:

CLSF

The CLSF parameter specifies the class file name or JAR file name that areattached to the Java programs to change. One or more directory namesmay qualify the class file name.

For the class-file-name, specify the name of the class file or a pattern foridentifying the name of the class files that are used. Specify a pattern inthe last part of the name. An asterisk matches any number of characters,and a question mark matches a single character. Enclose the name inapostrophes if it is qualified or contains a pattern. An example of aqualified class file name is:'/directory1/directory2/myclassname.class'

An example of a pattern is:'/directory1/directory2/myclass*.class'

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 75

Page 84: AS400 Developer Kit for Java (Rzaha)

For the JAR-file-name, specify the name of the JAR file or a pattern foridentifying the name of the JAR files that are used. A file is a JAR file if itends with .jar or .zip. Specify a pattern in the last part of the name. Anasterisk matches any number of characters, and a question mark matches asingle character. Enclose the name in apostrophes if it is qualified orcontains a pattern. An example of a qualified JAR file name is:'/directory1/directory2/myappname.jar'

An example of a pattern is:'/directory1/directory2/myapp*.zip'

Optional parameters:

OPTIMIZE

The OPTIMIZE parameter for the CHGJVAPGM command specifies theoptimization level of each AS/400 Java program that is attached to theclass object or the JAR file object. If you use the OPTIMIZE(*INTERPRET)parameter, the resulting Java program is verified and converted to aninternal form. It is then interpreted when it runs. For the otheroptimization levels, the internal form includes AS/400 machineinstructions. These AS/400 machine instructions are optimized based onthe specified optimization level. The AS/400 directly runs the machineinstructions when the program runs.

OPTIMIZE(*INTERPRET) Java programs are smaller, but run slower thanJava programs that are created with higher optimization levels. As theoptimization level increases beyond 10, Java program performancegradually improves, but the time that is required to create the Javaprogram increases. It also makes it more difficult to debug the Javaprogram as you increase the optimization level.

Typically, *INTERPRET is a good option during development and earlytesting, because quick edit, compile turnaround, and quality debugfunctions are important. As the program moves toward release, the level ofoptimization often increases.

This list shows how the optimization levels differ and what they do:

*SAMEThe value does not change.

10 The Java program contains a transformed version of the class filebytecodes, but has only minimal additional compiler optimization.You can display and change variables while debugging.

20 The Java program contains a compiled version of the class filebytecodes and has additional compiler optimization. You candisplay, but not change variables while debugging.

30 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimizationlevel 20. Debugging at higher optimization levels is more difficult,because optimization reduces the ability to stop at precise points inthe code and display program variables. You can display, but notchange variables while debugging. The values that are presentedmay not be the current value of the variable.

40 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimizationlevel 30. In addition, it includes optimization that disables call and

76 AS/400 Developer Kit for Java

Page 85: AS400 Developer Kit for Java (Rzaha)

instruction tracing.Note: If your Java program fails to optimize or throws anexception at optimization level 40, use optimization level 30.

*INTERPRETThe Java program that is created does not contain machine specificinstructions. When the program starts, it interprets the class filebytecodes. You can display and change variables while debugging.

ENBPFRCOL

The ENBPFRCOL parameter specifies whether or not to enable thecollection of performance data.

*SAMEThe value does not change.

*NONEThe collection of performance data is not enabled. No performancedata is collected.

*ENTRYEXITThe performance data is collected for procedure entry and exit.

*FULL The performance data is collected for procedure entry and exit.Performance data is also collected before and after calls to theexternal procedures.

MERGE

The MERGE parameter specifies whether or not you merge Java programs,which are attached to a JAR file, into the minimum number of Javaprograms possible. This parameter is ignored if you are processing a Javaclass file.

*RPL Specifies that you merge Java programs, which are attached to aJAR file, only if the Java programs need to be re-created andreplaced, because other Java program attributes are being changed.If no attributes are changed and no Java programs need to bere-created and replaced, then no merging of Java programs occurs.

*YES You merge all Java programs, which are attached to a JAR file, intothe minimum number of Java programs possible to save space orimprove class loader time.

SUBTREE

The SUBTREE parameter specifies whether or not subdirectories areprocessed when looking for files that match the CLSF keyword.

*NONEOnly the files that match the object name pattern are processed. Nosubtrees are processed. If the directory has subdirectories, neitherthe subdirectories nor the objects on the subdirectories areprocessed.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 77

Page 86: AS400 Developer Kit for Java (Rzaha)

*ALL The entire subtree of the path that is specified in CLSF is processedto create Java programs for files that match the name that wasspecified on the CLSF parameter.

LICOPT

The LICOPT parameter specifies one or more licensed internal codecompile-time optimization options. Only advanced programmers, whounderstand the potential benefits and drawbacks of each selected type ofoptimization, should use this parameter.

Note: You should contact your service representative for more informationon how to use these optimizations.

*SAMEThe value does not change.

*OPTIMIZEThe *OPTIMIZE option uses the set of compile-time optimizations,which are implicitly associated with the optimization level that isspecified on the OPTIMIZE parameter. If you specifyOPTIMIZE(*INTERPRET), no compile-time optimizations areperformed.

’options-string’See LICOPT parameter strings for a listing of recognized strings.

For more performance information, see tuning Java program performance with theAS/400 Developer Kit for Java.

See Example: Change Java Program (CHGJVAPGM) command for an example thatuses the CHGJVAPGM command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Change Java Program (CHGJVAPGM) commandTo change a Java program that is associated with the class file,myJavaClassFileName, use the Change Java Program (CHGJVAPGM) command.The Java program class file bytecodes are interpreted. To start the program, use theRun Java (RUNJVA) command. The Java program is re-created only if theattributes that are specified are different than those of the current program.

Example 1: Change an interpreted Java programCHGJVAPGM CLSF('/projectA/team2/myJavaClassFileName.class')

OPTIMIZE(*INTERPRET)

This example is the same as Example 1, except that the program is optimized. It ischanged with OPTIMIZE(10), so the program contains compiled machineinstructions that run when the Java program starts.

Example 2: Change an optimized Java program in a JAR file

78 AS/400 Developer Kit for Java

Page 87: AS400 Developer Kit for Java (Rzaha)

CHGJVAPGM CLSF('/projectB/myJavaappfile.jar')OPTIMIZE(10)

See the Change Java Program (CHGJVAPGM) command for syntax diagram andparameter details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

JAVA commandThe JAVA command functions exactly the same as the Run Java (RUNJVA)command. You can use them interchangeably. See Run Java (RUNJVA) commandfor information and parameters that you can use with the JAVA command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Run Java (RUNJVA) commandPurpose:

The Run Java (RUNJVA) command runs the AS/400 Java program, which isassociated with the Java class that is specified. If a Java program does not exist,one is created and associated with the class file.

Syntax:RUNJVA Command>>—RUNJVA—CLASS(—.-class-name—.—)———————————————————>

| (1)|'-*VERSION——'

(P)>—.———————————————————————————————————->

| .-*NONE—————————. || | <————————-> (2)| |'-PARM(—'—-parameter-value———'—)-'

>—.———————————————-.—.—————————————.—————>| .-*ENVVAR——. | | .-*WARN—-. |'-CLASSPATH(—'-class-path-'—)-' '-CHKPATH(—+-*SECURE-+—)-'

'-*IGNORE-'>—.———————————————.—.———————————————.———->

| .-10————-. | | .-*OPTIMIZE-. |'-OPTIMIZE(—+-*INTERPRET-+—)-' '-INTERPRET(—+-*NO———-+—)-'

+-*JIT———-+ |-*YES———|+-20————-+ '-*JIT———'

+-30————-+'-40————-'

>—.——————————————————————————-.—————————>| .-*NONE————————————————-. || | <————————————————> (3)| |'-PROP(—'—-property-name—property-value———-'—)-'

>—.———————————————————————————.—————————>| .-*NOMAX———————————————-. |'-GCHMAX(—'-garbage-collection-heap-maximum-size-'—)-'

>—.———————————————————————————.—————————>| .-*2048————————————————. |'-GCHINL(—'-garbage-collection-heap-initial-size-'—)-'

>—.—————————————————————————-.——————————->| .-50————————————————-. |'-GCFRQ(—'-garbage-collection-frequency-value-'—)-'

>—.——————————.—.———————————————————.————-><| .-20-. | | .-*NONE————————. |

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 79

Page 88: AS400 Developer Kit for Java (Rzaha)

'-GCPTY(—+-30-+—-)-' | | <———————-> (4)| |'-10-' '-OPTION(—'—.-*DEBUG——-.———'—)-'

|-*VERBOSE—-||-*VERBOSEGC-|'-*NOCLASSGC-'

Notes: (1) All other parameters are ignored if CLASS(*VERSION) is specified.(2) A maximum of 200 repetitions.(P) All parameters preceding this point can be specified positionally.(3) A maximum of 100 repetitions.(4) A maximum of 4 repetitions.

Required parameters:

CLASS

The CLASS parameter specifies the class name that is to be run. One ormore package names may qualify the class name. Follow each packagename with a period. For example, CLASS(’pkg1.pkg2.myclass’) identifies aclass that is qualified by two package names.

For class-name, specify the name of the class that runs.

The limit for the CLASS parameter is 5000 characters.

*VERSIONThe build version for Sun Microsystems, Inc. Java Development Kit(JDK), and the Java virtual machine displays. No Java programruns.

Optional parameters:

PARM

The PARM parameter specifies one or more parameter values that arepassed to the Java program. You may specify a maximum of 200 parametervalues.

For parameter-value, specify the parameters to pass to the Java program.

The limit for the PARM parameter is 256 characters.

*NONEThere are no input parameters to the Java program.

CLASSPATH

The CLASSPATH parameter specifies the path that is used to locate classes.Colons separate the directories.

The classpath locates classes. An example classpath:'/directory1/directory2:/QIBM/ProdData/Java400'

The limit for the CLASSPATH parameter is 5000 characters.

*ENVVARThe environment variable CLASSPATH determines the classpath.

80 AS/400 Developer Kit for Java

Page 89: AS400 Developer Kit for Java (Rzaha)

CHKPATH

The CHKPATH parameter specifies the level of warnings that are given fordirectories in the CLASSPATH that have public write authority. A directoryin the CLASSPATH that has public write authority may cause a securityexposure. An exposure could occur, because an undesired class may beinserted into the directory that is found before the official class.

*WARNA warning message is sent to the QJVACMDSRV job log for eachdirectory in the CLASSPATH that has public write authority.

*SECUREA warning message is sent for each directory in the CLASSPATHthat has public write authority. If one or more warning messagesare sent, an escape message is sent and the Java program does notrun.

*IGNOREIgnore the fact that directories in the CLASSPATH may have publicwrite authority. No warning messages are sent.

OPTIMIZE

The OPTIMIZE parameter specifies the optimization level of the AS/400Java program that is used if no Java program has ever been associatedwith the Java class. Optimization is a time consuming operation, soprograms run slowly the first time that they are optimized if you use theRUNJVA command instead of the CRTJVAPGM command. However,subsequent runs use the optimized form, so optimization is a one-timecost. This is true for class files, JAR files, and ZIP files.

The effect of the OPTIMIZE parameter depends on the currentoptimization level of the program. The current optimization level resultsfrom either the previous use of the RUNJVA command or the CRTJVAPGMcommand.

If the program has never run on AS/400, and no previous CRTJVAPGMcommand has run, then the optimization level that is selected is usedbefore the program runs. This optimization level is stored in the class file,JAR file, or ZIP file.

If the RUNJVA command or CRTJVAPGM command has been run againstthe program, then the OPTIMIZE parameter on the RUNJVA command hasno effect. One exception is the OPTIMIZE(*INTERPRET) parameter. Thisparameter forces all of the loaded Java classes to run interpretivelyregardless of the OPTIMIZE value of the associated Java program.

If you want to change the level of optimization of a program that has beenpreviously optimized, use the CRTJVAPGM command or CHGJVAPGMcommand. Using the RUNJVA command does not create the desiredoptimization level. Instead, it uses the saved value that is associated withthe class file, JAR file, or ZIP file.

Note:The *INTERPRET parameter behaves this way to debug code that hasbeen previously optimized. It does not require that you delete yourprogram, create the program again for low optimization, debug it, andthen optimize it again.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 81

Page 90: AS400 Developer Kit for Java (Rzaha)

If the OPTIMIZE(*INTERPRET) parameter is used, the resulting Javaprogram is verified and converted to an internal form. Then, it isinterpreted when it runs. For the other optimization levels, the internalform includes AS/400 machine instructions. These AS/400 machineinstructions are optimized based on the specified optimization level. TheAS/400 directly runs the machine instructions when the program runs.

OPTIMIZE(*INTERPRET) Java programs are smaller, but run slower thanJava programs that are created using higher optimization levels. As theoptimization level increases beyond 10, Java program performancegradually improves, but the time that is required to create the Javaprogram increases. It is also more difficult to debug the Java program.

Typically, *INTERPRET is a good option during development and earlytesting, because quick edit, compile turnaround, and quality debugfunctions are important. As the program moves toward release, the level ofoptimization often increases.

This list shows how the optimization levels differ and what they do:

10 The Java program contains a transformed version of the class filebytecodes, but has only minimal additional compiler optimization.While debugging, you can display and change variables.

*INTERPRETThe Java program that is created does not contain machine specificinstructions. When the program starts, it is interpreted. You can

display and change variables while debugging.

*JIT No Java program that contains machine instruction sequences iscreated. The class runs by using the Just-In-Time (JIT) compiler.

20 The Java program contains a compiled version of the class filebytecodes and has additional compiler optimization. You candisplay and change variables while debugging.

30 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimizationlevel 20. Debugging at higher optimization levels is more difficult,because optimization reduces the ability to stop at precise points inthe code and display program variables.

40 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimizationlevel 30. In addition, it includes optimization that disables call andinstruction tracing.Note: If your Java program fails to optimize or throws anexception at optimization level 40, use optimization level 30.

INTERPRET

The INTERPRET parameter specifies whether all Java class files should runinterpretively.

OPTIMIZEJava class files run interpretively depending on the value that isspecified for the OPTIMIZE parameter. If OPTIMIZE(*INTERPRET)is specified, all Java class files run interpretively. If another value is

82 AS/400 Developer Kit for Java

Page 91: AS400 Developer Kit for Java (Rzaha)

specified for the OPTIMIZE parameter, Java class files with Javaprograms, which were created by using the CRTJVAPGMcommand and by specifying OPTIMIZE(*INTERPRET), runinterpretively.

*NO Only Java class files with Java programs, which were created byusing the CRTJVAPGM command and by specifyingOPTIMIZE(*INTERPRET), run interpretively. Java class files thatneed to create a Java program are created with the optimizationlevel that is specified by using the OPTIMIZE parameter.

*YES All Java class files run interpretively regardless of whichOPTIMIZE value the associated Java program created. Java classfiles that need to create a Java program are created with theoptimization level that is specified by using the OPTIMIZE

parameter.

*JIT All Java class files run by using the Just-In-Time (JIT) compiler,regardless of what OPTIMIZE value was used when the associated

Java program was created.

PROP

The PROP parameter specifies a list of values to assign to Java systemproperties. You can assign up to 100 properties.

The limit for the PROP parameter is 5000 characters each for name and

value.

*NONENo properties are specified.

For property-name, specify the name of the property to change.

For property-value, specify the value that is assigned to the property.

GCHMAX

The GCHMAX parameter specifies the maximum amount of memory inkilobytes that the Java virtual machine can allocate. Normally, you shoulduse the default or set this value as large as possible. However, if you areconcerned about a program that uses all available memory, you can setGCHMAX to a smaller value. The default value is system dependent andmodel dependent.

If Java virtual machine memory allocation reaches GCHMAX, all otherJava virtual machine threads are stopped while garbage collection takesplace. If garbage collection cannot reduce the memory allocation, the Javavirtual machine stops.

*NOMAXThe garbage collection heap grows until all system resources aregone. Then, a synchronous garbage collection starts to reclaim theresources that are no longer in use. With *NOMAX, synchronousgarbage collection occurs only if all available heap storage has beenused.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 83

Page 92: AS400 Developer Kit for Java (Rzaha)

GCHINL

The GCHINL parameter provides a suggested threshold for initial garbagecollection. If this value is equal to GCHMAX, then garbage collection doesnot run until the amount of memory that is allocated by the Java virtualmachine approaches GCHMAX. Setting the value to a smaller valuetriggers an earlier garbage collection. The default value is systemdependent and model dependent.

GCFRQ

Note: This parameter is no longer supported. It exists solely forcompatibility with releases earlier than Version 4 Release 3 Modification 0of the AS/400 system.

The GCFRQ parameter provides a suggested garbage collection frequency.It may or may not be honored depending on the system release and model.

Values between 0 and 100 are allowed for GCFRQ. The default parameteris 50. A lower value means less frequent garbage collection. A higher valuemeans more frequent garbage collection.

GCPTY

Note: This parameter is no longer supported. It exists solely forcompatibility with releases earlier than Version 4 Release 3 Modification 0of the AS/400 system.

The GCPTY parameter provides a suggested garbage collection priority. Itmay or may not be honored depending on the system release and model.

The GCPTY parameter specifies the relative priority of the threads that rungarbage collection. The priority is relative to the default user Java threads.Higher values indicate higher priority. A low priority garbage collectionthread is less likely to run, because other higher priority tasks are running.

In most cases, GCPTY should be set to the default (equal) value or thehigher priority value. Setting GCPTY to the lower priority value can inhibitgarbage collection and cause in all Java threads to be held while thegarbage collector frees storage.

20 The default parameter value is 20. This indicates that the garbagecollection thread has the same priority as default user Java threads.

30 The 30 priority gives garbage collection higher priority than defaultuser Java threads. Garbage collection is more likely to run.

10 The 10 priority gives garbage collection lower priority than defaultuser Java threads. Garbage collection is less likely to run.

OPTION

The OPTION parameter specifies special options that are used when a Javaclass runs.

*NONENo special options are used when a Java class runs.

*DEBUGAllows the use of the AS/400 system debugger for the Javaprogram.

84 AS/400 Developer Kit for Java

Page 93: AS400 Developer Kit for Java (Rzaha)

*VERBOSEA message is displayed each time a class file is loaded.

*VERBOSEGCA message is displayed for each garbage collection sweep.

*NOCLASSGCUnused classes are not reclaimed when garbage collection runs.

See Example: Using the Run Java (RUNJVA) command for an example that usesthe RUNJVA command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Using the Run Java (RUNJVA) commandThe Run Java (RUNJVA) command runs the AS/400 Java program that isassociated with the class.

Example 1: Run a Java program

RUNJVA CLASS (’/projectA/myJavaclassname’)

See the Run Java (RUNJVA) command for syntax diagram and parameter details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Delete Java Program (DLTJVAPGM) commandSyntax:DLTJVAPGM Command

(1)>>-DLTJVAPGM—-CLSF(—'class-file-name'—)———————————>>——-+—————————————+——————————————-><

| .-NONE—-. |'-SUBTREE(—+-*ALL—-+—-)-'

Note:All parameters preceding this point can be specified positionally.

Purpose:

The Delete Java Program (DLTJVAPGM) command deletes an AS/400 Javaprogram that is associated with a Java class file, ZIP file, or JAR file. If no Javaprogram is associated with the file that is specified, informational messageJVAB526 is sent, and command processing continues.

Parameters:

CLSF

The CLSF parameter specifies the class file, ZIP file, or JAR file name fromwhich to delete the associated Java program on AS/400. One or moredirectory names may qualify the class file name.

For class-file-name, specify the name of the class file or a pattern toidentify file or files to be used. A pattern may be specified in the last part

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 85

Page 94: AS400 Developer Kit for Java (Rzaha)

of the name. An asterisk matches any number of characters, and a questionmark matches a single character. Enclose the name in apostrophes if it isqualified or contains a pattern. An example of a qualified class name is:'/directory1/directory2/myclassname.class'

SUBTREE

The SUBTREE parameter specifies whether or not subdirectories areprocessed when looking for files that match the CLSF keyword.

*NONEOnly the files that match the object name pattern are processed. Nosubtrees are processed. If the directory has subdirectories, neitherthe subdirectories nor the objects on the subdirectories areprocessed.

*ALL The entire subtree of the path that is specified in CLSF is processedto create Java programs for files that match the name that wasspecified on the CLSF parameter.

See Example: Delete Java Program (DLTJVAPGM) command for an example thatuses the DLTJVAPGM command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Delete Java Program (DLTJVAPGM) commandThe Delete Java Program (DLTJVAPGM) command deletes the Java program that isassociated with the specified class file that is named myJavaClassFileName.

Note: The DLTJVAPGM command does not delete the class file or ZIP file.

Example 1: Delete a Java program

DLTJVAPGM CLSF(’/projectA/team2/myJavaClassFileName.class’)

See the Delete Java Program (DLTJVAPGM) command for syntax diagram andparameter details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Dump Java Virtual Machine (DMPJVM) command

Purpose:

The Dump Java Virtual Machine (DMPJVM) command dumps information aboutthe Java virtual machine for a specified job. The dump includes formattedinformation about the classpath, garbage collection, and threads that are associatedwith the Java virtual machine.

Syntax:

86 AS/400 Developer Kit for Java

Page 95: AS400 Developer Kit for Java (Rzaha)

DMPJVM Command(1)

>>—DMPJVM——-.——————————————————————————.—->| .-*SRVJOB———————————————-. |'-JOB(—'-.————————————-.—job-name-'—)-'

'-.—————-.—user-name/-''-job-number/-'

>—.——————————————.—.——————————————.————><| .-10——-. | | .-*SELECT-. |'-STACKFRAME(—+-*ALL—-+—)-' '-DUPJOBOPT(—'-*MSG——'—)-'

'-number-'

Notes: All parameters preceding this point can be specified positionally.

Restrictions:

v The DMPJVM command uses the Start Service Job (STRSRVJOB) command andStart Debug (STRDBG) command. The user of this command must be authorizedto the STRSRVJOB command and STRDBG command.

v The DMPJVM command ships with public *EXECUTE authority, and theQPGMR, QSYSOPR, QSRV, and QSRVBAS user profiles have private authoritiesto use the DMPJVM command.

v The DMPJVM command must run under a user profile, which is the same as thejob user identity of the Java virtual machine job, or which has use (*USE)authority to the job user identity of the Java virtual machine job.

v The DMPJVM command is not allowed if the remote service operation foranother job has started, and that job is not the same job that was specified onthis command.

v The DMPJVM command is not allowed if the Java virtual machine job is held,suspended, or ending.

Optional parameters:

JOB The JOB parameter specifies the name of the job where the Java virtualmachine is running. If no job number is given, all of the jobs that arecurrently in the system are searched for the simple job name. The job nameentered must be a job in which a Java virtual machine is currently running.

*SRVJOBInformation about the Java virtual machine in the job that iscurrently being serviced is dumped. If no job is currently beingserviced, a job identifier is required.

A job identifier is a qualified name with up to three elements. Forexample:v job-namev user-name/job-namev job-number/user-name/job-name

job-nameSpecifies the name of the Java virtual machine job.

user-nameSpecifies the name of user of the Java virtual machine job.

job-nameSpecifies the number of the Java virtual machine job.

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 87

Page 96: AS400 Developer Kit for Java (Rzaha)

STACKFRAMEThe STACKFRAME parameter specifies the maximum number of stackframes for each thread to process. This value must be greater than zero,and cannot be greater than 100. If there are more than the specifiednumber of frames on a thread stack, the more recent frames on the stackare processed and ’...’ indicates that not all of the stack frames wereprocessed.

10 Each thread processes a maximum of ten stack frames.

*ALL Each thread processes all stack frames. If a thread has more than100 stack frames, only the first 100 frames are processed.

numberThe maximum number (1-100) of stack frames that the threadprocesses.

DUPJOBOPTSpecifies the action to be taken when the DMPJVM command findsduplicate jobs.

*SELECTWhen the DMPJVM command finds duplicate jobs during aninteractive session, the selection display is shown. Otherwise, anescape message is issued.

*MSG When the DMPJVM command finds duplicate jobs, an escapemessage is issued.

See Example: Dump Java Virtual Machine (DMPJVM) command for an example

that uses the DMPJVM command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Dump Java Virtual Machine (DMPJVM) commandThe Dump Java Virtual Machine (DMPJVM) command dumps information

about the Java virtual machine for a specified job.

Example 1: Dump a Java Virtual MachineDMPJVM JOB(099246/FRED/QJVACMDSRV)

The DMPJVM command dumps the information for the Java virtual machine thatis running in the job that is named 099246/FRED/QJVACMDSRV.

Example output:JAVA VIRTUAL MACHINE INFORMATION: 099246/FRED/QJVACMDSRV....................................................................... Classpath....................................................................../QIBM/ProdData/Java400/jdk117/lib/jdkptf117.zip:/QIBM/ProdData/Java400/jdk117/lib/classes.zip:/QIBM/ProdData/Java400/ext/IBMmisc.jar:/QIBM/ProdData/Java400/ext/db2_classes.jar:/QIBM/ProdData/Java400/ext/jssl.jar:/QIBM/ProdData/Java400/ext/ibmjssl.jar:/QIBM/ProdData/Java400/:/home/fred....................................................................... Garbage collection

88 AS/400 Developer Kit for Java

Page 97: AS400 Developer Kit for Java (Rzaha)

......................................................................Garbage collector parameters

Initial size: 2048 KMax size: *NOMAX

Current valuesHeap size: 9476 KGarbage collections: 0

......................................................................

. Thread information

......................................................................Information for 3 thread(s) of 3 thread(s) processedThread: 00000001 Thread-0

TDE: B000200002941000Thread priority: 5Thread status: Destroy waitThread group: mainRunnable: java/lang/ThreadStack:

NoneLocks:

None......................................................................Thread: 00000003 t2

TDE: B000100005B37000Thread priority: 5Thread status: Timed waitThread group: mainRunnable: dbgtest2Stack:

java/io/BufferedInputStream.read()I+11 (BufferedInputStream.java:154)pressEnter.theFirstMethod(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Str

ava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljtring;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/S0 (dbgtest2.java:15)

dbgtest2.run()V+69 (dbgtest2.java:44)java/lang/Thread.run()V+11 (Thread.java:466)

Locks:None

......................................................................Thread: 00000002 t1

TDE: B000100005B33000Thread priority: 5Thread status: Java waitThread group: mainRunnable: dbgtest2Stack:

pressEnter.theFirstMethod(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Strava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljtring;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/S(dbgtest2.java:14)

dbgtest2.run()V+69 (dbgtest2.java:44)java/lang/Thread.run()V+11 (Thread.java:466)

Locks:None

......................................................................

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Display Java Program (DSPJVAPGM) commandSyntax:

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 89

Page 98: AS400 Developer Kit for Java (Rzaha)

DSPJVAPGM Command(1)

>>-DSPJVAPGM—-CLSF(—'class-file-name'—)———————————>>——-+—————————————+——————————————-><

| .-*———. |'-OUTPUT(—+-*PRINT-+—-)—'

Note:

All parameters preceding this point can be specified positionally.

Purpose:

The Display Java Program (DSPJVAPGM) command displays information about aJava program on AS/400. This information includes creation and processingattributes, such as the optimization level and the size.

Parameters:

CLSF The CLSF parameter specifies the class file, ZIP file, or JAR file name fromwhich to display the associated Java program on AS/400. One or moredirectory names may qualify the class file name.

For class-file-name, specify the name of the class file, ZIP file, or JAR file.An example of a qualified class name is:'/directory1/directory2/myclassname.class'

OUTPUTThe OUTPUT parameter specifies where the output is to be sent.

* Display shows the output that was requested by an interactive job.Output that was requested by a batch job prints with the spooledoutput of the job.

*PRINTThe output prints with the spooled output of the job.

Display example:

This display example shows you what Display Java Program (DSPJVAPGM)output looks like for a ZIP file.+————————————————————————————————————————+

Display Java Program InformationFile name . . . . . . . . . . . . . . . : /user/classes.zip1Owner . . . . . . . . . . . . . . . . . : USER2Java program creation information:

File change date/time . . . . . . . . . . . . . : 07/18/98 09:03:373Java program creation date/time . . . . . . . . : 07/18/98 14:03:384Java programs . . . . . . . . . . . . . . . . . : 15Classes with current Java programs . . . . . . : 16Classes without current Java programs . . . . . : 07Optimization . . . . . . . . . . . . . . . . . : *INTERPRET8Enable performance collection . . . . . . . . . : *NONE9Use adopted authority . . . . . . . . . . . . . : *NO10User profile . . . . . . . . . . . . . . . . . : *USER11Licensed Internal Code options . . . . . . . . : ErrorReporting=012

Java program statistics:Java program size . . . . . . . . . . . . . . . : 270745613Release program created for . . . . . . . . . . : V4R5M014

90 AS/400 Developer Kit for Java

Page 99: AS400 Developer Kit for Java (Rzaha)

BottomPress Enter to continue.

+————————————————————————————————————————+

1. File name: The name of the file that has an attached Java program.Note: You must have *USE authority for the class file for the Java programthat is to be displayed.

2. Owner: The name of the user profile of the user who owns this Java program.3. File change date/time: The date and time when the class file was last

changed.4. Java program creation date/time: If this is a ZIP file, this is the date and time

when the first Java program was attached to the file. If this is a class file, thisis the date and time when the Java program was created.

5. Java programs: Indicates the number of Java programs that are associatedwith the file.Note: For the best performance, the number of Java programs should be low(1 or 2). The number of Java programs is large if your Java programs werecreated implicitly. This occurs when a Java program runs and classes in theJAR file were loaded before the Create Java Program (CRTJVAPGM) commandwas run on the JAR file. If the number of Java programs is high, you maywant to use the CHGJVAPGM MERGE(*YES) function to consolidate theprograms and improve class loader performance. If the number of classes islow, and the number of Java programs is high, this may be caused by multiplechanges of classes in the JAR file. Again, you can use either the CRTJVAPGMcommand or CHGJVAPGM command to consolidate the programs.

6. Classes with current Java programs: Indicates the number of classes in thefile that have current Java programs.

7. Classes without current Java programs: Indicates the number of classes in thefile that do not have current Java programs.Note: For the best performance, the number of classes without current Javaprograms should be low. If the number of classes without current Javaprograms is high, you may want to use the CRTJVAPGM command to updatethe program.

8. Optimization: Specifies the optimization level of the AS/400 Java program.For OPTIMIZE(*INTERPRET), the resulting Java program interprets the classfile bytecodes when started. For other optimization levels, the Java programcontains machine instruction sequences that run when the Java program starts.Java programs that use OPTIMIZE(*INTERPRET) are smaller, but run slowerthan Java programs that you create with higher optimization levels. As youincrease the optimization level beyond 10, the performance of the Javaprogram generally improves. However, the time that is required to create theJava program increases and debugging becomes more difficult.This list shows how the optimization levels differ and what they do:

10 The Java program contains a compiled version of the class filebytecodes, but has only minimal additional compiler optimization.You can display and change variables while debugging.

20 The Java program contains a compiled version of the class filebytecodes and has additional compiler optimization. You can display,but not change variables while debugging.

30 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimization level20. Debugging at higher optimization levels is more difficult, becauseoptimization reduces the ability to stop at precise points in the code

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 91

Page 100: AS400 Developer Kit for Java (Rzaha)

and display program variables. You can display, but not changevariables while debugging. The values that are presented may not bethe current value of the variable.

40 The Java program contains a compiled version of the class filebytecodes and has more compiler optimization than optimization level30. In addition, it includes optimization that disables call andinstruction tracing.Note: If your Java program fails to optimize or throws an exception atoptimization level 40, use optimization level 30.

*INTERPRETThe Java program is not optimized. When the program starts, itinterprets the class file bytecodes. You can display and changevariables while debugging.

9. Enable performance collection: This is the level of performance datacollection that is allowed for this Java program. These values can be returned:

*NONENo performance collection is enabled for this Java program.

*ENTRYEXITThis gives the entry and exit information on all of the procedures ofthe Java program, including those that were leaf procedures. This alsoincludes the PEP routine. *ENTRYEXIT is useful in capturinginformation on all procedures.

*FULL This gives the entry and exit information on all of the procedures ofthe Java program, including those that were leaf procedures. Also,precall and postcall hooks around other calls to other procedures.*FULL is useful in capturing information on all procedures.

10. Use adopted authority: Indicates if the Java programs use adopted authorityfrom previous call levels in the stack.

11. User profile: Indicates if the authority checking that was done while thisprogram is running should include only the user who is running the program(*USER), or both the user who is running the program and the program owner(*OWNER).

12. Licensed Internal Code options: The selected licensed internal code (LIC)

compile-time options that are used when the Java program was created.13. Java program size: The size, in bytes, of the Java programs that are attached

to the file.

14. Release program create for: The release of the operating system for which

the object was created.

See Example: Display Java Program (DSPJVAPGM) command for an example thatuses the DSPJVAPGM command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Display Java Program (DSPJVAPGM) commandThe DSPJVAPGM (Display Java Program) command displays the Java programthat is associated with the specified class file named myJavaClassFileName.

Example 1: Display a Java Program

92 AS/400 Developer Kit for Java

Page 101: AS400 Developer Kit for Java (Rzaha)

DSPJVAPGMCLSF('/projectA/team2/myJavaClassFileName.class')OUTPUT(*)

See the Display Java Program (DSPJVAPGM) command for syntax diagram andparameter details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Operations Navigator commands that are supported by JavaAS/400 Operations Navigator is a graphical interface for your Windows desktop. Itis part of Client Access for Windows and covers many AS/400 functions thatadministrators or users need to accomplish their daily work.

Operations Navigator supports Java as a third-party plug-in. To install thethird-party plug-in, you need to install the AS/400 Developer Kit for Java on yourAS/400. Then, install the AS/400 Developer Kit for Java on your personalcomputer through Selective Setup in the Client Access folder.

Class files reside in the integrated file system. Operations Navigator allows you tosee these class files in the right pane. Right-click the class file that you want to use.This brings up a context menu.

Selecting the New Java program from the context menu starts the Java transformer,which creates an AS/400 Java program that is associated with your class file. Adialog box allows you to specify details on how to create the program. You cancreate the program for either Java transformation or Java interpretation.

Note:If you select transformation, the bytecodes in your class file transform intoRISC instructions that result in better performance than if you used interpretation.

Selecting Change Java program from the context menu changes attributes of Javaprograms that are attached to Java class files, ZIP files, or JAR files.

Selecting Run Java program from the context menu runs your class file on AS/400.A dialog appears to allow you to specify details on how to run the program. If youhave already selected New Java program, the AS/400 Java program that isassociated with your class file is used when running the program. If an AS/400Java program is not already associated with your class file, then the AS/400 Javaprogram is created before the program runs.

Selecting Delete Java program from the context menu deletes the AS/400 Javaprogram that is associated with your class file.

See the online help information for the parameters and options of the New Javaprogram, Change Java program, Run Java program, and Delete Java programOperations Navigator commands.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 4. Commands and tools for the AS/400 Developer Kit for Java 93

Page 102: AS400 Developer Kit for Java (Rzaha)

94 AS/400 Developer Kit for Java

Page 103: AS400 Developer Kit for Java (Rzaha)

Chapter 5. Using Java with other programming languages

With Java, you have multiple ways to call code that was written in languages otherthan Java.

Java Native Interface:

One of the ways you can call code written in another language is to implementselected Java methods as ’native methods.’ Native methods are procedures, writtenin another language, that provide the actual implementation of a Java method.Native methods can access the Java virtual machine using the Java Native Interface(JNI). These native methods run under the Java thread, which is a kernel thread, sothey must be thread safe. A function is thread safe if you can start itsimultaneously in multiple threads within the same process. A function is threadsafe if and only if all the functions it calls are thread safe also.

Native methods are a “bridge” to access system functions that are not directlysupported in Java, or to interface to existing user code. Use caution when usingnative methods, because the code that is being called may not be thread safe. Seeusing the Java Native Interface for native methods for more information about JNIand native methods.

java.lang.Runtime.exec():

You can use java.lang.Runtime.exec() to call programs or commands from within aJava program. The exec() method starts another process in which any AS/400program or command can run. In this model, you can use standard in, standardout, and standard err of the child process for interprocess communication.

Interprocess communication:

One option is to use sockets for interprocess communication between the parentand child processes.

You can also use stream files for communication between programs. Or seeinterprocess communication examples for an overview of your options whencommunicating with programs that are running in another process.

To call Java from other languages, see calling Java from other languages.

You can also use the AS/400 Toolbox for Java to call existing programs andcommands on AS/400. Data queues and AS/400 messages are usually used forinterprocess communication with the AS/400 Toolbox for Java.

Note: By using Runtime.exec(), AS/400 Toolbox for Java, or JNI you maycompromise the portability of the Java program. You should avoid using thesemethods in a “pure” Java environment.

Java Invocation API:

Using the Java Invocation API, which is also a part of the Java Native Interface(JNI) specification, allows a non-Java application to use the Java virtual machine. Italso allows the use of Java code as an extension of the application.

© Copyright IBM Corp. 1998, 1999 95

Page 104: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Using the Java Native Interface for native methodsYou should only use native methods in cases where pure Java cannot meet yourprogramming needs. Limit the use of native methods by only using them underthese circumstances:v To access system functions that are not available using pure Java.v To implement extremely performance-sensitive methods that can benefit

significantly from a native implementation.v To interface to existing application program interfaces (API) that allow Java to

call other APIs.

To use the Java Native Interface (JNI) for native methods, do these steps:1. Design the class by specifying which methods will be native methods with the

standard Java language syntax.2. Decide on a library and program name for the service program (*SRVPGM)

that contains native method implementations. When coding theSystem.loadLibrary() method call in the static initializer for the class, specifythe name of the service program.

3. Use the javac tool to compile the Java source into a class file.4. Use the javah tool to create the header file (.h). This header file contains the

exact prototypes for creating the native method implementations. The -doption specifies the directory where you should create the header file.

5. Copy the header file from the integrated file system into a member in a sourcefile by using the Copy From Stream File (CPYFRMSTMF) command. You mustcopy the header file into a source file member for the C compiler to use it.Use the new stream file support for the Create Bound ILE C/400 Program(CRTCMOD) command to leave your C source and C header files in theintegrated file system. For more information on the CRTCMOD command andthe use of stream files, see the ILE C Programmer’s Guide, SC09-2712 book.

6. Write the native method code. See Java native methods and threadsconsiderations for details about the languages and functions that are used fornative methods.a. Include the header file that was created in the previous steps.b. Match the prototypes in the header file exactly.c. Convert strings to American National Standard Code for Information

Interchange (ASCII) if the strings are to pass to the Java virtual machine.For more information, see Java character encodings.

7. If your native method must interact with the Java virtual machine, use thefunctions that are provided with JNI.

8. Compile your C source code, using the CRTCMOD, into a module (*MOD)object.

9. Bind one or more module objects into a service program (*SRVPGM) by usingthe Create Service Program (CRTSRVPGM) command. The name of this serviceprogram must match the name that you supplied in your Java code that is inthe System.load() or System.loadLibrary() function calls.

96 AS/400 Developer Kit for Java

Page 105: AS400 Developer Kit for Java (Rzaha)

10. If you used the ’System.loadLibrary()’ call in your Java code, do one of thefollowing.

If you are using a version that is older than J2SDK:Add the AS/400 library that contains your new service program to theAS/400 library list. To add the library, use the Add Library List Entry(ADDLIBLE) command. This allows the Java program to find the serviceprogram when it processes the System.loadLibrary() function.If you are using J2SDK:You do not need to modify your library list. Instead, you can either:v Include the list of the libraries that you need in the LIBPATH environment

variable. You can modify the LIBPATH environment variable in QShell andfrom the AS/400 command line.– From the Qshell command prompt, type in:

export LIBPATH=/QSYS.LIB/MYLIB.LIBjava -Djava.version=1.2 myclass

– Or, from the command line:ADDENVVAR LIBPATH ’/QSYS.LIB/MYLIB.LIB’JAVA PROP((java.version 1.2)) myclass

v Or, supply the list in the java.library.path property. You can modify thejava.library.path property in QShell and from the AS/400 command line.– From the Qshell command prompt, type in:

java -Deja.library.path=/QSYS.LIB/MYLIB.LIB -Djava.version=1.2myclass

– Or, from the AS/400 command line, type in:JAVA PROP((java.library.path ’/QSYS.LIB/MYLIB.LIB’) (java.version’1.2’)) myclass

Where /QSYS.LIB/MYLIB.LIB is the library that you wish to load using the’System.loadLibrary()’ call, and myclass is the name of your Java application.

11.

The patches syntax for System.load(String patches) can be any of these:v “path” (integrated file system filename that specifies the library that the

service program provides), which is a symbolic link to a *SRVPGM, such as“/qsys.lib/mylib.lib/myNMsp.srvpgm”

v /qsys.lib/sysNMsp.srvpgmv /qsys.lib/mylib.lib/myNMsp.srvpgm

v If you have a version older than J2SDK:

/qsys.lib/%libl%.lib/myNMsp.srvpgmNote: This is equivalent to using the System.loadLibrary(“myNMsp”)method.

Note: If the “pathname” is used as a string literal, then you must enclose it inquotation marks. For example,System.load(“/qsys.lib/mylib.lib/myNMsp.srvpgm”).

12.

The “libya” syntax for System.loadLibrary(String libya) is mysp. The systemfinds mysp by using *LIBL. For example, loadLibrary(“myNMsp”) is

Chapter 5. Using Java with other programming languages 97

Page 106: AS400 Developer Kit for Java (Rzaha)

equivalent to System.load(“/qsys.lib/%libl%.lib/myNMsp.srvpgm”). If the“pathname” is used as a string literal, then you must enclose the libname inquotation marks.

Note: The %libl% syntax is not supported for J2SDK.

For a complete description of the JNI, refer to the Java Native Interface by Sun

Microsystems, Inc., and The Source for Java Technology java.sun.com.

See Examples: Using the Java Native Interface for native methods for an exampleof how to use the JNI for native methods.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java native methods and threads considerationsYou can use native methods to access functions that are not available in Java.

To better use Java with native methods you need to understand these concepts:v A Java thread, whether created by Java or an attached native thread, has all

floating point exceptions disabled. If the thread runs a native method thatreenables floating point exceptions, Java does not turn them off a second time. Ifthe user application does not disable them before returning to run Java code,then the Java code may not behave correctly if a floating point exception occurs.When a native thread detaches from the Java virtual machine, its floating pointexception mask is restored to the value that was in effect when it was attached.

v When a native thread attaches to the Java virtual machine, the Java virtualmachine changes the threads priority, if necessary, to conform to the one to tenpriority schemes that Java defines. When the thread detaches, the priority isrestored. After attaching, the thread can change the thread priority by using anative method interface (for example, a POSIX API). Java does not change thethread priority on transitions back to the Java virtual machine.

v The Invocation API component of the Java Native Interface (JNI) permits a userto embed a Java virtual machine within their application. If an applicationcreates a Java virtual machine and the Java virtual machine ends abnormally, theMCH74A5 “Java Virtual Machine Terminated” AS/400 exception is signalled tothe initial thread of the process if that thread was attached to the Java virtualmachine when the Java virtual machine ended. The Java virtual machine couldend abnormally for any of these reasons:– The user calls the java.lang.System.exit() method.– A thread that the Java virtual machine requires ends.– An internal error occurs in the Java virtual machine.

This behavior differs from most other Java platforms. On most other platforms,the process that automatically creates the Java virtual machine ends abruptly assoon as the Java virtual machine ends. If the application monitors and handles asignalled MCH74A5 exception, it may continue to run. Otherwise, the processends when the exception goes unhandled. By adding the code that deals withthe AS/400-specific MCH74A5 exception you can make the application lessportable to other platforms.

Because native methods always run in a multithreaded process, the code that theycontain must be thread safe. This places these restrictions on the languages andfunctions that are used for native methods:

98 AS/400 Developer Kit for Java

Page 107: AS400 Developer Kit for Java (Rzaha)

v You should not use ILE CL for native methods, because this language is notthread safe. To run thread safe CL commands, you can use the C languagesystem() function or the java.lang.Runtime.exec() method.– Use the C language system() function to run thread safe CL commands from

within a C or C++ native method.– Use the java.lang.Runtime.exec() method to run thread safe CL commands

directly from Java.v You can use ILE C, ILE C++, ILE COBOL, and ILE RPG to write a native

method, but all of the functions that are called from within the native methodmust be thread safe.Note: Compile-time support for writing native methods is currently onlysupplied for the C and C++ languages. While possible, writing native methodsin other languages may be much more complicated.Caution:Not all standard C, C++, COBOL, or RPG functions are thread safe.

v The C and C++ exit() and abort() functions should never be used within a nativemethod. These functions cause the entire process that runs the Java virtualmachine to stop. This includes all of the threads in the process, regardless of ifthey were originated by Java or not.Note: The exit() function referred to is the C and C++ function, and is not thesame as the java.lang.Runtime.exit() method.

For more information about threads on AS/400, see Developing multithreadedapplications.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Strings in native methodsMany Java Native Interface (JNI) functions accept C language-style strings asparameters. For example, the FindClass() JNI function accepts a string parameterthat specifies the fully-qualified name of a classfile. If the classfile is found, it isloaded by FindClass, and a reference to it is returned to the caller of FindClass.

All JNI functions expect their string parameters to be encoded in UTF-8. For detailson UTF-8, you can refer to the JNI Specification, but in most cases it is enough toobserve that 7-bit American National Standard Code for Information Interchange(ASCII) characters are equivalent to their UTF-8 representation. 7-bit ASCIIcharacters are actually 8-bit characters but their first bit is always 0. So, most ASCIIC strings are actually already in UTF-8.

The C compiler on the AS/400 system operates in extended binary-coded decimalinterchange code (EBCDIC) by default, so you can provide strings to the JNIfunctions in UTF-8. There are two ways to do this. You can use literal strings, oryou can use dynamic strings. Literal strings are strings whose value is knownwhen the source code is compiled. Dynamic strings are strings whose value is notknown at compile time, but rather is actually computed at run time.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Literal strings in native methodsIt is easier to encode literal strings in UTF-8 if the string is composed of characterswith a 7-bit American National Standard Code for Information Interchange (ASCII)

Chapter 5. Using Java with other programming languages 99

Page 108: AS400 Developer Kit for Java (Rzaha)

representation. If the string is representable in ASCII, as most are, then the stringcan be bracketed by ’pragma’ statements that modify the current codepage of thecompiler. Then, the compiler stores the string internally in the UTF-8 form that isrequired by the JNI. If the string is not representable in ASCII, it is easier to treatthe original extended binary-coded decimal interchange code (EBCDIC) string as adynamic string, and process it using iconv() before passing it to the JNI. For moreinformation on dynamic strings, see Dynamic strings.

For example, to find the class named “java/lang/String” the code looks like this:#pragma convert(819)myClass = (*env)->FindClass(env,“java/lang/String”);#pragma convert(0)

The first pragma, with the number 819, informs the compiler to store allsubsequent double-quoted strings (literal strings) in ASCII. The second pragma,with the number 0, tells the compiler to revert to the default code page of thecompiler for double-quoted strings, which is usually the EBCDIC code page 37. So,by bracketing this call with these pragmas, we satisfy the JNI requirement thatstring parameters are encoded in UTF-8.

Caution: Be careful with text substitutions. For example, if your code looks likethis:

#pragma convert(819)#define MyString “java/lang/String”#pragma convert(0)myClass = (*env)->FindClass(env,MyString);

Then, the resulting string is EBCDIC, because the value of MyString is substitutedinto the FindClass call during compilation. At the time of this substitution, thepragma, number 819, is not in effect. Thus, literal strings are not stored in ASCII.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Converting dynamic strings to and from EBCDIC, Unicode, andUTF-8To manipulate string variables that are computed at run time, it may be necessaryto convert strings to and from extended binary-coded decimal interchange(EBCDIC), Unicode, and UTF-8.

The system API that provides for code page conversion function is iconv(). To useiconv(), follow these steps:1. Create a conversion descriptor with QtqIconvOpen().2. Call iconv() to use the descriptor to convert to a string.3. Close the descriptor by using iconv_close.

In Example 3 of the using the Java Native Interface for native methods examples,the routine creates, uses, and then destroys the iconv conversion descriptor withinthe routine. This scheme avoids the problems with multithreaded use of an iconv_tdescriptor, but for performance sensitive code it is better to create a conversiondescriptor in static storage, and moderate multiple access to it using a mutualexclusion (mutex) or other synchronization facility.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

100 AS/400 Developer Kit for Java

Page 109: AS400 Developer Kit for Java (Rzaha)

Examples: Using the Java Native Interface for native methodsThis example program is a simple Java Native Interface (JNI) example in which aC native method is used to display “Hello, World.” Use thejavah tool with theNativeHello class file to generate the NativeHello.h file. This example assumes thatthe NativeHello C implementation is part of a service program that is calledNATHELLO.Note: The library where the NATHELLO service program is located must be in thelibrary list for this example to run.

Example 1:NativeHello classpublic class NativeHello {

// Declare a field of type 'String' in the NativeHello object.// This is an 'instance' field, so every NativeHello object// contains one.public String theString; // instance variable// Declare the native method itself. This native method// creates a new string object, and places a reference to it// into 'theString'public native void setTheString(); // native method to set string// This 'static initializer' code is called before the class is// first used.static {

// Attempt to load the native method library. If you do not// find it, write a message to 'out', and try a hardcoded path.// If that fails, then exit.try {

// System.loadLibrary uses the AS/400 library list in JDK1.1,// and uses the java.library.path property or the LIBPATH environment// variable in JDK1.2

System.loadLibrary(“NATHELLO”);}

catch (UnsatisfiedLinkError e1) {// Did not find the service program.System.out.println

(“I did not find NATHELLO *SRVPGM.”);System.out.println (“(I will try a hardcoded path)”);try {

// System.load takes the full integrated file system form path.System.load (“/qsys.lib/jniexample.lib/nathello.srvpgm”);}

catch (UnsatisfiedLinkError e2) {// If you get to this point, then you are done! Write the message// and exit.System.out.println

(“<sigh> I did not find NATHELLO *SRVPGM anywhere. Goodbye”);System.exit(1);}

}}// Here is the 'main' code of this class. This is what runs when you// enter 'java NativeHello' on the command line.public static void main(String argv[]){

// Allocate a new NativeHello object now.NativeHello nh = new NativeHello();// Echo location.System.out.println(“(Java) Instantiated NativeHello object”);System.out.println(“(Java) string field is '” + nh.theString + “'”);System.out.println(“(Java) Calling native method to set the string”);// Here is the call to the native method.nh.setTheString();// Now, print the value after the call to double check.System.out.println(“(Java) Returned from the native method”);

Chapter 5. Using Java with other programming languages 101

Page 110: AS400 Developer Kit for Java (Rzaha)

System.out.println(“(Java) string field is '” + nh.theString + “'”);System.out.println(“(Java) All done...”);

}}

Example 2:Generated NativeHello.h header file/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class NativeHello */#ifndef _Included_NativeHello#define _Included_NativeHello#ifdef __cplusplusextern “C” {#endif/** Class: NativeHello* Method: setTheString* Signature: ()V*/JNIEXPORT void JNICALL Java_NativeHello_setTheString

(JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif

This NativeHello.c example shows the implementation of the native method in C.This example simply shows how to link Java to native methods. However, it pointsout complications that arise from the fact that AS/400 is internally an extendedbinary-coded decimal interchange code (EBCDIC) machine. It also showscomplications from the current lack of true internationalization elements in the JNI.

These reasons, although they are not new with the JNI, cause some unique,AS/400-specific differences in the C code that you write. You must remember thatif you are writing to stdout or stderr or reading from stdin, your data is probablyencoded in EBCDIC form.

In C code, you can easily convert most literal strings, those that contain 7-bitcharacters only, into the UTF-8 form that is required by the JNI. To do this, bracketthe literal strings with code-page conversion pragmas. However, because you maywrite information directly to stdout or stderr from your C code, you might allowsome literals to remain in EBCDIC.

Note: The #pragma convert(0) statements convert character data to EBCDIC. The#pragma convert(819) statements convert character data to American NationalStandard Code for Information Interchange (ASCII). These statements convertcharacter data in the C program at compile time.

Example 3:NativeHello.c native method implementation of the NativeHello Javaclass#include <stdlib.h> /* malloc, free, and so forth */#include <stdio.h> /* fprintf(), and so forth */#include <qtqiconv.H> /* iconv() interface */#include <string.h> /* memset(), and so forth */#include “NativeHello.h” /* generated by 'javah-jni' *//* All literal strings are ISO-8859-1 Latin 1 code page (and with 7-bitcharacters, they are also automatically UTF-8). */#pragma convert(819) /* handle all literal strings as ASCII *//* Report and clear a JNI exception. */static void HandleError(JNIEnv*);/* Print an UTF-8 string to stderr in the coded character */

102 AS/400 Developer Kit for Java

Page 111: AS400 Developer Kit for Java (Rzaha)

set identifier (CCSID) of the current job. */static void JobPrint(JNIEnv*, char*);/* Constants describing which direction to covert: */#define CONV_UTF2JOB 1#define CONV_JOB2UTF 2/* Convert a string from the CCSID of the job to UTF-8, or vice-versa. */int StringConvert(int direction, char *sourceStr, char *targetStr);/* Native method implementation of 'setTheString()'. */JNIEXPORT void JNICALL Java_NativeHello_setTheString(JNIEnv *env, jobject javaThis){

jclass thisClass; /* class for 'this' object */jstring stringObject; /* new string, to be put in field in 'this' */jfieldID fid; /* field ID required to update field in 'this' */jthrowable exception; /* exception, retrieved using ExceptionOccurred *//* Write status to console. */JobPrint(env, “( C ) In the native method\n”);/* Build the new string object. */if (! (stringObject = (*env)->NewStringUTF(env, “Hello, native world!”))){

/* For nearly every function in the JNI, a null return value indicatesthat there was an error, and that an exception had been placed where itcould be retrieved by 'ExceptionOccurred()'. In this case, the errorwould typically be fatal, but for purposes of this example, go aheadand catch the error, and continue. */HandleError(env);return;

}/* get the class of the 'this' object, required to get the fieldID */if (! (thisClass = (*env)->GetObjectClass(env,javaThis))){

/* A null class returned from GetObjectClass indicates that therewas a problem. Instead of handling this problem, simply return andknow that the return to Java automatically 'throws' the stored Javaexception. */return;

}/* Get the fieldID to update. */if (! (fid = (*env)->GetFieldID(env,

thisClass,“theString”,“Ljava/lang/String;”)))

{/* A null fieldID returned from GetFieldID indicates that therewas a problem. Report the problem from here and clear it.Leave the string unchanged. */HandleError(env);return;

}JobPrint(env, “( C ) Setting the field\n”);/* Make the actual update.Note: SetObjectField is an example of an interface that doesnot return a return value that can be tested. In this case, itis necessary to call ExceptionOccurred() to see if therewas a problem with storing the value */(*env)->SetObjectField(env, javaThis, fid, stringObject);/* Check to see if the update was successful. If not, report the error. */if ((*env)->ExceptionOccurred(env)) {

/* A non-null exception object came back from ExceptionOccurred,so there is a problem and you must report the error. */HandleError(env);

}JobPrint(env, “( C ) Returning from the native method\n”);return;

}static void HandleError(JNIEnv *env){

Chapter 5. Using Java with other programming languages 103

Page 112: AS400 Developer Kit for Java (Rzaha)

/* A simple routine to report and handle an exception. */JobPrint(env, “( C ) Error occurred on JNI call: ”);(*env)->ExceptionDescribe(env); /* write exception data to the console */(*env)->ExceptionClear(env); /* clear the exception that was pending */

}static void JobPrint(JNIEnv *env, char *str){

char *jobStr;char buf[512];size_t len;len = strlen(str);/* Only print non-empty string. */if (len) {

jobStr = (len >= 512) ? malloc(len+1) : &buf;if (! StringConvert(CONV_UTF2JOB, str, jobStr))

(*env)->FatalError(env,“ERROR in JobPrint: Unable to convert UTF2JOB”);

fprintf(stderr, jobStr);if (len >= 512) free(jobStr);

}}int StringConvert(int direction, char *sourceStr, char *targetStr){

QtqCode_T source, target; /* parameters to instantiate iconv */size_t sStrLen, tStrLen; /* local copies of string lengths */iconv_t ourConverter; /* the actual conversion descriptor */int iconvRC; /* return code from the conversion */size_t originalLen; /* original length of the sourceStr *//* Make local copies of the input and output sizes that are initializedto the size of the input string. The iconv() requires thelength parameters to be passed by address (that is as int*). */originalLen = sStrLen = tStrLen = strlen(sourceStr);/* Initialize the parameters to the QtqIconvOpen() to zero. */memset(&source,0x00,sizeof(source));memset(&target,0x00,sizeof(target));/* Depending on direction parameter, set either SOURCEor TARGET CCSID to ISO 8859-1 Latin. */if (CONV_UTF2JOB == direction ) {

source.CCSID = 819;}else {

target.CCSID = 819;}/* Create the iconv_t converter object. */ourConverter = QtqIconvOpen(&target,&source);/* Make sure that you have a valid converter, otherwise return 0. */if (-1 == ourConverter.return_value) return 0;/* Perform the conversion. */iconvRC = iconv(ourConverter,

(char**) &sourceStr,&sStrLen,&targetStr,&tStrLen);

/* If the conversion failed, return a zero. */if (0 != iconvRC ) return 0;/* Close the conversion descriptor. */iconv_close(ourConverter);/* The targetStr returns pointing to the character justpast the last converted character, so set the nullterminator there now. */*targetStr = '\0';/* Return the number of characters that were processed. */return originalLen-tStrLen;

}#pragma convert(0)

104 AS/400 Developer Kit for Java

Page 113: AS400 Developer Kit for Java (Rzaha)

See Using the Java Native Interface for native methods for backgroundinformation.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Using java.lang.Runtime.exec()The java.lang.Runtime.exec() method calls programs or commands from within aJava program. The actual processing that occurs depends on exactly whatinformation is passed to the exec() method. In all cases, the Runtime.exec() methodcreates another thread-enabled batch immediate (BCI) job. The BCI job processesthe command string that is passed in on the Runtime.exec() method.

To use the java.lang.Runtime.exec() method, you must install the Qshell Interpreteron your AS/400. For more information about the Qshell Interpreter, see QshellInterpreter.

Note: The java.lang.Runtime.exec() method runs programs in a separate process.This differs from the C system function, which runs a program in the sameprocess.

If the command being processed is a Qshell utility, it runs in the second BCI job,and the third BCI job is not created. If the command being processed is a CLcommand, the second BCI job is started to run the Qshell, and the third BCI job isstarted to run the CL command. A Qshell utility is a built-in utility that QSH canrun directly. An example of a Qshell utility is the javac command, which compilesJava programs. The processing in the second (or third) BCI job runs concurrentlywith the Java virtual machine. Any exit or shutdown processing in those jobs doesnot affect the original Java virtual machine.

When calling an AS/400 command or program, you must ensure that anyparameters being passed to the called program are in the code page that isexpected by that program.

See calling another Java program, calling a CL program, or calling a CL commandfor java.lang.Runtime.exec() examples.

Chapter 5. Using Java with other programming languages 105

Page 114: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Calling another Java program withjava.lang.Runtime.exec()

This example shows how to call another Java program withjava.lang.Runtime.exec(). This class calls the Hello program that is shipped as partof the AS/400 Developer Kit for Java. When the Hello class writes to System.out,this program gets a handle to the stream and can read from it.

Note: You use the Qshell Interpreter to call the program.

Example 1: CallHelloPgm class

import java.io.*;public class CallHelloPgm{

public static void main(String args[]){

Process theProcess = null;BufferedReader inStream = null;System.out.println(“CallHelloPgm.main() invoked”);// call the Hello classtry{

theProcess = Runtime.getRuntime().exec(“java com.ibm.as400.system.Hello”);}catch(IOException e){

System.err.println(“Error on exec() method”);e.printStackTrace();

}// read from the called program's standard output streamtry{

inStream = new BufferedReader(new InputStreamReader( theProcess.getInputStream() ));

System.out.println(inStream.readLine());}catch(IOException e){

System.err.println(“Error on inStream.readLine()”);e.printStackTrace();

}} // end method

} // end class

For background information, see Using java.lang.Runtime.exec().

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

106 AS/400 Developer Kit for Java

Page 115: AS400 Developer Kit for Java (Rzaha)

Example: Calling a CL program with java.lang.Runtime.exec()This example shows how to run CL programs from within a Java program. Seecalling a CL command for an example of how to call a CL command from within aJava program. In this example, the Java class CallCLPgm runs a CL program. TheCL program uses the Display Java Program (DSPJVAPGM) command to displaythe program that is associated with the Hello class file. This example assumes thatthe CL program has been compiled and exists in a library that is calledJAVSAMPLIB. The output from the CL program is in the QSYSPRT spooled file.

Note: The JAVSAMPLIB is not created as part of the AS/400 Developer Kitlicensed program (LP) number 5769-JV1 installation process. You must explicitlycreate the library.

Example 1: CallCLPgm classimport java.io.*;public class CallCLPgm{

public static void main(String[] args){

try{

Process theProcess =Runtime.getRuntime().exec(“/QSYS.LIB/JAVSAMPLIB.LIB/DSPJVA.PGM”);

}catch(IOException e){

System.err.println(“Error on exec() method”);e.printStackTrace();

}} // end main() method

} // end class

Example 2: Display Java CL programPGM

DSPJVAPGM CLSF('/QIBM/ProdData/Java400/com/ibm/as400/system/Hello.class') +OUTPUT(*PRINT)

ENDPGM

For background information, see Using java.lang.Runtime.exec().

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Calling a CL command with java.lang.Runtime.exec()This example shows how to run a CL command from within a Java program. Inthis calling a CL command example, the Java class runs a CL command. The CLcommand uses the Display Java Program (DSPJVAPGM) command to display theprogram that is associated with the Hello class file. The output from the CLcommand is in the QSYSPRT spooled file.

Note: Every command that is passed in to the Runtime.getRuntime().exec()function needs to be in quotes and in Qshell format. In addition, in order to run aCL command from Qshell, it is necessary to pass in the string:“system \”CL COMMAND\“”Where CL COMMAND is the CL command you wish to run. So the line to call thecommand MYCLCOM should like this: Runtime.getRuntime().exec(“system\”MYCLCOM\“”);

Chapter 5. Using Java with other programming languages 107

Page 116: AS400 Developer Kit for Java (Rzaha)

Example 1: CallCLCom classimport java.io.*;public class CallCLCom{

public static void main(String[] args){

try{

Process theProcess =Runtime.getRuntime().exec(“system \”DSPJVAPGM CLSF('/com/ibm/as400/system/Hello.clas

}catch(IOException e){

System.err.println(“Error on exec() method”);e.printStackTrace();

}} // end main() method

} // end class

For background information, see Using java.lang.Runtime.exec().

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Interprocess communication examplesWhen communicating with programs that are running in another process, there area number of options.

One option is to use sockets for interprocess communication. One program can actas the server program, that listens on a socket connection for input from the clientprogram. The client program connects to the server with a socket. Once the socketconnection is established, either program can send or receive information.

Another option is to use stream files for communication between programs. To dothis, use the System.in, System.out, and System.err classes.

A third option is to use the AS/400 Toolbox for Java which provides data queuesand AS/400 message objects.

You can also calling Java from other languages.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Using sockets for interprocess communicationSockets streams communicate between programs that are running in separateprocesses. The programs can either start separately or start by using thejava.lang.Runtime.exec() method from within the main Java program. If a programis written in a language other than Java, you must ensure that any AmericanNational Standard Code for Information Interchange (ASCII) or extendedbinary-coded decimal interchange code (EBCDIC) conversion takes place. See Javacharacter encodings for more details.

For an example that uses sockets, see Example: Using sockets for interprocesscommunication.

108 AS/400 Developer Kit for Java

Page 117: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Using sockets for interprocess communicationThis example uses sockets to communicate between a Java program and a Cprogram. You should start the C program first, which listens on a socket. Once theJava program connects to the socket, the C program sends it a string by using thatsocket connection. The string that is sent from the C program is an AmericanNational Standard Code for Information Interchange (ASCII) string in codepage819.

The Java program should be started using this command, java TalkToC xxxxxnnnn on the Qshell Interpreter command line or on another Java platform. Or, enterJAVA TALKTOC PARM(xxxxx nnnn) on the AS/400 command line to start the Javaprogram. xxxxx is the domain name or Internet Protocol (IP) address of the systemon which the C program is running. nnnn is the port number of the socket that theC program is using. You should also use this port number as the first parameter onthe call to the C program.

Example 1: TalkToC client classimport java.net.*;import java.io.*;class TalkToC{

private String host = null;private int port = -999;private Socket socket = null;private BufferedReader inStream = null;public static void main(String[] args){

TalkToC caller = new TalkToC();caller.host = args[0];caller.port = new Integer(args[1]).intValue();caller.setUp();caller.converse();caller.cleanUp();

} // end main() methodpublic void setUp(){

System.out.println(“TalkToC.setUp() invoked”);try{

socket = new Socket(host, port);inStream = new BufferedReader(new InputStreamReader(

socket.getInputStream()));}catch(UnknownHostException e){

System.err.println(“Cannot find host called: ” + host);e.printStackTrace();System.exit(-1);

}catch(IOException e){

System.err.println(“Could not establish connection for ” + host);e.printStackTrace();System.exit(-1);

}} // end setUp() methodpublic void converse(){

System.out.println(“TalkToC.converse() invoked”);

Chapter 5. Using Java with other programming languages 109

Page 118: AS400 Developer Kit for Java (Rzaha)

if (socket != null && inStream != null){

try{

System.out.println(inStream.readLine());}catch(IOException e){

System.err.println(“Conversation error with host ” + host);e.printStackTrace();

}} // end if

} // end converse() methodpublic void cleanUp(){

try{

if(inStream != null){

inStream.close();}if(socket != null){

socket.close();}

} // end trycatch(IOException e){

System.err.println(“Error in cleanup”);e.printStackTrace();System.exit(-1);

}} // end cleanUp() method

} // end TalkToC class

SockServ.C starts by passing in a parameter for the port number. For example, CALLSockServ ’2001’.

Example 2: SockServ.C server program#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netinet/tcp.h>#include <unistd.h>#include <sys/time.h>void main(int argc, char* argv[]){

int portNum = atoi(argv[1]);int server;int client;int address_len;int sendrc;int bndrc;char* greeting;struct sockaddr_in local_Address;address_len = sizeof(local_Address);memset(&local_Address,0x00,sizeof(local_Address));local_Address.sin_family = AF_INET;local_Address.sin_port = htons(portNum);local_Address.sin_addr.s_addr = htonl(INADDR_ANY);#pragma convert (819)greeting = “This is a message from the C socket server.”;#pragma convert (0)

110 AS/400 Developer Kit for Java

Page 119: AS400 Developer Kit for Java (Rzaha)

/* allocate socket */if((server = socket(AF_INET, SOCK_STREAM, 0))<0){

printf(“failure on socket allocation\n”);perror(NULL);exit(-1);

}/* do bind */if((bndrc=bind(server,(struct sockaddr*)&local_Address, address_len))<0){

printf(“Bind failed\n”);perror(NULL);exit(-1);

}/* invoke listen */listen(server, 1);/* wait for client request */if((client = accept(server,(struct sockaddr*)NULL, 0))<0){

printf(“accept failed\n”);perror(NULL);exit(-1);

}/* send greeting to client */if((sendrc = send(client, greeting, strlen(greeting),0))<0){

printf(“Send failed\n”);perror(NULL);exit(-1);

}close(client);close(server);

}

For more information, see Using sockets for interprocess communication.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Using input and output streams for interprocesscommunication

Input and output streams communicate between programs that are running inseparate processes. The java.lang.Runtime.exec() method runs a program. Theparent program can get handles to the child process input and output streams andcan write to or read from those streams. If the child program is written in alanguage other than Java, you must ensure that any American National StandardCode for Information Interchange (ASCII) or extended binary-coded decimalinterchange code (EBCDIC) conversion takes place. See Java character encodingsfor more details.

For an example that uses input and output streams, see Example: Using input andoutput streams for interprocess communication.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Using input and output streams for interprocesscommunicationThis example shows how to call a C program from Java and use input and outputstreams for interprocess communication. In this example, the C program writes a

Chapter 5. Using Java with other programming languages 111

Page 120: AS400 Developer Kit for Java (Rzaha)

string to its standard output stream, and the Java program reads this string anddisplays it. This example assumes that a library, which is named JAVSAMPLIB, hasbeen created and that the CSAMP1 program has been created in it.

Note: The JAVSAMPLIB is not created as part of the AS/400 Developer Kitlicensed program (LP) number 5769-JV1 installation process. You must explicitlycreate it.

Example 1: CallPgm classimport java.io.*;public class CallPgm{

public static void main(String args[]){

Process theProcess = null;BufferedReader inStream = null;System.out.println(“CallPgm.main() invoked”);// call the CSAMP1 programtry{

theProcess = Runtime.getRuntime().exec(“/QSYS.LIB/JAVSAMPLIB.LIB/CSAMP1.PGM”);

}catch(IOException e){

System.err.println(“Error on exec() method”);e.printStackTrace();

}// read from the called program's standard output streamtry{

inStream = new BufferedReader(new InputStreamReader(theProcess.getInputStream()));

System.out.println(inStream.readLine());}catch(IOException e){

System.err.println(“Error on inStream.readLine()”);e.printStackTrace();

}} // end method

} // end class

Example 2: CSAMP1 C Program#include <stdio.h>#include <stdlib.h>void main(int argc, char* args[]){

/* Convert the string to ASCII at compile time */#pragma convert(819)

printf(“Program JAVSAMPLIB/CSAMP1 was invoked\n”);#pragma convert(0)

/* Stdout may be buffered, so flush the buffer */fflush(stdout);

}

For more information, see Using input and output streams for interprocesscommunication.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

112 AS/400 Developer Kit for Java

Page 121: AS400 Developer Kit for Java (Rzaha)

Calling Java from other languagesTo call Java programs from other languages, it is necessary to call a command torun the Java virtual machine. The application program interface (API) to call acommand differs, and depends on the language that calls Java. For example, fromC, the system() function runs the Run Java (RUNJVA) command. From CL, you candirectly call the RUNJVA command. Other ILE languages can use the QCMDEXCcall.

Note: Any of these calls cause another process to be created in which the Javavirtual machine is run. To communicate between the processes, you must use someform of interprocess communication. Some methods of interprocess communicationare sockets, data queues, and stream files. If data is passing between the programs,it is necessary to ensure that the programs convert that data properly.

For examples of how to call the Java Hello program in C or RPG, see Example:Calling Java from C or Example: Calling Java from RPG, respectively.

You can also use the Java Invocation API specification, which allows a non-Javaapplication, such as C, to use the Java virtual machine.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Calling Java from CThis is an example of a C program that uses the system() function to call the JavaHello program.

Example 1: Calling Java from C#include <stdlib.h>int main(void){

int result;/* The system function passes the given string to the CL command processor

for execution. */result = system(“JAVA CLASS('com.ibm.as400.system.Hello')”);

}

For more information, see calling Java from other languages.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Calling Java from RPGThis is an example of an RPG program that uses the QCMDEXC API to call theJava Hello program.

Example 1: Calling Java from RPGD* DEFINE THE PARAMETERS FOR THE QCMDEXC APID*DCMDSTRING S 25 INZ('JAVA CLASS(''com.ibm.as400.system.Hello'')')DCMDLENGTH S 15P 5 INZ(25)D* NOW THE CALL TO QCMDEXC WITH THE 'JAVA' CL COMMANDC CALL 'QCMDEXC'C PARM CMDSTRINGC PARM CMDLENGTHC* This next line will display 'DID IT' after you exit theC* Java Shell via F3 or F12.

Chapter 5. Using Java with other programming languages 113

Page 122: AS400 Developer Kit for Java (Rzaha)

C 'DID IT' DSPLYC* Set On LR to exit the RPG programC SETON LRC

For more information, see calling Java from other languages.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java Invocation APIThe Invocation API, which is part of the Java Native Interface (JNI), allowsnon-Java code to create a Java virtual machine, and load and use Java classes. Thisfunction lets a multithreaded program make use of Java classes that are running ina single Java virtual machine in multiple threads.

The application controls the Java virtual machine. The application can create theJava virtual machine, call Java methods (similar to the way in which an applicationcalls subroutines), and destroy the Java virtual machine. Once you create the Javavirtual machine, it remains ready to run within the process until the applicationexplicitly destroys it. While being destroyed, the Java virtual machine performsclean-up, such as running finalizers, ending Java virtual machine threads, andreleasing Java virtual machine resources.

With a Java virtual machine that is ready to run, an application written in C cancall into the Java virtual machine to perform any function. It also can return fromthe Java virtual machine to the C application, call into the Java virtual machineagain, and so on. The Java virtual machine is created once and does not have to bere-created before calling into the Java virtual machine to run a little or a lot of Javacode.

When using the Invocation API to run Java programs, the destination for STDOUTand STDERR is controlled by the use of an environment variable calledQIBM_USE_DESCRIPTOR_STDIO. If this environment variable is set to Y or I (forexample, QIBM_USE_DESCRIPTOR_STDIO=Y), the Java virtual machine uses filedescriptors for STDIN (fd 0), STDOUT (fd 1), and STDERR (fd 2). In this case, theprogram must set these file descriptors to valid values by opening them as the firstthree files or pipes in this job. The first file opened in the job is given fd of 0, thesecond fd of 1, and third is fd of 2. For jobs initiated with the spawn API, thesedescriptors can be preassigned using a file descriptor map (see documentation onSpawn API). If the environment variable QIBM_USE_DESCRIPTOR_STDIO is notset or is set to any other value, file descriptors are not used for STDIN, STDOUT,or STDERR. Instead, STDOUT and STDERR are routed to a spooled file that isowned by the current job, and use of STDIN results in an IO exception.

For an example that uses the Invocation API, see Example: Java Invocation API.See Invocation API functions for details about the Invocation API functions that aresupported by the AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

114 AS/400 Developer Kit for Java

Page 123: AS400 Developer Kit for Java (Rzaha)

Invocation API functionsThe AS/400 Developer Kit for Java supports the these Invocation API functions.Note: Before using this API, you must ensure that you are in a multithread-capablejob. See Developing multithreaded applications for more information aboutmultithread-capable jobs.v JNI_GetDefaultJavaVMInitArgs Note: This function is only supported for Java

Development Kit (JDK) 1.1.x.Returns a JDK 1.1 structure that contains default values for arguments that needto be passed to JNI_CreateJavaVM when you create a Java virtual machine.Signature:jint JNI_GetDefaultJavaVMInitArgs(void *args_);

v JNI_GetCreatedJavaVMs

Returns information about all Java virtual machines that were created.Signature:jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf,

jsize bufLen,jsize *nVMs);

vmBuf is an output area whose size is determined by bufLen, which is thenumber of pointers. Each Java virtual machine has an associated JavaVMstructure that is defined in java.h. This API stores a pointer to the JavaVMstructure that is associated with each created Java virtual machine into vmBuf,unless vmBuf is full. Pointers to JavaVM structures are stored in the order of thecorresponding Java virtual machines that are created. nVMs returns the numberof virtual machines that are currently created. AS/400 supports the creation ofmore than one Java virtual machine, so you may expect a value higher than one.This information, along with the size of the vmBuf, determines whether pointersto JavaVM structures for each created Java virtual machine are returned.

v JNI_CreateJavaVM

Allows a user to create a Java virtual machine and subsequently use it in anapplication.Signature for Java Development Kit 1.1.x:jint JNI_CreateJavaVM(JavaVM **p_vm,

JNIEnv **p_env,void *vm_args);

Signature for Java 2 Software Development Kit (J2SDK):jint JNI_CreateJavaVM(JavaVM **p_vm,

void **p_env,void *vm_args);

p_vm is the address of a JavaVM pointer for the newly created Java virtualmachine. Several other JNI Invocation APIs use p_vm to identify the Java virtualmachine. p_env is the address of a JNI Environment pointer for the newlycreated Java virtual machine. It points to a table of JNI functions that start thosefunctions. vm_args is a structure that contains Java virtual machine initializationparameters. When using JDK 1.1.x, you can obtain a structure that containsdefault values by calling JNI_GetDefaultJavaVMInitArgs. For details on how to

do this with J2SDK, see Java Native Interface .

If you start a Run Java (RUNJVA) command or JAVA command and specify aproperty that has an equivalent command parameter, then the command

Chapter 5. Using Java with other programming languages 115

Page 124: AS400 Developer Kit for Java (Rzaha)

parameter takes precedence. The property is ignored. For example, theos400.optimization parameter is ignored in this command:JAVA CLASS(Hello) PROP((os400.optimization 0))

For a list of 0S/400 unique properties that are supported by theJNI_CreateJavaVM API, see Java system properties.

Note:With multiple Java virtual machines within one process, all Java virtualmachines share the same process static storage that is allocated for any nativemethods. Java virtual machine internal implementation already partitions dataon a per-Java virtual machine basis, but you must consider that with nativemethod applications Java virtual machines share process static storage. For otherconsiderations, see support for multiple Java virtual machines.

v DestroyJavaVM

Destroys the Java virtual machine.Signature:jint DestroyJavaVM(JavaVM *vm)

When the Java virtual machine is created, vm is the JavaVM pointer that isreturned.

v AttachCurrentThread

Attaches a thread to a Java virtual machine, so it can use Java virtual machineservices.Signature for Java Development Kit (JDK) 1.1.x:jint AttachCurrentThread(JavaVM *vm,

JNIEnv **p_env,void *thr_args);

Signature for Java 2 Software Development Kit (J2SDK):jint AttachCurrentThread(JavaVM *vm,

void **p_env,void *thr_args);

The JavaVM pointer, vm, identifies the Java virtual machine to which the threadis being attached. p_env is the pointer to the location where the JNI Interfacepointer of the current thread is placed. thr_args contains VM specific threadattachment arguments.

v DetachCurrentThread

Signature:jint DetachCurrentThread(JavaVM *vm);

vm identifies the Java virtual machine from which the thread is being detached.

For a complete description of the Invocation API functions, refer to the Java NativeInterface Specification by Sun Microsystems, Inc., or The Source for Java

Technology java.sun.com.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

116 AS/400 Developer Kit for Java

Page 125: AS400 Developer Kit for Java (Rzaha)

Support for multiple Java virtual machines

Java on the AS/400 system, unlike the Sun Microsystems, Inc. referenceimplementation, supports the creation of multiple Java virtual machines within asingle job or process. This means that you can successfully call JNI_CreateJavaVM()more than once in a job, and JNI_GetCreatedJavaVMs() can return more than oneJava virtual machine in its list of results.

If you want to create multiple Java virtual machines for use within a single job orprocess, you should carefully consider the following:

Native method static storage scoping:

v Service programs that contain native method implementations are only activatedonce per job, regardless of the number of Java virtual machines that you create.This implies that native method static storage is scoped to the job and not to anyspecific Java virtual machine.

v Values that a native method places in static storage are independent of the Javavirtual machine that called the native method. These values are visible to anyJava virtual machine in the job.

v If you intentionally use native method static storage in a multiple Java virtualmachine scenario, you should carefully consider the possible requirements forsynchronization, above and beyond the use of synchronized methods andmonitors, which are Java virtual machine specific. The qualification of a nativemethod as synchronized only prevents simultaneous runs within a single Javavirtual machine and not simultaneous runs from multiple Java virtual machines.

Java virtual machine termination:

v If a Java virtual machine is abnormally terminated, either due to a user callingjava.lang.System.exit() or an internal Java virtual machine failure, the failingJava virtual machine and all of its attached threads are terminated.

v If the process initial thread is among the threads that were attached to the failedJava virtual machine, an exception is thrown to the initial thread. If the initialthread handles this exception, the other Java virtual machines can continue torun.

v If the process initial thread is terminated, either by an unhandled exception orany other reason, all of the Java virtual machines in the process are terminated,as well.

Abnormal termination from C

If you use the ILE/C exit() or abort() routines in any thread of a multithreadedjob you will immediately bring down the entire job, including all Java virtual

machines.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Java Invocation APIThis example follows the standard Invocation API paradigm. For example, it doesthe following:v Creates a Java virtual machine by using JNI_CreateJavaVM.v Uses the Java virtual machine to find the class file that you want to run.v Finds the methodID for the main method of the class.

Chapter 5. Using Java with other programming languages 117

Page 126: AS400 Developer Kit for Java (Rzaha)

v Calls the main method of the class.v Reports errors if an exception occurs.

To compile this program, you must bind it with a service program that exports thefunctions to start a new Java virtual machine. These are the entry points that youneed:v JNI_GetDefaultJavaVMInitArgs, which initializes the parameters to create.v JNI_CreateJavaVM, which creates the Java virtual machine.

When you compile the program, you do not need to do anything explicit with thecompile command. The service program that exports these entry points is in thesystem binding directory. The name of the service program is QJVAJNI.

To run this program, use SBMJOB CMD(CALL PGM(YOURLIB/PGMNAME))ALWMLTTHD(*YES). Any job that creates a Java virtual machine must bemultithread-capable. The only job on AS/400 that is multithread-capable is a batchimmediate (BCI) job. The output from the main program, as well as any outputfrom the program, ends up in QPRINT spooled files. These spooled files are visibleif you use the Work with Submitted Jobs (WRKSBMJOB) command and view thejob that you started with Submit Job (SBMJOB).

Note: The C runtime exit() routine used below is not recommended unless youknow that your program is the only thread in the process. When called from aprocess that is capable of supporting multiple threads, exit() immediately ends allthreads in a process.

Example:Using the Java Invocation API#include <stdlib.h>#include <stdio.h>#include <string.h>#include <jni.h>int main (int argc, char *argv[]){

JDK1_1InitArgs initArgs; /* Virtual Machine (VM) initialization structure.* This is the structure that is passed by reference to JNI_CreateJavaVM*See jni.h for details.*/

JavaVM* myJVM; /* The JavaVM and JNIEnv pointers that you get back. */JNIEnv* myEnv; /* ...from the JNI_CreateJavaVM() call. */char* myClasspath; /* You need to modify the classpath, so you have your own. */jclass myClass; /* The class you are going to find, called 'NativeHello'. */jmethodID mainID; /* The method ID of the class' “main” routine. */jclass stringClass; /* Required to create a string array argument for 'main'. */jobjectArray args; /* Because main expects an array of strings, you must pass one. *//* Set the version field of the initialization arguments. */initArgs.version = 0x00010001;/* Get the default initialization arguments. */JNI_GetDefaultJavaVMInitArgs(&initArgs);/* Now, you want to add the directory onto the end of the classpath,* so that the findClass finds it correctly. To do this, you have two options:* You can append your classpath entries to the default classpath that is returned* by the call to JNI_GetDefaultJavaVMInitArgs, or* you can use OS/400 specific functions for the same result. This is a* three-step solution:* 1. Set the CLASSPATH environment variable to its requirements with 'putenv()'* 2. Clear the initialization arguments classpath to NULL, which forces* JNI_CreateJavaVM to look at the CLASSPATH value* 3. Set the “os400.class.path.system=PRE” property, to force JNI_CreateJavaVM* to prepend the system default classpath to the effective classpath.** The first option is used in this example, because it is more platform independent*

118 AS/400 Developer Kit for Java

Page 127: AS400 Developer Kit for Java (Rzaha)

* NOTE: You must specify the directory name in UTF-8 format! So, you wrap* blocks of code in #pragma convert statements.*/

#pragma convert(819)myClasspath = malloc( strlen(initArgs.classpath) + strlen(“:/CrtJvmExample”) + 1 );strcpy( myClasspath, initArgs.classpath );strcat( myClasspath, “:/CrtJvmExample” );initArgs.classpath = myClasspath;

#pragma convert(0)/* Create the JVM. */if (JNI_CreateJavaVM(&myJVM, &myEnv, &initArgs)) {

fprintf(stderr, “Failed to create the JVM\n”);exit(1);

}/* Use the newly created JVM to find the example class.* NOTE: Again, you are dealing with UTF-8 here, so you* have to wrap the calls in #pragma convert.*/

#pragma convert(819)if (! (myClass = (*myEnv)->FindClass(myEnv, “NativeHello”))) {

#pragma convert(0)/* Cannot find the class, so write an error message* to C stderr and exit the program.*/fprintf(stderr, “Failed to find the class 'NativeHello'\n”);exit(1); /* Exit terminates the entire process on AS/400. */

}/* Now, get the method identifier for the 'main' entry point* of the class. Note: The signature of 'main' is always* the same for every class, “main” and “([Ljava/lang/String;)V”* Again, you are dealing with UTF-8.*/

#pragma convert(819)if (! (mainID = (*myEnv)->GetStaticMethodID(myEnv, myClass,

“main”,“([Ljava/lang/String;)V”))) {

/* The 'main' methodID is not found for some reason. */if ( (*myEnv)->ExceptionOccurred(myEnv) ) {

/* a java exception occurred, so print it out */(*myEnv)->ExceptionDescribe(myEnv);/* The JVM ends. */(*myEnv)->FatalError(myEnv, “Failed to find jmethodID of 'main()'”);}

#pragma convert(0)/* Cannot find the 'main' methodID, so write an error message* to C stderr and exit the program.*/fprintf(stderr, “Failed to find the 'main()' method\n”);exit(1); /* Exit terminates the entire process on AS/400. */

}#pragma convert(819)

if (! (stringClass = (*myEnv)->FindClass(myEnv,“java/lang/String”))) {#pragma convert(0)

/* Did not find java/lang/String, so write an error message* to C stderr and exit the program.*/fprintf(stderr, “Failed to find the java/lang/String”);exit(1); /* exit terminates the entire process on AS/400.*/

}/* Now, you need to create an empty array of strings,* because ([Ljava/lang/String) is a required part of the signature of* every Java main routine.*/if (! (args = (*myEnv)->NewObjectArray(myEnv,0,stringClass,0))) {

/* Empty array was not created, so write an error message* to C stderr and exit the program.*/

Chapter 5. Using Java with other programming languages 119

Page 128: AS400 Developer Kit for Java (Rzaha)

fprintf(stderr, “Failed to create empty array of strings”);exit(1); /* Exit terminate the entire process on AS/400. */

}/* Now, you have the methodID of main, and the class, so you can call the main method. */(*myEnv)->CallStaticVoidMethod(myEnv,myClass,mainID,args);/* Check for errors. */if ( (*myEnv)->ExceptionOccurred(myEnv) ) {

fprintf(stderr,“An exception occurred while running 'main'”);exit(1);

}/* Finally, destroy the JavaVM that you created. */if ( (*myJVM)->DestroyJavaVM(myJVM) ) {

fprintf(stderr, “Failed to destroy the JVM\n”);exit(1);

}/* All done. */return 0;

}

For more information, see Java Invocation API.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

120 AS/400 Developer Kit for Java

Page 129: AS400 Developer Kit for Java (Rzaha)

Chapter 6. Accessing your AS/400 database with the AS/400Developer Kit for Java JDBC driver

With the AS/400 Developer Kit for Java JDBC driver your Java programs canaccess AS/400 database files, access JDBC database functions with embeddedStructured Query Language (SQL) for Java, and run SQL statements and process

results. JDBC is a standard part of Java and is included on AS/400. JDBC is aJava API for running structured query language (SQL) statements. It allows theuser to issue SQL statements and process the results.

To utilize the JDBC driver:1. Import the required classes:v import java.sql.*;v import com.ibm.db2.jdbc.app.*;

2. Set up the Uniform Resource Locator (URL).3. Register the AS/400 Developer Kit for Java JDBC driver with the

DriverManager so that you can use JDBC to access data in an AS/400 databasefile.

4. Connect to an AS/400 database by using the DriverManager.getConnection()method.

5. Create the SQL statements that you want to use to update the data in yourtable. SQL statements can be any of these interfaces:v Statement is the standard SQL statement interface.v PreparedStatement is a precompiled statement that can accept input

parameters.v CallableStatement is a precompiled statement that can accept input and

output parameters.6. Set the parameters for your PreparedStatement and CallableStatement SQL

statements.7. Run the SQL statements.8. Close each of the SQL statements using the Statement.close() method.9. Close the connection to the AS/400 database.

JDBC defines these Java interfaces:v The Driver interface creates the connection and returns information about the

driver version.v The Connection interface represents a connection to a specific database.v The Statement interface runs SQL statements and obtains the results.v The PreparedStatement interface runs compiled SQL statements.v The CallableStatement interface runs SQL stored procedures.v The ResultSet interface provides access to a table of data that is generated by

running an SQL query or DatabaseMetaData catalog method.v The ResultSetMetaData interface determines the types and properties of the

columns in a ResultSet.v The DatabaseMetaData interface provides information about the database as a

whole.

© Copyright IBM Corp. 1998, 1999 121

Page 130: AS400 Developer Kit for Java (Rzaha)

v JDBC 2.0 defines the Blob interface provides access to binary large objects(BLOBs).

v JDBC 2.0 defines the Clob interface provides access to character large objects(CLOBs).

See Example: Creating a JDBC application for an example of how to combine all ofthe interfaces to build a JDBC application.

You can access AS/400 databases through two JDBC drivers: AS/400 Developer Kitfor Java driver or AS/400 Toolbox for Java JDBC driver. For specific informationabout the AS/400 Toolbox for Java JDBC driver, see AS/400 Toolbox for Java.

For more information about JDBC, see the JDBC by Sun Microsystems, Inc.documentation.

For more information about AS/400 Native JDBC Driver, see AS/400 DeveloperKit for Java JDBC Web Page.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Registering the AS/400 Developer Kit for Java JDBC driver beforeusing JDBC

You must register the AS/400 Developer Kit for Java JDBC driver with theDriverManager before using JDBC to access data in an AS/400 database file.

You can either use a Java system property or have the Java program register thedrivers.v Registration that uses a system property.

Each Java virtual machine has its own method of setting system properties. Forexample, the java command in Qshell uses the -d option to set systemproperties.To set the driver using system properties, specify this command from the QshellInterpreter:java -djdbc.drivers=com.ibm.db2.jdbc.app.DB2Driver MySQL

To set the driver using system properties, specify this from the CL commandline:JAVA CLASS(MySQL)

PROP((jdbc.drivers com.ibm.db2.jdbc.app.DB2Driver))

For system property details, see Java system properties.v Registration that uses the Java program.

To explicitly load the driver, add either of these commands to the Java programbefore the first JDBC call:–

java.sql.DriverManager.registerDriver (new com.ibm.db2.jdbc.app.DB2Driver ());

–Class.forName(“DB2Driver”);

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

122 AS/400 Developer Kit for Java

Page 131: AS400 Developer Kit for Java (Rzaha)

Connecting to an AS/400 database using the AS/400 Developer Kit forJava JDBC driver

To connect to the AS/400 database, use the DriverManager.getConnection()method.

DriverManager.getConnection() takes a Uniform Resource Locator (URL) string asan argument. The JDBC driver manager attempts to locate a driver that canconnect to the database that is represented by the URL. When using the AS/400Developer Kit for Java driver, use this syntax for the URL:“jdbc:db2:systemName”

The systemName contains an entry from the relational database directory. Enter theWork with Relational Database Directory Entries (WRKRDBDIRE) command todisplay or add the system name. Then, specify *LOCAL for the remote location inthe WRKRDBDIRE command. Typically, the name that is chosen is the same nameas the system name of the AS/400 that contains the database.

See Examples: Connecting to an AS/400 database using the AS/400 Developer Kitfor Java JDBC driver for an example of how to connect to an AS/400 database.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Examples: Connecting to an AS/400 database using theAS/400 Developer Kit for Java JDBC driver

These are examples of how to use the JDBC driver to connect to an AS/400.

Example 1: Connecting to the AS/400 database; no default schema or properties// Connect to system 'mySystem'. No default schema or properties are specified.Connection c = DriverManager.getConnection(“jdbc:db2://mySystem”);

Example 2: Connecting to the AS/400 database; default schema is specified// Connect to system 'mySys2'. The default schema 'mySchema' is specified.// A schema is the default library if none is specified on a query.Connection c2 = DriverManager.getConnection(“jdbc:db2://mySys2/mySchema”);

The Java program can specify a set of JDBC properties either by using thejava.util.Properties interface or by specifying the properties as part of the URL.This example specifies properties by using the Properties interface.

Example 3: Connecting to the AS/400 database; properties are specified usingJava.util.Properties// Create a properties object.Properties p = new Properties();// Set the properties for the connection.p.put(“naming”, “sql”);p.put(“user”, “JonDoe”);p.put(“password”, “JD1”);// Connect using the properties object.Connection c = DriverManager.getConnection(“jdbc:db2://mySystem”,p);

Example 4: Disconnecting from the database

Chapter 6. Accessing your AS/400 database with the AS/400 Developer Kit for Java JDBC driver 123

Page 132: AS400 Developer Kit for Java (Rzaha)

c.close();

For more information, see connecting to an AS/400 database using the AS/400Developer Kit for Java JDBC driver.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Creating a JDBC applicationJDBC is a Java API for running structured query language (SQL) statements. Itallows the user to issue SQL statements and process the results.

To utilize the JDBC driver:1. Import the required classes.2. Set up the Uniform Resource Locator (URL).3. Register the driver.4. Connect to the database.5. Create a statement object.6. Run SQL statements that create a table in the database and insert records.7. Close the statement.8. Create the PreparedStatement object.9. Set the parameters and run the statement.

10. Close the PreparedStatement.11. Create the CallableStatement object.12. Set the input parameters, register the output parameters, and run the stored

procedures.13. Close the CallableStatement.14. Close the connection.

See Example: Creating a JDBC application for an example of how to combine all ofthe interfaces to build a JDBC application.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Creating a JDBC applicationThese examples illustrate how to put all the interfaces together to build a JDBCapplication.

Example 1: JDBC application// Before running this example, some setup is required on the AS/400.//// 1. Find a *LOCAL Relational Database (e.g. AS400NAME) using CL Command WRKRDBDIRE,// or add one if there is no such entry. Modify the source code for this Java// program with this name and compile it.//// 2. Create stored procedure ADD on the AS/400 where this Java program will be run// using the following CL commands://// (Note: the example assumes library MYLIBRARY is empty, once created)//// > CRTLIB MYLIBRARY

124 AS/400 Developer Kit for Java

Page 133: AS400 Developer Kit for Java (Rzaha)

// > STRSQL// > CREATE PROCEDURE MYLIBRARY/ADD// (IN P1 INTEGER, IN P2 INTEGER, OUT P3 INTEGER)// LANGUAGE SQL SPECIFIC MYLIBRARY/ADD// JDCSPRSX: BEGIN// SET P3 = P1 + P2;// END JDCSPRSX//import java.lang.*;import java.util.*;import java.sql.*;import com.ibm.db2.jdbc.app.*;public class aJDBCApp

{public static void main(String args[]) throws Exception{

// Define a URL where AS400NAME is *LOCAL Relational Database// defined on an AS/400 using CL command WRKRDBDIRE.String url = “jdbc:db2://AS400NAME”;// Register the driver.Class.forName(“com.ibm.db2.jdbc.app.DB2Driver”);// Connect to the database.Connection c = DriverManager.getConnection(url, “” “”);// Create a Statement object.Statement s = c.createStatement();// Run an SQL statement that creates a table in the database.s.executeUpdate(“CREATE TABLE MYLIBRARY.MYTABLE (NAME VARCHAR(20), ID INTEGER)”);// Run an SQL statement that inserts a record into the table.s.executeUpdate(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('DAVE', 123)”);// Run an SQL statement that inserts a record into the table.s.executeUpdate(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('CINDY', 456)”);// Create the PreparedStatement object.// It precompiles the specified SQL statement.// The question marks indicate where parameters must be set before the statement is run.PreparedStatement ps = c.prepareStatement(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES (?,// Set parameters and run the statement.ps.setString(1, “JOSH”);ps.setInt(2, 789);ps.executeUpdate();// Set parameters and run the statement again.ps.setString(1, “DAVE”);ps.setInt(2, 456);ps.executeUpdate();// Close PreparedStatement.ps.close();// Create the CallableStatement object.// It pre-compiles the specified call to a stored procedure.// The question marks indicate where input parameters must be set// and where output parameters can be retrieved.// The first two parameters are input parameters,// and the third parameter is an output parameter.CallableStatement cs = c.prepareCall(“CALL MYLIBRARY.ADD (?, ?, ?)”);// Set input parameters.cs.setInt (1, 123);cs.setInt (2, 234);// Register the type of the output parameter.cs.registerOutParameter (3, Types.INTEGER);// Run the stored procedure.cs.execute ();// Get the value of the output parameter.int sum = cs.getInt (3);// Show the output parameter value returned by stored procedure ADDSystem.out.println(“sum = ” + sum + “\n”);// Close the CallableStatement.cs.close();// Define a complete SQL Statement.String myQuery =

Chapter 6. Accessing your AS/400 database with the AS/400 Developer Kit for Java JDBC driver 125

Page 134: AS400 Developer Kit for Java (Rzaha)

“select * from MYLIBRARY.MYTABLE”;// Run an SQL query on the table.ResultSet rs = s.executeQuery(myQuery);System.out.println(

“Query result: \n”);ResultSetMetaData rsmd = rs.getMetaData();System.out.println(rsmd.getColumnName(1) + “” + rsmd.getColumnName(2));System.out.println(“————”);while (rs.next()) {

String value1 = rs.getString(1);int value2 = rs.getInt(2);System.out.println(value1 + “” + value2);

}// Close the Statement.s.close();// Close the connection.c.close();

}}

For more information, see AS/400 Developer Kit for Java JDBC driver.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Statement interface for AS/400 Developer Kit for JavaA Statement object is an object that runs a structured query language (SQL)statement and optionally obtains the ResultSet that is produced by it. UseConnection.createStatement() to create new Statement objects.

CallableStatement inherits from PreparedStatement, and PreparedStatement inheritsfrom Statement. Statement runs a simple SQL statement that has no parameters.PreparedStatement runs a precompiled SQL statement that may or may not haveIN parameters. CallableStatement runs a call to a database-stored procedure. ACallableStatement may or may not have IN and OUT parameters.

See Example: Statement interface for AS/400 Developer Kit for Java for an exampleof a Statement object.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Statement interface for AS/400 Developer Kit forJava

This is an example of a Statement object.

Example 1: Statement object// Connect to AS/400.Connection c = DriverManager.getConnection(“jdbc:db2://mySystem”);// Create a Statement object.Statement s = c.createStatement();// Run an SQL statement that creates a table in the database.s.executeUpdate(“CREATE TABLE MYLIBRARY.MYTABLE (NAME VARCHAR(20), ID INTEGER)”);// Run an SQL statement that inserts a record into the table.s.executeUpdate(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('DAVE', 123)”);// Run an SQL statement that inserts a record into the table.s.executeUpdate(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('CINDY', 456)”);// Run an SQL query on the table.

126 AS/400 Developer Kit for Java

Page 135: AS400 Developer Kit for Java (Rzaha)

ResultSet rs = s.executeQuery(“SELECT * FROM MYLIBRARY.MYTABLE”);// Close the Statement and the Connection.s.close();c.close();

For more information, see Statement interface for AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

PreparedStatement interface for AS/400 Developer Kit for JavaA PreparedStatement object is an object that precompiles and stores structuredquery language (SQL) statements. Having been precompiled is what makes thestatement “prepared.” This approach is more efficient than running the samestatement multiple times with a Statement object that compiles the statement eachtime it runs. In addition, the SQL statement that is contained in aPreparedStatement object may have one or more IN parameters.

Use Connection.prepareStatement() to create PreparedStatement objects.

See Example: PreparedStatement interface for AS/400 Developer Kit for Java for anexample of the Prepared Statement interface.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: PreparedStatement interface for AS/400 DeveloperKit for Java

This is an example of the PreparedStatement interface.

Example 1: PreparedStatement interface// Connect to AS/400.Connection c = DriverManager.getConnection(“db2:as400://mySystem”);// Create the PreparedStatement object. It precompiles the specified SQL statement.// The question marks indicate where parameters must be set before the statement is run.PreparedStatement ps = c.prepareStatement(“INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES (?, ?)”// Set parameters and run the statement.ps.setString(1, “JOSH”);ps.setInt(2, 789);ps.executeUpdate();// Set parameters and run the statement again.ps.setString(1, “DAVE”);ps.setInt(2, 456);ps.executeUpdate();// Close PreparedStatement and the Connection.ps.close();c.close();

For more information, see PreparedStatement interface for AS/400 Developer Kitfor Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 6. Accessing your AS/400 database with the AS/400 Developer Kit for Java JDBC driver 127

Page 136: AS400 Developer Kit for Java (Rzaha)

CallableStatement interface for AS/400 Developer Kit for JavaA CallableStatement object runs structured query language (SQL) storedprocedures. The stored procedure that is being called must already be stored in thedatabase. CallableStatement does not contain the stored procedure, only the call tothe stored procedure.

A stored procedure can return one or more ResultSet objects, and can use INparameters, OUT parameters, and INOUT parameters.

Use Connection.prepareCall() to create new CallableStatement objects.

See Example: CallableStatement interface for AS/400 Developer Kit for Java for anexample of how to use the CallableStatement interface.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: CallableStatement interface for AS/400 Developer Kitfor Java

This is an example of how to use the CallableStatement interface.

Example 1: CallableStatement interface// Connect to AS/400.Connection c = DriverManager.getConnection(“jdbc:db2://mySystem”);// Create the CallableStatement object.// It precompiles the specified call to a stored procedure.// The question marks indicate where input parameters must be set and// where output parameters can be retrieved.// The first two parameters are input parameters, and the third parameter is an output parameter.CallableStatement cs = c.prepareCall(“CALL MYLIBRARY.ADD (?, ?, ?)”);// Set input parameters.cs.setInt (1, 123);cs.setInt (2, 234);// Register the type of the output parameter.cs.registerOutParameter (3, Types.INTEGER);// Run the stored procedure.cs.execute ();// Get the value of the output parameter.int sum = cs.getInt (3);// Close the CallableStatement and the Connection.cs.close();c.close();

For more information, see CallableStatement interface for AS/400 Developer Kit forJava.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

ResultSet interface for AS/400 Developer Kit for JavaThe ResultSet object is an object that provides access to a table of data that isgenerated by running a query. The table rows are retrieved in sequence. Within arow, column values can be accessed in any order.

128 AS/400 Developer Kit for Java

Page 137: AS400 Developer Kit for Java (Rzaha)

The data stored in ResultSet is retrieved by using the various get methodsdepending on the type of data being retrieved. The next() method moves to thenext row.

See Example: ResultSet interface for AS/400 Developer Kit for Java for an exampleof how to use the ResultSet interface.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: ResultSet interface for AS/400 Developer Kit forJava

This is an example of how to use the ResultSet interface.

Example 1: ResultSet interface// Connect to AS/400.Connection c = DriverManager.getConnection(“db2:as400://mySystem”);// Create a Statement object.Statement s = c.createStatement();// Run a query. The result is placed in a ResultSet object.ResultSet rs = s.executeQuery (“SELECT NAME,ID FROM MYLIBRARY.MYTABLE”);// Iterate through the rows of the ResultSet.while (rs.next ())

{// Get the values from the ResultSet.// The first value is a string, and the second value is an integer.String name = rs.getString(“NAME”);

int id = rs.getInt(“ID”);System.out.println(“Name = ” + name);System.out.println(“ID = ” + id);

}// Close the Statement and the Connection.s.close();c.close();

For more information, see ResultSet interface for AS/400 Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

DatabaseMetaData interface for AS/400 Developer Kit for JavaThe DatabaseMetaData object provides information about the database as a wholeas well as catalog information. DatabaseMetaData determines the specific supportthat is provided by the database.

See Example: DatabaseMetaData interface for AS/400 Developer Kit for Java for anexample of how to use the DatabaseMetaData interface.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 6. Accessing your AS/400 database with the AS/400 Developer Kit for Java JDBC driver 129

Page 138: AS400 Developer Kit for Java (Rzaha)

Example: DatabaseMetaData interface for AS/400 DeveloperKit for Java

This example shows how to return a list of tables.

Example 1: Returning a list of tables// Connect to AS/400.Connection c = DriverManager.getConnection(“jdbc:db2://mySystem”);// Get the database meta data from the connection.DatabaseMetaData dbMeta = c.getMetaData();// Get a list of tables matching this criteria.String catalog = “myCatalog”;String schema = “mySchema”;String table = “myTable%”; // % indicates search patternString types[] = {“TABLE”, “VIEW”, “SYSTEM TABLE”}:ResultSet rs = dbMeta.getTables(catalog, schema, table, types);// ... iterate through the ResultSet to get the values.// Close the Connection.c.close():

For more information, see DatabaseMetaData interface for AS/400 Developer Kitfor Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Blob interface for the AS/400 Developer Kit for Java

You can use a Blob object to access binary large objects (BLOBs), such as soundbyte (.wav) files or image (.gif) files.

NOTE: Only use the Blob interface if you are also using Java 2 to develop yourapplication.

With the Blob class, the lob threshold property can be used. This property specifiesthe maximum large object (LOB) size (in kilobytes) that can be retrieved as part ofa result set. LOBs that are larger than this threshold are retrieved in pieces usingextra communication to the server. Larger LOB thresholds reduce the frequency ofcommunication to the server, but they download more LOB data, even if it is notused. Smaller lob thresholds may increase frequency of communication to theserver, but they only download LOB data as it is needed.

Using the Blob interface, you can do the following:v Return the entire blob as a stream of uninterpreted bytesv Return part of the contents of the blobv Return the length of the blob

The following example shows how to use the DB2Blob interface:Blob blob = resultSet.getBlob (1);long length = blob.length ();byte[] bytes = blob.getBytes (0, (int) length);

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

130 AS/400 Developer Kit for Java

Page 139: AS400 Developer Kit for Java (Rzaha)

Clob interface for the AS/400 Developer Kit for Java

If you have JDBC 2.0, you can use a Clob object to access character largeobjects (CLOBs), such as large documents.

NOTE: Use the Clob interface only if you are using Java 2 to develop yourapplication.

With the Clob class, the lob threshold property can be used. This property specifiesthe maximum large object (LOB) size (in kilobytes) that can be retrieved as part ofa result set. LOBs that are larger than this threshold are retrieved in pieces usingextra communication to the server. Larger LOB thresholds reduce the frequency ofcommunication to the server, but they download more LOB data, even if it is notused. Smaller lob thresholds may increase frequency of communication to theserver, but they only download LOB data as it is needed.

Using the Clob interface, you can do the following:v Return the entire clob as a stream of ASCII charactersv Return the contents of the clob as a character streamv Return a part of the contents of the clobv Return the length of the clob

The following example shows how to use the DB2Clob interface:Clob clob = rs.getClob (1);int length = clob.getLength ();String s = clob.getSubString (0, (int) length);

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 6. Accessing your AS/400 database with the AS/400 Developer Kit for Java JDBC driver 131

Page 140: AS400 Developer Kit for Java (Rzaha)

132 AS/400 Developer Kit for Java

Page 141: AS400 Developer Kit for Java (Rzaha)

Chapter 7. Accessing databases using AS/400 Developer Kitfor Java DB2 SQLJ support

DB2 Structured Query Language for Java (SQLJ) support is based on the SQLJANSI standard. The DB2 SQLJ support is contained in the AS/400 Developer Kitfor Java. DB2 SQLJ support allows you to create, build, and run embedded SQL forJava applications.

The SQLJ support provided by the AS/400 Developer Kit for Java includes theSQLJ run-time classes, and is available in/QIBM/ProdData/Java400/ext/runtime.zip. For more information on the SQLJrun-time classes, refer to the Runtime API documentation supplied in the

Implementation from www.sqlj.org.

SQLJ toolsThe following tools are also included in the SQLJ support provided by the AS/400Developer Kit for Java.Note:These tools must be run in the Qshell Interpreter:v The SQLJ translator, sqlj, replaces embedded SQL statements in the SQLJ

program with Java source statements and generates a serialized profile thatcontains information about the SQLJ operations that are found in the SQLJprogram.

v The DB2 SQLJ Profile Customizer, db2profc, precompiles the SQL statementsstored in the generated profile and generates a package in the DB2 database.

v The DB2 SQLJ Profile Printer, db2profp, prints the contents of a DB2 customizedprofile in plain text.

v The SQLJ profile auditor installer, profdb, installs and uninstalls debuggingclass-auditors into an existing set of binary profiles.

v The SQLJ profile conversion tool, profconv, converts a serialized profile instanceto Java class format.

DB2 SQLJ restrictionsWhen you create DB2 applications with SQLJ, you should be aware of thefollowing restrictions:v DB2 SQLJ support adheres to standard DB2 Universal Database restrictions on

issuing SQL statements.v The DB2 SQLJ profile customizer should only be run on profiles associated with

connections to the local database.v The SQLJ Reference Implementation requires JDK 1.1.x. See Support for multiple

Java Development Kits (JDKs) for more information on running multipleversions of the Java Development Kit.

For information on using SQL in your Java applications, see Embedding SQLStatements in your Java application and Compiling and running SQLJ Programs.

© Copyright IBM Corp. 1998, 1999 133

Page 142: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Embedding SQL statements in your Java application

Static SQL statements in SQLJ are in SQLJ clauses. SQLJ clauses begin with#sql and end with a semicolon (;) character.

Before you create any SQLJ clauses in your Java application, import the followingpackages:v import java.sql.*;v import sqlj.runtime.*;v import sqlj.runtime.ref.*;

The simplest SQLJ clauses are executable clauses and consist of the token #sqlfollowed by an SQL statement enclosed in braces. For example, the following SQLJclause may appear wherever a Java statement may legally appear:

#sql { DELETE FROM TAB };

The example above will delete all the rows in the table named TAB.

Note: For information on compiling and running SQLJ applications, see Compilingand running SQLJ Programs.

In an SQLJ executable clause, the tokens that appear inside the braces are eitherSQL tokens or host variables. All host variables are distinguished by the colon (:)character. SQL tokens never occur outside the braces of an SQLJ executable clause.For example, the following Java method inserts its arguments into an SQL table:public void insertIntoTAB1 (int x, String y, float z) throws SQLException{

#sql { INSERT INTO TAB1 VALUES (:x, :y, :z) };}

The method body consists of an SQLJ executable clause containing the hostvariables x, y, and z. For more information on host variables, see Host variables inSQLJ.

In general, SQL tokens are case insensitive (except for identifiers delimited bydouble quotation marks), and can be written in upper, lower, or mixed case. Javatokens, however, are case sensitive. For clarity in examples, case insensitive SQLtokens are uppercase, and Java tokens are lowercase or mixed case. Throughoutthis chapter, the lowercase null is used to represent the Java “null” value, and theuppercase NULL is used to represent the SQL “null” value.

The following kinds of SQL constructs may appear in SQLJ programs:v Queries

For example, SELECT statements and expressions.v SQL Data Change statements (DML)

For example, INSERT, UPDATE, DELETE.v Data statements

For example, FETCH, SELECT..INTO.

134 AS/400 Developer Kit for Java

Page 143: AS400 Developer Kit for Java (Rzaha)

v Transaction Control statementsFor example, COMMIT, ROLLBACK, etc.

v Data Definition Language (DDL, also known as Schema Manipulation Language)statementsFor example, CREATE, DROP, ALTER.

v Calls to stored proceduresFor example, CALL MYPROC(:x, :y, :z)

v Invocations of stored functionsFor example, VALUES( MYFUN(:x) )

For an example of embedded SQLJ, see Example: Embedding SQL Statements in

your Java application.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Compiling and running SQLJ programs

If your Java program has embedded SQLJ statements, you need to follow aspecial procedure in order to compile and run it. To compile and run yourstructured query language for Java (SQLJ) Program, follow these steps.

Note:Before you begin, set up your CLASSPATH to contain the following:/QIBM/ProdData/Java400/ext/sqlj_classes.jar

/QIBM/ProdData/Java400/ext/translator.zip

/QIBM/ProdData/Java400/ext/runtime.zip1. Use the SQLJ translator, sqlj, on your Java source code with embedded SQL to

generate Java source code and associated profiles. There will be one profilegenerated for each connection.

For example, type in the command:sqlj MyClass.sqlj

Where MyClass.sqlj is the name of your SQLJ file. In this example, the SQLJtranslator will generate a MyClass.java source code file and any associatedprofiles. The associated profiles will be named MyClass_SJProfile0.ser,MyClass_SJProfile1.ser, MyClass_SJProfile2.ser, and so on.

Note: The SQLJ translator automatically compiles the translated Java sourcecode into a class file unless you explicitly turn off the compile option with the-compile=false clause.

2. Use the SQLJ Profile Customizer tool, db2profc, to install DB2 SQLJCustomizers on generated profiles and create the DB2 packages on the localsystem.

For example, type in the command:db2profc MyClass_SJProfile0.ser

Where MyClass_SJProfile0.ser is the name of the profile on which the DB2SQLJ Customizer will run.

Note: This step is optional but is recommended to increase runtimeperformance.

3. Run the Java class file just like any other Java class file.

Chapter 7. Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support 135

Page 144: AS400 Developer Kit for Java (Rzaha)

For example, type in:java MyClass

Where MyClass is the name of your Java class file.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Host variables in Structured Query Language for JavaArguments to embedded SQL statements are passed through host variables. Hostvariables are variables of the host language, and they can appear in SQLstatements. Hose variables have up to three parts:v A colon (:) prefix.v A Java host variable that is a Java identifier for a parameter, variable, or field.v An optional parameter mode identifier.

This mode identifier can be one of the following:IN, OUT, or INOUT.

The evaluation of a Java identifier does not have side effects in a Java program, soit may appear multiple times in the Java code generated to replace an SQLJ clause.

The following query contains the host variable, :x. This host variable is the Javavariable, field, or parameter x that is visible in the scope containing the query.

SELECT COL1, COL2 FROM TABLE1 WHERE :x > COL3

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Structured Query Language for Java profiles

Profiles are generated by the SQLJ Translator, sqlj, when you translate the SQLJsource file. Profiles are serialized binary files. That is why these files have a .serextension. These files contain the SQL statements from the associated SQLJ sourcefile.

To generate profiles from your SQLJ source code, run the SQLJ translator, sqlj, onyour .sqlj file.

For more information, see Compiling and running SQLJ Programs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Embedding SQL Statements in your Java applicationThe following example SQLJ application, App.sqlj, uses static SQL to retrieve

and update data from the EMPLOYEE table of the DB2 sample database.

Example: Embedding SQL Statements in your Java application:

136 AS/400 Developer Kit for Java

Page 145: AS400 Developer Kit for Java (Rzaha)

import java.sql.*;import sqlj.runtime.*;import sqlj.runtime.ref.*;#sql iterator App_Cursor1 (String empno, String firstnme) ; // 1#sql iterator App_Cursor2 (String) ;class App{

/************************ Register Driver ************************/

static{

try{

Class.forName(“com.ibm.db2.jdbc.app.DB2Driver”).newInstance();}catch (Exception e){

e.printStackTrace();}

}/********************** Main **********************/

public static void main(String argv[]){

try{

App_Cursor1 cursor1;App_Cursor2 cursor2;String str1 = null;String str2 = null;long count1;// URL is jdbc:db2:dbnameString url = “jdbc:db2:sample”;DefaultContext ctx = DefaultContext.getDefaultContext();if (ctx == null){

try{

// connect with default id/passwordConnection con = DriverManager.getConnection(url);con.setAutoCommit(false);ctx = new DefaultContext(con);

}catch (SQLException e){

System.out.println(“Error: could not get a default context”);System.err.println(e) ;System.exit(1);

}DefaultContext.setDefaultContext(ctx);

}// retrieve data from the databaseSystem.out.println(“Retrieve some data from the database.”);#sql cursor1 = {SELECT empno, firstnme FROM employee}; // 2// display the result set// cursor1.next() returns false when there are no more rowsSystem.out.println(“Received results:”);while (cursor1.next()) // 3{

str1 = cursor1.empno(); // 4str2 = cursor1.firstnme();System.out.print (“ empno= ” + str1);System.out.print (“ firstname= ” + str2);System.out.println(“”);

}

Chapter 7. Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support 137

Page 146: AS400 Developer Kit for Java (Rzaha)

cursor1.close(); // 9// retrieve number of employee from the database#sql { SELECT count(*) into :count1 FROM employee }; // 5if (1 == count1)

System.out.println (“There is 1 row in employee table”);else

System.out.println (“There are ” + count1+ “ rows in employee table”);

// update the databaseSystem.out.println(“Update the database.”);#sql { UPDATE employee SET firstnme = 'SHILI' WHERE empno = '000010' };// retrieve the updated data from the databaseSystem.out.println(“Retrieve the updated data from the database.”);str1 = “000010”;#sql cursor2 = {SELECT firstnme FROM employee WHERE empno = :str1}; // 6// display the result set// cursor2.next() returns false when there are no more rowsSystem.out.println(“Received results:”);while (true){

#sql { FETCH :cursor2 INTO :str2 }; // 7if (cursor2.endFetch()) break; // 8System.out.print (“ empno= ” + str1);System.out.print (“ firstname= ” + str2);System.out.println(“”);

}cursor2.close(); // 9// rollback the updateSystem.out.println(“Rollback the update.”);#sql { ROLLBACK work };System.out.println(“Rollback done.”);

}catch( Exception e ){

e.printStackTrace();}

}}

1. Declare iterators. This section declares two types of iterators:

App_Cursor1Declares column data types and names, and returns the values of thecolumns according to column name (Named binding to columns).

App_Cursor2Declares column data types, and returns the values of the columns bycolumn position (Positional binding to columns).

2. Initialize the iterator. The iterator object cursor1 is initialized using the resultof a query. The query stores the result in cursor1.

3. Advance the iterator to the next row. The cursor1.next() method returns aBoolean false if there are no more rows to retrieve.

4. Move the data. The named accessor method empno() returns the value of thecolumn named empno on the current row. The named accessor methodfirstnme() returns the value of the column named firstnme on the current row.

5. SELECT data into a host variable. The SELECT statement passes the numberof rows in the table into the host variable count1.

6. Initialize the iterator. The iterator object cursor2 is initialized using the resultof a query. The query stores the result in cursor2.

7. Retrieve the data. The FETCH statement returns the current value of the firstcolumn declared in the ByPos cursor from the result table into the host variablestr2.

138 AS/400 Developer Kit for Java

Page 147: AS400 Developer Kit for Java (Rzaha)

8. Check the success of a FETCH..INTO statement. The endFetch() methodreturns a Boolean true if the iterator is not positioned on a row, that is, if thelast attempt to fetch a row failed. The endFetch() method returns false if thelast attempt to fetch a row was successful. DB2 attempts to fetch a row whenthe next() method is called. A FETCH...INTO statement implicitly calls thenext() method.

9. Close the iterators. The close() method releases any resources held by theiterators. You should explicitly close iterators to ensure that system resourcesare released in a timely fashion.

For background information on this example, see Embedding SQL Statements in

your Java application.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

The structured query language for Java (SQLJ) translator (sqlj)

The SQLJ translator, sqlj, generates a serialized profile containing informationabout the SQL operations found in the SQLJ program. The SQLJ translator uses the/QIBM/ProdData/Java400/ext/translator.zip file.

For more information on sqlj command line options, refer to the SQLJ User’s Guide

and Reference supplied in the Implementation from www.sqlj.org .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Precompiling SQL statements in a profile using the DB2 SQLJ profilecustomizer, db2profc

You can use the DB2 SQLJ Profile Customizer, db2profc, to make your Javaapplication work more efficiently with your database.The DB2 SQLJ Profile Customizer does the following:v Precompiles the SQL statements that are stored in a profile and generates a

package in the DB2 database.v Customizes the SQLJ profile by replacing the SQL statements with references to

the associated statement in the package that was created.

To precompile the SQL statements in a profile, type in the following at the Qshellcommand prompt:db2profc MyClass_SJProfile0.serWhere MyClass_SJProfile0.ser is the name of the profile you wish to precompile.

DB2 SQLJ Profile Customizer usage and syntax

db2profc[options] <SQLJ profile name>

Where SQLJ profile name is the name of the profile to be printed and options isthe list of options you want.

The options available for db2profp are:-url=<JDBC URL>

Chapter 7. Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support 139

Page 148: AS400 Developer Kit for Java (Rzaha)

-user=<user name>

-password=<password>

-package=<library name/ package name>

-commitctrl=<commitment control>

-datefmt=<date format>

-datesep=<date separator>

-timefmt=<time format>

-timesep=<time separator>

-decimalpt=<decimal point>

-stmtCCSID=<coded character set identifier for the SQL statementtext>

-sorttbl=<library name/sort sequence table name>

-langID=<language identifier>

For detailed descriptions of these options, see below.

-url=<JDBC URL>Where JDBC URL is the url of the JDBC connection. The syntax for the urlis:“jdbc:db2:systemName”For more information, see Database access using the AS/400 Developer Kitfor Java JDBC driver.

-user=<user name>Where user name is your user name. The default value is the userid of thecurrent user that is signed on for local connection.

-password=<password>Where password is your password. The default value is the password ofthe current user that is signed on for local connection.

-package=<library name/package name>Where library name is the library where the package will be put, andpackage name is the name of the package to be generated. The defaultlibrary name is QUSRSYS. The default package name will be generatedfrom the name of the profile. The maximum length for the package nameis 10 characters. Because the SQLJ profile name will always be longer than10 characters, the default package name that is constructed will be differentfrom the profile name. The default package name will be constructed byconcatenating the first letters of the profile name with the profile keynumber. If the profile key number is greater than 10 characters long thenthe last 10 characters of the profile key number will be used for the defaultpackage name. For example, the following chart shows some profile namesand their default package names:

Profile name Default package name

App_SJProfile0 App_SJPro0

App_SJProfile01234 App_S01234

App_SJProfile012345678 A012345678

App_SJProfile01234567891 1234567891

140 AS/400 Developer Kit for Java

Page 149: AS400 Developer Kit for Java (Rzaha)

-commitctrl=<commitment control>Where commitment control is the level of commitment control you want.Commitment control can have any one of the following character values:

Value DefinitionC *CHG. Dirty reads, non-repeatable reads and

phantom reads are possible.S *CS. Dirty reads are not possible but

non-repeatable reads and phantom reads arepossible.

A *ALL. Dirty reads and non-repeatable readsare not possible but phantom reads arepossible.

N *NONE. Dirty reads, non-repeatable reads,and phantom reads are not possible. This isthe default.

-datefmt=<date format>Where date format is the type of date formatting you want. Date formatcan have any one of the following values:

Value DefinitionUSA IBM USA standard (mm.dd.yyyy,hh:mm

a.m., hh:mm p.m.)ISO International Standards Organization

(yyyy-mm-dd, hh.mm.ss) This is the default.EUR IBM European Standard (dd.mm.yyyy,

hh.mm.ss)JIS Japanese Industrial Standard Christian Era

(yyyy-mm-dd, hh:mm:ss)MDY Month/Day/Year (mm/d/yy)DMY Day/Month/Year (dd/mm/yy)YMD Year/Month/Day (yy/mm/dd)JUL Julian (yy/ddd)

Date format is used when accessing date result columns. All output datefields are returned in the specified format. For input date strings, thespecified value is used to determine whether the date is specified ina validformat. The default value is ISO.

-datesep=<date separator>Where date separator is the type of separator you want to use. Dateseparator is used when accessing date result columns. Date separator canbe any of the following values:

Value Definition/ A slash is used.. A period is used., A comma is used.- A dash is used. This is the default.blank A space is used.

-timefmt=<time format>Where time format is the format you want to use to display time fields.Time format is used when accessing time result columns. For input timestrings, the specified value is used to determine whether the time isspecified in a valid format. Time format can be any one of the followingvalues:

Chapter 7. Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support 141

Page 150: AS400 Developer Kit for Java (Rzaha)

Value DefinitionUSA IBM USA standard (mm.dd.yyyy,hh:mm

a.m., hh:mm p.m.)ISO International Standards Organization

(yyyy-mm-dd, hh.mm.ss) This is the default.EUR IBM European Standard (dd.mm.yyyy,

hh.mm.ss)JIS Japanese Industrial Standard Christian Era

(yyyy-mm-dd, hh:mm:ss)HMS Hour/Minute/Second (hh:mm:ss)

-timesep=<time separator>Where time separator is the character you wish to use to access your timeresult columns. Time separator can be any one of the following values:

Value Definition: A colon is used.. A period is used. This is the default., A comma is used.blank A space is used.

-decimalpt=<decimal point>Where decimal point is the decimal point you want to use. The decimalpoint is used for numeric constants in SQL statements. Decimal point canbe any one of the following values:

Value Definition. A period is used. This is the default., A comma is used.

-stmtCCSID=<CCSID>Where CCSID is the coded character set identifier for the SQL statementsthat are prepared into the package. The value of the job duringcustomization time is the default value.

-sorttbl=<library name/sort sequence table name>Where library name/sort sequence table name is the location and tablename of the sort sequence table you want to use. The sort sequence table isused for string comparisons in SQL statements. The library name and sortsequence table name each have limits of 10 characters. The default value istaken from the job during customization time.

-langID=<language identifier>Where language identifier is the language identifier you want to use.The default value for the language identifier is taken from the current jobduring customization time. The language identifier is used in conjunctionwith the sort sequence table.

For a more detailed information on any of the above fields, see DB2 for AS/400

SQL Programming, SC41-5611

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

142 AS/400 Developer Kit for Java

Page 151: AS400 Developer Kit for Java (Rzaha)

Printing the contents of DB2 SQLJ profiles (db2profp and profp)

The DB2 SQLJ Profile Printer, db2profp, prints the contents of a DB2customized profile in plain text. The Profile Printer, profp, prints the contents ofprofiles generated by the SQLJ translator in plain text.

To print the content of the profiles generated by the SQLJ translator in plain text,use the profp utility as follows:profp MyClass_SJProfile0.serWhere MyClass_SJProfile0.ser is the name of the profile you wish to print.

To print the content of the DB2 customized version of the profile in plain text, usethe db2profp utility as follows:db2profp MyClass_SJProfile0.serWhere MyClass_SJProfile0.ser is the name of the profile you wish to print.

Note: If you run db2profp on an uncustomized profile, it will simply tell you thatthe profile has not been customized. If you run profp on a customized profile, itwill display the contents of the profile without the customizations.

DB2 SQLJ Profile Printer usage and syntax:

db2profp [options] <SQLJ profile name>

Where SQLJ profile name is the name of the profile to be printed and options isthe list of options you want.

The options available for db2profp are:

-url=<JDBC URL>Where JDBC URL is the url you wish to connect to. See Connecting to anAS/400 database using the AS/400 Developer Kit for Java JDBC driver formore information.

-user=<user name>Where user name is the user name is your user profile.

-password=<password>Where password is the password of your user profile.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

The SQLJ profile auditor installer (profdb)

The SQLJ profile auditor installer (profdb) installs and uninstalls debuggingclass-auditors. The debugging class-auditors are installed into an existing set ofbinary profiles. Once the debugging class-auditors are installed, all RTStatementand RTResultSet calls made during application run time are logged. They can belogged to a file or standard output. The logs can then be inspected to verify thebehavior and trace errors of the application. Note that only the calls made to theunderlying RTStatement and RTResultSetcall interface at run time are audited.

Chapter 7. Accessing databases using AS/400 Developer Kit for Java DB2 SQLJ support 143

Page 152: AS400 Developer Kit for Java (Rzaha)

To install debugging class-auditors, enter the following at the Qshell commandprompt:

profdb MyClass_SJProfile0.ser

Where MyClass_SJProfile0.ser is the name of the profile that was generated bythe SQLJ Translator.

To uninstall debugging class-auditors, enter the following at the Qshellcommand prompt:

profdb -Cuninstall MyClass_SJProfile.ser

Where MyClass_SJProfile0.ser is the name of the profile that was generated bythe SQLJ Translator.

For more information on profdb command line options, see www.sqlj.org ,select the Implementation category and go to thesqlj.runtime.profile.util.AuditorInstaller class that is in the Runtime API

documentation.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Converting a serialized profile instance to Java class format using theSQLJ profile conversion tool (profconv)

The SQLJ profile conversion tool (profconv) converts a serialized profileinstance to Java class format. The profconv tool is needed because some browsersdo not support loading a serialized object from a resource file that is associatedwith an applet. Run the profconv utility to perform the conversion.

To run the profconv utility, type the following on the Qshell command line:profconv MyApp_SJProfile0.serWhere MyApp_SJProfile0.ser is the name of profile instance you wish to convert.

The profconvtool invokes sqlj -ser2class. See sqlj for command line options.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

144 AS/400 Developer Kit for Java

Page 153: AS400 Developer Kit for Java (Rzaha)

Chapter 8. Running your Java application on a host that doesnot have a graphical user interface

If you want to run your Java application on a host that does not have agraphical user interface (GUI), such as an AS/400 system, you can either theRemote Abstract Window Toolkit (AWT) or the Class Broker for Java (CBJ).

You use Remote AWT with install and administration interfaces of serverapplications. These interfaces typically have a minimum of complex graphics andhighly-interactive content. Remote AWT distributes AWT processing betweenAS/400 and a workstation. So, responsiveness of graphic-intensive andhighly-interactive operations are not as fast as AWT implementations on platformswith locally-attached graphic terminals. To use Remote AWT, see setting upRemote AWT.

You can use the CBJ for high performance GUI services. Since Remote AWT is notrecommended for complex graphics or highly-interactive operations, you can usethe CBJ instead, which was designed for these environments. To use CBJ, see

setting up CBJ.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Setting up the Remote Abstract Window Toolkit for Java on a remotedisplay

With the Remote Abstract Window Toolkit (AWT), you can run Java AWTgraphical programs without making any changes on AS/400 and display thegraphics remotely. To use Remote AWT you must have Transmission ControlProtocol/Internet Protocol (TCP/IP) set up, and Sun Microsystems, Inc., JavaDevelopment Kit (JDK) 1.1.x or Java 2 SDK (J2SDK), Standard Edition, version 1.2.installed on your AS/400 and remote display.

You can use any graphics-capable hardware, including IBM Network Station, as aremote display for Remote AWT if it meets these requirements:v Graphics-capable hardware that runs Windows 95, Windows NT 4.0, IBM

Operating System/2 (OS/2), Sun Solaris, or AIXv Configured hardware to access your AS/400 with TCP/IPv Java Development Kit 1.1.x (JDK 1.1.7 or later is recommended) or J2SDK,

version 1.2.

To set up Remote AWT, complete these tasks:1. Make the Remote AWT class files accessible to the remote display by copying

the files to the remote display or mapping the path to a network drive on theremote display.

2. Add RAWTGui.zip or RAWTGui.jar to the CLASSPATH of the remotedisplayFor JDK 1.1.x, add the RAWTGui.zip file to the CLASSPATH of theremote display by setting the CLASSPATH environment variable or by using

the -classpath parameter of the java command. For J2SDK, version 1.2,

© Copyright IBM Corp. 1998, 1999 145

Page 154: AS400 Developer Kit for Java (Rzaha)

the RAWTGui.jar file is automatically added to the CLASSPATH when using

-jarparameter of the java command.3. Start Remote AWT on the remote display.

For details and hints for using Remote AWT, see these topics:v Running a Java program using Remote Abstract Window Toolkit provides

instructions on how to run a Java program with AS/400 using multiple JDKsand Netscape.

v Printing with the Remote Abstract Window Toolkit explains how to print, whichis the same as standard Java AWT printing. It also shows you how to print toAS/400.

v Remote Abstract Window Toolkit properties shows you how to run a RemoteAWT application using the os400.class.path.rawt property.

v Remote Abstract Window Toolkit SecurityManager restrictions providesinformation about the restrictions that apply when you are running Javaapplications using Remote AWT under the control of a SecurityManager.

For more information about setting up TCP/IP, please see “How do I set up

TCP/IP” in the 0S/400 TCP/IP Configuration and Reference, SC41-5420 book.

See Example: Setting up the Remote Abstract Window Toolkit for Java on aWindows remote display, for an example of how to set up Remote AWT.

For more information about AWT, see the Abstract Window Toolkit by SunMicrosystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Setting up the Remote Abstract Window Toolkit forJava on a Windows remote display

This example shows one way that you can set up Remote AWT on a Windowsremote display. There are many other ways you can do this, depending on yourpreference. You can use a similar process on other remote display operatingsystems. The setup and starting process are automated with a Windows “.bat” fileor other programming facility that the remote display operating system provides.

To set up the Remote Abstract Window Toolkit (AWT) for Java on a Windowsremote display, do these tasks:v Make the Remote AWT class files accessible to the remote display.

Copy the Remote AWT class files to the remote display. Copy/QIBM/ProdData/Java400/jdk117/RAWTGui.zip to c:\rawt\RAWTGui.zip or

/QIBM/ProdData/Java400/jdk12/RAWTGui.jar to c:\rawt2\RAWTGui.jar

v Start the Remote AWT on the remote display by entering this on the commandline:java -classpath c:\jdk1.1.7\lib\classes.zip;c:\rawt\RAWTGui.zip

java com.ibm.rawt.server.RAWTPCServer

orjava -jar c:\rawt2\RAWTGui.jar

146 AS/400 Developer Kit for Java

Page 155: AS400 Developer Kit for Java (Rzaha)

For more information, see Setting up the Remote Abstract Window Toolkit for Javaon a remote display.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Making the Remote Abstract Window Toolkit for Java classfiles accessible to the remote display

To make the Remote Abstract Window Toolkit (AWT) class files accessible to theremote display, follow these steps for either Java Development Kit (JDK) 1.1. x orJava 2 SDK (J2SDK), Standard Edition, version 1.2.

If you are using JDK 1.1.x, you can either:v Copy the Remote AWT class files to the remote display.

The Remote AWT files are installed with the AS/400 Developer Kit for Java intwo ZIP files: /QIBM/ProdData/Java400/jdk1.1.x/RAWTApplHost.zip and/QIBM/ProdData/Java400/jdk1.1.x/RAWTGui.zip.The RAWTApplHost.zip file contains the Remote AWT classes for AS/400. TheRAWTGui.zip file contains the Remote AWT classes for your remote display.Copy RAWTGui.zip from /QIBM/ProdData/Java400/jdk1.1.x to your remotedisplay.

v Map the path, /QIBM/ProdData/Java400/jdk1.1.x/RAWTGui.zip, to a networkdrive on your remote display.

If you are using J2SDK, version 1.2, you can either:v Copy the Remote AWT class files to the remote display.

The Remote AWT files are installed with the AS/400 Developer Kit for Java intwo JAR files: /QIBM/ProdData/Java400/jdk1.2/RAWTAHost.jar and/QIBM/ProdData/Java400/jdk1.2/RAWTGui.jarThe RAWTAHost.jar file contains the Remote AWT classes for AS/400. TheRAWTGui.jar file contains the Remote AWT classes for your remote display.Copy RAWTGui.jar from /QIBM/ProdData/Java400/jdk1.2 to a network driveon your remote display.

v Map the path, /QIBM/ProdData/Java400/jdk1.2/RAWTGui.jar, to a network

drive on your remote display.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Adding RAWTGui.zip or RAWTGui.jar to the CLASSPATH ofthe remote display

Setting the CLASSPATH allows the Remote Abstract Window Toolkit (AWT)classes to be found by the Java virtual machine on the remote display. To add theRAWTGui.zip file to the CLASSPATH of the remote display, do either of thesesteps:v Set the CLASSPATH environment variable. See the Java Development Kit (JDK)

information for your remote display for details.Add the path where the RAWTGui.zip file is located to the CLASSPATHenvironment variable.

Chapter 8. Running your Java application on a host that does not have a graphical user interface 147

Page 156: AS400 Developer Kit for Java (Rzaha)

v Use the -classpath parameter of the java command.When you use the java command to start Remote AWT, you can use the-classpath parameter to specify a CLASSPATH. The CLASSPATH includes thepath where the RAWTGui.zip file is located.For example, in Windows, the CLASSPATH parameter may look like this:-classpath c:\jdk1.1.7\lib\classes.zip;c:\rawt\RAWTGui.zip

J2SDK, version 1.2 JAR support sets the CLASSPATH, so you do not needto explicitly set the CLASSPATH parameter. To set the classpath and startRemote AWT on a remote display enter this command:java -jar <PATH>RAWTGui.jar

where <PATH> is the fully qualified drive and directory where the RAWTGui.jar

file is located. For example, java -jar c:\rawt2\RAWTGui.jar.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Starting the Remote Abstract Window Toolkit for Java on aremote display

You need to start the server daemon on your remote display once and it staysactive until you end it. Java programs that exit on AS/400 do not end the server.

Note: The Welcome dialog stays active when you start the server daemon. Whenthe Welcome dialog display closes, the server daemon ends. You can minimize theWelcome dialog display while the server daemon is active and use the display toend the server daemon.

To start the Remote Abstract Window Toolkit (AWT) server daemon for JDK 1.1.x,enter this on the command line:java com.ibm.rawt.server.RAWTPCServer

To start the Remote AWT server daemon for J2SDK, version 1.2, enter this onthe command line:java -jar <PATH>RAWTGui.jar

where “PATH” is the fully qualified drive and directory where the RAWTGui.jar

file is located. For example, java -jar c:\rawt2\RAWTGui.jar .

The server daemon selects the first free port above 2000 when the Java applicationconnects using Remote AWT. The Java application uses this port until theapplication ends. Additional Java applications are connected to subsequent freeports above 2000. The available range of ports goes up to 9999.

For more information about setting up TCP/IP, see “How do I set up TCP/IP” in

the OS/400 TCP/IP Configuration and Reference, SC41-5420 book.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

148 AS/400 Developer Kit for Java

Page 157: AS400 Developer Kit for Java (Rzaha)

Running a Java program using Remote Abstract WindowToolkit

To run Java using the Remote Abstract Window Toolkit (AWT):1. Start Remote AWT on the remote display.2. Start the Java program on AS/400.

a. Enter the Run Java (RUNJVA) command on the command line.Note: You must define the Java classpath to the Java program.

b. Press F4 (Prompt).c. Enter the Java program class name on the class parameter line.d. Press F10 (Additional parameters).e. Press the Page Down key.f. Enter RmtAwtServer on the next property name parameter line.g. Enter the Transmission Control Protocol/Internet Protocol (TCP/IP) address

(for example, 1.1.11.11) of the remote display on the next property valueparameter line.

h. Enter os400.class.path.rawt on the property name parameter line.i. Enter 1 on the property value parameter line.

j. Enter +for more properties.

k. Enter java.version on the property name parameter line.

l. Enter 1.2 on the property value parameter line.The command line should look like this:java class (classname) prop((RmtAwtServer '1.1.11.11') (os400.class.path.rawt 1)(java versio

m. Press Enter.

You can also run a Java program using Remote AWT with Netscape.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Running a Java program using Remote Abstract Window Toolkitwith NetscapeWhen running Java applications with Netscape, you can run them one of twoways.

One option is to start the Remote Abstract Window Toolkit (AWT) server withinthe Netscape Java virtual machine by opening an HTML file that containscom.ibm.rawt.server.StartRAWT.class. For example, see the RAWT.html file below.Once started, you can then start a Java application on your AS/400.

Or, you can start the Remote AWT server within the Netscape Java virtual machineby opening an HTML file that contains com.ibm.rawt.server.StartRAWT400.classand the AS/400 Toolbox for Java classes. For example, see the RAWT400.html fileshown below. Once started, you can sign on to your AS/400 where the Javaapplication resides and start the application.

Running within the Remote AWT server within the Netscape Java virtualmachine:

Chapter 8. Running your Java application on a host that does not have a graphical user interface 149

Page 158: AS400 Developer Kit for Java (Rzaha)

To run the Remote AWT server within the Netscape Java virtual machine followthese steps:1. Edit this example .html file for your specific installation information for

RAWTGui.zip. This file, RAWT.html, starts Remote AWT within the NetscapeJava virtual machine.<HTML><BODY TEXT=“#000000” LINK=“#0000EE” VLINK=“#551A8B” ALINK=“#FF0000”><CENTER><APPLET CODE=“com.ibm.rawt.server.StartRAWT.class”codebase=“file://C|remote_awt\jdk1.1.7\lib\RAWTGui.zip”WIDTH=600 HEIGHT=50></APPLET></CENTER></BODY></HTML>

2. Browse the RAWT.html page with Netscape 4.05 or higher. After granting all ofthe requested privileges, Netscape starts the Remote AWT server and runs itwithin its Java virtual machine.

3. Start a Java application on your AS/400 using Remote AWT.4. After you exit the application, click on the Reload button while pushing the

Shift key to start the Remote AWT server again.

Running the Remote AWT server within the Netscape Java virtual machine andsigning on to your AS/400:

To run the Remote AWT server within the Netscape Java virtual machine and signon to your AS/400 follow these steps:1. Edit this example .html file for your specific installation information for

jt400.zip and RAWTGui.zip. This file, RAWT400.html, starts Remote AWT anduses the AS/400 Toolbox for Java to sign on to AS/400.<HTML><BODY TEXT=“#000000” LINK=“#0000EE” VLINK=“#551A8B” ALINK=“#FF0000”><CENTER><APPLET ARCHIVE=“file://C\jt400\lib\jt400.zip”code=“com.ibm.rawt.server.StartRAWT400.class”codebase=“file://C|remote_awt\jdk1.1.1\lib\RAWTGui.zip”WIDTH=600 HEIGHT=50></APPLET></CENTER></BODY></HTML>

2. Browse this RAWT400.html page with Netscape 4.05. After granting all of therequested privileges, Netscape starts the Remote AWT applet that displays apanel where you can do any of these options:v Sign on to your AS/400 with Remote AWT using AS/400 Toolbox for Java to

access AS/400.v Enter the Java application name and arguments with Remote AWT

properties.v Push the Start Application button to start the specified Java application with

Remote AWT.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

150 AS/400 Developer Kit for Java

Page 159: AS400 Developer Kit for Java (Rzaha)

Printing with the Remote Abstract Window ToolkitPrinting with the Remote Abstract Window Toolkit (AWT) is the same as standardJava AWT printing. The Remote AWT remote display processes print output anddirects the output to any printer that is known to the remote display operatingsystem. This can be a printer that is directly attached to the remote display, or anetwork printer that is known to the remote display operating system.

You can select to print on the remote display or to an AS/400. A new print dialogdisplays when an application issues a print request. The print request allows youto select either a Remote Display printer or OS/400 printer. If you select OS/400printer, a sign on dialog display appears. Once you have signed on, the PrintDialog display appears. You can specify the OS/400 print queue, print file, file andbanner page title. You can also select paper size, orientation, and number of copies.

To use remote printing, you must install the AS/400 Toolbox for Java (5763-JC1)and add this to your classpath on AS/400:QIBM/ProdData/HTTP/Public/jt400/lib/jt400.zip

You can update the classpath by adding the classpath environment variable or byusing the classpath parameter.

Note:If this message appears while printing to AS/400, either the AS/400 Toolboxfor Java is not installed or the AS/400 Toolbox for Java classes are not in theclasspath.Failed to load class file: com/ibm/as400/access/PrintObjectList.classException occurred during event dispatching:java.lang.NoClassDefFoundError: com/ibm/as400/access/PrintObjectList

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Remote Abstract Window Toolkit propertiesWhen running a Java Remote AWT application on the AS/400 system, the

os400.class.path.rawt property must be used with a value of 1. There are anumber of default properties that are required when you use Remote AWT. Thesedefault properties along with the proper version of Remote AWT and theCLASSPATH are set when you use the os400.class.path.rawt property. The versionof Remote AWT is set according to the JDK version, which is either the defaultversion, if not specified, or the version that you specify with the java.versionproperty.

Here are the default properties that are required for Remote AWT.

For JDK 1.1.x:v awt.toolkit=com.ibm.rawt.CToolkit

For J2SDK, version 1.2:v awt.toolkit=com.ibm.rawt2.ahost.java.awt.AHToolkitv java.awt.graphicsenv=com.ibm.rawt2.ahost.java.awt.AHGraphicsEnvironment

v java.awt.printerjob=com.ibm.rawt2.ahost.java.awt.print.AHPrinterjob

Remote AWT properties for remote display:

Chapter 8. Running your Java application on a host that does not have a graphical user interface 151

Page 160: AS400 Developer Kit for Java (Rzaha)

If the server daemon or Java application abnormally ends with this message, checkthe Java version on your remote display.The JDK version in the Application-host/User-station is incompatible with the Remote-AWT version...

To check the version level, enter java -version on the command line. You can usethis new property on a remote display if you have a problem with the JDKversion. This property is not applicable for the AS/400. If the version is not at level1.1.x, then you must install the proper level. If it is at level 1.1.x, you can run theRemote AWT server and or the Java application with this property that indicatesthe Java version: -DJdkVersion=1.1.x.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Remote Abstract Window Toolkit SecurityManager restrictionsJava applications that use the Remote Abstract Window Toolkit (AWT) runningunder the control of a SecurityManager have some restrictions. Remote AWTclasses start methods, which call SecurityManager check methods in cases wherethe SecurityManager is set. In these cases, a Java application that runs with RemoteAWT may encounter a SecurityException. The check methods that are called as aresult of running with Remote AWT are:v SecurityManager.checkAccess(..)v SecurityManager.checkMemberAccess(..)v SecurityManager.checkExit(..)v SecurityManager.checkRead(String file)v SecurityManager.checkConnect(...)v SecurityManager.checkListen(...)v SecurityManager.checkAccept(...)v SecurityManager.checkPropertiesAccess(..)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Setting up the Class Broker for Java on a remote display

With the Class Broker for Java (CBJ) you can run Class Broker forJava-enabled Java graphical programs on AS/400 and display the graphicsremotely.

You can either install CBJ yourself or have the system administrator install it foryou. If the system administrator installs the product, all programmers can sharethe same Java code.

You can either install CBJ on Windows 95/98/NT, UNIX, or AS/400. In mostcircumstances, you must install CBJ on your client machine and server machine.

Note:If your client machine is running a client applet that is accessed through aweb server on the server machine, then you do not need to install CBJ on the clientmachine.

To install CBJ on AS/400, see Installing Class Broker for Java on AS/400.

152 AS/400 Developer Kit for Java

Page 161: AS400 Developer Kit for Java (Rzaha)

To install CBJ on your workstation, see Installing Class Broker for Java on

Windows 95/98/NT or UNIX .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Installing Class Broker for Java on AS/400

To install Class Broker for Java (CBJ) on AS/400, follow these steps:1. Make sure that the AS/400 Developer Kit for Java is properly installed. See

Installing the AS/400 Developer Kit for Java to test installation.2. Select a directory in the integrated file system to store the CBJ package named

cbj_1.1.jar. For example, /usr/local.3. Start the Qshell Interpreter by entering the QSH command and go to the

directory that you selected in the integrated file system. For example,/usr/local. When you install the AS/400 Developer Kit for Java, thecbj_1.1.jar package is installed in QIBM/ProdData/Java400/ext.

4. Enter this command in Qshell:jar xvf “PATH”cbj_1.1.jar

“PATH” is the directory path where the cbj_1.1.jar package is located. Forexample, QIBM/ProdData/Java400/ext.

The CBJ files are extracted into the subdirectory, named /usr/local/JCBroker.See Package content of cbj_.1.1.jar for more information.

5. Create an Java program on AS/400 for jcb.jar, by entering this command:CRTJVAPGM CLSF('/usr/local/JCBroker/lib/jcb.jar')

6. If you want to use the CBJ classes (not in debug mode), you have to addJCBroker\lib and JCBroker\lib\jcb.jar to the classpath option in the Javacommand line. We do not recommended that you add JCBroker\lib andJCBroker\lib\jcb.jar to the CLASSPATH environment variable, because itmight conflict with class loading when you run applets that set applet_jcb.jarin the ARCHIVE tag.

7. If you want to run CBJ in debug mode, replace jcb.jar with jcbd.jar in theclasspath or override the classpath value on the Java command line. You canalso use this command:

CRTJVAPGM CLSF('/usr/local/JCBroker/lib/jcbd.jar')

8. For more information on CBJ APIs, running demos, editing properties,designing and writing CBJ applications, and other topics, refer to the

JCBroker/index.html file in the cpj_1.1.jar package.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Installing Class Broker for Java on Windows or UNIX

To install Class Broker for Java (CBJ) on Windows, follow these steps:1. Make sure that either JDK/JRE1.1 or JDK/JRE1.2 is properly installed.2. Select a directory in to store the CBJ package, named cbj_1.1.jar. For example,

C:\.

Chapter 8. Running your Java application on a host that does not have a graphical user interface 153

Page 162: AS400 Developer Kit for Java (Rzaha)

3. Change to your directory (C:\) and enter this command:C:\ > jar xvf cbj_1.1.jar

The CBJ files are extracted and are copied into the directory. See Packagecontent of cbj_.1.1.jar for more information.

4. If you want to use the CBJ classes (not in debug mode), add C:\JCBroker\liband C:\JCBroker\lib\jcb.jar to the classpath option on the Java commandline. Note:We do not recommended that you add it to the system CLASSPATHenvironment variable, because it might conflict with class loading whenrunning applets that set applet_jcb.jar in the ARCHIVE tag.

5. To run CBJ in debug mode, replace jcb.jar with jcbd.jar in the classpath.To install CBJ on UNIX follow the same step for Windows, except for thefollowing system dependent changes:v Replace the Windows file separator “\” with the UNIX file separator “/”.v Replace the Windows classpath separator “;” with the UNIX classpath

separator “:”.v Replace the Windows system environment variables “%XXX%” with the

UNIX system environment variables “$XXX”.6. For more information on CBJ APIs, running demos, editing properties,

designing and writing CBJ applications, and other topics, refer to the

JCBroker/index.html file in the cpj_1.1.jar package.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Package content of cbj_1.1.jar

Here is the CBJ package (cbj_1.1.jar). The bold items denote main directoriesof subdirectories. The non-bold items denote files.

JCBroker||____ demo| |______ bin| |______ binx| |______ html| |______ images| |______ lib| | |___ discovery| | |___ distreetable| | |___ ftp| | |___ hellojcb| | |___ jcbcalc| | |___ jcbchat| | |___ lhellojcb| | |___ remotethread| | |___ stylepad| | |___ websmdemo| |______ log| |______ src|____ doc| |_______ api| |_______ guide| |_______ FAQ.html| |_______ quickStart.html|____ lib| |________ com| | |____ ibm

154 AS/400 Developer Kit for Java

Page 163: AS400 Developer Kit for Java (Rzaha)

| | |______ jcb| | |____ resources| | |_______ JCB.properties| |________ jcb.jar| |________ jcbd.jar| |________ applet_jcb.jar| |________ applet_jcbd.jar| |________ Editor.class|____ src| |________ com (for designated users only)| | |_____ ibm| | |_____ jcb| | | |___ proxies| | | |___ resources| | | |___ u t i l| | |_____ jcbimpl| | |___ transport| |________ version.log|_______ index.html (open it)

The next level of directories under the JCBroker directory consists of the this data:

demo

This directory contains these subdirectories: bin, binx, html, images, lib, log andsrc. These directories contain the Windows executable, UNIX executable, HTMLpages, GIF files, class files, and source code (for some examples) of several demoapplications. You can run these demo examples by following the demoinstructions. The log directory is a placeholder for debug log files.

doc

This directory contains these two subdirectories: api and guide. The CBJ API guideand a user guide about CBJ are stored here. The API documentation was generatedwith the J2SDK, version 1.2, javadoc tool. To browse the API document or the userguide, open the index.html file in the corresponding directory. The user guide is anintroductory level document, whereas the QuickStart guide is a fast track entrydocument.

This directory also contains a FAQ.html file and the quickStart.html gile thatexplains how to install and use CBJ, and shows you how to run the demoexamples.

lib

This directory contains the CBJ classes and resources that are needed for you todevelop, run, and deploy new CBJ based applications. The classes are packaged inthe jcb.jar file, For debug mode, the classes are packaged in the jcbd.jar file. Theclasses that are included in the ARCHIVE tag of an applet are packaged in theapplet_jcb.jar file. For debug mode, the classes are packaged in the applet_ jcbd.jarfile. The JCB properties file, named JCB.properties, is in thecom/ibm/jcb/resources subdirectory. It is read by the CBJ runtime when started.You can change this file to reflect your preferences. The properties are explained inthe installation and setting up section. The properties that only to applets arecontained in the applet_JCB.properties file, which is part of the applet_ jcb.jar andapplet_ jcbd.jar. You can also change this file to reflect your preferences whenrunning in applet mode. To change this file, run the Editor Java application thatresides in this directory.

Chapter 8. Running your Java application on a host that does not have a graphical user interface 155

Page 164: AS400 Developer Kit for Java (Rzaha)

src

This directory contains the CBJ source code and the internal version log file, calledversion.log. The directory is empty except for selected packages.

index.html

This is the starting page that references you to the rest of the documentation.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

156 AS/400 Developer Kit for Java

Page 165: AS400 Developer Kit for Java (Rzaha)

Chapter 9. Java security

The majority of the Java programs that run on AS/400 are applications, notapplets, so the “sandbox” security model does not restrict them. From a securitypoint of view, Java applications are subject to the same security restrictions as anyother program on AS/400. To run a Java program on AS/400, you must haveauthority to the class file in the integrated file system. Once the program starts, itruns under the user’s authority.

You can use adopted authority to access objects with the authority of the user thatis running the program, and the program owner’s authority. Adopted authoritytemporarily gives a user authority to objects that they would not have originallyhad authority to access. See the Create Java Program (CRTJVAPGM) commandinformation for details on the two new adopted authority parameters, which areUSRPRF and USEADPAUT.

The bytecode loader and verifier, within the Java virtual machine, also provide ameasure of Java security using the Java security model. Just as with applets, thebytecode loader and verifier check that the bytecodes are valid and data types areused properly. They also check that registers and memory are accessed correctly,and that the stack does not overflow or underflow. These checks ensure that theJava virtual machine can safely run the class without compromising the integrity ofthe system.

The Secure sockets layer (SSL) Java Standard Extension to JDK 1.1 is another itemof security supported by AS/400 Developer Kit for Java. SSL provides a means ofauthenticating a server and a client to provide privacy and data integrity. All SSLcommunication begins with a “handshake” between the server and the client.During a handshake, SSL negotiates the cipher suite that the client and server useto communicate with each other. This cipher suite is a combination of the varioussecurity features available through SSL. The combination of a number of differentsecurity features provides increased security for client and server communications.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java security modelYou can download Java applets from any system; thus security mechanisms existwithin the Java virtual machine to protect against malicious applets. The Javaruntime system verifies the bytecodes as the Java virtual machine loads them. Thisensures that they are valid bytecodes and that the code does not violate any of therestrictions that the Java virtual machine places on Java applets. Java applets arerestricted in what operations they can perform, how they access memory, and howthey use the Java virtual machine. The restrictions are in place to prevent a Javaapplet from gaining access to underlying operating system or data on the system.This is the “sandbox” security model, because the Java applet can only “play” inits own sandbox.

The “sandbox” security model is a combination of the class loader, class fileverifier, and the java.lang.SecurityManager class.

© Copyright IBM Corp. 1998, 1999 157

Page 166: AS400 Developer Kit for Java (Rzaha)

For more information about security, see the Security by Sun Microsystems, Inc.documentation and Securing your Java applications with SSL.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Making a Java application secure with secure sockets layerYou can use the secure sockets layer (SSL) to make your Java application moresecure. SSL does the following to improve the security of your applicaiton:v Protects communication data through encryption.v Authenticates remote user IDs.v Authenticates remote system names.

Note:SSL uses a digital certificate to encrypt the socket communication of yourJava application. Digital certificates are an Internet standard for identifying securesystems, users, and applications. You can control digital certificates using IBMDigital Certificate Manager. For more information, see IBM Digital CertificateManager.

To make your Java application more secure by using SSL:v Prepare AS/400 to support SSL.v Design your Java application to use SSL by:

– Modifying your Java socket code to use socket factories if you do not usesocket factories already.

– Modifying your Java code to use SSL.v Use a digital certificate to make your Java application more secure by:

1. Choosing a type of digital certificate to use.2. Using the digital certificate when you run your application.

You can also register your Java application as a secure application by using theQsyRegisterAppForCertUse API. For more information, see theQsyRegisterAppForCertUse section in the System API Reference: Security APIs

book .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Preparing AS/400 for secure sockets layer supportTo prepare your system to use secure sockets layer (SSL), you need to install theDigital Certificate Manager LP:v 5769-SS1 OS/400 - Digital Certificate Manager

You also need to install one of these Cryptographic Access Provider LPs:v 5769-AC1 Cryptographic Access Provider 40-Bitv 5769-AC2 Cryptographic Access Provider 56-Bitv 5769-AC3 Cryptographic Access Provider 128-Bit

You also need to make sure you can access or create a digital certificate on yoursystem. For more information on AS/400 digital certificate management and theInternet, see Getting started with IBM Digital Certificate Manager.

158 AS/400 Developer Kit for Java

Page 167: AS400 Developer Kit for Java (Rzaha)

For more information on AS/400 security in general, see Firewall: getting started.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Cryptographic Access ProvidersThe Cryptographic Access Providers offer many cipher suites for your system touse. A cipher suite is a combination of different security features. This list showswhich cipher suite each Cryptographic Access Provider offers:

5769-AC1 Cryptographic Access Provider 40-BitSSL_RSA_WITH_NULL_MD5

SSL_RSA_WITH_NULL_SHA

SSL_RSA_EXPORT_WITH_RC4_40_MD5

SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5

5769-AC2 Cryptographic Access Provider 56-BitSSL_RSA_WITH_NULL_MD5

SSL_RSA_WITH_NULL_SHA

SSL_RSA_WITH_DES_CBC_SHA

SSL_RSA_WITH_DES_CBC_MD5

SSL_RSA_EXPORT_WITH_RC4_40_MD5

SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5

5769-AC3 Cryptographic Access Provider 128-BitSSL_RSA_WITH_NULL_MD5

SSL_RSA_WITH_NULL_SHA

SSL_RSA_EXPORT_WITH_RC4_40_MD5

SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5

SSL_RSA_WITH_RC4_128_SHA

SSL_RSA_WITH_DES_CBC_SHA

SSL_RSA_WITH_3DES_EDE_CBC_SHA

SSL_RSA_WITH_RC4_128_MD5

SSL_RSA_WITH_RC2_CBC_128_MD5

SSL_RSA_WITH_DES_CBC_MD5

SSL_RSA_WITH_3DES_EDE_CBC_MD5

You may be limited on the Cryptographic Access Provider that you can choosefrom, depending on which country you are in. Once you load a CryptographicAccess Provider, you can use any of the cipher suites that that Access Provideroffers.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 9. Java security 159

Page 168: AS400 Developer Kit for Java (Rzaha)

Choosing a digital certificate to useYou should consider several factors when deciding which digital certificate to use.You can use your system’s default certificate or you can specify another certificateto use.

You want to use your system’s default certificate if:v You do not have any specific security requirements for your Java application.v You do not know what kind of security you need for your Java application.v Your system’s default certificate meets the security requirements for your Java

application.

Note: If you decide that you want to use your system’s default certificate, checkwith your system administrator to make sure that a default system certificate hasbeen created. For more information on digital certificate management, see Gettingstarted with IBM Digital Certificate Manager.

If you do not want to use your system’s default certificate, you need to choose adifferent certificate to use. You can choose from two types of certificates:v User certificate that identifies the user of the application.v System certificate that identifies the system on which the application is running.

These questions can help you decide whether to use a user certificate or a systemcertificate:v Does your Java application run as a client application or a server application?

– If your application runs as a client application, you probably want to use auser certificate.

– If your application runs as a server application, you probably want to use asystem certificate.

v Do you want the certificate to identify the user who is working with theapplication or the system on which the application is running?– If you want the certificate to identify the user who is working with the

application, then you want to use a user certificate.– If you want the certificate to identify on which system the application is

running, then you want to use a system certificate.

Once you know what kind of certificate you need, you can choose from any of thedigital certificates in any of the certificate containers that you are able to access.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Using the digital certificate when you run your Javaapplication

To use secure sockets layer (SSL), you need to run your Java application using adigital certificate.

To specify which digital certificate to use, use the following properties:v -os400.certificateContainerv -os400.certificateLabel

For example, if you want run the Java application MyClass.class using the digitalcertificate MYCERTIFICATE, and MYCERTIFICATE was in the digital certificatecontainer YOURDCC, then the java command would look like this:

160 AS/400 Developer Kit for Java

Page 169: AS400 Developer Kit for Java (Rzaha)

java -os400.certificateContainer=YOURDCC-os400.certificateLabel=MYCERTIFICATE MyClass

If you have not already decided which digital certificate to use, see deciding whichdigital certificate to use. You may also decide to use your system’s defaultcertificate, which is stored in the system’s default certificate container.

To use your system’s default digital certificate, you do not need to specify acertificate or a certificate container anywhere. Your Java application uses yoursystem’s default digital certificate automatically.

Continue reading for more information on the following topics:v Digital certificates and the -os400.certificateLabel property (page “Digital

certificates and the -os400.certificateLabel property”)v Digital certificate containers and the -os400.certificateContainer property (page

“Digital certificate containers and the -os400.certificateContainer property”)

For more information on AS/400 digital certificate management and the Internet,see Getting started with IBM Digital Certificate Manager.

Digital certificates and the -os400.certificateLabel propertyDigital certificates are an Internet standard for identifying secure systems, users,and applications. Digital certificates are stored in digital certificate containers. Ifyou want to use a digital certificate container’s default certificate, you do not needto specify a certificate label. If you want to use a specific digital certificate, youmust specify that certificate’s label in the java command using this property:-os400.certificateLabel=

For example, if the name of the certificate you want to use is MYCERTIFICATE,then the java command you enter would look like this:java -os400.certificateLabel=MYCERTIFICATE MyClass

In this example, the Java application MyClass would use the certificateMYCERTIFICATE. MYCERTIFICATE would need to be in the system’s defaultcertificate container in order to be used by MyClass.

Digital certificate containers and the -os400.certificateContainerpropertyDigital certificate containers store digital certificates. If you want to use the AS/400system default certificate container, you do not need to specify a certificatecontainer. To use a specific digital certificate container, you need to specify thatdigital certificate container in the java command using this property:-os400.certificateContainer=

For example, if the name of the certificate container that contains the digitalcertificate you want to use is named MYDCC, then the java command you enterwould look like this:java -os400.certificateContainer=MYDCC MyClass

In this example, the Java application, named MyClass.class, would run on thesystem by using the default digital certificate that is in the digital certificatecontainer named MYDCC. Any sockets that you create in the application use thedefault certificate that is in MYDCC to identify themselves and make all of theircommunications secure.

Chapter 9. Java security 161

Page 170: AS400 Developer Kit for Java (Rzaha)

If you wanted to use the digital certificate MYCERTIFICATE in the digitalcertificate container, then the java command that you would enter would look likethis:java -os400.certificateContainer=MYDCC-os400.certificateLabel=MYCERTIFICATE MyClass

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Modifying your Java code to use socket factoriesTo use secure sockets layer (SSL) with your existing code, you must first modifyyour code to use socket factories.

To modify your code to use socket factories:1. Add this line to your program to import the SocketFactory class:

import javax.net.*;

2. Add a line that declares an instance of a SocketFactory object. For example:SocketFactory socketFactory

3. Initialize the SocketFactory instance by setting it equal to the methodSocketFactory.getDefault(). For example:socketFactory = SocketFactory.getDefault();

v The whole declaration of the SocketFactory should look like this:SocketFactory socketFactory =SocketFactory.getDefault();

4. Initialize your existing sockets. Call the SocketFactory methodcreateSocket(host,port) on your socket factory for each socket you declare.Your socket declarations should now look like this:Socket s = socketFactory.createSocket(host,port);

s is the socket that is being created.socketFactory is the SocketFactory that was created in step 2.host is a string variable that represents the name of a host server.port is an integer variable that represents the port number of the socketconnection.

When you have completed all of these steps, your code uses socket factories. Youdo not need to make any other changes to your code. All of the methods that youcall and all the syntax with your sockets still work.

See Examples: Modifying your Java code to use server socket factories for anexample of a client program being converted to use socket factories.

See Example: Modifying your Java code to use client socket factories for anexample of a client program being converted to use socket factories.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Examples: Modifying your Java code to use server socketfactoriesThese examples show you how to modify a simple socket class, namedsimpleSocketServer, so that it uses socket factories to create all of the sockets. Thefirst example shows you the simpleSocketServer class without socket factories. The

162 AS/400 Developer Kit for Java

Page 171: AS400 Developer Kit for Java (Rzaha)

second example shows you the simpleSocketServer class with socket factories. Inthe second example, simpleSocketServer is renamed to factorySocketServer.

Example 1: Socket server program without socket factories/* File simpleSocketServer.java*/import java.net.*;import java.io.*;public class simpleSocketServer {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java simpleSocketServer serverPort”);System.out.println(“Defaulting to port 3000 since serverPort not specified.”);

}else

serverPort = new Integer(args[0]).intValue();System.out.println(“Establishing server socket at port ” + serverPort);ServerSocket serverSocket =

new ServerSocket(serverPort);// a real server would handle more than just one client like this...Socket s = serverSocket.accept();BufferedInputStream is = new BufferedInputStream(s.getInputStream());BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());// This server just echoes back what you send it...byte buffer[] = new byte[4096];int bytesRead;// read until “eof” returnedwhile ((bytesRead = is.read(buffer)) > 0) {

os.write(buffer, 0, bytesRead); // write it backos.flush(); // flush the output buffer

}s.close();serverSocket.close();

} // end main()} // end class definition

Example 2: Simple socket server program with socket factories/* File factorySocketServer.java */// need to import javax.net to pick up the ServerSocketFactory classimport javax.net.*;import java.net.*;import java.io.*;public class factorySocketServer {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java simpleSocketServer serverPort”);System.out.println(“Defaulting to port 3000 since serverPort not specified.”);

}else

serverPort = new Integer(args[0]).intValue();System.out.println(“Establishing server socket at port ” + serverPort);// Change the original simpleSocketServer to use a// ServerSocketFactory to create server sockets.ServerSocketFactory serverSocketFactory =

ServerSocketFactory.getDefault();// Now have the factory create the server socket. This is the last// change from the original program.ServerSocket serverSocket =

serverSocketFactory.createServerSocket(serverPort);// a real server would handle more than just one client like this...Socket s = serverSocket.accept();BufferedInputStream is = new BufferedInputStream(s.getInputStream());BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());// This server just echoes back what you send it...

Chapter 9. Java security 163

Page 172: AS400 Developer Kit for Java (Rzaha)

byte buffer[] = new byte[4096];int bytesRead;while ((bytesRead = is.read(buffer)) > 0) {

os.write(buffer, 0, bytesRead);os.flush();

}s.close();serverSocket.close();

}}

For background information, see modifying your code to use socket factories.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Examples: Modifying your Java code to use client socketfactoriesThese examples show you how to modify a simple socket class, namedsimpleSocketClient, so that it uses socket factories to create all of the sockets. Thefirst example shows you the simpleSocketClient class without socket factories. Thesecond example shows you the simpleSocketClient class with socket factories. Inthe second example, simpleSocketClient is renamed to factorySocketClient.

Example 1: Socket client program without socket factories/* Simple Socket Client Program */import java.net.*;import java.io.*;public class simpleSocketClient {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java simpleSocketClient serverHost serverPort”);System.out.println(“serverPort defaults to 3000 if not specified.”);return;

}if (args.length == 2)

serverPort = new Integer(args[1]).intValue();System.out.println(“Connecting to host ” + args[0] + “ at port ” +

serverPort);// Create the socket and connect to the server.Socket s = new Socket(args[0], serverPort);...// The rest of the program continues on from here.

Example 2: Simple socket client program with socket factories/* Simple Socket Factory Client Program */// Notice that javax.net.* is imported to pick up the SocketFactory class.import javax.net.*;import java.net.*;import java.io.*;public class factorySocketClient {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java factorySocketClient serverHost serverPort”);System.out.println(“serverPort defaults to 3000 if not specified.”);return;

}if (args.length == 2)

serverPort = new Integer(args[1]).intValue();

164 AS/400 Developer Kit for Java

Page 173: AS400 Developer Kit for Java (Rzaha)

System.out.println(“Connecting to host ” + args[0] + “ at port ” +serverPort);

// Change the original simpleSocketClient program to create a// SocketFactory and then use the socket factory to create sockets.SocketFactory socketFactory = SocketFactory.getDefault();// Now the factory creates the socket. This is the last change// to the original simpleSocketClient program.Socket s = socketFactory.createSocket(args[0], serverPort);...// The rest of the program continues on from here.

For background information, see modifying your code to use socket factories.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Modifying your Java code to use secure sockets layerIf your code already uses socket factories to create its sockets, then you can addsecure socket layer (SSL) support to your program. If your code does not alreadyuse socket factories, see modifying your code to use socket factories.

To modify your code to use SSL:v Import javax.net.ssl.* to add SSL support:

import javax.net.ssl.*;

v Declare a SocketFactory by using SSLSocketFactory to initialize it:SocketFactory newSF = SSLSocketFactory.getDefault();

v Use your new SocketFactory to initialize your sockets the same way that youused your old SocketFactory:Socket s = newSF.createSocket(args[0], serverPort);

Your code now uses SSL support. You do not need to make any other changes toyour code.

See Examples: Modifying your Java client to use secure sockets layer andExamples: Modifying your Java server to use secure sockets layer for examplecode.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Examples: Modifying your Java server to use secure socketslayerThese examples show you how to modify one class, named factorySocketServer, touse secure sockets layer (SSL).

The first example shows you the factorySocketServer class not using SSL. Thesecond example shows you the same class, renamed factorySSLSocketServer, usingSSL.

Example 1: Simple factorySocketServer class without SSL support/* File factorySocketServer.java */// need to import javax.net to pick up the ServerSocketFactory classimport javax.net.*;import java.net.*;

Chapter 9. Java security 165

Page 174: AS400 Developer Kit for Java (Rzaha)

import java.io.*;public class factorySocketServer {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java simpleSocketServer serverPort”);System.out.println(“Defaulting to port 3000 since serverPort not specified.”);

}else

serverPort = new Integer(args[0]).intValue();System.out.println(“Establishing server socket at port ” + serverPort);// Change the original simpleSocketServer to use a// ServerSocketFactory to create server sockets.ServerSocketFactory serverSocketFactory =

ServerSocketFactory.getDefault();// Now have the factory create the server socket. This is the last// change from the original program.ServerSocket serverSocket =

serverSocketFactory.createServerSocket(serverPort);// a real server would handle more than just one client like this...Socket s = serverSocket.accept();BufferedInputStream is = new BufferedInputStream(s.getInputStream());BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());// This server just echoes back what you send it.byte buffer[] = new byte[4096];int bytesRead;while ((bytesRead = is.read(buffer)) > 0) {

os.write(buffer, 0, bytesRead);os.flush();

}s.close();serverSocket.close();

}}

Example 2: Simple factorySocketServer class with SSL support/* File factorySocketServer.java */// need to import javax.net to pick up the ServerSocketFactory classimport javax.net.*;import java.net.*;import java.io.*;public class factorySocketServer {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java simpleSocketServer serverPort”);System.out.println(“Defaulting to port 3000 since serverPort not specified.”);

}else

serverPort = new Integer(args[0]).intValue();System.out.println(“Establishing server socket at port ” + serverPort);// Change the original simpleSocketServer to use a// ServerSocketFactory to create server sockets.ServerSocketFactory serverSocketFactory =

ServerSocketFactory.getDefault();// Now have the factory create the server socket. This is the last// change from the original program.ServerSocket serverSocket =

serverSocketFactory.createServerSocket(serverPort);// a real server would handle more than just one client like this...Socket s = serverSocket.accept();BufferedInputStream is = new BufferedInputStream(s.getInputStream());BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());// This server just echoes back what you send it.byte buffer[] = new byte[4096];int bytesRead;

166 AS/400 Developer Kit for Java

Page 175: AS400 Developer Kit for Java (Rzaha)

while ((bytesRead = is.read(buffer)) > 0) {os.write(buffer, 0, bytesRead);os.flush();

}s.close();serverSocket.close();

}}

For background information, see modifying your Java code to use secure socketslayer.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Examples: Modifying your Java client to use secure socketslayerThese examples show you how to modify one class, named factorySocketClient, touse secure sockets layer (SSL).

The first example shows you the factorySocketClient class not using SSL. Thesecond example shows you the same class, renamed factorySSLSocketClient, usingSSL.

Example 1: Simple factorySocketClient class without SSL support/* Simple Socket Factory Client Program */import javax.net.*;import java.net.*;import java.io.*;public class factorySocketClient {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java factorySocketClient serverHost serverPort”);System.out.println(“serverPort defaults to 3000 if not specified.”);return;

}if (args.length == 2)

serverPort = new Integer(args[1]).intValue();System.out.println(“Connecting to host ” + args[0] + “ at port ” +

serverPort);SocketFactory socketFactory = SocketFactory.getDefault();Socket s = socketFactory.createSocket(args[0], serverPort);...// The rest of the program continues on from here.

Example 2: Simple factorySocketClient class with SSL support// Notice that we import javax.net.ssl.* to pick up SSL supportimport javax.net.ssl.*;import javax.net.*;import java.net.*;import java.io.*;public class factorySSLSocketClient {

public static void main (String args[]) throws IOException {int serverPort = 3000;if (args.length < 1) {

System.out.println(“java factorySSLSocketClient serverHost serverPort”);System.out.println(“serverPort defaults to 3000 if not specified.”);return;

}

Chapter 9. Java security 167

Page 176: AS400 Developer Kit for Java (Rzaha)

if (args.length == 2)serverPort = new Integer(args[1]).intValue();

System.out.println(“Connecting to host ” + args[0] + “ at port ” +serverPort);

// Change this to create an SSLSocketFactory instead of a SocketFactory.SocketFactory socketFactory = SSLSocketFactory.getDefault();// We don't need to change anything else.// That's the beauty of using factories!Socket s = socketFactory.createSocket(args[0], serverPort);...// The rest of the program continues on from here.

For background information, see modifying your Java code to use secure socketslayer.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

168 AS/400 Developer Kit for Java

Page 177: AS400 Developer Kit for Java (Rzaha)

Chapter 10. Creating an internationalized Java program

If you need to customize a Java program for a specific region of the world, youcan create an internationalized Java program with Java locales.

Creating an internationalized Java program involves these steps:1. Isolating the locale-sensitive code and data. For example, strings, dates, and

numbers in your program.2. Setting or getting the locale using the Locale class.3. Formatting dates and numbers to specify a locale if you do not want to use the

default locale.4. Creating resource bundles to handle strings and other locale-sensitive data.

To carry out these tasks in your own Java programs, refer to these examples:v Internationalization of dates using the java.util.DateFormat classv Internationalization of numeric display using the java.util.NumberFormat classv Internationalization of locale-specific data using the java.util.ResourceBundle

class

For more information about internationalization, click on any of these links:

v AS/400 National Language Support, SC41-5101

v AS/400 International Application Development, SC41-5603v Internationalization by Sun Microsystems, Inc.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java localesA locale is a geographic or political region of the world that shares the samelanguage and customs. In Java, the Locale class represents a locale.

Supported Java locales:

The AS/400 Developer Kit for Java supports these locales. The AS/400 jobLANGID and CNTRYID determine the default locale. See Java system propertiesfor more details.

Locale Name in JDK 1.1.6 ISO Locale Name Language/Countryar ar_EG Arabic/Egyptbe be_BY Belorussian/Belarusbg bg_BG Bulgarian/Bulgariaca ca_ES Catalan/Spaincs cs_CZ Czech/Czech Republicda da_DK Danish/Denmarkde de_DE German/Germanyde_AT de_AT German/Austriade_CH de_CH German/Switzerlandel el_GR Greek/Greece

© Copyright IBM Corp. 1998, 1999 169

Page 178: AS400 Developer Kit for Java (Rzaha)

Locale Name in JDK 1.1.6 ISO Locale Name Language/Countryen en_US English/USAen_AU en_AU English/Australiaen_CA en_CA English/Canadaen_GB en_GM English/Great Britainen_IE en_IE English/Irelanden_NZ en_NZ English/New Zealanden_ZA en_ZA English/South Africaes es_ES Spanish/Spaines_AR es_AR Spanish/Argentinaes_BO es_BO Spanish/Boliviaes_CL es_CL Spanish/Chilees_CR es_CR Spanish/Costa Ricaes_DO es_DO Spanish/Dominican Republices_EC es_EC Spanish/Ecuadores_GT es_GT Spanish/Guatemalaes_HN es_HN Spanish/Hondurases_MX es_MX Spanish/Mexicoes_NI es_NI Spanish/Nicaraguaes_PA es_PA Spanish/Panamaes_PE es_PE Spanish/Perues_PR es_PR Spanish/Puerto Ricoes_PY es_PY Spanish/Paraguayes_SV es_SV Spanish/El Salvadores_UY es_UY Spanish/Uruguayes_VE es_VE Spanish/Venezuelaet et_EE Estonian/Estoniafi fi_FI Finnish/Finlandfr fr_FR French/Francefr_BE fr_BE French/Belgiumfr_CA fr_CA French/Canadafr_CH fr_CH French/Switzerlandhr hr_HR Croatian/Croatiahu hu_HU Hungarian/Hungaryis is_IS Icelandic/Icelandit it_IT Italian/Italyit_CH it_CH Italian/Switzerlandiw iw_IL Hebrew/Israelja ja_JP Japanese/Japanko ko_KR Korean/Korealt lt_LT Lithuanian/Lithuanialv lv_LV Latvian/Latviamk mk_MK Macedonian/Macedonianl nl_NL Dutch/Netherlandsnl_BE nl_BE Dutch/Belgiumno no_NO_B Norwegian/Norwayno_NO_NY no_NO_NY Norwegian/Norway, NYpl pl_PL Polish/Polandpt pt_PT Portuguese/Portugalro ro_RO Romanian/Romaniaru ru_RU Russian/Russiash sh_SP Serbo-Croatian/Serbiask sk_SK Slovak/Slovakiasl sl_SI Slovene/Sloveniansq sq_AL Albanian/Albania

170 AS/400 Developer Kit for Java

Page 179: AS400 Developer Kit for Java (Rzaha)

Locale Name in JDK 1.1.6 ISO Locale Name Language/Countrysr sr_SP Serbian/Serbiasv sv_SE Swedish/Swedentr tr_TR Turkish/Turkeyuk uk_UA Ukrainian/Ukrainezh zh_CN Simplified Chinese/Chinazh_TW zh_TW Traditional Chinese/Taiwan

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Internationalization of dates using the java.util.DateFormatclass

This example shows how you can use locales to format dates.

Example 1: Demonstrates use of java.util.DateFormat class for internationalizationof dates//************************// File: DateExample.java//************************import java.text.*;import java.util.*;import java.util.Date;public class DateExample {

public static void main(String args[]) {// Get the DateDate now = new Date();// Get date formatters for default, German, and French localesDateFormat theDate = DateFormat.getDateInstance(DateFormat.LONG);DateFormat germanDate = DateFormat.getDateInstance(DateFormat.LONG, Locale.GERMANY);DateFormat frenchDate = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);// Format and print the datesSystem.out.println(“Date in the default locale: ” + theDate.format(now));System.out.println(“Date in the German locale : ” + germanDate.format(now));System.out.println(“Date in the French locale : ” + frenchDate.format(now));

}}

For more information, see creating an internationalized Java program.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Internationalization of numeric display using thejava.util.NumberFormat class

This example shows how you can use locales to format numbers.

Example 1: Demonstrates use of java.util.NumberFormat class forinternationalization of numeric output//**************************// File: NumberExample.java//**************************import java.lang.*;import java.text.*;import java.util.*;

Chapter 10. Creating an internationalized Java program 171

Page 180: AS400 Developer Kit for Java (Rzaha)

public class NumberExample {public static void main(String args[]) throws NumberFormatException {

// The number to formatdouble number = 12345.678;// Get formatters for default, Spanish, and Japanese localesNumberFormat defaultFormat = NumberFormat.getInstance();NumberFormat spanishFormat = NumberFormat.getInstance(new

Locale(“es”, “ES”));NumberFormat japaneseFormat = NumberFormat.getInstance(Locale.JAPAN);// Print out number in the default, Spanish, and Japanese formats// (Note: NumberFormat is not necessary for the default format)System.out.println(“The number formatted for the default locale; ” +

defaultFormat.format(number));System.out.println(“The number formatted for the Spanish locale; ” +

spanishFormat.format(number));System.out.println(“The number formatted for the Japanese locale; ” +

japaneseFormat.format(number));}

}

For more information, see creating an internationalized Java program.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Internationalization of locale-specific data using thejava.util.ResourceBundle class

This example shows how you can use locales with resource bundles tointernationalize program strings.

These property files are required for the ResourceBundleExample program to workas intended:

Contents of RBExample.propertiesHello.text=Hello

Contents of RBExample_de.propertiesHello.text=Guten Tag

Contents of RBExample_fr_FR.propertiesHello.text=Bonjour

Example 1: Demonstrates use of java.util.ResourceBundle class forinternationalization of locale-specific data//*********************************// File: ResourceBundleExample.java//*********************************import java.util.*;public class ResourceBundleExample {

public static void main(String args[]) throws MissingResourceException {String resourceName = “RBExample”;ResourceBundle rb;// Default localerb = ResourceBundle.getBundle(resourceName);System.out.println(“Default : ” + rb.getString(“Hello” + “.text”));// Request a resource bundle with explicitly specified localerb = ResourceBundle.getBundle(resourceName, Locale.GERMANY);System.out.println(“German : ” + rb.getString(“Hello” + “.text”));// No property file for China in this example... will use defaultrb = ResourceBundle.getBundle(resourceName, Locale.CHINA);System.out.println(“Chinese : ” + rb.getString(“Hello” + “.text”));

172 AS/400 Developer Kit for Java

Page 181: AS400 Developer Kit for Java (Rzaha)

// Here is another way to do it...Locale.setDefault(Locale.FRANCE);rb = ResourceBundle.getBundle(resourceName);System.out.println(“French : ” + rb.getString(“Hello” + “.text”));// No property file for China in this example... will use default, which is now fr_FR.rb = ResourceBundle.getBundle(resourceName, Locale.CHINA);System.out.println(“Chinese : ” + rb.getString(“Hello” + “.text”));

}}

For more information, see creating an internationalized Java program.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 10. Creating an internationalized Java program 173

Page 182: AS400 Developer Kit for Java (Rzaha)

174 AS/400 Developer Kit for Java

Page 183: AS400 Developer Kit for Java (Rzaha)

Chapter 11. Tuning Java program performance with theAS/400 Developer Kit for Java

You should take several aspects of Java application performance into considerationwhen building a Java application for AS/400. Here are some links to details andhints on how you can get better performance:v Use the Create Java Program (CRTJVAPGM) command before running Java class

files, JAR files, or ZIP files to improve the runtime performance of your Javacode.

v Change your optimization levels to achieve the best transformation performance.v Carefully set your values for optimal garbage collection performance.v Only use native methods to start system functions that are relatively long

running and are not available directly in Java.v Use the javac -o option at compilation time to perform method inlining and

significantly improve your method call performance.v Use Java exceptions in cases that are not the normal flow through your

application.

Use these tools with the Performance Explorer (PEX) to locate performanceproblems in your Java programs:v You can collect Java trace events using the AS/400 Java virtual machine.v To determine the time that is spent in each Java method, use Java call traces.v Java profiling locates the relative amount of CPU time that is spent in each Java

method and all system functions that are in use by your Java program.v Use the Java Performance Data Collector to provide profile information about

the programs that run on AS/400.

Any job session can start and end PEX. Normally, the data that is collected issystem wide and pertains to all jobs on the system, including your Java programs.At times it may be necessary to start and stop the performance collection frominside a Java application. This reduces the collection time and may reduce the largevolume of data that is usually produced by a call/return trace. PEX cannot runfrom within a Java thread. To start and stop a collection you need to write a nativemethod that communicates to an independent job though a queue or sharedmemory. Then, the second job starts and stops the collection at the appropriatetime.

In addition to application-level performance data, you can use existing AS/400system level performance tools. These tools report statistics on a Java thread basis.

For examples of PEX reports, see the Performance Tools/400, SC41-4340 book.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

© Copyright IBM Corp. 1998, 1999 175

Page 184: AS400 Developer Kit for Java (Rzaha)

Java runtime performance considerationsTo greatly improve the runtime performance of your Java code, use the Create JavaProgram (CRTJVAPGM) command before running Java class files, JAR files, or ZIPfiles. The CRTJVAPGM command uses the bytecodes to create a Java program,which contains optimized native instructions for AS/400, and associates the Javaprogram object with the class file, JAR file, or ZIP file.

If the CRTJVAPGM command is not used before running a Java class file, JAR file,or ZIP file, then the Java code runs more slowly the first time, because anoptimized Java program at optimization level 10 is created. Future runs will bemuch faster because the Java program is saved and remains associated with theclass file or JAR file. Running the bytecodes interpretively may provide acceptableperformance during application development, but you may want to use theCRTJVAPGM command before running the Java code in a production environment.

A Just-In-Time compiler improves performance by compiling code, which isoptimized to a particular Java virtual machine runtime environment. You shouldcompare the benefit of this type of optimization to the time that it takes togenerate this code each time a Java virtual machine is created.

If your program is running slowly, enter the Display Java Program (DSPJVAPGM)command to view the attributes of a Java program.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java transformation performance considerationsYou can determine the speed of transformation by the optimization level that youset. Optimization level 10 transforms the fastest, but the resulting program isgenerally slower than one set at a higher optimization level. Optimization level 40takes longer to transform, but is likely to run faster.

At optimization level 40, some Java program optimizations are not 100 percentJava compatible. Thus, a few programs that do not run at level 40, may run atlevel 30 instead. You can run programs that do not run at optimization level 40 byusing licensed internal code optimization LICOPT parameter strings. However,performance at level 30 may be sufficient for your program.

If you are having problems running Java code that seemed to work on anotherJava virtual machine, try using optimization level 30 instead of level 40. If thisworks, and your performance is acceptable, you do not need to do anything else. Ifyou need better performance, see LICOPT parameter strings for information onhow to enable and disable various forms of optimization. For example, you couldfirst try creating the program using OPTIMIZE(40) LICOPT(NoPreresolveExtRef). Ifyour application contains dead calls to classes that are not available, this LICOPTvalue allows your program to run without problems.

To determine what level of optimization your Java programs were created at, youcan use the Display Java Program (DSPJVAPGM) command. To change theoptimization level of your Java program, use the Create Java Program(CRTJVAPGM) command.

176 AS/400 Developer Kit for Java

Page 185: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java garbage collection performance considerationsGarbage collection on the AS/400 Java virtual machine operates in a continuousasynchronous mode. The garbage collection-initial size (GCHINL) parameter on theRun Java (RUNJVA) command may affect application performance. This parameterspecifies the amount of new object space that is allowed between garbagecollections. A small value may cause too much garbage collection overhead. A largevalue may limit garbage collection and cause out of memory errors. However, formost applications, the default values should be correct.

Garbage collection determines that an object is no longer needed by evaluatingwhether there are any valid references to that object.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java Native Method Invocation performance considerationsNative method invocation on AS/400 may not perform as well as native methodinvocation on other platforms. Java on AS/400 has been optimized by moving theJava virtual machine below the machine interface (MI). Native method invocationrequires a call to above MI code and may require expensive Java Native Interface(JNI) calls back into the Java virtual machine. Native methods should not carry outsmall routines, which you can easily write in Java. Only use native methods tostart system functions that are relatively long running and are not availabledirectly in Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java method inlining performance considerationsMethod inlining can significantly improve method call performance. Any methodthat is final is a potential candidate for inlining. The inline feature is available onAS/400 through the javac -o option at compilation time. The size of your classfiles and transformed Java program increases if you use the javac -o option. Youshould consider both the space and performance characteristics of your applicationwhen using the -o option.

The Java transformer enables inlining for optimization level 30 and optimizationlevel 40. Optimization level 30 enables some inlining of final methods within asingle class. Optimization level 40 enables inlining of final methods within a ZIPfile or JAR file. You can control method inlining with the AllowInlining andNoAllowInlining LICOPT parameter strings. The AS/400 interpreter does notperform method inlining.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 11. Tuning Java program performance with the AS/400 Developer Kit for Java 177

Page 186: AS400 Developer Kit for Java (Rzaha)

Java exception performance considerationsAS/400 exception architecture allows versatile interrupt and retry capabilities. Itallows mixed language interaction. Throwing Java exceptions on AS/400 may bemore expensive than on other platforms. This should not affect overall applicationperformance unless Java exceptions are routinely used in the normal applicationpath.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java event trace performance toolsThe AS/400 Java virtual machine enables the trace of certain Java events. Theseevents can be collected without any instrumentation in the Java code. These eventsinclude activities, such as garbage collection, thread creation, class loading, andlocking. The Run Java (RUNJVA) command does not specify these events. Instead,you create a Performance Explorer (PEX) definition and use the Start PerformanceExplorer (STRPEX) command to collect the events. Each event contains usefulperformance information, such as time stamp and central processing unit (CPU)cycles. You can trace both Java events and other system activities, such as diskinput and output, with the same trace definition.

For a complete description of the Java events, see the Performance Tools/400,

SC41-4340 book.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java call trace performance toolsJava method call traces provide significant performance information about the timethat is spent in each Java method. On other Java virtual machines you may haveused the -prof (profiling) option on the java command. To enable method calltracing on AS/400, you must specify the Enable Performance Collection(ENBPFRCOL) command on the Create Java Program (CRTJVAPGM) commandline. After creating your Java program with this keyword, you can start thecollection of method call traces by using a Performance Explorer (PEX) definitionthat includes the call/return trace type.

Call/return trace output produced with the Print Performance Explorer Report(PRTPEXRPT) command shows the central processing unit (CPU) time for each callfor every Java method that is traced. In some cases, you may not be able to enableall of the class files for call return tracing. Or, you may be calling native methodsand system functions that are not enabled for tracing. In this situation, all of theCPU time that is spent in these methods or system functions accumulates. Then, itis reported to the last Java method that is called and has been enabled.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

178 AS/400 Developer Kit for Java

Page 187: AS400 Developer Kit for Java (Rzaha)

Java profiling performance toolsSystem wide central processing unit (CPU) profiling calculates the relative amountof CPU time that is spent in each Java method and all system functions in use byyour Java program. Use a Performance Explorer (PEX) definition that tracesperformance monitor counter overflow (*PMCO) run cycle events. Samples aretypically specified in intervals of one millisecond. To collect a valid trace profile,you should run your Java application until it accumulates two to three minutes ofCPU time. This should produce over 100,000 samples. The Print PerformanceExplorer Report (PRTPEXRPT) command produces a histogram of CPU time that isspent across the entire application. This includes every Java method and allsystem-level activity. The Performance Data Collector (PDC) tool also providesprofile information about the programs that run on AS/400.

Note: CPU profiling does not show relative CPU usage for Java programs that areinterpreted.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Collecting Java performance dataTo collect Java performance data on AS/400, follow these steps:1. Create a Performance Explorer (PEX) definition that specifies:v A user-defined namev Type of data collectionv Job namev Series of system events that you would like to collect system information

about

Note: A PEX definition of *STATS is preferable to a *TRACE definition if theoutput that you want is the java_g -prof type, and you know the specific jobname of the Java program.

Here is an example of a *STATS definition: ADDPEXDFN DFN(YOURDFN)JOB(*ALL/YOURID/QJVACMDSRV) DTAORG(*HIER) TEXT(’your stats definition’)This *STATS definition does not get all Java events running. Only the Javaevents that are in your own Java session are profiled. This mode of operationmay increase the time that it takes to run the Java program.

Here is an example of a *TRACE definition: ADDPEXDFN DFN(YOURDFN)TYPE(*TRACE) JOB(*ALL) TRCTYPE(*SLTEVT) SLTEVT(*YES) PGMEVT(*JVAENTRY*JVAEXIT) This *TRACE definition collects any Java entry event and exit eventfrom any Java program in the system that you create withENBPFRCOL(*ENTRYEXIT). This causes the analysis of this type of collectionto be slower than a *STATS trace, depending on how many Java programevents you have and the duration of the PEX data collection.

2. Enable the *JVAENTRY and *JVAEXIT, under the program events category onthe PEX definition, so that PEX recognizes the Java entry and exits. Note: Ifyou are running the Java code using the Just-in-time (JIT) compiler, you do notenable entry and exit as you would if you were using the CRTJVAPGMcommand for direct execution. Instead, JIT generates code with entry and exithooks when you use the os400.enbprfcol system property.

Chapter 11. Tuning Java program performance with the AS/400 Developer Kit for Java 179

Page 188: AS400 Developer Kit for Java (Rzaha)

3. Prepare the Java program to report program events to the AS/400 PerformanceData Collector. You can do this by using the Create Java Program(CRTJVAPGM) command on any Java program that you want to reportperformance data on. You must create the Java program by using theENBPFRCOL(*ENTRYEXIT) parameter.Note: You must repeat this step for every Java program that you want to collectperformance data on. If you do not perform this step, no performance data iscollected by the PEX and no output is produced by running the JavaPerformance Data Converter (JPDC) tool.

4. Start the PEX data collection by using the Start Performance Explorer (STRPEX)command.

5. Run the program that you would like to analyze. This program should not bein a production environment. It will generate a large amount of data in a smallamount of time. You should limit the collection time to five minutes. A JavaProgram that runs for this amount of time generates a lot of PEX system data.If too much data is collected, an unreasonable amount of time is required toprocess the data.

6. End the PEX data collection by using the End Performance Explorer (ENDPEX)command.Note: If this is not the first time that you have ended PEX data collection, youmust specify a replace file of *YES or it will not save your data.

7. Run the JPDC tool.8. Connect the integrated file system directory to the system with the viewer of

your choice: java_g -prof viewer or Jinsight viewer. You can copy this file fromAS/400 and use it as input to any suitable profiling tool.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Performance Data Collector toolThe Performance Data Collector (PDC) tool provides profile information about theprograms that run on AS/400.

The industry-standard profile option on many Java virtual machines depends onthe implementation of the java_g feature. This is a special debug version of theJava virtual machine, which offers the -prof option. You specify this option on acall to a Java program. When you specify this option, the Java virtual machineproduces a record file that contains information about which parts of the Javaprogram were operating during the duration of the program. The Java virtualmachine generates this information in real time.

On AS/400, the Performance Explorer (PEX) feature analyzes programs andrecord-specific system events. A DB/2 database stores this information andretrieves it using SQL functions. PEX information is the repository for specificprogram information that produces Java profile data. This profile data iscompatible with java_g -prof program profile information. The Java PerformanceData Converter (JPDC) tool provides java_g -prof program output and programprofile information for a specific IBM tool, which is known as Jinsight.

For information on how collect Java performance data, see collecting Javaperformance data.

180 AS/400 Developer Kit for Java

Page 189: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Java Performance Data Converter toolThe Java Performance Data Converter (JDPC) tool provides a way for you to createJava performance data about the Java programs that are running on AS/400. Thisperformance data is compatible with the performance data output of SunMicrosystems, Inc.’s Java virtual machine java_g -prof option and IBM Jinsightoutput.

Note: The JDPC tool does not produce readable output. Use a Java profiling toolthat accepts java_g -prof or Jinsight data to analyze your data.

The JDPC tool accesses the AS/400 Performance Explorer (PEX) data that DB2/400(using JDBC) stores. It converts the data to either Jinsight or general performancetypes. Then, JDPC stores the output file in the integrated file system at auser-specified location.

Note: You must follow appropriate AS/400 PEX data collection procedures tocollect PEX data while running your specified Java application on AS/400. Youmust set a PEX definition with defines the entrance and exit of a program or acollect and store procedure. For details on how collect PEX data and set a PEX

definition, see the Performance Tools/400, SC41-4340 book.

For information on how to run JPDC, see Running the Java Performance DataConverter.

You can start the JPDC program by using either the Qshell command line interfaceor Run Java (RUNJVA) command.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Running the Java Performance Data ConverterTo run the Java Performance Data Converter (JPDC) for performance datacollection, follow these steps.1. Enter the first input argument, which is either general for the java_g -prof or

jinsight for Jinsight output.2. Enter the second input argument, which is the name of the Performance

Explorer (PEX) definition that was used to collect the data.Note: You should restrict this name to four or five characters, because of theinternal use of connections of this name.

3. Enter the third input argument, which is the name of the file that the JPDC toolgenerates. This generated file writes to your current integrated file systemdirectory. Use the cd (PF4) command to specify an integrated file systemcurrent directory.

4. Enter the fourth input argument, which is the name of the AS/400 hostrelational database directory entry. Use the Work with Relational DatabaseDirectory Entry (WRKRDBDIRE) command to see what the name is. It is theonly relational database where the *LOCAL is indicated.

Chapter 11. Tuning Java program performance with the AS/400 Developer Kit for Java 181

Page 190: AS400 Developer Kit for Java (Rzaha)

To operate this code the /QIBM/ProdData/Java400/ext/JPDC.jar file must be inthe Java classpath on AS/400. When the program is done running, a text outputfile can be found in the current directory.

You can run JPDC by using the AS/400 command line or Qshell environment. SeeExample: Running the Java Performance Data Converter for details.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Example: Running the Java Performance Data ConverterYou can either use the AS/400 command line or the Qshell environment to run theJava Performance Data Converter (JPDC).

Using the AS/400 command line:

1. Enter the Run Java (RUNJVA) command or JAVA command on the AS/400command line.

2. Enter com.ibm.as400.jpdc.JPDC on the class parameter line.3. Enter general pexdfn mydir/myfile myrdbdire on the parameter line.4. Enter ’/QIBM/ProdData/Java400/ext/JPDC.jar’ on the classpath parameter line.

Note: You can omit the classpath if the ’/QIBM/ProdData/Java400/ext/JPDC.jar’string is in the CLASSPATH environment variable. You can use either the AddEnvironment Variable (ADDENVVAR) command, Change EnvironmentVariable (CHGENVVAR) command, or Work with Environment Variable(WRKENVVAR) command to add this string to the CLASSPATH environmentvariable.

Using the Qshell environment:

1. Enter the Start Qshell (STRQSH) command to start the Qshell Interpreter.2. Enter this on the command line:

java -classpath /QIBM/ProdData/Java400/ext/JPDC.jar com.ibm.as400/jpdc/JPDCjiinsight pexdfn mydir/myfile myrdbdire

Note: You can omit the classpath if the ’/QIBM/ProdData/Java400/ext/JPDC.jar’string is added to your current environment. You can use either theADDENVVAR command, CHGENVVAR, or WRKENVVAR command to addthis string to your current environment.

For background information, see running the Java Performance Data Converter .

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

182 AS/400 Developer Kit for Java

Page 191: AS400 Developer Kit for Java (Rzaha)

Chapter 12. Debugging programs using the AS/400 DeveloperKit for Java

If you need to debug your Java programs, select one of these options:v Debugging a Java programv Debugging Java and native method programsv Debugging a Java program from another displayv Debugging servlets

When you debug a Java program, your Java program is actually running in theJava virtual machine in a batch immediate (BCI) job. Your source code displays inthe interactive display, but the Java program is not running there. It is running inthe other job, which is a serviced job. When your Java program ends, the servicedjob ends, and a message displays, stating that Job being serviced ended.

The interface between the two jobs is established when you specify the *DEBUGoption on the Run Java (RUNJVA) command.

For more information about the system debugger, see the ILE C Programmer’s

Guide, SC09-2515 book , and online help information.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Debugging a Java programThere are many different ways to debug a Java program. You can use the *DEBUGoption to view the source code before running the program. Then, you can setbreakpoints, or step over or into a program to analyze errors while the program isrunning.

To debug Java programs:1. Compile the Java program by using the DEBUG option, which is the -g option

on the javac tool. See Debugging Java programs by using the *DEBUG optionfor more details.

2. Insert the class file (.class) and source file (.java) in the same directory onAS/400.

3. Run the Java program by using the Run Java (RUNJVA) command on theAS/400 command line. Specify OPTION(*DEBUG) on the Run Java (RUNJVA)command.

4. The Java program source displays.5. Press F6 (Add/Clear breakpoint) to set breakpoints, or press F10 (Step) to step

through the program. For more information about setting breakpoints, seesetting breakpoints. For details on stepping, see Stepping through Javaprograms to debug.

Note:While using breakpoints and steps, check the logical flow of the Javaprogram, then view and change variables, as necessary.

© Copyright IBM Corp. 1998, 1999 183

Page 192: AS400 Developer Kit for Java (Rzaha)

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Debugging Java programs by using the *DEBUG optionUse the *DEBUG option to view the source code before running the program. The*DEBUG option allows you to set breakpoints within the code.

To use the *DEBUG option, enter the Run Java (RUNJVA) command that isfollowed by the name of your classfile and OPTION(*DEBUG) on the commandline. For example, the AS/400 command line should look like this:RUNJVA CLASS(classname) OPTION(*DEBUG)

Note: If you are not authorized to use the Start Service Job (STRSRVJOB)command, OPTION(*DEBUG) is ignored.

To view the debugging displays, see Initial debugging displays for Java programs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Initial debugging displays for Java programsAs you debug your Java programs, follow these example displays for yourprograms. These displays show an example program, named Hellod.v Enter ADDENVVAR ENVVAR(CLASSPATH) VALUE (’/MYDIR’).v Enter this command: RUNJVA CLASS(HELLOD) OPTION(*DEBUG). Insert the name of

your Java program in place of HELLOD.v Wait for the Display Module Source display to display. This is the source for the

HELLOD Java program.+————————————————————————————————————————+| Display Module Source || || Class file name: HELLOD || 1 import java.lang.*; || 2 || 3 public class Hellod extends Object || 4 { || 5 int k; || 6 int l; || 7 int m; || 8 int n; || 9 int o; || 10 int p; || 11 String myString; || 12 Hellod myHellod; || 13 int myArray[]; || 14 || 15 public Hellod() || More... || Debug . . . || || F3=End program F6=Add/Clear breakpoint F10=Step F11=Display variable || F12=Resume F17=Watch variable F18=Work with watch F24=More keys || |+————————————————————————————————————————+

v Press F14 (Work with Module List).

184 AS/400 Developer Kit for Java

Page 193: AS400 Developer Kit for Java (Rzaha)

v The Work with Module List display is shown. You can add other classes andprograms to debug by entering option 1 (Add program). Display their sourcewith option 5 (Display module source).+————————————————————————————————————————+| Work with Module List || System: AS400 || Type options, press enter. || 1=Add program 4=Remove program 5=Display module source || 8=Work with module breakpoints || || Opt Program/module Library Type || *LIBL *SRVPGM || HELLOD *CLASS Selected || || || || || || || || || || Bottom || Command || ===> || F3=Exit F4=Prompt F5=Refresh F9=Retrieve F12=Cancel || F22=Display class file name || |+————————————————————————————————————————+

v When adding a class to debug, you may need to enter a package-qualified classname that is longer than the Program/module input field. To enter a longername, follow these steps:1. Enter Option 1 (Add program).2. Leave the Program/module field blank.3. Leave the library field as *LIBL.4. Enter *CLASS for Type.5. Press Enter.6. A pop up window is displayed where you have more room to enter the

package-qualified class file name.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Setting breakpointsThe running of a program can be controlled with breakpoints. Breakpoints stop arunning program at a specific statement.

To set breakpoints:1. Place the cursor on the line of code where you would like to set a breakpoint.2. Press F6 (Add/Clear breakpoint) to set the breakpoint.3. Press F12 (Resume) to run the program.

Note:Just before the line of code runs, where the breakpoint is set, the programsource is displayed indicating that the breakpoint was hit.+————————————————————————————————————————+| Display Module Source || |

Chapter 12. Debugging programs using the AS/400 Developer Kit for Java 185

Page 194: AS400 Developer Kit for Java (Rzaha)

|Current thread: 00000019 Stopped thread: 00000019 ||Class file name: Hellod ||35 public static void main(String[] args) ||36 { ||37 int i,j,h,B[],D[][]; ||38 Hellod A=new Hellod(); ||39 A.myHellod = A; ||40 Hellod C[]; ||41 C = new Hellod[5]; ||42 for (int counter=0; counter<2; counter++) { ||43 C[counter] = new Hellod(); ||44 C[counter].myHellod = C[counter]; ||45 } ||46 C[2] = A; ||47 C[0].myString = null; ||48 C[0].myHellod = null; || ||49 A.method1(); ||Debug . . . || ||F3=End program F6=Add/Clear breakpoint F10=Step F11=Display variable ||F12=Resume F17=Watch variable F18=Work with watch F24=More key ||Breakpoint added to line 41. |+————————————————————————————————————————+

When you hit a breakpoint, if you want to set breakpoints that are only hit withinthe current thread, use the TBREAK command.

For more information about system debugger commands, see the ILE C

Programmer’s Guide, SC09-2515 book, and online help information.

For information about evaluating variables when a program stops running at abreakpoint, see Evaluating variables in Java programs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Stepping through Java programs to debugYou can step through your program while debugging. You can either step over orstep into other functions. Java programs and native methods can use the stepfunction.

When the program source first displays, you can start stepping. The program stopsbefore running the first statement. Press F10 (Step). Continue to press F10 (Step) tostep through the program. Press F22 (Step into) to step into any function that yourprogram calls. You can also start stepping anytime a breakpoint is hit. Forinformation about setting breakpoints, see Setting breakpoints.+————————————————————————————————————————+| Display Module Source || ||Current thread: 00000019 Stopped thread: 00000019 ||Class file name: Hellod ||35 public static void main(String[] args) ||36 { ||37 int i,j,h,B[],D[][]; ||38 Hellod A=new Hellod(); ||39 A.myHellod = A; ||40 Hellod C[]; ||41 C = new Hellod[5]; ||42 for (int counter=0; counter<2; counter++) { |

186 AS/400 Developer Kit for Java

Page 195: AS400 Developer Kit for Java (Rzaha)

|43 C[counter] = new Hellod(); ||44 C[counter].myHellod = C[counter]; ||45 } ||46 C[2] = A; ||47 C[0].myString = null; ||48 C[0].myHellod = null; ||49 A.method1(); ||Debug . . . || ||F3=End program F6=Add/Clear breakpoint F10=Step F11=Display variable ||F12=Resume F17=Watch variable F18=Work with watch F24=More key ||Step completed at line 42 in thread 00000019 |+————————————————————————————————————————+

To stop stepping and continue running the program, press F12 (Resume).

For more information about stepping, see the ILE C Programmer’s Guide,

SC09-2515 book, and online help information.

For information about evaluating variables when a program stops running at astep, see Evaluating variables in Java programs.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Evaluating variables in Java programsThere are two ways to evaluate a variable when a program stops running at abreakpoint or step:v Enter EVAL VariableName on the debug command line.v Put the cursor on the variable name in the displayed source code and press F11

(Display variable).

Use the EVAL command for evaluating variables in a Java program.Note:You can also change the contents of a variable by using the EVAL command.For more information about the variations of the EVAL command, see the ILE C

Programmer’s Guide, SC09-2515 book, and online help information.

When looking at variables in a Java program, note the following:v If you evaluate a variable that is an instance of a Java class, the first line of the

display shows what kind of object it is. It also shows an identifier for the object.Following the first display line, the contents of each data member in the objectdisplays. If the variable is null, the first line of the display indicates that it isnull. Asterisks show the contents of each data member (of a null object).

v If you evaluate a variable that is a Java string object, the contents of that stringdisplays. If the string is null, then null displays.

v You cannot change a variable that is a string.v If you evaluate a variable that is an array, ’ARR’ displays followed by an

identifier for that array. You can evaluate elements of the array by using asubscript of the variable name. If the array is null, then null displays.

v You cannot change a variable that is an array. You can change an element of anarray if it is not an array of strings or objects.

v For variables that are arrays, you can specify arrayname.length to see how manyelements are in the array.

Chapter 12. Debugging programs using the AS/400 Developer Kit for Java 187

Page 196: AS400 Developer Kit for Java (Rzaha)

v If you want to see the contents of a variable that is a data member of a class,you can specify classvariable.membername.

v If you try to evaluate a variable before it has been initialized one of two thingscan happen. Either a Variable not available to display message is shown, orthe unitialized contents of the variable are shown, which could be a strangevalue.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Debugging Java and native method programsYou can debug Java programs and native method programs at the same time.While you are debugging your source on the interactive display, you can debug anative method that is programmed in C, which is within a service program(*SRVPGM).

To debug Java programs and native method programs at once:1. Press F14 (Work with module list) when your Java program source displays to

show the Work with Module List (WRKMODLST) display.2. Select option 1 (Add program) to add your service program.3. Select option 5 (Display module source) to display the *MODULE that you

want to debug and the source.4. Press F6 (Add/Clear breakpoint) to set breakpoints in the service program. For

more information about setting breakpoints, see Setting breakpoints.5. Press F12 (Resume) to run the program.

Note:When the breakpoint is hit in your service program, the program will stoprunning, and the source for the service program displays.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Debugging a Java program from another displayWhile debugging a Java program, the program source displays whenever itencounters a breakpoint. This may interfere with the display output of the Javaprogram. To avoid this, debug the Java program from another display. The outputfrom the Java program displays where the Java command is running and theprogram source shows on the other display.

To debug Java from another display:1. The Java program must be held, while you start setting up to debug.

You can hold the Java program by making the program:v Wait for input from the keyboard.v Wait for a time interval.v Loop to test a variable, which requires that you set a value to eventually get

the Java program out of the loop.2. Once the Java program is held, go to another display to perform these steps:

a. Enter the Work with Active Jobs (WRKACTJOB) command on the commandline.

188 AS/400 Developer Kit for Java

Page 197: AS400 Developer Kit for Java (Rzaha)

b. Find the batch immediate (BCI) job where your Java program is running.Look under the Subsystem/Job listing for QJVACMDSRV. Look under theUser listing for your User ID. Look under Type for BCI.

c. Enter option 5 to work with that job.d. At the top of the Work with Job display, the Number, User, and Job is

displayed. Enter STRSRVJOB Number/User/Job.e. Enter STRDBG CLASS(classname). Classname is the name of the Java class

that you want to debug. It can either be the class name that you specifiedon the Java command, or it can be another class.

f. The source for that class appears in the Display Module Source display.g. Set breakpoints, by pressing F6 (Add/Clear breakpoint), whenever you

would like to stop in that Java class. Press F14 to add other classes,programs, or service programs to debug. For more information aboutsetting breakpoints, see setting breakpoints.

h. Press F12 (Resume) to continue running the program.3. Stop holding your original Java program. When the breakpoints are hit, the

Display Module Source display appears on the display where the Start ServiceJob (STRSRVJOB) command and the Start Debug (STRDBG) command wereentered. When the Java program ends, a Job being serviced ended messageappears.

4. Enter the End Debug (ENDDBG) command.5. Enter the End Service Job (ENDSRVJOB) command.

See QIBM_CHILD_JOB_SNDINQMSG environment variable for more informationabout this variable that controls whether the BCI job waits before calling the Javavirtual machine.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

QIBM_CHILD_JOB_SNDINQMSG environment variableThe QIBM_CHILD_JOB_SNDINQMSG environment variable is the variable thatcontrols whether the batch immediate (BCI) job, where the Java virtual machineruns, waits before starting the Java virtual machine.

If you set the environment variable to 1 when the Run Java (RUNJVA) commandruns, a message is sent to the user’s message queue. The message is sent before theJava virtual machine starts in the BCI job. The message looks like this:Spawned (child) process 023173/JOB/QJVACMDSRV is stopped (G C)

To view this message, enter SYSREQ and select option 4.

The BCI job waits until you enter a reply to this message. A reply of (G) starts theJava virtual machine.

You can set breakpoints in a *SRVPGM or *PGM, which the BCI job calls, beforereplying to the message.Note: You cannot set breakpoints in a Java class, because at this point, the Javavirtual machine has not been started.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 12. Debugging programs using the AS/400 Developer Kit for Java 189

Page 198: AS400 Developer Kit for Java (Rzaha)

Debugging servlets

Debugging servlets is more complicated than debugging regular Javaapplications, since servlets run in the Java runtime of the IBM HTTP Server.

To debug a servlet, follow these steps:1. Use the javac -gcommand in the Qshell Interpreter to compile your servlet.2. Copy the source code (.java file) and compiled code (.class file) to

/QIBM/ProdData/Java400.3. Run the Create Java Program (CRTJVAPGM) command against the .class file

using optimization level 10, OPTIMIZE(10).4. Start the server.5. Run the Start Service Job (STRSRVJOB) command on the job where the servlet

will run.6. Enter STRDBG CLASS(myServlet), where myServlet is the name of your servlet.

The source should be displayed.7. Set a breakpoint in the servlet and press F12.8. Run your servlet. When the servlet hits the breakpoint, you can continue

debugging.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

190 AS/400 Developer Kit for Java

Page 199: AS400 Developer Kit for Java (Rzaha)

Chapter 13. Troubleshooting the AS/400 Developer Kit forJava

If you encounter problems while using the AS/400 Developer Kit for Java, takeany of these steps to determine the source of the problem.v Find the job log from the job that ran the Java command. Also, look for the job

log from the batch immediate (BCI) job where the Java program ran to analyzethe cause of failure.

v Collect useful data for an authorized program analysis report (APAR).v Apply program-temporary fixes (PTFs).v Know how to get support if you detect a potential defect in the AS/400

Developer Kit for Java.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Finding job logs for Java problem analysisUse the job log from the job that ran the Java command, and the batch immediate(BCI) job log where the Java program ran, to analyze causes of a Java failure. Theyboth may contain important error information.

There are two ways to find the job log for the BCI job. You can find the name ofthe BCI job that is logged in the job log of the job that ran the Java command.Then, use that job name to find the job log for the BCI job.

You can also find the job log for the BCI job by following these steps:1. Enter the Work with Submitted Jobs (WRKSBMJOB) command on the AS/400

command line.2. Go to the bottom of the list.3. Look for the last job in the list, called QJVACMDSRV.4. Enter option 8 (Work with Spooled Files) for that job.5. A file called QPJOBLOG displays.6. Press F11 to see view 2 of the spooled files.7. Verify that the date and time match the date and time when the failure

occurred.Note:If the date and time do not match the date and time when you signed off,continue looking through the list of submitted jobs. Try to find aQJVACMDSRV job log with a date and time that matches when you signed off.

If you are unable to find a job log for the BCI job, one may not have beenproduced. This happens if you set the ENDSEP value for the QDFTJOBD jobdescription too high or the LOG value for the QDFTJOBD job description specifies*NOLIST. Check these values, and change them so that a job log is produced forthe BCI job.

To produce a job log for the job that ran the Run Java (RUNJVA) command.1. Enter SIGNOFF *LIST.2. Then, sign back on.

© Copyright IBM Corp. 1998, 1999 191

Page 200: AS400 Developer Kit for Java (Rzaha)

3. Enter the Work with Spooled Files (WRKSPLF) command on the AS/400command line.

4. Go to the bottom of the list.5. Find a file named QPJOBLOG.6. Press F11.7. Verify that the date and time match the date and time when you entered the

signoff command. Note: If the date and time do not match the date and timewhen you signed off, continue looking through the list of submitted jobs. Try tofind a QJVACMDSRV job log with a date and time that matches when yousigned off.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Collecting data for Java problem analysisTo collect data for an authorized program analysis report (APAR):1. Include a complete description of the problem.2. Save the Java class file that caused the problem while running.3. You can use the SAV command to save objects from the integrated file system.

You may need to save other class files that this program needs to run. You mayalso want to save and send in an entire directory for IBM to use when trying toreproduce the problem, if necessary. This is an example of how to save anentire directory.Example:SAV DEV('/QSYS.LIB/TAP01.DEVD') OBJ(('/mydir'))

If possible, save the source files for any Java classes that are involved in theproblem. This is helpful to IBM when reproducing and analyzing the problem.

4. Save any service programs that contain native methods that are needed to runthe program.

5. Save any data files that are needed to run the Java program.6. Add a complete description of how to reproduce the problem. This should

include:v The value of the CLASSPATH environment variable.v A description of the Java command that was run.v A description of how to respond to any input that is required by the

program.7. Include any vertical licensed internal code (VLIC) logs that have occurred near

the time of failure.8. Add the job log from both the interactive job and the BCI job where the Java

virtual machine was running.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

192 AS/400 Developer Kit for Java

Page 201: AS400 Developer Kit for Java (Rzaha)

Getting support for the AS/400 Developer Kit for JavaSupport services for the AS/400 Developer Kit for Java are provided under theusual terms and conditions for AS/400 software products. Support services includeprogram services, voice support, and consulting services. Use the online

information that is provided at IBM AS/400 Home Page under the topic“Support” for more information. Use IBM Support Services for 5769-JV1 (AS/400Developer Kit for Java). Or, contact your local IBM representative.

You may, at IBM direction, be required to obtain a more current level of theAS/400 Developer Kit for Java to receive Continued Program Services. For moreinformation, see support for multiple Java Development Kits (JDKs).

Resolving defects of the AS/400 Developer Kit for Java program are supportedunder program services or voice support. Resolving application programming ordebugging issues are supported under consulting services.

The AS/400 Developer Kit for Java application program interface (API) calls aresupported under consulting services, unless:1. It is clearly a Java API defect as demonstrated by re-creation in a relatively

simple program.2. It is a question that asks for documentation clarification,3. It is a question about the location of samples or documentation.

All programming assistance is supported under consulting services. This includesthe program samples that are provided in the AS/400 Developer Kit for Javalicensed program (LP) product. Additional samples may be available on the

Internet at IBM AS/400 Home Page on an unsupported basis.

The AS/400 Developer Kit for Java LP provides information about solvingproblems. If you believe that there is a potential defect in the AS/400 DeveloperKit for Java API, a simple program that demonstrates the error is required.

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

Chapter 13. Troubleshooting the AS/400 Developer Kit for Java 193

Page 202: AS400 Developer Kit for Java (Rzaha)

194 AS/400 Developer Kit for Java

Page 203: AS400 Developer Kit for Java (Rzaha)

Chapter 14. Code examples for the AS/400 Developer Kit forJava

CL Commands:

v CRTJVAPGMv CHGJVAPGMv RUNJVAv DLTJVAPGM

v DMPJVMv DSPJVAPGM

Other Programming Languages:

v Calling another Java programv Calling a CL programv Calling a CL commandv Input and output streamsv Socketsv Calling Java from Cv Calling Java from RPGv Invocation API

JDBC:

v Connectingv Statement interfacev PreparedStatement interfacev CallableStatement interfacev ResultSet interfacev DatabaseMetaData interfacev JDBC applicationv Embedding SQL Statements

SQLJ:

v Embedding SQL Statements in your Java application

Remote Abstract Window Toolkit:

v Setting up Remote AWT

Secure sockets layer:

v Socket factoriesv Server socket factoriesv Secure sockets layerv Secure sockets layer server

Internationalization:

v DateFormatv NumberFormatv ResourceBundle

© Copyright IBM Corp. 1998, 1999 195

Page 204: AS400 Developer Kit for Java (Rzaha)

Performance tools:

v Java Performance Data Converter

[ Information Center Home Page | Feedback]

[ Legal | AS/400 Glossary ]

196 AS/400 Developer Kit for Java

Page 205: AS400 Developer Kit for Java (Rzaha)
Page 206: AS400 Developer Kit for Java (Rzaha)

����

Printed in U.S.A.