IBM Toolbox For Java
IBM Toolbox For Java
7.2
Programming
IBM Toolbox for Java
IBM
Note
Before using this information and the product it supports, read the information in “Notices” on page
537.
This document may contain references to Licensed Internal Code. Licensed Internal Code is Machine Code and is
licensed to you under the terms of the IBM License Agreement for Machine Code.
© Copyright International Business Machines Corporation 1999, 2013.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
IBM Corp.
Contents
iii
Keyed data queues....................................................................................................................40
Digital certificates........................................................................................................................... 41
EnvironmentVariable class............................................................................................................. 42
Exceptions.......................................................................................................................................43
FileAttributes class......................................................................................................................... 44
FTP class......................................................................................................................................... 44
Integrated file system classes........................................................................................................45
IFSFile class.............................................................................................................................. 46
IFSJavaFile class.......................................................................................................................47
IFSFileInputStream...................................................................................................................48
IFSTextFileInputStream class.................................................................................................. 48
IFSFileReader............................................................................................................................49
IFSFileOutputStream class....................................................................................................... 49
IFSTextFileOutputStream class................................................................................................ 50
IFSFileWriter..............................................................................................................................51
IFSRandomAccessFile.............................................................................................................. 51
IFSKey class.............................................................................................................................. 52
File sharing mode...................................................................................................................... 53
IFSSystemView..........................................................................................................................53
ISeriesNetServer class................................................................................................................... 53
JavaApplicationCall class............................................................................................................... 54
JDBC classes...................................................................................................................................54
AS400JDBCBlob class.............................................................................................................. 56
CallableStatement interface..................................................................................................... 57
AS400JDBCClob class.............................................................................................................. 58
AS400JDBCConnection class................................................................................................... 59
AS400JDBCConnectionPool..................................................................................................... 60
AS400JDBCManagedConnectionPoolDataSource class..........................................................61
DatabaseMetaData interface.................................................................................................... 70
AS400JDBCDataSource class...................................................................................................70
Registering the JDBC driver...................................................................................................... 71
AS400JDBCParameterMetaData class.....................................................................................73
PreparedStatement interface................................................................................................... 74
ResultSet class.......................................................................................................................... 75
AS400JDBCRowSet class......................................................................................................... 77
AS400JDBCSavepoint class......................................................................................................77
Running SQL statements with Statement objects....................................................................79
JDBC XA Distributed Transaction Management....................................................................... 80
Jobs classes.................................................................................................................................... 81
Job class.................................................................................................................................... 82
JobList class.............................................................................................................................. 82
JobLog class.............................................................................................................................. 83
Message classes............................................................................................................................. 84
NetServer class............................................................................................................................... 86
ObjectReferences class.................................................................................................................. 87
Permission classes......................................................................................................................... 87
DLOPermission class................................................................................................................. 89
QSYSPermission........................................................................................................................ 89
RootPermission......................................................................................................................... 91
Print classes.................................................................................................................................... 92
Listing Print objects................................................................................................................... 93
Working with Print objects........................................................................................................ 94
Retrieving PrintObject attributes.............................................................................................. 94
AFP Resource Attributes .......................................................................................................... 95
Output queue attributes............................................................................................................96
Printer Attributes ...................................................................................................................... 96
Printer file attributes................................................................................................................. 98
Spooled file attributes.............................................................................................................101
iv
Writer Job Attributes ..............................................................................................................105
Print Object Attributes............................................................................................................ 105
Copying spooled files.............................................................................................................. 148
Creating new spooled files......................................................................................................150
Generating an SCS data stream..............................................................................................151
Reading spooled files and AFP resources.............................................................................. 152
Reading spooled files using PrintObjectPageInputStream and
PrintObjectTransformedInputStream............................................................................... 152
ProductLicense class.................................................................................................................... 153
ProgramCall class......................................................................................................................... 153
QSYSObjectPathName class........................................................................................................ 155
Record-level access......................................................................................................................156
AS400File................................................................................................................................ 157
KeyedFile................................................................................................................................. 157
SequentialFile......................................................................................................................... 159
AS400FileRecordDescription................................................................................................. 160
Creating and deleting files and members...............................................................................162
Reading and writing records................................................................................................... 164
Locking files.............................................................................................................................165
Using record blocking............................................................................................................. 166
Setting the cursor position......................................................................................................167
Commitment control............................................................................................................... 168
SaveFile class............................................................................................................................... 170
ServiceProgramCall class............................................................................................................. 170
Subsystem class........................................................................................................................... 170
SystemStatus classes...................................................................................................................171
SystemPool class.................................................................................................................... 171
System values............................................................................................................................... 172
Trace class.................................................................................................................................... 174
User and group classes................................................................................................................ 176
UserSpace class............................................................................................................................177
Commtrace classes............................................................................................................................ 177
Commtrace model........................................................................................................................ 178
Format and FormatProperties classes.........................................................................................179
Running Format as a standalone program............................................................................. 180
Prolog class...................................................................................................................................181
Frame class...................................................................................................................................181
LanHeader class........................................................................................................................... 182
IPPacket class.............................................................................................................................. 182
Header class................................................................................................................................. 183
Example: Using the commtrace classes...................................................................................... 184
HTML Classes..................................................................................................................................... 185
BidiOrdering class.........................................................................................................................186
HTMLAlign class........................................................................................................................... 186
HTMLDocument class...................................................................................................................187
Using HTMLDocument to create HTML data.......................................................................... 188
Using HTMLDocument to create XSL FO data........................................................................ 189
Examples: Using HTMLDocument.......................................................................................... 191
HTML form classes....................................................................................................................... 195
FormInput classes.................................................................................................................. 196
LayoutFormPanel class........................................................................................................... 199
TextAreaFormElement class...................................................................................................201
LabelFormElement class.........................................................................................................201
SelectFormElement class....................................................................................................... 202
SelectOption class.................................................................................................................. 202
RadioFormInputGroup class...................................................................................................203
HTMLHead class........................................................................................................................... 203
HTMLHeading class...................................................................................................................... 204
v
HTMLHyperlink class.................................................................................................................... 205
HTMLImage class......................................................................................................................... 205
HTMLList classes.......................................................................................................................... 206
HTMLMeta class............................................................................................................................208
HTMLParameter class...................................................................................................................209
HTMLServlet class........................................................................................................................ 209
HTML Table classes...................................................................................................................... 210
HTMLTableCell class............................................................................................................... 210
HTMLTableRow class.............................................................................................................. 211
HTMLTableHeader class..........................................................................................................211
HTMLTableCaption class......................................................................................................... 212
HTML Text class............................................................................................................................ 212
HTMLTree classes......................................................................................................................... 212
HTMLTreeElement class..........................................................................................................213
FileTreeElement class............................................................................................................. 214
FileListElement class.............................................................................................................. 214
FileListRenderer class.............................................................................................................215
ReportWriter classes..........................................................................................................................216
Context classes.............................................................................................................................216
JSPReportProcessor class............................................................................................................217
XSLReportProcessor class............................................................................................................217
Security classes..................................................................................................................................218
Secure Sockets Layer................................................................................................................... 218
Using SSL to encrypt data between IBM Toolbox for Java and IBM i servers.......................218
Authentication services................................................................................................................219
Servlet classes................................................................................................................................... 221
Authentication classes................................................................................................................. 222
RowData class...............................................................................................................................222
ListRowData class................................................................................................................... 223
RecordListRowData class........................................................................................................223
ResourceListRowData class....................................................................................................224
SQLResultSetRowData class...................................................................................................224
RowMetaData classes.................................................................................................................. 225
ListMetaData class.................................................................................................................. 225
RecordFormatMetaData class................................................................................................ 225
SQLResultSetMetaData class................................................................................................. 226
Converter classes......................................................................................................................... 226
StringConverter class.............................................................................................................. 226
HTMLFormConverter class......................................................................................................226
HTMLTableConverter class..................................................................................................... 227
Utility classes..................................................................................................................................... 227
Client installation and update classes......................................................................................... 227
AS400ToolboxJarMaker............................................................................................................... 228
Components supported by IBM Toolbox for Java.................................................................. 229
CCSID and encoding values supported by IBM Toolbox for Java..........................................231
CommandHelpRetriever class......................................................................................................235
CommandPrompter class............................................................................................................. 236
RunJavaApplication......................................................................................................................237
JPing..............................................................................................................................................237
IBM Toolbox for Java beans.................................................................................................................... 238
JDBC.........................................................................................................................................................238
Enhancements to IBM Toolbox for Java JDBC support for IBM i 7.2............................................... 239
Enhancements to IBM Toolbox for Java JDBC support for IBM i 7.1............................................... 239
Enhancements to IBM Toolbox for Java JDBC support for IBM i 6.1............................................... 242
Enhancements to IBM Toolbox for Java JDBC support for IBM i 5.4............................................... 246
IBM Toolbox for Java JDBC properties..............................................................................................247
JDBC Librarylist property............................................................................................................. 265
JDBC SQL Types................................................................................................................................. 267
vi
Proxy Support.......................................................................................................................................... 267
Secure Sockets Layer and Java Secure Socket Extension..................................................................... 273
Extensible Markup Language components............................................................................................. 273
Program Call Markup Language......................................................................................................... 273
Requirements for using PCML...................................................................................................... 273
Building IBM i program calls with PCML...................................................................................... 274
PCML syntax..................................................................................................................................278
PCML program tag...................................................................................................................278
PCML struct tag....................................................................................................................... 281
PCML data tag......................................................................................................................... 287
Record Format Markup Language......................................................................................................301
Requirements for using RFML...................................................................................................... 302
Example: Using RFML compared to using IBM Toolbox for Java Record classes.......................302
RecordFormatDocument class.....................................................................................................303
Record format documents and RFML syntax...............................................................................304
RFML document type definition (DTD)................................................................................... 305
The RFML data tag.................................................................................................................. 306
The RFML rfml tag................................................................................................................... 310
The RFML recordformat tag.................................................................................................... 310
The RFML struct tag................................................................................................................ 311
XML parser and XSLT processor........................................................................................................ 311
Extensible Program Call Markup Language....................................................................................... 312
Advantages of XPCML over PCML................................................................................................ 312
Requirements for using XPCML....................................................................................................313
XPCML schema and syntax...........................................................................................................314
Comparison of XPCML source to PCML source...................................................................... 314
Schema xpcml.xsd file............................................................................................................ 315
XPCML syntax..........................................................................................................................328
XPCML tag attributes.............................................................................................................. 329
Using XPCML................................................................................................................................. 331
Converting existing PCML to XPCML.......................................................................................331
Using XPCML to call a program on your server...................................................................... 332
Obtaining program call results as XPCML.............................................................................. 333
Passing in parameter values as XPCML..................................................................................334
Using condensed XPCML........................................................................................................ 334
Identifying parse errors in XPCML.......................................................................................... 335
Frequently asked questions (FAQ).......................................................................................................... 335
Tips for programming.............................................................................................................................. 336
Shutting down your Java program..................................................................................................... 336
Integrated file system path names for server objects...................................................................... 336
Managing connections in Java programs.......................................................................................... 338
IBM i Java virtual machine.................................................................................................................344
Comparing the IBM i Java virtual machine and the IBM Toolbox for Java classes.................... 344
Running IBM Toolbox for Java classes on the IBM i Java virtual machine................................. 345
Setting system name, user ID, and password with an AS400 object in the IBM i Java virtual
machine................................................................................................................................... 346
Independent auxiliary storage pool (ASP)........................................................................................ 348
Exceptions.......................................................................................................................................... 348
Trace class..........................................................................................................................................349
IBM i optimization.............................................................................................................................. 351
Performance improvements.............................................................................................................. 353
Client installation and update classes...............................................................................................354
AS400ToolboxJarMaker.....................................................................................................................354
Java national language support.........................................................................................................356
Service and support for the IBM Toolbox for Java............................................................................ 356
Code examples........................................................................................................................................ 357
Examples: Access classes................................................................................................................. 357
Examples: JavaBeans........................................................................................................................ 434
vii
Examples: Commtrace classes..........................................................................................................441
Examples from the HTML classes......................................................................................................441
Examples: Program Call Markup Language (PCML).......................................................................... 461
Examples: ReportWriter classes........................................................................................................469
Examples: RFML.................................................................................................................................483
Example: Using a profile token credential to swap the IBM i thread identity.................................. 484
Examples from the servlet classes....................................................................................................485
Simple programming examples......................................................................................................... 508
Examples: Tips for programming.......................................................................................................520
Examples: Utility classes................................................................................................................... 521
Examples: XPCML.............................................................................................................................. 522
Related information for IBM Toolbox for Java........................................................................................ 533
Notices..............................................................................................................537
Programming interface information........................................................................................................ 538
Trademarks.............................................................................................................................................. 538
Terms and conditions.............................................................................................................................. 539
viii
IBM Toolbox for Java
IBM® Toolbox for Java™ is a set of Java classes that allow you to use Java programs to access data on your
system. You can use these classes to write client/server applications, applets, and servlets that work with
data on your system. You can also run Java applications that use the IBM Toolbox for Java classes on the
IBM i Java virtual machine (JVM).
IBM Toolbox for Java uses the IBM i Host Servers as access points to the system. Because IBM Toolbox
for Java uses communication functions built into Java, you do not need to use IBM i Access for Windows
to use IBM Toolbox for Java. Each server runs in a separate job on the server, and each server job sends
and receives data streams on a socket connection.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 534.
Other information
You can also download a zipped package of the IBM Toolbox for Java topic that includes the Javadocs at
the IBM Toolbox for Java and JTOpen Web site .
Note: The information in the zipped package has links to documents that are not included in the zipped
package, so these links do not work.
To use the command line to enable the QUSER profile, complete the following steps:
1. Type CHGUSRPRF USRPRF(QUSER) and press ENTER.
2. Change the Status field to *ENABLED and press ENTER.
The QUSER user profile is now ready to start the IBM i Host Servers.
Using IBM Toolbox for Java to connect from a client back to the server
You can use different versions of IBM Toolbox for Java on a client and on the server to which you are
connecting. To use IBM Toolbox for Java to access data and resources on an IBM i server, the server to
which you are connecting must be running one of the following:
• IBM i 7.2
• IBM i 7.1
• IBM i 6.1
The following table shows the compatibility requirements for connecting back to different versions of IBM
i.
;C:\jt400\lib\jt400.jar
You also have the option of using the open source version of IBM Toolbox for Java, called JTOpen. For
more information about JTOpen, see the IBM Toolbox for Java and JTOpen Web site .
JAR files
The IBM Toolbox for Java is shipped as a set of JAR files. Each JAR file contains Java packages that
provide specific functions. You can reduce the amount of required storage space by using only the JAR
files required to enable the specific functions that you want.
To use a JAR file, make sure that you include an entry for it in your CLASSPATH.
The following chart indicates which JAR files you must add to your CLASSPATH to use the associated
function or package.
IBM Toolbox for Java package or function JAR files required to be in your CLASSPATH
Access classes jt400.jar (client) or jt400Native.jar (server) Note 1, or
jt400Proxy.jar in a proxy environment
“CommandHelpRetriever class” on page 235 jt400.jar (client) or jt400Native.jar (server) Note 1
and an XML parser and XSLT processor Note 3
CommandPrompter Note 3 jt400.jar, jui400.jar, util400.jar Note 4, and an XML
parser Note 3
Commtrace classes jt400.jar (client) or jt400Native.jar (server) Note 1
HTML classes jt400.jar Note 1 plus jt400Servlet.jar (client), or
jt400Native.jar (server) Note 1
HTMLDocument class The same JAR files required for HTML classes, plus
an XML parser and XSLT processor Note 3
JCA classes jt400.jar (client) or jt400Native.jar (server) Note 1
Note 1: Do not put both jt400.jar and jt400Native.jar in your CLASSPATH. Choose the JAR file most
appropriate for your environment and use only that JAR in your CLASSPATH.
Note 2: Some of the IBM Toolbox for Java classes are in more than one JAR file:
• jt400.jar - Access, commtrace, JCA, JDBC support, PCML, RFML, security, utilities, and XPCML.
• jt400.zip - Use jt400.jar instead of jt400.zip. jt400.zip is shipped to retain compatibility with previous
releases of IBM Toolbox for Java.
• jt400Access.zip - The same classes that are in jt400.jar. jtAccess400.zip is shipped to retain
compatibility with previous releases of IBM Toolbox for Java. Use jt400.jar or jt400Native.jar instead
of jt400Access.zip.
• jt400Native.jar - Access, HTML, PCML, RFML, security, XPCML, and native optimizations. Native
optimizations is a set of classes (fewer than 20) that take advantage of IBM i function when running
on the IBM i JVM. Because jt400Native.jar contains the native optimizations, when running on theIBM
i JVM, use jt400Native.jar instead of jt400.jar. jt400Native.jar ships with IBM i and resides in directory /
QIBM/ProdData/OS400/jt400/lib.
• jt400Native11x.jar - Use jt400Native.jar instead of jt400Native11x.jar. jt400Native11x.jar is shipped to
retain compatibility with previous releases of IBM Toolbox for Java.
Note 3: When you must use an XML parser or XSLT processor, make sure that they are JAXP-compliant.
For more information, see the following page:
“XML parser and XSLT processor” on page 311
Note 4: Using CommandPrompter or the IBM i Debugger also requires one additional JAR file that is
not part of IBM Toolbox for Java: jhall.jar. For more information about downloading jhall.jar, see the Sun
JavaHelp Web site .
Note 5: util400.jar contains IBM i-specific classes for formatting input and for using the command line
prompter. Using the CommandPrompter class requires util400.jar.
Note 6: jui400.jar contains the classes necessary to use the JDBC DataSource GUI interface. jt400.jar
( Note 1) contains the classes necessary for all other JDBC functions.
System properties
You can specify system properties to configure various aspects of the IBM Toolbox for Java.
For example, you can use system properties to define a proxy server or a level of tracing. System
properties are useful for convenient runtime configuration without needing to recompile code. System
properties work like environment variables in that when you change a system property during runtime, the
change is generally not reflected until the next time you run the application.
There are several ways that you can set system properties:
• Using the java.lang.System.setProperties() method
You can set system properties programmatically by using the java.lang.System.setProperties() method.
For example, the following code sets the com.ibm.as400.access.AS400.proxyServer property to
hqoffice:
com.ibm.as400.access.AS400.proxyServer=hqoffice
The backslash character (\) functions as an escape character in properties files. Specify a literal
backslash character by using two backslashes (\\).
Modify this sample of a jt400.properties file for your environment.
• Using a Properties class
Some browsers do not load properties files without explicitly changing security settings. However, most
browsers do allow properties in .class files, so IBM Toolbox for Java system properties can also be
specified by a class called com.ibm.as400.access.Properties which extends java.util.Properties.
For example, to set the com.ibm.as400.access.AS400.proxyServer property to hqoffice, use
the following Java code:
package com.ibm.as400.access;
Modify and compile this sample of a Properties.java source file for your environment.
If an IBM Toolbox for Java system property is set using more than one of the mechanisms described
above, then the precedence is as follows (in order of decreasing precedence):
1. The system property set programmatically using java.lang.System.setProperties()
2. The system property set using the -D option of the java command
3. The system property set using a Properties class
4. The system property set using a jt400.properties file
IBM Toolbox for Java supports the following system properties:
• “Proxy server properties” on page 11
• “Trace properties” on page 11
• “CommandCall/ProgramCall properties” on page 11
• “FTP properties” on page 12
• “Connection properties” on page 12
hostName:portNumber
Trace properties
Trace property Description
com.ibm.as400.access.Trace.category Specifies which trace categories to enable. This is a
comma-delimited list containing any combination of
trace categories. The complete list of trace categories
is defined in the Trace class.
com.ibm.as400.access.Trace.file Specifies the file to which trace output is written. The
default is to write trace output to System.out.
com.ibm.as400.access.ServerTrace.JDBC Specifies which trace categories to start on the JDBC
server job. For information about supported values,
see the JDBC server trace property.
CommandCall/ProgramCall properties
CommandCall/ProgramCall property Description
com.ibm.as400.access.CommandCall.threadSafe Specifies whether CommandCalls might be assumed
to be thread-safe. If true, all CommandCalls
are assumed to be thread-safe. If false, all
CommandCalls are assumed to be non-thread-safe.
This property is ignored for a given CommandCall
object if either CommandCall.setThreadSafe()
or AS400.setMustUseSockets(true) has been
performed on the object.
FTP properties
FTP property Description
com.ibm.as400.access.FTP.reuseSocket Specifies whether the socket is reused for multiple
file transfers (through a single FTP instance), when
in "active" mode. If true, the socket is reused. If
false, a new socket is created for each file transfer.
This property is ignored for a given FTP object if
FTP.setReuseSocket() has been performed on the
object.
Connection properties
Connection property Description
com.ibm.as400.access.AS400.guiAvailable Indicates whether the current environment has GUI
capability. If true, prompting may occur during signon
to display error conditions, to prompt for additional
information, or to prompt for change password. If
false, error conditions or missing information will
result in exceptions. Applications that are running as
IBM i applications or want to control the signon user
interface may want to run with prompting mode set to
false. The default is true.
com.ibm.as400.access.AS400.mustAddLanguageLibr Indicates whether AS400 objects should attempt to
ary add the appropriate secondary language library to
the library list when running on the system. Setting
the language library will ensure that any system
error messages that are returned, will be returned
in the appropriate national language for the client
locale. If true, AS400 objects will attempt to add
the secondary language library to the library list when
running on the system. If false, no attempt is made
by AS400 objects to add the secondary language
library to the library list. The default is false.
com.ibm.as400.access.AS400.mustUseNetSockets Specifies whether AS400 objects should use Internet
domain sockets only. When your Java program runs
on the system, some IBM Toolbox for Java classes
create UNIX domain socket connections. If true,
only Internet domain sockets will be used by AS400
objects. If false, AS400 objects may use UNIX
domain socket connections in addition to Internet
domain sockets. The default is false.
#=========================================================#
# IBM Toolbox for Java #
#---------------------------------------------------------#
# Sample properties file #
# #
# Name this file jt400.properties and store it in a #
# com/ibm/as400/access directory that is pointed to by #
# the classpath. #
#=========================================================#
#---------------------------------------------------------#
# Proxy server system properties #
#---------------------------------------------------------#
#---------------------------------------------------------#
# Trace system properties #
#---------------------------------------------------------#
#---------------------------------------------------------#
# Command Call system properties #
#---------------------------------------------------------#
#---------------------------------------------------------#
# Program Call system properties #
#---------------------------------------------------------#
#---------------------------------------------------------#
# FTP system properties #
#---------------------------------------------------------#
#---------------------------------------------------------#
# Connection system properties #
#---------------------------------------------------------#
//=========================================================
// IBM Toolbox for Java
//---------------------------------------------------------
// Sample properties class source file
//
// Compile this source file and store the class file in
// the classpath.
//=========================================================
package com.ibm.as400.access;
/*---------------------------------------------------------*/
/* Trace system properties */
/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
/* Command Call system properties */
/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
/* Program Call system properties */
/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
/* FTP system properties */
/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
/* Connection system properties */
/*---------------------------------------------------------*/
}
}
JTOpenLite
The JTOpenLite package (com.ibm.jtopenlite) enables you to write Java programs that allow a variety of
mobile devices to directly access IBM i data and resources. Although JTOpenLite is considered a part of
IBM Toolbox for Java, it is not included in the licensed product. The JTOpenLite jar file (jtopenlite.jar)
is included in the open source version of IBM Toolbox for Java, called JTOpen. You must separately
download and set up JTOpenLite, which is contained in JTOpen.
Access classes
The IBM Toolbox for Java access classes represent IBM i data and resources.
Related information
EventLog classes Javadoc
Access package summary
The default user ID information is discarded when the last AS400 object for the server is garbage
collected.
SecureAS400 class
The SecureAS400 class enables you to use an AS400 object when sending or receiving encrypted data.
When an AS400 object communicates with the server, user data (except the user password) is sent
unencrypted to the server. So, IBM Toolbox for Java objects associated with an AS400 object exchange
data with the server over a normal connection.
When you want to use IBM Toolbox for Java to exchange sensitive data with the server, you can encrypt
data by using Secure Sockets Layer (SSL). Use the SecureAS400 object to designate which data you want
to encrypt. IBM Toolbox for Java objects associated with a SecureAS400 object exchange data with the
server over a secure connection.
For more information, see Secure Sockets Layer and Java Secure Socket Extension.
The SecureAS400 class is a subclass of the AS400 class.
You can set up a secure server connection by creating an instance of a SecureAS400 object in the
following ways:
• SecureAS400(String systemName, String userID) prompts you for sign-on information
• SecureAS400(String systemName, String userID, String password) does not prompt you for sign-on
information
The following example shows you how to use CommandCall to send commands to the server using a
secure connection:
// Create a secure AS400 object. This is the only statement that changes
// from the non-SSL case.
SecureAS400 sys = new SecureAS400("mySystem.myCompany.com");
Related information
SecureAS400 Javadoc
AS400 Javadoc
Related information
AS400JPing class
BidiTransform class
The IBM Toolbox for Java BidiTransform class provides layout transformations that enable you to convert
bidirectional text in IBM i format (after first converting it to Unicode) to bidirectional text in Java format, or
from Java format to IBM i format.
AS400BidiTransform class
The AS400BidiTransform class allows you to:
• Get and set the system CCSID
• Get and set the string type of IBM i data
• Get and set the string type of Java data
• Convert data from a Java layout to IBM i
• Convert data from an IBM i layout to Java
Note: Read the Code example disclaimer for important legal information.
BidiConversionProperties class
The BidiConversionProperties class provides a set of properties that can be used to control the conversion
of character set data.
Related information
BidiConversionProperties Javadoc
ClusteredHashTable classes
The IBM Toolbox for Java ClusteredHashTable classes enable your Java programs to use highly available
clustered hash tables to share and replicate data to nonpersistent storage among the nodes in a cluster.
To use the ClusteredHashTable classes, ensure that you can use nonpersistent storage for the data.
Replicated data is not encrypted.
Note: The following information assumes that you understand the concepts and terminology common to
IBM i cluster technology. See IBM i cluster technology for details.
Using the ClusteredHashTable class requires that you have defined and activated a cluster on the
systems. You must also start a clustered has table server. For more information, see Configure clusters
and Clustered Hash Table APIs.
Required parameters are the name of the clustered hash table server and the AS400 object, which
represents the system that contains the clustered hash table server.
In order to store data in a clustered hash table server, you need a connection handle and a key:
• When you open a connection, the clustered hash table server assigns the connection handle that you
must specify on subsequent requests to the clustered hash table server. This connection handle is good
only for the instantiated AS400 object, so you must open another connection if you use a different
AS400 object.
• You must specify the key to access and change data in the clustered hash table. Duplicate keys are not
supported.
The ClusteredHashTable class provides methods that enable you to perform the following actions:
• Open a connection to the clustered hash table server job
• Generate a unique key to store data into the clustered hash table
• Close the active connection to the clustered hash table server job
Some methods in the ClusteredHashTable class use the ClusteredHashTableEntry class to perform the
following actions:
• Get an entry from the clustered hash table
• Store an entry in the clustered hash table
• Get a list of entries from the clustered hash table for all user profiles
// Prepare some data that you want to store into the hash table.
// ENTRY_AUTHORITY_ANY_USER means that any user can access the
// entry in the clustered hash table.
// DUPLICATE_KEY_FAIL means that if the specified key already exists,
// the ClusteredHashTable.put() request will not succeed.
int timeToLive = 500;
myEntry = new ClusteredHashTableEntry(key,myData.getBytes(),timeToLive,
ClusteredHashTableEntry.ENTRY_AUTHORITY_ANY_USER,
ClusteredHashTableEntry.DUPLICATE_KEY_FAIL);
Using the ClusteredHashTable class causes the AS400 object to connect to the server. For more
information, see Managing connections.
CommandCall class
The CommandCall class allows a Java program to call a non-interactive IBM i command.
Results of the command are available in a list of AS400Message objects.
Input to CommandCall is as follows:
• The command string to run
• The AS400 object that represents the system that will run the command
The command string can be set on the constructor, through the CommandCall setCommand() method, or
on the run() method. After the command is run, the Java program can use the getMessageList() method to
retrieve any IBM i messages resulting from the command.
Using the CommandCall class causes the AS400 object to connect to the system. See managing
connections for information about managing connections.
When the Java program and the IBM i command are on the same server, the default IBM Toolbox for
Java behavior is to look up the thread safety for the command on the system. If threadsafe, the command
is run on-thread. You can suppress the run-time lookup by explicitly specifying thread-safety for the
command by using the setThreadSafe() method.
Examples
The following examples show ways you can use the CommandCall class to run different kinds of
commands.
Note: Read the Code example disclaimer for important legal information.
Example: Running a command
The following example shows how to use the CommandCall class to run a command on the system:
Connection pooling
Use connection pools to share connections and manage sets (pools) of connections to an IBM i system.
For example, an application can retrieve a connection from a pool, use it, then return it to the pool for
reuse.
The AS400ConnectionPool class manages a pool of AS400 objects. The AS400JDBCConnectionPool class
represents a pool of AS400JDBCConnections that are available for use by a Java program as part of IBM
Toolbox for Java support for the JDBC 2.0 Optional Package API. The JDBC ConnectionPool interface is
also supported in the JDBC 3.0 API, which is bundled with the Java 2 Platform, Standard Edition, version
1.4.
A connection pool of either type keeps track of the number of connections it creates. Using methods
inherited from ConnectionPool, you can set several connection pool properties, including:
• the maximum number of connections that can be given out by a pool
• the maximum lifetime of a connection
• the maximum inactivity time of a connection
In terms of performance, connecting to the server is an expensive operation. Using connection pools
can improve performance by avoiding repeated connection times. For example, create connections when
you create the connection pool by filling the pool with active (preconnected) connections using the
AS400ConnectionPool class. Instead of creating new connections, you can use a connection pool to easily
retrieve, use, return, and reuse the connection objects.
Retrieve a connection using an AS400ConnectionPool by specifying the system name, user id, the
password, and (optionally) the service. To specify the service to which you want to connect, use constants
from the AS400 class (FILE, PRINT, COMMAND, and so on).
After retrieving and using the connection, applications return connections to the pool. It is the
responsibility of each application to return connections to the pool for reuse. When connections are not
returned to the pool, the connection pool continues to grow in size and connections are not reused.
See managing connections for more information about managing when a connection to the system is
opened when using the AS400ConnectionPool classes.
CharacterDataArea
The CharacterDataArea class represents a data area on the server that contains character data. Character
data areas do not have a facility for tagging the data with the proper CCSID; therefore, the data area
object assumes that the data is in the user's CCSID. When writing, the data area object converts from a
string (Unicode) to the user's CCSID before writing the data to the server. When reading, the data area
object assumes that the data is the CCSID of the user and converts from that CCSID to Unicode before
returning the string to the program. When reading data from the data area, the amount of data read is by
number of characters, not by the number of bytes.
Using the CharacterDataArea class, you can do the following:
• Clear the data area so that it contains all blanks.
• Create a character data area on the system using default property values
• Create a character data area with specific attributes
• Delete the data area from the system where the data area exists
• Return the IFS path name of the object represented by the data area.
• Read all of the data that is contained in the data area
• Read a specified amount of data from the data area starting at offset 0 or the offset that you specified
• Set the fully qualified integrated file system path name of the data area
• Write data to the beginning of the data area
• Write a specified amount of data to the data area starting at offset 0 or the offset that you specified
DecimalDataArea
The DecimalDataArea class represents a data area on the server that contains decimal data.
Using the DecimalDataArea class, you can do the following:
• Clear the data area so that it contains 0.0
• Create a decimal data area on the system using default property values
• Create a decimal data area with specified attributes
• Delete the data area from the server where the data area exists
• Return the number of digits to the right of the decimal point in the data area
• Return the IFS path name of the object represented by the data area.
• Read all of the data that is contained in the data area
LocalDataArea
The LocalDataArea class represents a local data area on the server. A local data area exists as a character
data area on the server, but the local data area does have some restrictions of which you should be aware.
The local data area is associated with a server job and cannot be accessed from another job. Therefore,
you cannot create or delete the local data area. When the server job ends, the local data area associated
with that server job is automatically deleted, and the LocalDataArea object that is referring to the job is no
longer valid. You should also note that local data areas are a fixed size of 1024 characters on the server.
Using the LocalDataArea class, you can do the following:
• Clear the data area so that it contains all blanks
• Read all of the data that is contained in the data area
• Read a specified amount of data from the data area starting at offset that you specified
• Write data to the beginning of the data area
• Write a specified amount of data to the data area where the first character is written to offset
LogicalDataArea
The LogicalDataArea class represents a data area on the server that contains logical data.
Using the LogicalDataArea class, you can do the following:
• Clear the data area so that it contains false
• Create a character data area on the server using default property values
• Create a character data area with specified attributes
• Delete the data area from the server where the data area exists
• Return the IFS path name of the object represented by the data area.
• Read all of the data that is contained in the data area
• Set the fully qualified integrated file system path name of the data area
• Write data to the beginning of the data area
DataAreaEvent
The DataAreaEvent class represents a data area event.
DataAreaListener
The DataAreaListener class provides an interface for receiving data area events.
You can use the the DataAreaListener class with any of the DataArea classes. You can invoke the
DataAreaListener class when any of the following are performed:
• Clear
• Create
• Delete
• Read
• Write
DataArea Javadoc
CharacterDataArea Javadoc
DecimalDataArea Javadoc
LocalDataArea Javadoc
LogicalDataArea Javadoc
DataAreaEvent Javadoc
DataAreaListener Javadoc
Data types
The AS400DataType is an interface that defines the methods required for data conversion. A Java
program uses data types when individual pieces of data need to be converted. Conversion classes exist
for the following types of data:
• Numeric
• Text (character)
• Composite (numeric and text)
Example: Using AS400DataType classes
The following example illustrates using AS400DataType classes with ProgramCall to supply data for
program parameters and to interpret the data returned in program parameters.
Example: Using AS400DataType classes with ProgramCall
Examples
The following examples show data conversions that use a numeric type in the system format and a Java
int:
Example: Converting from the system format to a Java int
// Create a buffer to hold the system data type. Assume the buffer is
// filled with numeric data in the system format by data queues,
// program call, and so on.
byte[] data = new byte[100];
// Convert from system type to Java object. The number starts at the
// beginning of the buffer.
Integer intObject = (Integer) bin4Converter.toObject(data,0);
// Find out how many bytes of the buffer were filled with the
// system value.
int length = bin4Converter.getByteLength();
Text conversion
Character data is converted through the IBM Toolbox for Java AS400Text class. This class converts
character data between an EBCDIC code page and character set (CCSID), and Unicode.
When the AS400Text object is constructed, the Java program specifies the length of the string to be
converted and the server CCSID or encoding. The CCSID of the Java program is assumed to be 13488
Unicode. The toBytes() method converts from Java form to byte array inIBM i format. The toObject()
method converts from a byte array in IBM i format to Java format.
The AS400BidiTransform class provides layout transformations that allow the conversion of bidirectional
text in IBM i format (after its conversion to Unicode) to bidirectional text in Java format, or from Java
format to IBM i format. The default conversion is based on the CCSID of the job. To alter the direction and
shaping of the text, specify a BidiStringType. Note that where IBM Toolbox for Java objects perform the
conversion internally, as in the DataArea class, the objects have a method to override the string type. For
example, the DataArea class has addVetoableChangeListener() method that you can specify to listen for a
veto changes to certain properties, including string type.
// Note: You can also create a converter with just the AS400 object.
// This converter assumes the IBM i code page matches
// the CCSID returned by the AS400 object.
AS400Text textConverter = new AS400Text(textLength, system);
Related information
AS400Text Javadoc
AS400BidiTransform Javadoc
BidiStringType Javadoc
// Create the Java object that holds the data to send to the server.
Object[] myData =
{
new Integer(88), // the four-byte number
new byte[0], // the pad (let the conversion object 0 pad)
new Double(23.45), // the eight-byte floating point number
"This is my structure" // the character string
};
// Pull the third object out of the structure. This is the double.
Double doubleObject = (Double) myRoundTripData[2];
AS400Array Javadoc
AS400Structure Javadoc
FieldDescription classes
The field description classes allow the Java program to describe the contents of a field or parameter
with a data type and a string containing the name of the field. If the program is working with data from
record-level access, it can also specify any IBM i data definition specification (DDS) keywords that further
describe the field.
Field description classes
The field description classes are as follows:
• BinaryFieldDescription
• CharacterFieldDescription
• DateFieldDescription
• DBCSEitherFieldDescription
• DBCSGraphicFieldDescription
• DBCSOnlyFieldDescription
• DBCSOpenFieldDescription
• FloatFieldDescription
• HexFieldDescription
• PackedDecimalFieldDescription
• TimeFieldDescription
• TimestampFieldDescription
• ZonedDecimalFieldDescription
// Create a field description for the numeric data. Note it uses the
// AS400Bin4 data type. It also names the field so it can be accessed by
// name in the record class.
BinaryFieldDescription bfd = new BinaryFieldDescription(new AS400Bin4(), "msgNumber");
// Create a field description for the character data. Note it uses the
// AS400Text data type. It also names the field so it can be accessed by
// name by the record class.
CharacterFieldDescription cfd1 = new CharacterFieldDescription(new AS400Text(8),
"msgTime");
// Create a field description for the character data. Note it uses the
// AS400Text data type. It also names the field so it can be accessed by
// name by the record class.
CharacterFieldDescription cfd2 = new CharacterFieldDescription(new AS400Text(50),
"msgText");
RecordFormat class
The IBM Toolbox for Java RecordFormat class allows the Java program to describe a group of fields or
parameters. A record object contains data described by a RecordFormat object. If the program is using
record-level access classes, the RecordFormat class also allows the program to specify descriptions for
key fields.
A RecordFormat object contains a set of field descriptions. The field description can be accessed by index
or by name. Methods exist on the RecordFormat class to do the following:
• Add field descriptions to the record format.
• Add key field descriptions to the record format.
• Retrieve field descriptions from the record format by index or by name.
• Retrieve key field descriptions from the record format by index or by name.
• Retrieve the names of the fields that make up the record format.
• Retrieve the names of the key fields that make up the record format.
• Retrieve the number of fields in the record format.
• Retrieve the number of key fields in the record format.
• Create a Record object based on this record format.
To see how to create a record from the record format, see the example on the following page:
“Record class” on page 35
RecordFormat Javadoc
Record class
The IBM Toolbox for Java record class allows the Java program to process data described by the record
format class.
Data is converted between byte arrays containing the server data and Java objects. Methods are provided
in the record class to do the following:
• Retrieve the contents of a field, by index or by name, as a Java object.
• Retrieve the number of fields in the record.
• Set the contents of a field, by index or by name, with a Java object.
• Retrieve the contents of the record as server data into a byte array or output stream.
• Set the contents of the record from a byte array or an input stream.
• Convert the contents of the record to a String.
// Assume data queue setup work has already been done. Now read a
// record from the data queue.
DataQueueEntry dqe = dq.read();
// The data from the data queue is now in a data queue entry. Get
// the data out of the data queue entry and put it in the record.
// We obtain a default record from the record format object and
// initialize it with the data from the data queue entry.
Record dqRecord = rf.getNewRecord(dqe.getData());
// Now that the data is in the record, pull the data out one
// field at a time, converting the data as it is removed. The result
// is data in a Java object that the program can now process.
Integer msgNumber = (Integer) dqRecord.getField("msgNumber");
String msgTime = (String) dqRecord.getField("msgTime");
String msgText = (String) dqRecord.getField("msgText");
Related information
Record Javadoc
Related information
Record Javadoc
Related information
Record Javadoc
LineDataRecordWriter class
The LineDataRecordWriter class writes the record data, in line data format, to an OutputStream. The class
translates the data into bytes by using the specified CCSID. The record format associated with the record
determines the format of the data.
LineDataRecordWriter
Using LineDataRecordWriter requires that the following record format attributes be set:
• Record format ID
• Record format type
In conjunction with the Record or the RecordFormat classes, the LineDataRecordWriter takes a record as
input to the writeRecord() method. (Record takes a RecordFormat as input when you instantiate it.)
The LineDataRecordWriter class provides methods that allow you to:
• Get the CCSID
• Get the name of the encoding
• Write the record data, in line data format, to an OutputStream
SpooledFileOutputStream os = null;
try {
// create the output spooled file to hold the record data
os = new SpooledFileOutputStream(system_, parms, null, outQ);
}
catch (Exception e) {
System.out.println("Error occurred creating spooled file");
e.printStackTrace();
}
catch(Exception e)
{
failed(e, "Exception occurred.");
}
LineDataRecordWriter Javadoc
Record Javadoc
RecordFormat Javadoc
Data queues
The DataQueue classes allow the Java program to interact with server data queues.
IBM i data queues have the following characteristics:
• The data queue allows for fast communications between jobs. Therefore, it is an excellent way to
synchronize and pass data between jobs.
• Many jobs can simultaneously access the data queues.
• Messages on a data queue are free format. Fields are not required as they are in database files.
• The data queue can be used for either synchronous or asynchronous processing.
• The messages on a data queue can be ordered in one the following ways:
– Last-in first-out (LIFO). The last (newest) message that is placed on the data queue is the first
message that is taken off the queue.
– First-in first-out (FIFO). The first (oldest) message that is placed on the data queue is the first
message that is taken off the queue.
– Keyed. Each message on the data queue has a key associated with it. A message can be taken off the
queue only by specifying the key that is associated with it.
Related information
BaseDataQueue Javadoc
DataQueue Javadoc
KeyedDataQueue Javadoc
DataQueueEntry Javadoc
KeyedDataQueueEntry Javadoc
Digital certificates
Digital certificates are digitally-signed statements used for secured transactions over the internet.
To make a secure connection using the Secure Sockets Layer (SSL), a digital certificate is required.
Digital certificates comprise the following:
• The public encryption key of the user
• The name and address of the user
• The digital signature of a third-party certification authority (CA). The authority's signature means that
the user is a trusted entity.
• The issue date of the certificate
• The expiration date of the certificate
As an administrator of a secured server, you can add a certification authority's "trusted root key" to the
server. This means that your server will trust anyone who is certified through that particular certification
authority.
Digital certificates also offer encryption, ensuring a secure transfer of data through a private encryption
key.
You can create digital certificates through the javakey tool. (For more information about javakey and Java
security, see the Sun Microsystems, Inc., Java Security page .) The IBM Toolbox for Java has classes
that administer digital certificates on the system.
The AS400Certificate classes provide methods to manage X.509 ASN.1 encoded certificates. Classes are
provided to do the following:
• Get and set certificate data.
• List certificates by validation list or user profile.
• Manage certificates, for example, add a certificate to a user profile or delete a certificate from a
validation list.
Using a certificate class causes the AS400 object to connect to the server. See managing connections for
information about managing connections.
On the server, certificates belong to a validation list or to a user profile.
• The AS400CertificateUserProfileUtil class has methods for managing certificates on a user profile.
• The AS400CertificateVldlUtil class has methods for managing certificates in a validation list.
Using AS400CertificateUserProfileUtil and AS400CertificateVldlUtil requires that you install base
operating system option 34 (Digital Certificate Manager). These two classes extend AS400CertificateUtil,
which is an abstract base classes that defines methods common to both subclasses.
The AS400Certificate class provides methods to read and write certificate data. Data is accessed as an
array of bytes. The Java.Security package in Java virtual machine 1.2 provides classes that can be used to
get and set individual fields of the certificate.
Listing certificates
To get a list of certificates, the Java program must do the following:
1. Create an AS400 object.
2. Construct the correct certificate object. Different objects are used for listing certificates on
a user profile (AS400CertificateUserProfileUtil) versus listing certificates in a validation list
(AS400CertificateVldlUtil).
// Retrieve the list that matches the criteria. User space "myspace"
// in library "mylib" will be used for storage of the certificates.
// The user space must exist before calling this API.
int count = certificateList.listCertificates(attributeList, "/QSYS.LIB/MYLIB.LIB/
MYSPACE.USRSPC");
AS400CertificateUserProfileUtil Javadoc
AS400CertificateVldUtil Javadoc
AS400CertificateAttribute Javadoc
EnvironmentVariable class
The IBM Toolbox for Java EnvironmentVariable class and the EnvironmentVariableList class enable you to
access and set IBM i system-level environment variables.
Each variable has unique identifiers: the system name and the environment variable name. Each
environment variable is associated with a CCSID, which is by default the CCSID of the current job, which
describes where the contents of the variable are stored.
Note: Environment variables are different than system values, although they are often used for the same
purpose. See SystemValues for more information on how to access system values.
Use an EnvironmentVariable object to perform the following actions on an environment variable:
• Get and set the name
• Get and set the system
• Get and set the value (which allows you to change the CCSID)
• Refresh the value
// Create the background color environment variable and get its value.
EnvironmentVariable bg = new EnvironmentVariable(system, "BACKGROUND");
String background = bg.getValue();
EnvironmentVariable Javadoc
EnvironmentVariableList Javadoc
Exceptions
The IBM Toolbox for Java access classes throw exceptions when device errors, physical limitations,
programming errors, or user input errors occur. The exception classes are based upon the type of error
that occurs instead of the location where the error originates.
Most exceptions contain the following information:
• Error type: The exception object that is thrown indicates the type of error that occurred. Errors of the
same type are grouped together in an exception class.
• Error details: The exception contains a return code to further identify the cause of the error that
occurred. The return code values are constants within the exception class.
• Error text: The exception contains a text string that describes the error that occurred. The string is
translated in the locale of the client Java virtual machine.
// All the setup work to delete a file on the server through the
// IFSFile class is done. Now try deleting the file.
try
{
aFile.delete();
// Get the return code out of the exception and display additional
// information based on the return code.
int rc = e.getReturnCode()
switch (rc)
{
case ExtendedIOException.FILE_IN_USE:
System.out.println("Delete failed, file is in use "):
break;
case ExtendedIOException.PATH_NOT_FOUND:
System.out.println("Delete failed, path not found ");
break;
default:
System.out.println("Delete failed, rc = ");
System.out.println(rc);
}
}
FileAttributes class
The IBM Toolbox for Java FileAttributes class represents the set of file attributes that can be retrieved and
set through the Get Attributes (Qp0lGetAttr) and Set Attributes (Qp0lSetAttr) APIs.
To obtain the attributes of an object, the object must exist and the caller must have authority to it.
Only attributes supported by the specific file system, object type, and system operating release can be
retrieved or set.
You can find a complete list of the available attributes in the FileAttributes Javadoc.
Related information
FileAttributes Javadoc
Get Attributes (Qp0lGetAttr) API
Set Attributes (Qp0lSetAttr) API
FTP class
The IBM Toolbox for Java FTP class provides a programmable interface to FTP functions.
You are no longer required to use java.runtime.exec() or tell your users to run FTP commands in a
separate application. That is, you can program FTP functions directly into your application. So, from within
your program, you can do the following:
• Connect to an FTP server
• Send commands to the server
• List the files in a directory
• Get files from the server and put files to the server
Example: Using FTP to copy files from a server
Note: Read the Code example disclaimer for important legal information.
For example, with the FTP class, you can copy a set of files from a directory on a server:
client.disconnect();
FTP is a generic interface that works with many different FTP servers. Therefore, it is up to the
programmer to match the semantics of the server.
FTP Javadoc
AS400FTP Javadoc
/DIR1/DIR2/FILE1
IFSFile class
The IBM Toolbox for Java IFSFile class represents an object in the IBM i integrated file system.
The methods on IFSFile represent operations that are done on the object as a whole. You can use
IFSFileInputStream, IFSFileOutputStream, and IFSRandomAccessFile to read and write to the file. The
IFSFile class allows the Java program to do the following:
• Determine if the object exists and is a directory or a file
• Determine if the Java program can read from or write to a file
• Determine the length of a file
• Determine the permissions of an object and set the permissions of an object
• Create a directory
• Delete a file or directory
• Rename a file or directory
• Get or set the last modification date of a file
• List the contents of a directory
• List the contents of a directory and save the attribute information to a local cache
• Determine the amount of space available on the system
• Determine the type of the file object when it is in the QSYS.LIB file system
You can get the list of files in a directory by using either the list() method or the listFiles() method:
• The listFiles() method caches information for each file on the initial call. After calling listFiles(), using
other methods to query file details results in better performance because the information is retrieved
from the cache. For example, calling isDirectory() on an IFSFile object returned from listFiles() does not
require a call to the server.
• The list() method retrieves information about each file in a separate request to the server, making it
slower and more demanding of server resources.
Note: Using listFiles() means that the information in the cache may eventually become stale, so you may
need to refresh the data by calling listFiles() again.
Examples
The following examples show how to use the IFSFile class:
• “Example: Creating a directory” on page 388
• “Example: Using IFSFile exceptions to track errors” on page 388
• “Example: Listing files with a .txt extension” on page 389
• “Example: Using the IFSFile listFiles() method to list the contents of a directory” on page 389
Related information
IFSFile Javadoc
try
{
IFSFileOutputStream os =
new IFSFileOutputStream(file.getSystem(), file, IFSFileOutputStream.SHARE_ALL, false);
byte[] data = new byte[256];
int i = 0;
for (; i < data.length; i++)
{
data[i] = (byte) i;
os.write(data[i]);
}
os.close();
}
catch (Exception e)
{
System.err.println ("Exception: " + e.getMessage());
}
IFSFileInputStream
The IBM Toolbox for Java IFSFileInputStream class represents an input stream for reading data from a file
on the server.
As in the IFSFile class, methods exist in IFSFileInputStream that duplicate the methods in
FileInputStream from the java.io package. In addition to these methods, IFSFileInputStream has
additional methods specific to the IBM i platform. The IFSFileInputStream class allows a Java program to
do the following:
• Open a file for reading. The file must exist since this class does not create files on the server. You can
use a constructor that allows you to specify the file sharing mode.
• Determine the number of bytes in the stream.
• Read bytes from the stream.
• Skip bytes in the stream.
• Lock or unlock bytes in the stream.
• Close the file.
As in FileInputStream in java.io, this class allows a Java program to read a stream of bytes from the file.
The Java program reads the bytes sequentially with only the additional option of skipping bytes in the
stream.
In addition to the methods in FileInputStream, IFSFileInputStream gives the Java program the following
options:
• Locking and unlocking bytes in the stream. See IFSKey for more information.
• Specifying a sharing mode when the file is opened. See sharing modes for more information.
Related information
IFSFileInputStream Javadoc
IFSTextFileInputStream class
IFSTextFileInputStream has been deprecated and replaced by class IFSFileReader.
The IFSTextFileInputStream class represents a stream of character data read from a file. The data read
from the IFSTextFileInputStream object is supplied to the Java program in a Java String object, so it is
always Unicode. When the file is opened, the IFSTextFileInputStream object determines the CCSID of the
Related reference
“IFSFileReader” on page 49
Use this class for reading character files in the integrated file system.
IFSFileReader
Use this class for reading character files in the integrated file system.
IFSFileReader is meant for reading streams of characters. IFSFileReader replaces
IFSTextFileOutputStream.
import java.io.BufferedReader;
Related information
IFSFileReader Javadoc
IFSFileOutputStream class
The IFSFileOutputStream class represents an output stream for writing data to a file on the server.
As in the IFSFile class, methods exist in IFSFileOutputStream that duplicate the methods in
FileOutputStream from the java.io package. IFSFileOutputStream also has additional methods specific
to the server. The IFSFileOutputStream class allows a Java program to do the following:
• Open a file for writing. If the file already exists, it is replaced. Constructors are available that specify the
file sharing mode and whether the contents of an existing file have been appended.
• Write bytes to the stream.
• Commit to disk the bytes that are written to the stream.
• Lock or unlock bytes in the stream.
• Close the file.
IFSFileOutputStream Javadoc
IFSTextFileOutputStream class
IFSTextFileOutputStream has been deprecated and replaced by class IFSFileWriter.
The IFSTextFileOutputStream class represents a stream of character data being written to a file. The data
supplied to the IFSTextFileOutputStream object is in a Java String object so the input is always Unicode.
The IFSTextFileOutputStream object can convert the data to another CCSID as it is written to the file,
however. The default behavior is to write Unicode characters to the file, but the Java program can set
the target CCSID before the file is opened. In this case, the IFSTextFileOutputStream object converts the
characters from Unicode to the specified CCSID before writing them to the file. If the data cannot be
converted, an UnsupportedEncodingException is thrown.
Related reference
“IFSFileWriter” on page 51
IFSFileWriter
Use IFSFileWriter for writing character files in the integrated file system. IFSFileWriter is meant for writing
streams of characters.
IFSFileWriter is the replacement of IFSTextFileOutputStream.
import java.io.PrintWriter;
import java.io.BufferedWriter;
Related information
IFSFileWriter Javadoc
IFSRandomAccessFile
The IBM Toolbox for Java IFSRandomAccessFile class represents a file on the server for reading and
writing data.
The Java program can read and write data sequentially or randomly. As in IFSFile, methods exist in
IFSRandomAccessFile that duplicate the methods in RandomAccessFile from the java.io package. In
addition to these methods, IFSRandomAccessFile has additional methods specific to IBM i. Through
IFSRandomAccessFile, a Java program can do the following:
• Open a file for read, write, or read/write access. The Java program can optionally specify the file sharing
mode and the existence option.
• Read data at the current offset from the file.
• Write data at the current offset to the file.
• Get or set the current offset of the file.
• Close the file.
In addition to the methods in java.io RandomAccessFile, IFSRandomAccessFile gives the Java program
the following options:
• Committing to disk bytes written.
• Locking or unlocking bytes in the file.
• Locking and unlocking bytes in the stream. See IFSKey for more information.
• Specifying a sharing mode when the file is opened. See sharing modes for more information.
• Specify the existence option when a file is opened. The Java program can choose one of the following:
– Open the file if it exists; create the file if it does not.
– Replace the file if it exists; create the file if it does not.
– Fail the open if the file exists; create the file if it does not.
– Open the file if it exists; fail the open if it does not.
– Replace the file if it exists; fail the open if it does not.
Related information
IFSRandomAccessFile Javadoc
IFSKey class
If the Java program allows other programs access to a file at the same time, the Java program can lock
bytes in the file for a period of time. During that time, the program has exclusive use of that section of the
file. When a lock is successful, the integrated file system classes return an IFSKey object.
This object is supplied to the unlock() method to indicate which bytes to unlock. When the file is closed,
the system unlocks all locks that are still on the file (the system does an unlock for every lock that the
program did not unlock).
Related information
IFSKey Javadoc
IFSSystemView
IFSSystemView provides a gateway to the IBM i integrated file system, for use when constructing
javax.swing.JFileChooser objects.
JFileChooser is a standard Java way to build dialogs for navigating and choosing files.
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.IFSJavaFile;
import com.ibm.as400.access.IFSSystemView;
import javax.swing.JFileChooser;
import java.awt.Frame;
Related information
IFSSystemView Javadoc
ISeriesNetServer class
The ISeriesNetServer class represents the NetServer service on a server. This class allows the user to
query and modify the state and configuration of the NetServer.
ISeriesNetServer replaces the NetServer class.
Related information
ISeriesNetServer Javadoc
Example
The example in the JavaApplicationCall Javadoc reference documentation shows how to run a program
on the server (that outputs "Hello World!") from the client:
JavaApplicationCall
Related information
JavaApplicationCall Javadoc
JDBC classes
JDBC is an application programming interface (API) included in the Java platform that enables Java
programs to connect to a wide range of databases.
Supported interfaces
The following table lists the supported JDBC interfaces and the API required to use them:
Related reference
“JDBC” on page 238
JDBC is an application programming interface (API) included in the Java platform that enables Java
programs to connect to a wide range of databases.
“Example: Using JDBCPopulate to create and populate a table” on page 396
This program uses the IBM Toolbox for Java JDBC driver to create and populate a table.
“Example: Using JDBCQuery to query a table” on page 406
This program uses the IBM Toolbox for Java JDBC driver to query a table and output its contents.
Related information
JTOpen: The Open Source version of the IBM Toolbox for Java
AS400JDBCBlob class
You can use a AS400JDBCBlob object to access binary large objects (BLOBs), such as sound byte (.wav)
files or image (.gif) files.
The key difference between the AS400JDBCBlob class and the AS400JDBCBlobLocator class is where
the blob is stored. With the AS400JDBCBlob class, the blob is stored in the database, which inflates the
size of the database file. The AS400JDBCBlobLocator class stores a locator (think of it as a pointer) in the
database file that points to where the blob is located.
With the AS400JDBCBlob class, the lob threshold property can be used. This property specifies the
maximum large object (LOB) size (in kilobytes) that can be retrieved as part of a result set. LOBs that
are larger than this threshold are retrieved in pieces using extra communication to the server. Larger LOB
thresholds reduce the frequency of communication to the server, but they download more LOB data, even
if it is not used. Smaller lob thresholds may increase frequency of communication to the server, but they
only download LOB data as it is needed. See JDBC properties for information about additional properties
that are available.
Using the AS400JDBCBlob class, you can do the following:
• Return the entire blob as a stream of uninterpreted bytes
• Return part of the contents of the blob
• Return the length of the blob
• Create a binary stream to write to the blob
• Write a byte array to the blob
• Write all or a portion of byte array to the blob
• Truncate the blob
Examples
The following examples show how to use the AS400JDBCBlob class to read from a blob and update a
blob:
Example: Using the AS400JDBCBlob class to read from a blob
//Update the blob in the result set, changing the blob starting
// at the seventh byte of the blob (1-based) and truncating the
// blob at the end of the updated bytes (the blob now has 9 bytes).
rs.updateBlob(1, blob);
// Update the database with the change. This will change the blob
// in the database starting at the seventh byte of the blob, and
// truncating at the end of the updated bytes.
rs.updateRow();
rs.close();
CallableStatement interface
Use a CallableStatement object to run SQL stored procedures. The stored procedure being called must
already be stored in the database. CallableStatement does not contain the stored procedure, it only calls
the stored procedure.
A stored procedure can return one or more ResultSet objects and can use IN parameters, OUT
parameters, and INOUT parameters. Use Connection.prepareCall() to create new CallableStatement
objects.
The CallableStatement object allows you to submit multiple SQL commands as a single group to a
database through the use of batch support. You may get better performance by using batch support
because processing a group of operations is usually faster than processing them one at a time.
CallableStatement allows you to get and set parameters and columns by name, although using the
column index results in better performance.
AS400JDBCCallableStatement Javadoc
Examples
The following examples show how to use the AS400JDBCClob class to read from a clob and update a
clob:
Example: Using the AS400JDBCClob class to read from a clob
// Update the database with the updated clob. This will change the
// clob in the database starting at the third character of the clob,
// and truncating at the end of the update string.
rs.updateRow();
rs.close();
AS400JDBCClobLocator class
You can use a AS400JDBCClobLocator object to access character large objects (CLOBs).
Using the AS400JDBCClobLocator class, you can do the following:
AS400JDBCConnection class
The AS400JDBCConnection class provides a JDBC connection to a specific DB2® for IBM i database.
Use DriverManager.getConnection() to create new AS400JDBCConnection objects. For more information,
see “Registering the JDBC driver” on page 71.
There are many optional properties that can be specified when the connection is created. Properties can
be specified either as part of the URL or in a java.util.Properties object. See “IBM Toolbox for Java JDBC
properties” on page 247 for a complete list of properties supported by the AS400JDBCDriver.
Note: A connection may contain at most 9999 open statements.
AS400JDBCConnection includes support for savepoints and statement-level holdability, and limited
support for returning auto-generated keys.
To use Kerberos tickets, set only the system name (and not the password) on your JDBC URL object.
The user identity is retrieved through the Java Generic Security Services (JGSS) framework, so you also
do not need to specify a user on your JDBC URL. You can set only one means of authentication in an
AS400JDBCConnection object at a time. Setting the password clears any Kerberos ticket or profile token.
For more information, see the “AS400 class” on page 19.
Using the AS400JDBCConnection class, you can do the following:
• Create a statement (Statement, PreparedStatement, or CallableStatement objects)
• Create a statement that has a specific result set type and concurrency (Statement, PreparedStatement,
or CallableStatement objects)
• Commit and rollback changes to the database and release database locks currently held
• Close the connection, closing server resources immediately instead of waiting for them to be
automatically released
• Set holdability and get holdability for the Connection
• Set the transaction isolation and get the transaction isolation for the Connection
• Get the meta data for the Connection
• Set auto commit on or off
• Get the job identifier of the host server job that corresponds to the Connection
If you use JDBC 3.0 and connect to a server running IBM i 5.2 or later, you can use
AS400JDBCConnection to perform the following actions:
• Create a statement with a specific result set holdability (Statement, PreparedStatement, or
CallableStatement object)
• Create a prepared statement that returns any auto-generated keys (when getGeneratedKeys() is called
on the Statement object)
• Use savepoints, which offer more granular control over transactions:
– Set savepoints
– Rollback savepoints
AS400JDBCConnectionPool
The AS400JDBCConnectionPool class represents a pool of AS400JDBCConnection objects that are
available for use by a Java program as part of IBM Toolbox for Java support for the JDBC 2.0 Optional
Package API.
You can use an AS400JDBCConnectionPoolDataSource to specify properties for the connections that are
created in the pool, as in the following example.
You cannot change the connection pool data source after you have requested a connection and the pool is
in use. To reset the connection pool data source, first call close() on the pool.
Return connections to an AS400JDBCConnectionPool by using close() on the AS400JDBCConnection
object.
Note: When connections are not returned to the pool, the connection pool continues to grow in size and
connections are not reused.
Set properties on the pool by using methods inherited from ConnectionPool. Some of the properties that
you can set include:
• maximum number of connections to allow in the pool
• maximum lifetime of a connection
• maximum inactivity time of a connection.
You can also register AS400JDBCConnectionPoolDataSource objects by using a Java Naming and
Directory Interface (JNDI) service provider. For more information about JNDI service providers, see IBM
Toolbox for Java reference links.
// ... Application works with some more connections from the pool.
AS400JDBCConnectionPool Javadoc
AS400JDBCConnectionPool Javadoc
AS400JDBCConnectionPoolDataSource Javadoc
Example 1
This brief example shows the basic use of the AS400JDBCManagedConnectionPoolDataSource class.
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.ibm.as400.access.AS400JDBCManagedConnectionPoolDataSource;
import com.ibm.as400.access.AS400JDBCManagedDataSource;
// Set general datasource properties. Note that both connection pool datasource (CPDS) and
managed
// datasource (MDS) have these properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
Connection c = dataSource_.getConnection();
Example 2
This example shows more details about how to use the AS400JDBCManagedConnectionPoolDataSource
class.
import java.awt.TextArea;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Vector;
import java.util.Properties;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.*;
import java.util.Date;
import java.util.ArrayList;
import java.util.Random;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCManagedConnectionPoolDataSource;
import com.ibm.as400.access.AS400JDBCManagedDataSource;
import com.ibm.as400.access.Trace;
// If you turn this flag on, be sure to also turn on the following flag:
// AS400JDBCConnection.TESTING_THREAD_SAFETY.
private static final boolean TESTING_THREAD_SAFETY = false;
// Note: For consistency, all time values are stored units of milliseconds.
private boolean keepDaemonsAlive_ = true; // When this is false, the daemons shut down.
static
{
try {
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
}
catch(Exception e){
System.out.println("Unable to register JDBC driver.");
System.exit(0);
}
}
cptest.setup();
cptest.runTest();
}
if (TESTING_THREAD_SAFETY)
{
// Adjust values for performing thread-intensive stress testing.
// NOTE: This assumes that the AS400JDBCConnection class has also been modified to
// not make actual connections to an actual server.
// To do this, edit AS400JDBCConnection.java, changing its TESTING_THREAD_SAFETY
// flag to 'false', and recompile.
minPoolSize_ = 100;
maxPoolSize_ = 190;
initialPoolSize_ = 150; // this should get reset to maxPoolSize_
numDaemons_ = 75;
if (timeToRunDaemons_ == 0) {
timeToRunDaemons_ = 180*1000; // 180 seconds == 3 minutes
}
}
else
{ // Set more conservative values, as we'll be making actual connections to an
// actual server, and we don't want to monopolize the server.
minPoolSize_ = 5;
maxPoolSize_ = 15;
initialPoolSize_ = 9;
numDaemons_ = 4;
if (timeToRunDaemons_ == 0) {
timeToRunDaemons_ = 15*1000; // 15 seconds
}
}
maxLifetime_ = (int)timeToRunDaemons_ / 3;
maxIdleTime_ = (int)timeToRunDaemons_ / 4;
if (DEBUG)
System.out.println("setup: Constructing "
+ "AS400JDBCManagedConnectionPoolDataSource (cpds0)");
AS400JDBCManagedConnectionPoolDataSource cpds0 =
new AS400JDBCManagedConnectionPoolDataSource();
// Set datasource properties. Note that both CPDS and MDS have these
// properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
ctx.rebind("mydatasource", cpds0);
// We can now do lookups on cpds, by the name"mydatasource".
if (DEBUG)
System.out.println("setup: lookup(\"mydatasource\"" + ")");
// AS400JDBCManagedConnectionPoolDataSource cpds1 =
// (AS400JDBCManagedConnectionPoolDataSource)ctx.lookup("mydatasource");
// if (DEBUG) System.out.println("setup: cpds1.getUser() == |" + cpds1.getUser() + "|");
if (DEBUG)
System.out.println("setup: Constructing AS400JDBCManagedDataSource (mds0)");
AS400JDBCManagedDataSource mds0 = new AS400JDBCManagedDataSource();
mds0.setDescription("DataSource supporting connection pooling");
mds0.setDataSourceName("mydatasource");
ctx.rebind("ConnectionPoolingDataSource", mds0);
if (DEBUG)
System.out.println("setup: lookup(\"ConnectionPoolingDataSource\"" + ")");
dataSource_ = (DataSource)ctx.lookup("ConnectionPoolingDataSource");
//dataSource_.setLogWriter(output_);
if (DEBUG)
System.out.println("setup: dataSource_.getUser() == |" +
((AS400JDBCManagedDataSource)dataSource_).getUser() + "|");
mds_ = (AS400JDBCManagedDataSource)dataSource_;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Setup error during Trace file creation.");
}
}
/**
* Gets and returns connections from and to a connection pool for a while.
**/
public void runTest()
{
boolean ok = true;
try
{
System.out.println("Started test run at " + new Date());
if (DEBUG)
System.out.println("Checking health just after datasource creation "
+ "(we expect that the pool does not exist yet) ...");
if (mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool exists prior to first getConnection().");
}
mds_.setAccess("read only");
if (!mds_.getAccess().equals("read only")) {
ok = false;
System.out.println("\nERROR: getAccess() returned unexpected value: "
+ "|" + mds_.getAccess()+"|");
}
oldBool = mds_.isKeepAlive();
newBool = (oldBool ? false : true);
mds_.setKeepAlive(newBool);
if (mds_.isKeepAlive() != newBool) {
ok = false;
System.out.println("\nERROR: isKeepAlive() returned unexpected value: "
+ "|"+mds_.isKeepAlive()+"|");
}
mds_.setKeepAlive(oldBool);
oldInt = mds_.getReceiveBufferSize();
newInt = (oldInt == 256 ? 512 : 256);
mds_.setReceiveBufferSize(newInt);
if (mds_.getReceiveBufferSize() != newInt) {
ok = false;
System.out.println("\nERROR: getReceiveBufferSize() returned unexpected value: "
+ "|"+mds_.getReceiveBufferSize()+"|");
}
mds_.setReceiveBufferSize(oldInt);
System.out.println("CONNECTION 1");
Object o = dataSource_.getConnection();
System.out.println(o.getClass());
System.out.println("******LOOK ABOVE*******");
Connection c1 = dataSource_.getConnection();
if (DEBUG)
System.out.println("Checking health after first getConnection() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first getConnection().");
}
if (!TESTING_THREAD_SAFETY)
{
try
{
c1.setAutoCommit(false);
if (DEBUG)
System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c1.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG)
System.out.println(rs.getString(2));
}
rs.close();
s.close();
}
catch (Exception e) {
e.printStackTrace();
if (DEBUG)
System.out.println("Checking health after fatal connection error ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after fatal connection "
+ "error.");
}
}
}
System.out.println("CONNECTION 2");
Connection c2 = dataSource_.getConnection(userid, password);
if (DEBUG)
displayConnectionType(c2, false);
System.out.println("CONNECTION 3");
Connection c3 = dataSource_.getConnection();
if (DEBUG)
displayConnectionType(c3, true);
c1.close();
if (DEBUG)
System.out.println("Checking health after first close() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first close().");
}
System.out.println("CONNECTION 4");
Connection c4 = dataSource_.getConnection();
if (DEBUG) displayConnectionType(c4, true);
// Run the test daemons for a while; check pool health periodically.
if (DEBUG)
System.out.println("Checking health after connectionGetter daemons have run...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after test daemons stopped.");
}
if (!TESTING_THREAD_SAFETY)
{
System.out.println("CONNECTION 5");
Connection c = dataSource_.getConnection();
if (DEBUG) displayConnectionType(c, true);
c.setAutoCommit(false);
if (DEBUG) System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG) System.out.println(rs.getString(2));
}
rs.close();
s.close();
c.close();
}
if (DEBUG)
System.out.println("Checking health after pool closed ...");
Trace.setTraceJDBCOn(true); // make sure the final stats get printed out
Trace.setTraceOn(true);
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after pool closed.");
}
System.out.println();
if(ok==true)
System.out.println("test ran ok");
else
System.out.println("test failed");
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
finally {
System.out.println("Ended test at " + new Date());
}
}
void startThreads()
{
// Create a bunch of threads that call getConnection().
Thread[] threads = new Thread[numDaemons_];
for (int i=0; i<numDaemons_; i++)
{
ConnectionGetter getter;
// Flip a coin to see if this daemon will specify the default uid, or unique uid.
if (random_.nextBoolean())
{
getter = new ConnectionGetter(userid,password);
if (TESTING_THREAD_SAFETY) { // we can use fictional userid
getter = new ConnectionGetter("Thread"+i, "Pwd"+i);
}
else { // must use a real userid
void stopThreads()
{
// Tell the threads to stop.
keepDaemonsAlive_ = false;
synchronized (daemonSleepLock_) {
daemonSleepLock_.notifyAll();
}
// ConnectionGetter --------------------------------------------------------------------
/**
Helper class. This daemon wakes up at random intervals and either
gets another connection from the connection pool or returns a
previously-gotten connection to the pool.
**/
private final class ConnectionGetter implements Runnable
{
private String uid_;
private String pwd_;
private boolean useDefaultUid_;
private long maxSleepTime_;
private String threadName_;
private boolean firstConnection_ = true;
ArrayList connections_ = new ArrayList();
// list of connections that this getter currently 'owns'.
try
{
while (keepDaemonsAlive_)
{
try
{
// Pick a random sleep-time, between min and max values.
long sleepTime = Math.max((long)(maxSleepTime_ * random_.nextFloat()),
daemonMinSleepTime_);
// Note: Must never call wait(0), because that waits forever.
synchronized (daemonSleepLock_) {
try {
daemonSleepLock_.wait(sleepTime);
System.out.print(".");
}
catch (InterruptedException ie) {}
}
if (!keepDaemonsAlive_) break;
if (conn == null) {
System.out.println("ConnectionGetter("+threadName_+") ERROR: "
+ "getConnection() returned null");
}
else
{
// Occasionally "forget" that we own a connection, and neglect to
// close it.
// Orphaned connections should eventually exceed their maximum
// lifetime and get "reaped" by the connection manager.
float val = random_.nextFloat();
if (firstConnection_ || val < 0.1) {
// 'orphan' a few gotten connections
firstConnection_ = false;
}
else {
connections_.add(conn);
}
if (DEBUG) displayConnectionType(conn, useDefaultUid_);
if (conn instanceof com.ibm.as400.access.AS400JDBCConnectionHandle)
{ // We got a pooled connection. Try speeding up our cycle time.
if (maxSleepTime_ > 100)
maxSleepTime_--;
else
maxSleepTime_ = 100;
}
else
{ // We didn't get a pooled connection. That means that the pool
// must be at capacity. Slow down our cycle time a bit.
maxSleepTime_ = maxSleepTime_ + 50;
}
}
}
else { // Close a connection that we currently own.
if (connections_.size() != 0) {
conn = (Connection)connections_.remove(0);
conn.close();
}
}
} // inner try
catch (Exception e)
{
e.printStackTrace();
}
} // outer while
} // outer try
finally
{
if (DEBUG)
System.out.println("ConnectionGetter("+threadName_+") Stopping");
// Return all the connections that I still have in my list.
for (int i=0; i<connections_.size(); i++) {
Connection conn = (Connection)connections_.remove(0);
try { conn.close(); } catch (Exception e) { e.printStackTrace(); }
}
}
}
Related information
AS400JDBCDatabaseMetaData Javadoc
AS400JDBCDataSource class
The AS400JDBCDataSource class represents a factory for IBM i database connections. The
AS400JDBCConnectionPoolDataSource class represents a factory for AS400JDBCPooledConnection
objects.
You can register either kind of data source object by using a Java Naming and Directory Interface (JNDI)
service provider. For more information about JNDI service providers, see “Related information for IBM
Toolbox for Java” on page 533.
Examples
The following examples demonstrate ways to create and use AS400JDBCDataSource objects. The last
two examples show how to register an AS400JDBCDataSource object with JNDI and then use the object
returned from JNDI to obtain a database connection. Notice that even when using different JNDI service
providers, the code is very similar.
Example: Creating an AS400JDBCDataSource object
The following example shows you how to create an AS400JDBCDataSource object and connect it to a
database:
// Register the datasource with the Java Naming and Directory Interface (JNDI).
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
Context context = new InitialContext(env);
context.bind("jdbc/customer", dataSource);
Example: Using AS400JDBCDataSource objects and IBM SecureWay Directory classes with a
Lightweight Directory Access Protocol (LDAP) directory server
The following examples shows how you can use IBM SecureWay Directory classes to store an object to a
Lightweight Directory Access Protocol (LDAP) directory server:
// Register the datasource with the Java Naming and Directory Interface (JNDI).
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.jndi.LDAPCtxFactory");
Context context = new InitialContext(env);
context.bind("cn=myDatasource, cn=myUsers, ou=myLocation,o=myCompany,c=myCountryRegion",
dataSource);
AS400JDBCDataSource Javadoc
AS400JDBCConnectionPoolDataSource Javadoc
AS400JDBCPooledConnection Javadoc
"-Djdbc.drivers=com.ibm.as400.access.AS400JDBCDriver"
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
The IBM Toolbox for Java JDBC driver registers itself when it is loaded, which is the preferred way to
register the driver. You can also explicitly register the IBM Toolbox for Java JDBC driver by using the
following:
Calling DriverManager.registerDriver() results in the IBM Toolbox for Java JDBC driver getting registered
twice. Once when AS400JDBCDriver is loaded by the JVM and once for the explicit call to the
registerDriver() method. This is a result of the DriverManager implementation, which IBM Toolbox
for Java has no control over. Having a driver being listed twice in the DriverManager's registry is
normally not a problem. Although there may be situations where both registered driver listings get
used. For example, this could happen when trying to get a connection with an incorrect password. The
DriverManager will fail on the first registered driver to obtain a connection and so it will then try the
second registered driver.
The IBM Toolbox for Java JDBC driver does not require an AS400 object as an input parameter like
the other IBM Toolbox for Java classes that get data from a server. An AS400 object is used internally,
however, to manage default user and password caching. When a connection is first made to the server,
the user may be prompted for user ID and password. The user has the option to save the user ID as
the default user ID and add the password to the password cache. As in the other IBM Toolbox for Java
functions, if the user ID and password are supplied by the Java program, the default user is not set and
the password is not cached. See “Managing connections in Java programs” on page 338 for information
about managing connections.
"jdbc:as400://systemName/defaultSchema;listOfProperties"
Example: Connecting to the server database and using java.util.Properties to specify properties
The Java program can specify a set of JDBC properties either by using the java.util.Properties interface or
by specifying the properties as part of the URL. See “IBM Toolbox for Java JDBC properties” on page 247
for a list of supported properties.
For example, to specify properties using the Properties interface, use the following code as an example:
Example: Connecting to the server database and using a uniform resource locator (URL) to specify
properties
Example: Connecting to the server database and specifying user ID and password
c.close();
AS400JDBCDriver Javadoc
AS400JDBCParameterMetaData class
The AS400JDBCParameterMetaData class enables your programs to retrieve information about the
properties of parameters in PreparedStatement and CallableStatement objects.
AS400JDBCParameterMetaData provides methods that allow you to perform the following actions:
• Get the class name of the parameter
• Get the number of parameters in the PreparedStatement
• Get the SQL type of the parameter
• Get the database-specific type name for the parameter
Related information
AS400JDBCParameterMetaData Javadoc
PreparedStatement interface
You can use a PreparedStatement object when an SQL statement is going to be run many times. A
prepared statement is an SQL statement that has been precompiled.
This approach is more efficient than running the same statement multiple times using a Statement
object, which compiles the statement each time it is run. In addition, the SQL statement contained in a
PreparedStatement object may have one or more IN parameters. Use Connection.prepareStatement() to
create PreparedStatement objects.
The PreparedStatement object allows you to submit multiple SQL commands as a single group to a
database through the use of batch support. You may improve performance by using batch support
because processing a group of operations is typically faster than processing them one at a time.
Related information
AS400JDBCPreparedStatement Javadoc
ResultSet class
You can use a ResultSet object to access a table of data that was generated by running a query. The table
rows are retrieved in sequence. Within a row, column values can be accessed in any order.
The data stored in ResultSet is retrieved by using the various get methods, depending on the type of data
being retrieved. The next() method is used to move to the next row.
ResultSet allows you to get and update columns by name, although using the column index results
improves performance.
Cursor movement
A cursor, which is an internal pointer, is used by a result set to point the row in the result set that is being
accessed by the Java program.
The performance of the getRow() method has been improved. Before V5R2, using ResultSet.last(),
ResultSet.afterLast(), and ResultSet.absolute() with a negative value made the current row number not
available. The previous restrictions are lifted, which makes the getRow() method fully functional.
JDBC 2.0 and later JDBC specifications provide additional methods for accessing specific positions within
a database:
absolute isFirst
afterLast isLast
beforeFirst last
first moveToCurrentRow
getRow moveToInsertRow
isAfterLast previous
isBeforeFirst relative
Scrolling capabilities
If a result set is created by executing a statement, you can move (scroll) backward (last-to-first) or
forward (first-to-last) through the rows in a table.
A result set that supports this movement is called a scrollable result set. Scrollable result sets also
support absolute positioning. Absolute positioning allows you to move directly to a row by specifying its
position in the result set.
With JDBC 2.0 and later JDBC specifications, you have two additional scrolling capabilities available to
use when working with the ResultSet class: scroll-insensitive and scroll-sensitive result sets.
A scroll-insensitive result set is not usually sensitive to changes that are made while it is open, while the
scroll-sensitive result set is sensitive to changes.
Note: IBM i only allows read-only access for scrollable insensitive cursors. IBM Toolbox for Java supports
a scroll-insensitive cursor if the result set concurrency is read-only. If the result set type is specified as
insensitive and the concurrency is specified as updateable, the result set type changes to sensitive and
issues a warning to you.
ResultSetMetaData
The ResultSetMetaData interface determines the types and properties of the columns in a ResultSet.
When connecting to a server running IBM i 5.2 or later, using the extended metadata property enables you
to increase the accuracy of the following ResultSetMetaData methods:
• getColumnLabel(int)
• isReadOnly(int)
• isSearchable(int)
• isWriteable(int)
Additionally, setting this property to true enables support for the
ResultSetMetaData.getSchemaName(int) method. Be aware that using the extended metadata property
may degrade performance because it requires retrieving more information from the server.
AS400JDBCRowSet class
The AS400JDBCRowSet class represents a connected rowset that encapsulates a JDBC result set. The
methods on AS400JDBCRowSet are very similar to those of the AS400JDBCResultSet. The database
connection is maintained while in use.
You can use an instance of AS400JDBCDataSource or AS400JDBCConnectionPoolDataSource to create
the connection to the database that you want to use to access the data for the AS400JDBCRowSet.
Examples
The following examples show how you can use the AS400JDBCRowSet class.
Example: Creating, populating, and updating an AS400JDBCRowSet object
DriverManager.registerDriver(new AS400JDBCDriver());
// Establish connection by using a URL.
AS400JDBCRowSet rowset = new AS400JDBCRowSet("jdbc:as400://mySystem","myUser",
"myPassword");
Example: Creating and populating an AS400JDBCRowSet object, while getting the data source from
JNDI
// Get the data source that is registered in JNDI (assumes JNDI environment is set).
Context context = new InitialContext();
AS400JDBCDataSource dataSource = (AS400JDBCDataSource) context.lookup("jdbc/customer");
AS400JDBCRowSet Javadoc
AS400JDBCResultSet Javadoc
AS400JDBCSavepoint class
The IBM Toolbox for Java AS400JDBCSavepoint class represents a logical breaking point in a transaction.
Using savepoints gives you more granular control over which changes are affected when you roll back a
transaction.
Figure 1: Using savepoints to control rollbacks in a transaction
// An error is detected, so we need to roll back Jane's record, but not John's.
// Rollback the transaction to savepoint 1. The change to Jane's record is
// removed while the change to John's record remains.
connection.rollback(savepoint1);
// Commit the transaction; only John's 'B' grade is committed to the database.
connection.commit();
Statement interface
Use Connection.createStatement() to create new Statement objects.
The following example shows how to use a Statement object.
AS400JDBCStatement Javadoc
For more information, see the Sun Web sites for JDBC and the JTA .
Use the following objects to enable the IBM Toolbox for Java JDBC driver to participate in XA distributed
transactions:
• AS400JDBCXADataSource - A factory for AS400JDBCXAConnection objects. This is a subclass of
AS400JDBCDataSource.
• AS400JDBCXACConnection - A pooled connection object that provides hooks for connection pool
management and XA resource management.
• AS400JDBCXAResource - A resource manager for use in XA transaction management.
Note: Prior to V5R3, the database host server used XA APIs for Job Scoped Locks (XA model). In V5R3
and subsequent releases, the database host server uses XA APIs for Transaction Scoped Locks (NTS
model) for all MTS functions. For more information about how these APIs differ, see XA APIs.
Jobs classes
The IBM Toolbox for Java Jobs classes, which are in the access package, allow a Java program to retrieve
and change job information.
Use the Jobs classes to work with the following type of job information:
• Date and Time Information
• Job Queue
• Language Identifiers
• Message Logging
• Output Queue
• Printer Information
Examples
The following examples show some of the ways you can use the Job, JobList, and JobLog classes. The
first example shows one way to use a cache with the Job class. Links to other examples immediately
follow the sample code.
Note: Read the Code example disclaimer for important legal information.
Example: Using a cache when setting a value and getting a value
try {
The following examples show how to list the jobs belonging to a specific user, list jobs with the job status
information, and display the messages in a job log:
“Example: Using JobList to list job identification information” on page 408
“Example: Using JobList to get a list of jobs” on page 410
“Example: Using JobLog to display messages in the job log” on page 412
Access package Javadoc
Job class
The Job class (in the access package) allows a Java program to retrieve and change server job
information.
The following type of job information can be retrieved and changed with the Job class:
• Job queues
• Output queues
• Message logging
• Printer device
• Country or region identifier
• Date format
The job class also allows the ability to change a single value at a time, or cache several changes using
the setCacheChanges(true) method and committing the changes using the commitChanges() method. If
caching is not turned on, you do not need to do a commit.
Example
For a code example, see the Javadoc reference documentation for the Job class. The example shows
how to set and get values to and from the cache in order to set the run priority with the setRunPriority()
method and set the date format with the setDateFormat() method.
Job Javadoc
JobList class
You can use the JobList class (in the access package) to list IBM i jobs.
With the JobList class, you can retrieve the following:
• All jobs
• Jobs by name, job number, or user
System.out.println(j.getName() + "." +
j.getUser() + "." +
j.getNumber());
}
Job Javadoc
JobLog class
TheJobLog class (in the access package) retrieves messages in the job log of a server job by calling
getMessages().
if (j.getUser().trim().equalsIgnoreCase(userID))
{
// A job matching the current user
// was found. Create a job log
// object for this job.
JobLog jlog = new JobLog(system, j.getName(), j.getUser(), j.getNumber());
while (messageList.hasMoreElements())
{
AS400Message message = (AS400Message) messageList.nextElement();
System.out.println(message.getText());
}
}
}
Job Javadoc
AS400Message
The AS400Message object allows the Java program to retrieve an IBM i message that is generated from
a previous operation (for example, from a command call). From a message object, the Java program can
retrieve the following:
• The IBM i library and message file that contain the message
• The message ID
• The message type
• The message severity
• The message text
• The message help text
The following example shows how to use the AS400Message object:
Note: Read the Code example disclaimer for important legal information.
QueuedMessage
The QueuedMessage class extends the AS400Message class.
The QueuedMessage class accesses information about a message on an IBM i message queue. With this
class, a Java program can retrieve:
• Information about where a message originated, such as program, job number, and user.
• The message queue
• The message key
• The message reply status
The following example prints all messages in the message queue of the current (signed-on) user:
Note: Read the Code example disclaimer for important legal information.
MessageFile
The MessageFile class allows you to receive a message from an IBM i message file. The MessageFile class
returns an AS400Message object that contains the message. Using the MessageFile class, you can do the
following:
• Return a message object that contains the message
• Return a message object that contains substitution text in the message
The following example shows how to retrieve and print a message:
Note: Read the Code example disclaimer for important legal information.
MessageQueue
The MessageQueue class allows a Java program to interact with an IBM i message queue.
The MessageQueue class acts as a container for the QueuedMessage class. The getMessages() method, in
particular, returns a list of QueuedMessage objects. The MessageQueue class can do the following:
• Set message queue attributes
• Get information about a message queue
• Receive messages from a message queue
• Send messages to a message queue
• Reply to messages
The following example lists messages in the message queue for the current user:
Note: Read the Code example disclaimer for important legal information.
NetServer class
The NetServer class has been deprecated and replaced by the ISeriesNetServer class.
The NetServer class represents the NetServer service on the server. NetServer objects allow you to query
and modify the state and configuration of the NetServer service.
For example, you can use the NetServer class to:
• Start or stop the NetServer
• Get a list of all current file shares and print shares
• Get a list of all current sessions
• Query and change attribute values (using methods inherited from ChangeableResource)
Note: In order to use the NetServer class, you need a server user profile that has *IOSYSCFG authority.
The NetServer class is an extension of ChangeableResource and Resource, so it provides a collection of
"attributes" to represent the various NetServer values and settings. You query or change the attributes in
order to access or change the configuration of your NetServer. Some of the NetServer attributes are:
• NAME
• NAME_PENDING
• DOMAIN
• ALLOW_SYSTEM_NAME
• AUTOSTART
• CCSID
• WINS_PRIMARY_ADDRESS
Pending attributes
Many of the NetServer attributes are pending (for example, NAME_PENDING). Pending attributes
represent NetServer values that take effect the next time you start (or restart) the NetServer on the
server.
When you have a pair of related attributes and one attribute is pending while the other is nonpending:
• The pending attribute is read/write, so you can change it
• The nonpending attribute is read-only, so you can query it but you cannot change it
// The NetServer name will get set to NEWNAME the next time the NetServer
// is ended and started.
ObjectReferences class
The IBM Toolbox for Java ObjectReferences class represents the set of information about integrated file
system references on an object that can be retrieved through the Retrieve Object References (QP0LROR)
API.
A reference is an individual type of access or lock obtained on the object when using integrated file
system interfaces. An object may have multiple references concurrently held, provided that the reference
types do not conflict with one another. This class will not return information about byte range locks that
may currently be held on an object.
The user must have execute (*X) data authority to each directory preceding the object whose references
are to be obtained. The user must have read (*R) data authority to the object whose references are to be
obtained.
For more information, see the ObjectReferences Javadoc.
Related information
ObjectReferences Javadoc
Retrieve Object References (QP0LROR) API
Permission classes
The IBM Toolbox for Java permission classes allow you to get and set object authority information. Object
authority information is also known as permission. The Permission class represents a collection of many
users' authority to a specific object. The UserPermission class represents a single user's authority to a
specific object.
Permission class
The Permission class allows you to retrieve and change object authority information. It includes a
collection of many users who are authorized to the object. The Permission object allows the Java program
to cache authority changes until the commit() method is called. Once the commit() method is called, all
changes made up to that point are sent to the server. Some of the functions provided by the Permission
class include:
• addAuthorizedUser(): Adds an authorized user.
• commit(): Commits the permission changes to the server.
• getAuthorizationList(): Returns the authorization list of the object.
• getAuthorizedUsers(): Returns an enumeration of authorized users.
• getOwner(): Returns the name of the object owner.
• getSensitivityLevel(): Returns the sensitivity level of the object.
UserPermission class
The UserPermission class represents the authority of a single, specific user. UserPermission has three
subclasses that handle the authority based on the object type:
• DLOPermission
• QSYSPermission
• RootPermission
The UserPermission class allows you to do the following:
• Determine if the user profile is a group profile
• Return the user profile name
• Indicate whether the user has authority
• Set the authority of authorization list management
Example: Using UserPermission
Note: Read the Code example disclaimer for important legal information.
The following example shows you how to retrieve the users and groups that have permission on an object
and print them out one at a time.
// Retrieve the various users/groups that have permissions set on that object.
Enumeration enum = objectInQSYS.getUserPermissions();
while (enum.hasMoreElements())
{
// Print out the user/group profile names one at a time.
UserPermission userPerm = (UserPermission)enum.nextElement();
System.out.println(userPerm.getUserID());
}
Permission Javadoc
UserPermission Javadoc
You must use one of the following methods to change or determine the user's authority:
• Use getDataAuthority() to display the authority value of the user
• Use setDataAuthority() to set the authority value of the user
After setting permissions, it is important that you use the commit() method from the Permissions class to
send the changes to the server.
For more information about permissions and authorities, see the Security reference topic.
Related information
DLOPermission Javadoc
QSYSPermission
QSYSPermission is a subclass of the UserPermission class. QSYSPermission allows you to display and set
the permission a user has for an object in the traditional IBM i library structure stored in QSYS.LIB. You
can set authority for an object stored in QSYS.LIB by setting a system-defined authority value or by setting
the individual object and data authorities.
The following table lists and describes the valid system-defined authority values:
Each system-defined authority value actually represents a combination of the individual object authorities
and data authorities. The following table illustrates the relationships of system-defined authorities to the
individual object and data authorities:
Table 1. Y refers to those authorities that can be assigned. n refers to those authorities that cannot be
assigned.
System- Object authority Data authority
defined
Opr Mgt Exist Alter Ref Read Add Upd Dlt Exe
authority
All Y Y Y Y Y Y Y Y Y Y
Change Y n n n n Y Y Y Y Y
Exclude n n n n n n n n n n
Use Y n n n n Y n n n Y
Autl Only valid with user (*PUBLIC) and a specified authorization list that determines the
individual object and data authorities.
QSYSPermission Javadoc
“UserPermission class” on page 88
RootPermission
The RootPermission class represents a user's authority to objects contained in the root directory
structure. RootPermissions objects are those objects not contained in QSYS.LIB or QDLS.
RootPermission is a subclass of the UserPermission class. The RootPermission class allows you to display
and set the permissions for the user of an object contained in the root directory structure.
An object on the root directory structure can set the data authority or the object authority. You can set the
data authority to the values listed in the following table. Use the getDataAuthority() method to to display
the current values and the setDataAuthority() method to set the data authority.
The following table lists and describes the valid data authority values:
The object authority can be set to one or more of the following values: alter, existence, management, or
reference. You can use the setAlter(), setExistence(), setManagement(), or setReference() methods to set
the values on or off.
After setting either the data authority or the object authority of an object, it is important that you use the
commit() method from the Permissions class to send the changes to the server.
Related information
RootPermission Javadoc
Print classes
Print objects include spooled files, output queues, printers, printer files, writer jobs, and Advanced
Function Printing (AFP) resources, which include fonts, form definitions, overlays, page definitions, and
page segments.
The IBM Toolbox for Java classes for print objects are organized on a base class, PrintObject, and on a
subclass for each of the six types of print objects. The base class contains the methods and attributes
common to all server print objects. The subclasses contain methods and attributes specific to each
subtype.
Examples
• Example: Creating spooled files shows how to create a spooled file on a server from an input stream
• Example: Creating SCS spooled files shows how to generate a SCS data stream using the
SCS3812Writer class, and how to write the stream to a spooled file on the server
• Example: Reading spooled files shows how to use PrintObjectInputStream to read an existing server
spooled file
• Example: Reading and transforming spooled files shows how to use PrintObjectPageInputStream and
PrintObjectTransformedInputStream to obtain different transformations when reading spooled file data
• Example: Copying a spooled file shows how to copy a spooled file to the same queue that contains the
file you want to copy.
• Example: Listing spooled files asynchronously (using listeners) shows how to asynchronously list all
spooled files on a system and how to use the PrintObjectListListener interface to get feedback as the list
is being built
• Example: Listing spooled files asynchronously (without using listeners) shows how to asynchronously
list all spooled files on a system without using the PrintObjectListListener interface
• Example: Listing spooled files synchronously shows how to synchronously list all spooled files on a
system
Related information
PrintObject Javadoc
After the list has been opened and the objects in the list processed, close the list using the close()
method. This frees up any resources allocated to the garbage collector during the open. After a list has
been closed, its filters can be modified, and the list can be opened again.
When print objects are listed, attributes about each print object listed are sent from the server and stored
with the print object. These attributes can be updated using the update() method in the PrintObject class.
Which attributes are sent back from the server depends on the type of print object being listed. A default
list of attributes for each type of print object that can be overridden by using the setAttributesToRetrieve()
method in PrintObjectList exists. See the Retrieving PrintObject attributes section for a list of the
attributes each type of print object supports.
Examples
The following examples show different ways to list spooled files.
“Example: Listing spooled files asynchronously (using listeners)” on page 418 shows how to
asynchronously list all spooled files on a system and how to use the PrintObjectListListener
interface to get feedback as the list is being built
“Example: Listing spooled files asynchronously (without using listeners)” on page 420
shows how to asynchronously list all spooled files on a system without using the
PrintObjectListListener interface
setAttributes method
You can use the SpooledFile setAttributes method to change the attributes of spooled files and printer file
objects. Select the following links for a list or which attributes may be set:
• PrinterFileAttrs file for printer files
• SpooledFileAttrs for spooled files
The setAttributes method takes a PrintParameterList parameter, which is a class that is used to hold a
collection of attributes IDs and their values. The list starts out empty, and the caller can add attributes to
the list by using the various setParameter() methods on it.
PrintParameterList class
You can use the PrintParameterList class to pass a group of attributes to a method that takes any of a
number of attributes as parameters. For example, you can send a spooled file using TCP (LPR) by using
the SpooledFile method, sendTCP(). The PrintParameterList object contains the required parameters for
the send command, such as the remote system and queue, plus any optional parameters desired, such as
whether to delete the spooled file after it is sent. In these cases, the method documentation gives a list
of required and optional attributes. The PrintParameterList setParameter() method does not check which
attributes you are setting and the values that you set them to. The PrintParameterList setParameter()
method simply contains the values to pass along to the method. In general, extra attributes in the
PrintParameterList are ignored, and illegal values on the attributes that are used are diagnosed on the
server.
PrintObject Javadoc
SpooledFile Javadoc
PrintParameterList Javadoc
Retrieve Attributes
The following attributes may be retrieved for an AFP resource using the appropriate getIntegerAttribute(),
getStringAttribute(), or getFloatAttribute() method:
• ATTR_AFP_RESOURCE - AFP resource Integrated File System Path
• ATTR_OBJEXTATTR - Object Extended Attribute
• ATTR_DESCRIPTION - Text Description
• ATTR_DATE - Date File Opened
• ATTR_TIME - Time File Opened
• ATTR_NUMBYTES - Number of bytes to read/write
Retrieve attributes
The following attributes may be retrieved for an output queue using the appropriate getIntegerAttribute(),
getStringAttribute(), or getFloatAttribute() method:
• ATTR_AUTHCHCK - Authority to Check
• ATTR_DATA_QUEUE - Data Queue Integrated File System Name
• ATTR_DISPLAYANY - Display any File
• ATTR_JOBSEPRATR - Job Separators
• ATTR_NUMFILES - Number of Files
• ATTR_NUMWRITERS - Number of Writers Started to Queue
• ATTR_OPCNTRL - Operator Controlled
• ATTR_ORDER - Order of Files On Queue
• ATTR_OUTPUT_QUEUE - Output Queue Integrated File System Name
• ATTR_OUTQSTS - Output Queue Status
• ATTR_PRINTER - Printer
• ATTR_SEPPAGE - Separator page
• ATTR_DESCRIPTION - Text Description
• ATTR_USRDEFOPT - User defined option(s)
• ATTR_USER_DEFINED_OBJECT - User defined object Integrated File System Name
• ATTR_USER_TRANSFORM_PROG - User transform program Integrated File System Name
• ATTR_USER_DRIVER_PROG - User driver program Integrated File System Name
• ATTR_WTRJOBNAME - Writer Job Name
• ATTR_WTRJOBNUM - Writer Job Number
• ATTR_WTRJOBSTS - Writer Job Status
• ATTR_WTRJOBUSER - Writer Job User Name
Set attributes
Attributes are not allowed to be set for an output queue.
Printer Attributes
The following attributes may be retrieved for a printer using the appropriate getIntegerAttribute(),
getStringAttribute(), or getFloatAttribute() method:
Retrieve Attributes
• ATTR_AFP - Advanced Function Printing
• ATTR_ALIGNFORMS - Align Forms
• ATTR_ALWDRTPRT - Allow Direct Print
• ATTR_BTWNCPYSTS - Between copies status
• ATTR_BTWNFILESTS - Between files status
• ATTR_CODEPAGE - Code Page
Set Attributes
Attributes are not allowed to be set for a printer.
Retrieve attributes
The following attributes may be retrieved for a printer file using the appropriate getIntegerAttribute(),
getStringAttribute(), or getFloatAttribute() method:
• ATTR_ALIGN - Align Page
• ATTR_BKMGN_ACR - Back Margin Offset Across
• ATTR_BKMGN_DWN - Back Margin Offset Down
• ATTR_BACK_OVERLAY - Back Overlay Integrated File System Name
• ATTR_BKOVL_DWN - Back Overlay Offset Down
• ATTR_BKOVL_ACR - Back Overlay offset across
• ATTR_CPI - Characters per Inch
• ATTR_CODEDFNTLIB - Coded Font Library Name
• ATTR_CODEPAGE - Code Page
• ATTR_CODEDFNT - Code Font Name
• ATTR_CONTROLCHAR - Control Character
• ATTR_CONVERT_LINEDATA - Convert Line Data
• ATTR_COPIES - Copies
• ATTR_CORNER_STAPLE - Corner staple
• ATTR_DBCSDATA - User Specified DBCS Data
• ATTR_DBCSEXTENSN - DBCS Extension Characters
• ATTR_DBCSROTATE - DBCS Character Rotation
• ATTR_DBCSCPI - DBCS Characters per Inch
• ATTR_DBCSSISO - DBCS SO/SI Spacing
• ATTR_DFR_WRITE - Defer Write
• ATTR_PAGRTT - Degree of Page Rotation
• ATTR_EDGESTITCH_NUMSTAPLES - Edge Stitch Number of Staples
• ATTR_EDGESTITCH_REF - Edge Stitch Reference
• ATTR_EDGESTITCH_REFOFF - Edge Stitch Reference
• ATTR_ENDPAGE - Ending Page
• ATTR_FILESEP - File Separators
• ATTR_FOLDREC - Fold Records
• ATTR_FONTID - Font Identifier
AFP Resource
ID
ATTR_AFP_RESOURCE
Type
String
Description
The Integrated File System path of the external AFP (Advanced Function Print) resource. The format
of the Integrated File System path is "/QSYS.LIB/library.LIB/resource.type" where library is the library
that contains the resource, resource is the name of the resource and type is the resource type. Valid
values for type include "FNTRSC", "FORMDF", "OVL", "PAGSEG", and "PAGDFN".
Align Forms
ID
ATTR_ALIGNFORMS
Type
String
Description
The time at which a forms alignment message will be sent. Valid values are *WTR, *FILE, *FIRST.
Align Page
ID
ATTR_ALIGN
Type
String
Description
Indicates whether a forms alignment message is sent before printing this spooled file. Valid values are
*YES, *NO.
Authority
ID
ATTR_AUT
Type
String
Description
Specifies the authority that is given to users who do not have specific authority to the output queue.
Valid values are *USE, *ALL, *CHANGE, *EXCLUDE, *LIBCRTAUT.
Authority to Check
ID
ATTR_AUTCHK
Type
String
Description
Indicates what type of authorities to the output queue allow the user to control all the files on the
output queue. Valid values are *OWNER, *DTAAUT.
Auxiliary Storage
ID
ATTR_AUX_POOL
Type
Integer
Description
Specifies the number of the auxiliary storage pool (ASP) that the spooled file is stored on. The
possible values are:
• 1: System ASP
• 2-32: One of the user ASPs
Back Overlay
ID
ATTR_BACK_OVERLAY
Type
String
Description
The Integrated File System path of the back overlay or a special value. If the value is an Integrated
File System path it will have the format "/QSYS.LIB/library.LIB/overlay.OVL" where library is the library
of the resource and overlay is the name of the overlay. Valid special values include *FRONTOVL.
Changes
ID
ATTR_CHANGES
Type
String
Description
The time at which pending changes take effect. Valid values are *NORDYF, *FILEEND, or blank which
implies no changes pending to the writer.
Code Page
ID
ATTR_CODEPAGE
Type
String
Description
The mapping of graphic characters to code points for this spooled file. If the graphic character set
field contains a special value, this field may contain a zero (0).
Control Character
ID
ATTR_CONTROLCHAR
Type
String
Description
Whether this file uses the American National Standards printer control character. The possible values
are *NONE for no print control characters are passed in the data that is printed or *FCFC which means
that the first character of every record is an American National Standards printer control character.
Copies
ID
ATTR_COPIES
Type
Integer
Description
The total number of copies to be produced for this spooled file.
Corner Staple
ID
ATTR_CORNER_STAPLE
Type
String
Description
The reference corner to be used for a corner staple. A staple is driven into the media at the reference
corner. Valid values are *NONE, *DEVD, *BOTRIGHT, *TOPRIGHT, *TOPLEFT, and *BOTLEFT.
Data Format
ID
ATTR_DATAFORMAT
Type
String
Description
Data format. Valid values are *RCDDATA, *ALLDATA.
Data Queue
ID
ATTR_DATA_QUEUE
Type
String
Description
Specifies the Integrated File System path of the data queue that is associated with the output queue
or "*NONE" if no data queue is associated with the the output queue. The format of the Integrated File
System path is "/QSYS.LIB/library.LIB/dataqueue.DTAQ" where library is the library that contains the
data queue and dataqueue is the name of the data queue.
Defer Write
ID
ATTR_DFR_WRITE
Type
String
Description
Whether print data is held in system buffers before
Destination Type
ID
ATTR_DESTINATION
Type
String
Description
Destination type. Valid values are *OTHER, *AS400, *PSF2.
Device Class
ID
ATTR_DEVCLASS
Type
String
Description
The device class.
Device Model
ID
ATTR_DEVMODEL
Type
String
Description
The model number of the device.
Device Status
ID
ATTR_DEVSTATUS
Type
Integer
Description
The status of the printer device. Valid values are 0 (varied off), 10 (vary off pending), 20 (vary on
pending), 30 (varied on), 40 (connect pending), 60 (active), 66 (active writer), 70 (held), 75 (powered
off), 80 (recovery pending), 90 (recovery canceled), 100 (failed), 106 (failed writer), 110 (being
serviced), 111 (damaged), 112 (locked), 113 (unknown).
Device Type
ID
ATTR_DEVTYPE
Type
String
Ending Page
ID
ATTR_ENDPAGE
Type
Integer
Description
The page number at which to end printing the spooled file. Valid values are 0 or the ending page
number. The value *END is encoded as 0.
Envelope Source
ID
ATTR_ENVLP_SOURCE
Type
String
Description
The size of the envelope in the envelope source. If this field is not specified or the value is not valid,
the special value of *MFRTYPMDL is used. Valid values are *NONE - there is no envelope source,
*MFRTYPMDL - the envelope size suggested by the manufacturer type and model is used, *MONARCH
(3.875 x 7.5 inches), *NUMBER9 (3.875 x 8.875 inches), *NUMBER10 (4.125 x 9.5 inches), *B5
(176mm x 250mm), *C5 (162mm x 229mm), *DL (110mm x 220mm).
File Separators
ID
ATTR_FILESEP
Type
Integer
Description
The number of file separator pages that are placed at the beginning of each copy of the spooled file.
Valid values are -1, or the number of separators. The value *FILE is encoded as -1.
Fold Records
ID
ATTR_FOLDREC
Type
String
Description
Whether records that exceed the printer forms width are folded (wrapped) to the next line. Valid
values are *YES, *NO.
Font Identifier
ID
ATTR_FONTID
Form Definition
ID
ATTR_FORM_DEFINITION
Type
String
Description
The Integrated File System path name of the form definition or a special value. If an Integrated File
System path is specified the format is "/QSYS.LIB/library.LIB/formdef.FORMDF" where library is the
library of the form definition and formdef is the name of the form definition. Valid special values
include *NONE, *INLINE, *INLINED, and *DEVD.
Form Feed
ID
ATTR_FORMFEED
Type
String
Description
The manner in which forms feed to the printer. Valid values are *CONT, *CUT, *AUTOCUT, *DEVD.
Form Type
ID
ATTR_FORMTYPE
Type
String
Description
The type of form to be loaded in the printer to print this spooled file.
Front Overlay
ID
ATTR_FRONT_OVERLAY
Type
String
Description
The Integrated File System path of the front overlay. The format of the Integrated File System path
is "/QSYS.LIB/library.LIB/overlay.OVL" where library is the library of the resource and overlay is the
name of the overlay. The string "*NONE" is used to indicate that no front overlay is specified.
Hardware Justification
ID
ATTR_JUSTIFY
Type
Integer
Held Status
ID
ATTR_HELDSTS
Type
String
Description
Whether the writer is held. Valid values are *YES, *NO.
Image Configuration
ID
ATTR_IMGCFG
Type
String
Description
The transform services for a variety of image and print data-stream formats.
Internet Address
ID
ATTR_INTERNETADDR
IPP Attributes-charset
ID
ATTR_IPP_ATTR_CHARSET
Type
String
Description
Indicates the charset (coded character set and encoding method) of the IPP specified spooled file
attributes.
IPP Job ID
ID
ATTR_IPP_JOB_ID
Type
Integer
Description
IPP Job ID relative to the IPP printer that created the job.
Job Name
ID
ATTR_JOBNAME
Type
String
Description
The name of the job that created the spooled file.
Job Number
ID
ATTR_JOBNUMBER
Type
String
Description
The number of the job that created the spooled file.
Job Separators
ID
ATTR_JOBSEPRATR
Type
Integer
Description
The number of job separators to be placed at the beginning of the output for each job having spooled
files on this output queue. Valid values are -2, 0-9. The value *MSG is encoded as -2. Job separators
are specified when the output queue is created.
Job System
ID
ATTR_JOBSYSTEM
Type
String
Description
The system job which created spooled file was running.
Length of Page
ID
ATTR_PAGELEN
Type
Float
Description
The length of a page. Units of measurement are specified in the measurement method attribute.
Library Name
ID
ATTR_LIBRARY
Type
String
Description
The name of the library.
Line Spacing
ID
ATTR_LINESPACING
Type
String
Description
How a file's line data records are spaced when printed. The information is returned only for *LINE and
*AFPDSLINE printer device types files. Valid values are *SINGLE, *DOUBLE, *TRIPLE, or *CTLCHAR.
Measurement Method
ID
ATTR_MEASMETHOD
Type
String
Description
The measurement method that is used for the length of page and width of page attributes. Valid
values are *ROWCOL, *UOM.
Message Help
ID
ATTR_MSGHELP
Type
char(*)
Description
The message help, which is sometimes known as second-level text, can be returned by a "retrieve
message" request. The system limits the length to 3000 characters (English version must be 30% less
to allow for translation).
Message ID
ID
ATTR_MESSAGEID
Type
String
Message Queue
ID
ATTR_MESSAGE_QUEUE
Type
String
Description
The Integrated File System path of the message queue that the writer uses for operational messages.
The format of the Integrated File System path is "/QSYS.LIB/library.LIB/messageque.MSGQ" where
library is the library that contains the message queue and messageque is the name of the message
queue.
Message Reply
ID
ATTR_MSGREPLY
Type
String
Description
The message reply. Text string to be provided by the client which answers a message of type "inquiry".
In the case of message retrieved, the attribute value is returned by the server and contains the
default reply which the client can use. The system limits the length to 132 characters. Must be
null-terminated due to variable length.
Message Text
ID
ATTR_MSGTEXT
Type
String
Description
The message text, that is sometimes known as first-level text, can be returned by a "retrieve
message" request. The system limits the length to 132 characters.
Message Type
ID
ATTR_MSGTYPE
Type
String
Description
The message type, a 2-digit, EBCDIC encoding. Two types of messages indicate whether one can
"answer" a "retrieved" message: '04' Informational messages convey information without asking for a
reply (may require a corrective action instead), '05' Inquiry messages convey information and ask for a
reply.
Message Severity
ID
ATTR_MSGSEV
Type
Integer
Network Identifier
ID
ATTR_NETWORK
Type
String
Description
The network identifier of the system where the file was created.
Number of Files
ID
ATTR_NUMFILES
Type
Integer
Description
The number of spooled files that exist on the output queue.
Operator Controlled
ID
ATTR_OPCNTRL
Type
String
Description
Whether users with job control authority are allowed to manage or control the spooled files on this
queue. Valid values are *YES, *NO.
Output Bin
ID
ATTR_OUTPUTBIN
Type
Integer
Description
The output bin the printer uses for the printed output. Values range from 1 to 65535. The value *DEVD
is encoded as 0.
Output Priority
ID
ATTR_OUTPTY
Type
String
Description
The priority of the spooled file. The priority ranges from 1 (highest) to 9 (lowest). Valid values are 0-9,
where 0 represents *JOB.
Output Queue
ID
ATTR_OUTPUT_QUEUE
Type
String
Description
The Integrated File System path of the output queue. The format of the Integrated File System path
is "/QSYS.LIB/library.LIB/queue.OUTQ" where library is the library that contains the output queue and
queue is the name of the output queue.
Overall Status
ID
ATTR_OVERALLSTS
Type
Integer
Description
The overall status of the "logical printer". "Logical printer" refers to printer device, output queue
and writer job. Valid values are 1 (unavailable), 2 (powered off or not yet available), 3 (stopped),
4 (message waiting), 5 (held), 6 (stop pending), 7 (hold pending), 8 (waiting for printer), 9 (waiting
Page At A Time
ID
ATTR_PAGE_AT_A_TIME
Type
String
Description
Specifies whether the spooled file is to be opened in page-at-a-time mode. Valid values are *YES and
*NO.
Page Definition
ID
ATTR_PAGE_DEFINITION
Type
String
Description
The Integrated File System path name of the page definition or a special value. If an Integrated File
System path is specified the format is "/QSYS.LIB/library.LIB/pagedef.PAGDFN" where library is the
library of the page definition and pagedef is the name of the page definition. Valid special values
include *NONE.
Page Number
ID
ATTR_PAGENUMBER
Type
Integer
Description
The number of the page to be read from a spooled file opened in page-at-a-time mode.
Paper Source 1
ID
ATTR_PAPER_SOURCE_1
Type
String
Description
The size of the paper in paper source one. If this field is not specified or the value is not valid, the
special value of *MFRTYPMDL is used. Valid values are *NONE - there is no paper source one or the
paper is manually fed into the printer, *MFRTYPMDL - the paper size suggested by the manufacturer
type and model is used, *LETTER (8.5 x 11.0 inches), *LEGAL (8.5 x 14.0 inches), *EXECUTIVE (7.25
x 10.5 inches), *LEDGER (17.0 x 11.0 inches), *A3 (297mm x 420mm), *A4 (210mm x 297mm), *A5
(148mm x 210mm), *B4 (257mm x 364mm), *B5 (182mm x 257mm), *CONT80 (8.0 inches wide with
continuous form), *CONT132 (13.2 inches wide with continuous form).
Paper Source 2
ID
ATTR_PAPER_SOURCE_2
Type
String
Description
The size of the paper in paper source two. If this field is not specified or the value is not valid, the
special value of *MFRTYPMDL is used. Valid values are *NONE - there is no paper source two or the
paper is manually fed into the printer, *MFRTYPMDL - the paper size suggested by the manufacturer
type and model is used, *LETTER (8.5 x 11.0 inches), *LEGAL (8.5 x 14.0 inches), *EXECUTIVE (7.25
x 10.5 inches), *LEDGER (17.0 x 11.0 inches), *A3 (297mm x 420mm), *A4 (210mm x 297mm), *A5
(148mm x 210mm), *B4 (257mm x 364mm), *B5 (182mm x 257mm), *CONT80 (8.0 inches wide with
continuous form), *CONT132 (13.2 inches wide with continuous form).
Pel Density
ID
ATTR_PELDENSITY
Type
String
Description
For font resources only, this value is an encoding of the number of pels ("1" represents a pel size
of 240, "2" represents a pel size of 320). Additional values may become meaningful as the server
defines them.
Point Size
ID
ATTR_POINTSIZE
Print Fidelity
ID
ATTR_FIDELITY
Type
String
Description
The kind of error handling that is performed when printing. Valid values are *ABSOLUTE, *CONTENT.
Print Quality
ID
ATTR_PRTQUALITY
Type
String
Description
The print quality that is used when printing this spooled file. Valid values are *STD, *DRAFT, *NLQ,
*FASTDRAFT.
Print Sequence
ID
ATTR_PRTSEQUENCE
Type
String
Description
Print sequence. Valid values are *NEXT.
Print Text
ID
ATTR_PRTTEXT
Type
String
Description
The text that is printed at the bottom of each page of printed output and on separator pages. Valid
special values include *BLANK and *JOB.
Printer Assigned
ID
ATTR_PRTASSIGNED
Type
String
Description
Indicates if the printer is assigned. Valid values are 1 (assigned to a specific printer), 2 (assigned to
multiple printers), 3 (not assigned).
Printer File
ID
ATTR_PRINTER_FILE
Type
String
Description
The Integrated File System path of the printer file. The format of the Integrated File System path is
"/QSYS.LIB/library.LIB/printerfile.FILE" where library is the library that contains the printer file and
printerfile is the name of the printer file.
Printer Queue
ID
ATTR_RMTPRTQ
Type
String
Description
The name of the destination printer queue when sending spooled files via SNDTCPSPLF (LPR).
Record Length
ID
ATTR_RECLENGTH
Type
Integer
Reduce Output
ID
ATTR_REDUCE
Type
String
Description
The manner in which multiple logical pages print on each side of a physical page. Valid values *TEXT
or ????.
Remote System
ID
ATTR_RMTSYSTEM
Type
String
Description
Remote system name. Valid special values include *INTNETADR.
Replacement Character
ID
ATTR_RPLCHAR
Type
String
Description
The character that replaces any unprintable characters.
Restart Printing
ID
ATTR_RESTART
Type
Integer
Description
Restart printing. Valid values are -1, -2, -3, or the page number to restart at. The value *STRPAGE is
encoded as -1, the value *ENDPAGE is encoded as -2, and the value *NEXT is encoded as -3.
Seek Offset
ID
ATTR_SEEKOFF
Type
Integer
Description
Seek offset. Allows both positive and negative values relative to the seek origin.
Seek Origin
ID
ATTR_SEEKORG
Type
Integer
Description
Valid values include 1 (beginning or top), 2 (current), and 3 (end or bottom).
Send Priority
ID
ATTR_SENDPTY
Type
String
Description
Send priority. Valid values are *NORMAL, *HIGH.
Source Drawer
ID
ATTR_SRCDRWR
Type
Integer
Description
The drawer to be used when the automatic cut sheet feed option is selected. Valid values are -1, -2,
1-255. The value *E1 is encoded as -1, and the value *FORMDF is encoded as -2.
Spool SCS
ID
ATTR_SPLSCS
Type
Long
Description
Determines how SCS data is used during create spool file.
Started By User
ID
ATTR_STARTEDBY
Type
String
Description
The name of the user who started the writer.
Text Description
ID
ATTR_DESCRIPTION
Type
String
Description
Text to describe an instance of an AS400 object.
Total Pages
ID
ATTR_PAGES
Type
Integer
Description
The number of pages that are contained in a spooled file.
Unit of Measure
ID
ATTR_UNITOFMEAS
Type
String
Description
The unit of measure to use for specifying distances. Valid values are *CM, *INCH.
User Comment
ID
ATTR_USERCMT
Type
String
User Data
ID
ATTR_USERDATA
Type
String
Description
The 10 characters of user-specified data that describe the spooled file. Valid special values include
*SOURCE.
User ID
ID
ATTR_TOUSERID
Type
String
Description
User id to whom the spooled file is sent.
User ID Address
ID
ATTR_TOADDRESS
Type
String
Description
Address of user to whom the spooled file is sent.
VM/MVS Class
ID
ATTR_VMMVSCLASS
Type
String
Description
VM/MVS class. Valid values are A-Z and 0-9.
Width of Page
ID
ATTR_PAGEWIDTH
Type
Float
Description
The width of a page. Units of measurement are specified in the measurement method attribute.
Writer Started
ID
ATTR_WTRSTRTD
Type
String
Description
Indicates whether a writer is started for this printer. Values are 1 - yes a writer is started, 0 - no writer
is started.
Writing Status
ID
ATTR_WRTNGSTS
NPS CCSID
ID
ATTR_NPSCCSID
Type
Integer
Description
CCSID that the Network Print Server expects that all strings will be encoded in.
NPS Level
ID
ATTR_NPSLEVEL
Description
The version, release, and modification level of the Network Print Server. This attribute is a character
string encoded as VXRYMY (ie. "V3R1M0") where
X is in (0..9)
Y is in (0..9,A..Z)
SpooledFile Javadoc
Create Spooled File (QSPCRTSP) API
To construct an SCS writer, the caller needs an output stream and, optionally, an encoding. The data
stream is written to the output stream. To create an SCS spooled file, the caller first constructs a
SpooledFileOutputStream, and then uses that to construct an SCS writer object. The encoding parameter
gives a target EBCDIC coded character set identifier (CCSID) to convert the characters to.
Once the writer is constructed, use the write() methods to output text. Use the carriageReturn(),
lineFeed(), and newLine() methods to position the write cursor on the page. Use the endPage() method to
end the current page and start a new page.
When all of the data has been written, use the close() method to end the data stream and close the output
stream.
Example
“Example: Creating SCS spooled files” on page 415 shows how to generate a SCS data stream using the
SCS3812Writer class, and how to write the stream to a spooled file on the server:
Example
The following example shows how to use PrintObjectInputStream to read an existing server spooled file
Example: Reading spooled files
PrintObjectInputStream Javadoc
Example
The following example shows how to use PrintObjectPageInputStream and
PrintObjectTransformedInputStream to obtain different transformations when reading spooled file data:
“Example: Reading and transforming spooled files” on page 417
Related information
PrintObjectPageInputStream Javadoc
PrintObjectTransformedInputStream Javadoc
ProgramCall class
The IBM Toolbox for Java ProgramCall class allows the Java program to call a IBM i program. You can use
the ProgramParameter class to specify input, output, and input/output parameters. If the program runs,
the output and input/output parameters contain the data that is returned by the IBM i program. If the IBM
i program fails to run successfully, the Java program can retrieve any resulting IBM i messages as a list of
AS400Message objects.
Required parameters are as follows:
• The program and parameters to run
• The AS400 object that represents the server that has the program.
The program name and parameter list can be set on the constructor, through the ProgramCall
setProgram() method, or on the run() method The run() method calls the program.
Using the ProgramCall class causes the AS400 object to connect to the server. See managing connections
for information about managing connections.
Example: Using ProgramCall
Note: Read the Code example disclaimer for important legal information.
The following example shows how to use the ProgramCall class:
The ProgramCall object requires the integrated file system path name of the program.
The default behavior is for IBM i programs to run in a separate server job, even when the Java program
and the IBM i program are on the same server. You can override the default behavior and have the IBM i
program run in the Java job using the ProgramCall setThreadSafe() method.
ProgramCall Javadoc
ProgramParameter Javadoc
AS400Message Javadoc
AS400 Javadoc
CommandCall Javadoc
ProgramParameter Javadoc
QSYSObjectPathName class
You can use the QSYSObjectPathName class to represent an object in the integrated file system. Use
this class to build an integrated file system name or to parse an integrated file system name into its
components.
Several of the IBM Toolbox for Java classes require an integrated file system path name in order to be
used. Use a QSYSObjectPathName object to build the name.
Note: Read the Code example disclaimer for important legal information.
The following examples show how to use the QSYSObjectPathName class:
Example 1: The ProgramCall object requires the integrated file system name of the server program
to call. A QSYSObjectPathName object is used to build the name. To call program PRINT_IT in library
REPORTS using a QSYSObjectPathName:
Example 2: If the name of the object is used just once, the Java program can use the toPath() method to
build the name. This method is more efficient than creating a QSYSObjectPathName object.
Example 3: In this example, a Java program was given an integrated file system path. The
QSYSObjectPathName class can be used to parse this name into its components.
QSYSObjectPathName Javadoc
Record-level access
The record-level access classes create, read, update, and delete IBM i files and members.
• Create a IBM i physical file specifying one of the following:
– The record length
– An existing data description specifications (DDS) source file
– A RecordFormat object
• Retrieve the record format from a physical or logical file, or the record formats from a IBM i multiple
format logical file.
Note: The record format of the file is not retrieved in its entirety. The record formats retrieved are meant
to be used when setting the record format for an AS400File object. Only enough information is retrieved
to describe the contents of a record of the file. Record format information, such as column headings and
aliases, is not retrieved.
• Access the records in an IBM i file sequentially, by record number, or by key.
• Write records to a system file.
• Update records in a system file sequentially, by record number, or by key.
• Delete records in a system file sequentially, by record number, or by key.
• Lock a file for different types of access.
• Use commitment control to allow a Java program to do the following:
– Start commitment control for the connection.
– Specify different commitment control lock levels for different files.
– Commit and rollback transactions.
• Delete system files.
• Delete a member from a system file.
Note: The record-level access classes do not support logical join files or null key fields.
The following classes perform these functions:
• The AS400File class is the abstract base class for the record-level access classes. It provides the
methods for sequential record access, creation and deletion of files and members, and commitment
control activities.
• The KeyedFile class represents a system file that has access by key.
• The SequentialFile class represents a system file that has access by record number.
• The AS400FileRecordDescription class provides the methods for retrieving the record format of a
system file.
AS400File
The AS400File class provides the methods for several actions.
• Creating and deleting server physical files and members
• Reading and writing records in server files
• Locking files for different types of access
• Using record blocking to improve performance
• Setting the cursor position within an open server file
• Managing commitment control activities
Related information
AS400File Javadoc
KeyedFile
The KeyedFile class gives a Java program keyed access to a file on the server. Keyed access means that
the Java program can access the records of a file by specifying a key. Methods exist to position the cursor,
read, update, and delete records by key.
To position the cursor, use the following methods:
• positionCursor(Object[]) - set cursor to the first record with the specified key.
• positionCursorAfter(Object[]) - set cursor to the record after the first record with the specified key.
• positionCursorBefore(Object[]) - set cursor to the record before the first record with the specified key.
To delete a record, use the following method:
• deleteRecord(Object[]) - delete the first record with the specified key.
The read methods are:
• read(Object[]) - read the first record with the specified key.
• readAfter(Object[]) - read the record after the first record with the specified key.
• readBefore(Object[]) - read the record before the first record with the specified key.
• readNextEqual() - read the next record whose key matches the specified key. Searching starts from the
record after the current cursor position.
• readPreviousEqual() - read the previous record whose key matches the specified key. Searching starts
from the record before the current cursor position.
A KeyedFile object accepts partial keys as well as complete keys. However, the key field values that are
specified must be in order.
For example:
....
Related information
KeyedFile Javadoc
SequentialFile
The SequentialFile class gives a Java program access to a file on the server by record number. Methods
exist to position the cursor, read, update, and delete records by record number.
To position the cursor, use the following methods:
• positionCursor(int) - set cursor to the record with the specified record number.
• positionCursorAfter(int) - set cursor to the record after the specified record number.
• positionCursorBefore(int) - set cursor to the record before the specified record number.
To delete a record, use the following method:
• deleteRecord(int) - delete the record with the specified record number.
To read a record, use the following methods:
• read(int) - read the record with the specified record number.
• readAfter(int) - read the record after the specified record number.
• readBefore(int) - read the record before the specified record number.
To update a record, use the following method:
• update(int) - update the record with the specified record number.
SequentialFile is a subclass of AS400File; all methods in AS400File are available to SequentialFile.
The following example shows how to use the SequentialFile class:
// ....
Related information
SequentialFile Javadoc
AS400FileRecordDescription
The IBM Toolbox for Java AS400FileRecordDescription class provides the methods for retrieving the
record format of a file on the server.
This class provides methods for creating Java source code for subclasses of RecordFormat and for
returning RecordFormat objects, which describe the record formats of user-specified physical or logical
files on the server. The output of these methods can be used as input to an AS400File object when setting
the record format.
It is recommended that the AS400FileRecordDescription class always be used to generate the
RecordFormat object when the file already exists on the server.
Note: The AS400FileRecordDescription class does not retrieve the entire record format of a file. Only
enough information is retrieved to describe the contents of the records that make up the file. Information
such as column headings, aliases, and reference fields is not retrieved. Therefore, the record formats
retrieved cannot necessarily be used to create a file whose record format is identical to the file from which
the format was retrieved.
Creating Java source code for subclasses of RecordFormat to represent the record format of files on
the server
The AS400FileRecordDescription createRecordFormatSource() method creates Java source files for
subclasses of the RecordFormat class. The files can be compiled and used by an application or applet as
input to the AS400File.setRecordFormat() method.
// Assuming that the format name for file MYFILE is FILE1, the
// file FILE1Format.java will be created in the current working directory.
// It will overwrite any file by the same name. The name of the class
// will be FILE1Format. The class will extend from RecordFormat.
Example 2: Compile the file you created above, FILE1Format.java, and use it as follows:
myFile.setRecordFormat(new FILE1Format());
Creating RecordFormat objects to represent the record format of files on the server
The AS400FileRecordDescription retrieveRecordFormat() method returns an array of RecordFormat
objects that represent the record formats of an existing file on the server. Typically, only one
RecordFormat object is returned in the array. When the file for which the record format is being retrieved
is a multiple format logical file, more than one RecordFormat object is returned. Use this method to
dynamically retrieve the record format of an existing file on the server during runtime. The RecordFormat
object then can be used as input to the AS400File.setRecordFormat() method.
The following example shows how to use the retrieveRecordFormat() method:
AS400FileRecordDescription Javadoc
RecordFormat Javadoc
AS400File Javadoc
// ....
// ....
Example 3: When creating a file specifying a RecordFormat object, the RecordFormat object is specified
on the create() method. The method sets the record format for the object. The setRecordFormat() method
must not be called for the object.
// ....
....
Use the update() method to update the record at the cursor position.
For example:
....
Use the write() method to append records to the end of a file. A single record or an array of records can be
appended to the file.
Use the deleteCurrentRecord() method to delete the record at the cursor position.
Related information
AS400File Javadoc
Locking files
The Java program can lock a file to prevent other users from accessing the file while the first Java
program is using the file.
Lock types are as follows. You can find more information about the lock types in the AS400File Javadoc.
• Read/Exclusive Lock - The current Java program reads records, and no other program can access the
file.
• Read/Allow shared read Lock - The current Java program reads records, and other programs can read
records from the file.
• Read/Allow shared write Lock - The current Java program reads records, and other programs can
change the file.
• Write/Exclusive Lock - The current Java program changes the file, and no other program can access the
file.
• Write/Allow shared read Lock - The current Java program changes the file, and other programs can read
records from the file.
// The records read in this loop will be served out of the block of
// records cached on the client.
record = myFile.readNext();
}
....
• If the file is opened for write-only access, the blocking factor indicates how many records are written to
the file at one time when the write(Record[]) method is invoked.
For example:
....
• If the file is opened for read-write access, no blocking is done. Any blocking factor specified on open() is
ignored.
AS400File Javadoc
....
Related information
AS400File Javadoc
Commitment control
Through commitment control, your Java program has another level of control over changing a file. With
commitment control turned on, transactions to a file are pending until they are either committed or
rolled back. If committed, all changes are put to the file. If rolled back, all changes are discarded. The
transaction can be changing an existing record, adding a record, deleting a record, or even reading a
record depending on the commitment control lock level specified on the open().
The levels of commitment control are as follows. To see more details about each level, refer to the
AS400File Javadoc.
• All - Every record accessed in the file is locked until the transaction is committed or rolled back.
• Change - Updated, added, and deleted records in the file are locked until the transaction is committed
or rolled back.
• Cursor Stability - Updated, added, and deleted records in the file are locked until the transaction is
committed or rolled back. Records that are accessed but not changed are locked only until another
record is accessed.
• None - There is no commitment control on the file. Changes are immediately put to the file and cannot
be rolled back.
You can use the AS400File startCommitmentControl() method to start commitment control. Commitment
control applies to the AS400 connection. Once commitment control is started for a connection,
it applies to all files opened under that connection from the time that commitment control was
started. Files opened before commitment control is started are not under commitment control.
The level of commitment control for individual files is specified on the open() method. Specify
COMMIT_LOCK_LEVEL_DEFAULT to use the same level of commitment control as was specified on the
startCommitmentControl() method.
For example:
ourFile.setRecordFormat(new OURFILEFormat());
// Specify a different commit lock level than
// when commitment control was started
ourFile.open(AS400File.READ_WRITE, 0, COMMIT_LOCK_LEVEL_CURSOR_STABILITY);
The commit() method commits all transactions since the last commit boundary for the connection.
The rollback() method discards all transactions since the last commit boundary for the connection.
Commitment control for a connection is ended through the endCommitmentControl() method. If a file is
closed before invoking the commit() or rollback() method, all uncommitted transactions are rolled back.
All files opened under commitment control must be closed before the endCommitmentControl() method
is called.
The following examples shows how to start commitment control, commit or roll back functions, and then
end commitment control:
Related information
AS400File Javadoc
SaveFile class
The SaveFile class represents a save file on a server.
Related information
SaveFile Javadoc
ServiceProgramCall class
The IBM Toolbox for Java ServiceProgramCall class allows you to call an IBM i service program.
ServiceProgramCall is a subclass of the ProgramCall class that you use to call IBM i programs. If you
want to call an IBM i program, use the ProgramCall class.
The ServiceProgramCall class makes it possible for you to call an IBM i service program, pass data to a
service program through input parameters, and access data the service program returns through output
parameters. Using ServiceProgramCall causes the AS400 object to connect to the server. See managing
connections for information about managing connections.
The default behavior is for service programs to run in a separate server job, even when the Java program
and the service program are on the same server. You can override the default behavior and have the
service program run in the Java job using the setThreadSafe() method, inherited from ProgramCall.
Using the ServiceProgramCall class
In order to use the ServiceProgramCall class, you must be sure to meet the following requirements:
• The service program must be on an server
• You can pass no more than seven parameters to the service program
• The return value of the service program is void or numeric
Working with ProgramParameter objects
The ProgramParameter class works with the ServiceProgramCall class to pass parameter data to and from
an IBM i service program. You pass input data to the service program with setInputData().
You request the amount of output data you want returned with setOutputDataLength(). You retrieve
the output data after the service program is finished running with getOutputData(). In addition to the
data itself, ServiceProgramCall needs to know how to pass parameter data to the service program. The
setParameterType() method of ProgramParameter is used to supply this information. The type indicates
if the parameter is pass by value or pass by reference. In either case, data is sent from the client to the
server. Once the data is on the server, the server uses the parameter type to correctly call the service
program.
All parameters will be in the form of a byte array. Therefore, to convert between IBM i and Java formats,
you use the data conversion and description classes.
ServiceProgramCall Javadoc
ProgramCall Javadoc
ProgramParameter Javadoc
Subsystem class
The Subsystem class represents a subsystem on the server.
Related information
Subsystem Javadoc
SystemStatus Javadoc
SystemPool class
The SystemPool class allows you to retrieve and change system pool information.
The SystemPool class includes the following methods:
• The getPoolSize() method returns the size of the pool, and the setPoolSize() method sets the size of the
pool.
Related information
SystemPool Javadoc
System values
The system value classes allow a Java program to retrieve and change system values and network
attributes. You can also define your own group to contain the system values you want.
A SystemValue object primarily contains the following information:
• Name
• Description
• Release
• Value
Using the SystemValue class, retrieve a single system value by using the getValue() method and change a
system value by using the setValue() method.
You can also retrieve group information about a particular system value:
• To retrieve the system-defined group to which a system value belongs, use the getGroup() method.
• To retrieve the user-defined group to which a SystemValue object belongs (if any), use the
getGroupName() and getGroupDescription() methods.
Whenever the value of a system value is retrieved for the first time, the value is retrieved from the server
and cached. On subsequent retrievals, the cached value is returned. If the current value is what you want
instead of the cached value, a clear() must be done to clear the current cache.
//At this point QSECOND is cached. Clear the cache to retrieve the most
//up-to-date value from the system.
sysval.clear();
second = (String)sysval.getValue();
//Create a system value group initially representing all of the network attributes on the
system.
String name = "My Group";
String description = "This is one of my system values.";
SystemValueGroup svGroup = new SystemValueGroup(sys, name, description,
SystemValueList.GROUP_NET);
//Add some more system value names to the group and remove some we do not want.
svGroup.add("QDATE");
svGroup.add("QTIME");
svGroup.remove("NETSERVER");
svGroup.remove("SYSNAME");
//Obtain the actual SystemValue objects. They are returned inside a Vector.
Vector sysvals = svGroup.getSystemValues();
//We can add another SystemValue object from another system into the group.
AS400 sys2 = new AS400("otherSystem.myCompany.com");
SystemValue sv = new SystemValue(sys2, "QDATE");
sysvals.addElement(sv);
SystemValue Javadoc
SystemValueList Javadoc
SystemValueGroup Javadoc
Trace class
The Trace class allows the Java program to log trace points and diagnostic messages. This information
helps reproduce and diagnose problems.
Note: You can also set tracing by using the trace system properties.
The Trace class logs the following categories of information:
The IBM Toolbox for Java classes also use the trace categories. When a Java program enables logging,
IBM Toolbox for Java information is included with the information that is recorded by the application.
You can enable the trace for a single category or a set of categories. Once the categories are selected,
use the setTraceOn method to turn tracing on and off. Data is written to the log using the log method.
You can send trace data for different components to separate logs. Trace data, by default, is written
to the default log. Use component tracing to write application-specific trace data to a separate log or
standard output. By using component tracing, you can easily separate trace data for a specific application
from other data.
Examples
Note: Read the Code example disclaimer for important legal information.
The following examples show how to use the Trace class.
Example Using setTraceOn() and writing data to a log by using the log method
// Send IBM Toolbox for Java and the component trace data each to separate files.
// The trace will contain all trace information, while each
// component log file will only contain trace information specific to
// that component. If a Trace file is not specified, all trace data
// will go to standard out with the component specified in front of
// each trace message.
// Trace.setFileName("c:\\bit.bucket");
// Trace.setFileName(myComponent1, "c:\\Component1.log");
// Trace.setFileName(myComponent2, "c:\\Component2.log");
// Log component specific trace data or general IBM Toolbox for Java
// trace data.
Trace.setFileName("c:\\bit.bucket");
Trace.setFileName(myComponent1, "c:\\Component1.log");
Related information
Trace Javadoc
UserSpace class
The UserSpace class represents a user space on the server. Required parameters are the name of the user
space and the AS400 object that represents the server that has the user space.
Methods exist in user space class to do the following:
• Create a user space.
• Delete a user space.
• Read from a user space.
• Write to user space.
• Get the attributes of a user space. A Java program can get the initial value, length value, and automatic
extendible attributes of a user space.
• Set the attributes of a user space. A Java program can set the initial value, length value, and automatic
extendible attributes of a user space.
The UserSpace object requires the integrated file system path name of the program. See integrated file
system path names for more information.
Using the UserSpace class causes the AS400 object to connect to the server. See managing connections
for information about managing connections.
The following example creates a user space, then writes data to it.
Note: Read the Code example disclaimer for important legal information.
UserSpace Javadoc
AS400 Javadoc
Commtrace classes
The IBM Toolbox for Java commtrace classes enable your Java programs to work with communications
trace data for a specified LAN (Ethernet or token ring) line description. The commtrace package includes a
class that you can run as a standalone utility program to format communications trace data.
When you dump a communications trace for a server to a stream file, the information is saved in a binary
format. The commtrace classes enable you to work with the various components of the stream file.
Note: Communications trace files may contain confidential information, for example, unencrypted
passwords. When the communications trace file is on server, only users who have *SERVICE special
authority can access the trace data. If you move the file to a client, make sure that you protect the file in
Commtrace model
The following illustration shows how the commtrace classes correspond to a communications trace file.
The graphic also indicates the naming conventions that the commtrace classes use for the components in
a communications trace.
Figure 1: Commtrace model
Each Frame in the trace file contains two initial sections (that provide general information about the
contents of the frame) and the packet that the server transmitted between itself and a different point on
the network.
The very first 24-byte section of data contains general information about the contents of the frame, such
as the frame number and data length. Use the Frame class to process this information.
Format class
Use the format class to read both the raw trace data and the trace data that you have already formatted
by using the commtrace classes.
Note: You cannot use the commtrace classes to read a communications trace that you formatted by using
the Print Communications Trace (PRTCMNTRC) control language command.
Use the Format class to parse and format the information in a trace, then send that formatted information
to a file or a print device. Additionally, you might want to create a graphical front end that displays the
information in a standalone application or within a browser. When you want to select only specific data,
use the Format class to supply that information to your Java program. For example you could use the
Format class to read IP addresses out of a trace and then use that data in your program.
The Format constructors accept arguments that represent unformatted data, such as an
IFSFileInputStream object, a local file, or the binary trace file. To display a trace that you have already
formatted, use the default Format constructor, then use Format.openIFSFile() or Format.openLclFile() to
specify the formatted file that you want to display.
Examples
The following examples show how you can display a saved trace or format a binary trace.
Note: Read the Code example disclaimer for important legal information.
Example: Displaying a saved trace
FormatProperties class
Use the FormatProperties class to specify and retrieve the properties for your Format object. In other
words, when you use the Format class to send information to a file, use the FormatProperties class to
filter the information that you want to send.
These properties specify how you want your Format object to handle the information that it encounters
in the Frames of the communications trace. The default behavior is for the Format object to ignore
properties for which you have not given a specific value.
The FormatProperties class provides constants that you use to set properties. Setting properties enables
the Format object to verify which filters you want to use. For example, the following code sets a Format
object to display a progess dialog and not display broadcast frames:
Most of the properties are available to your Format object as filters that you set to explicitly include
specific data. Once you set the filters, the Format object displays only data that matches those filters. For
example, the following code set a filter to display frames that occurred between a particular start and end
time:
Example
The following example shows how you can use many of the commtrace classes, including the Format and
FormatProperties classes, to display trace information to your monitor:
“Example: Using the commtrace classes” on page 184
Format Javadoc
FormatProperties Javadoc
where [options] equals one or more of the available options. Options include:
String[] args2 =
{ "-c", "true", "-t", "/path/to/trace", "-o", "/path/to/trace.extension"};
jaCall.setParameters(args2);
if (jaCall.run() != true) {
// Call Failed
}
Related information
Format Javadoc
Prolog class
The IBM Toolbox for Java Prolog class represents the initial 256-byte section of a communications trace
for a LAN line description. The Prolog contains general information about the trace, such as start and end
times, number of bytes collected, and so on. Use the Prolog class to retrieve information from this section
of trace, which you can then print, display, filter, or process in some other way.
The Prolog class provides methods that allow you to perform a variety of actions that include the
following:
• Retrieve values from the fields of the prolog, such as the trace description, Ethernet Type, data
direction, IP address, and so on
• Return a formatted String that contains all the fields of the prolog
• Test the prolog fields for invalid data
Example
The following example shows how you can use many of the commtrace classes, including the Prolog
class, to display trace information to your monitor:
“Example: Using the commtrace classes” on page 184
Related information
Prolog Javadoc
Frame class
The Frame class represents all the data in one record, or frame, in a communications trace for a LAN line
description.
Each Frame contains three main sections of data that appear in the following order:
Example
The following example shows how you can use many of the commtrace classes, including the Format and
FormatProperties classes, to display trace information to your monitor:
“Example: Using the commtrace classes” on page 184
LanHeader class
The LanHeader class retrieves information from the section of data that occurs once, near the beginning
of a frame, in the initial 24-byte section. This section typically contains hardware-specific information that
includes general information about the frame, such as the frame number, and data length.
Use the LanHeader class to parse and print the information in the LanHeader. The kind of information
contained by the LanHeader includes:
• The byte that identifies the start of the first header in this packet
• Medium Access Control (MAC) addresses
• Token ring addresses and routing information
LanHeader also provides two methods that enable you to return a formatted String that contains the
following:
• Token ring routing data
• Source MAC addresses, destination MAC addresses, frame format, and frame type
Related information
LanHeader Javadoc
IPPacket class
The IBM Toolbox for Java IPPacket class represents all the data packets that the network transmitted
for this frame during the communications trace. IPPacket is an abstract class, so you will use the various
concrete subclasses to process the headers and data in the packets.
The subclasses of IPPacket include:
Header class
The Header class is the abstract superclass for creating classes that represent specific kinds of packet
headers. Packet headers include the associated data (or payload), which can be other headers and
payloads.
The subclasses of Header include:
• ARPHeader
• ExtHeader
• ICMP4Header
• ICMP6Header
• IP4Header
• IP6Header
• TCPHeader
• UDPHeader
• UnknownHeader
Header classes enable you to retrieve the data for the header and the payload. One header can
encapsulate other headers and their payloads.
Creating an instance of a Packet class automatically creates the appropriate Header object. The Header
classes provide methods that allow you to perform a variety of actions that include the following:
• Return the length, name, and type of the header
• Retrieve the data in the header as a byte array
• Retrieve the next header in the packet
• Retrieve the payload as a byte array, ASCII string, and hexadecimal string
//////////////////////////////////////////////////////////////////////
//
// Example using the commtrace classes to print communications trace
// data to a monitor by using a communications trace binary file as
// the source for the data.
//
// Command syntax:
// java CommTraceExample
//
//////////////////////////////////////////////////////////////////////
import com.ibm.as400.util.commtrace.*;
public CommTraceExample() {
// Create a FormatProperties. By default display everything.
FormatProperties fmtprop = new FormatProperties();
// If IP6 IPPacket
if (p.getType() == IPPacket.IP6) {
// If IP6 Header
if (h.getType() == Header.IP6) {
// If it is a TCP header
if (h.getType() == Header.TCP) {
// Cast so we can access methods
TCPHeader tcp = (TCPHeader) h;
System.out.println(h.getName() +" src:" + tcp.getSrcPort() +" dst:" +
tcp.getDstPort());
System.out.println("Complete " + h.getName() + ":\n" + tcp.toString(fmtprop));
// If it is a UDP header
} else if (h.getType() == Header.UDP) {
// Cast so we can access methods
UDPHeader udp = (UDPHeader) h;
System.out.println(h.getName() +" src:" + udp.getSrcPort() + " dst:" +
udp.getDstPort());
System.out.println("Complete " + h.getName() + ":\n" + udp.toString(fmtprop));
}
}
}
}
}
}
}
HTML Classes
The IBM Toolbox for Java HTML classes provide representations for many common HTML tag elements.
IBM Toolbox for Java HTML classes assist you in:
• Setting up forms and tables for HTML pages
• Aligning text
• Working with a variety of HTML tags
• Creating Extensible Stylesheet Language (XSL) formatting object (FO) source data
• Altering the language and direction of text
• Creating ordered and unordered lists
• Creating file lists and HTML hierarchical trees (and the elements within them)
• Adding tag attributes not already defined in the HTML classes (for example, bgcolor and style attributes)
The HTML classes implement the HTMLTagElement interface. Each class produces an HTML tag for a
specific element type. The tag may be retrieved using the getTag() method and can then be embedded
into any HTML document. The tags you generate with the HTML classes are consistent with the HTML 3.2
specification.
The HTML classes can work with servlet classes to get data from the server. However, they can also be
used alone if you supply the table or form data.
Additionally, you can use the HTMLDocument class to easily create HTML pages or XSL FO source data.
You can convert XSL FO data into Portable Document Format (PDF) documents. Using the PDF format
enables your documents to retain the same graphical appearance when you print them as when you view
them electronically.
BidiOrdering class
The IBM Toolbox for Java BidiOrdering class represents an HTML tag that alters the language and
direction of text. An HTML <BDO> string requires two attributes, one for language and the other for
the direction of the text.
The BidiOrdering class allows you to:
• Get and set the language attribute
• Get and set the direction of text
For more information about using the <BDO> HTML tag, see the W3C Web site.
// Add the text to the BidiOrdering and get the HTML tag.
bdo.addItem(text);
bdo.getTag();
When you use this tag in an HTML page, browsers that can understand the <BDO> tag display the
example like this:
.txeT cibarA emoS
Related information
BidiOrdering Javadoc
HTMLAlign class
The IBM Toolbox for Java HTMLAlign class enables you to align sections of your HTML document, instead
of just aligning individual items such as paragraphs or headings.
The HTMLAlign class represents the <DIV> tag and its associated align attribute. You can use right, left, or
center alignment.
<div align="center">
<ul type="disc">
<li>Centered unordered list</li>
<li>Another item</li>
</ul>
When you use this tag in an HTML page, it looks like this:
• Centered unordered list
• Another item
Related information
HTMLAlign Javadoc
HTMLDocument class
The HTMLDocument class enables you to use existing IBM Toolbox for Java HTML classes to create either
HTML pages or Portable Document Format (PDF) documents.
When you create an HTMLDocument, you specify whether it contains HTML tags or Extensible Stylesheet
Language (XSL) Formatting Object (FOs) tags:
• When you want to create HTML pages, the HTMLDocument class offers you an easier way to group all
the required HTML tags. However, HTML pages do not always look the same when you print them as
when you view them in a Web browser.
• When you want to create PDF documents, the HTMLDocument class offers you the ability to create
XSL FO source that contains all the information you need to produce a PDF document. PDF documents
retain the same graphical appearance when you print them as when you view them electronically.
To use HTMLDocument, you need to include an XML parser and an XSLT processor in your CLASSPATH
environment variable. For more information, see the following pages:
• “JAR files” on page 7
• “XML parser and XSLT processor” on page 311
Example: Using HTMLDocument to generate both HTML source and XSL FO source
The following example shows how to generate both HTML source data and XSL FO source data at the
same time:
“Example: Using HTMLDocument to generate both HTML source and XSL FO source” on page
193
///////////////////////////////////////////////////////////////////////////////
//
// Example: Converting XSL FO source to a PDF.
//
// This program uses the IBM Toolbox for Java ReportWriter classes to convert
// XSL FO source data (created by using HTMLDocument) to a PDF.
//
// This example requires the following.jars to be in the classpath.
//
// composer.jar
// outputwriters.jar
// reportwriter.jar
// x4j400.jar
// xslparser.jar
//
// These JAR files are part of the IBM ToolBox for Java, and reside in directory
// /QIBM/ProdData/HTTP/Public/jt400/lib on your server.
//
// You will also need the class definition for
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.awt.print.Paper;
import java.awt.print.PageFormat;
import org.w3c.dom.Document;
import com.ibm.xsl.composer.framework.Context;
import com.ibm.as400.util.reportwriter.pdfwriter.PDFContext;
import com.ibm.as400.util.reportwriter.processor.XSLReportProcessor;
try
{
String inName = args[0];
String outName = args[1];
try
{
fin = new FileInputStream(inName);
fout = new FileOutputStream(outName);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
/*
* Setup Page format.
*/
Paper paper = new Paper();
paper.setSize(612, 792);
paper.setImageableArea(0, 0, 756, 936);
/*
* Create a PDF context. Set output file name.
*/
PDFContext pdfContext = new PDFContext(fout, pageFormat);
/*
* Create XSLReportProcessor instance.
*/
XSLReportProcessor report = new XSLReportProcessor(pdfContext);
/*
* Open XML FO source.
*/
try
{
report.setXSLFOSource(fin);
}
catch (Exception e)
/*
* Process the report.
*/
try
{
report.processReport();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
/* exit */
System.exit(0);
}
}
Example: Using HTMLDocument to generate both HTML source and XSL FO source
This example uses the HTMLDocument class to generate HTML and XSL FO source data.
Note: Read the Code example disclaimer for important legal information.
///////////////////////////////////////////////////////////////////////////////
//
// Example: Using the Toolbox HTMLDocument Class
// to generate both HTML and XSL FO source data.
//
// This program uses the HTMLDocument class to
// generate two files: one that has HTML source and
// another than has XSL FO source.
//
// Command syntax:
// HTMLDocumentExample
//
///////////////////////////////////////////////////////////////////////////////
import com.ibm.as400.util.html.*;
import java.*;
import java.io.*;
import java.lang.*;
import java.beans.PropertyVetoException;
// Create an UnorderedList.
UnorderedList uList = new UnorderedList(HTMLConstants.SQUARE);
// Create and set the data for UnorderedListItems.
UnorderedListItem listItem1 = new UnorderedListItem();
UnorderedListItem listItem2 = new UnorderedListItem();
listItem1.setItemData(new HTMLText("First item"));
listItem2.setItemData(new HTMLText("Second item"));
// Add the list items to the UnorderedList.
uList.addListItem(listItem1);
uList.addListItem(listItem2);
// Create an OrderedList.
OrderedList oList = new OrderedList(HTMLConstants.SMALL_ROMAN);
// Create the OrderedListItems.
OrderedListItem olistItem1 = new OrderedListItem();
OrderedListItem olistItem2 = new OrderedListItem();
OrderedListItem olistItem3 = new OrderedListItem();
// Set the data in the OrderedListItems.
olistItem1.setItemData(new HTMLText("First item"));
olistItem2.setItemData(new HTMLText("Second item"));
olistItem3.setItemData(new HTMLText("Third item"));
// Add the list items to the OrderedList.
oList.addListItem(olistItem1);
oList.addListItem(olistItem2);
// Add (nest) the unordered list to OrderedListItem2
oList.addList(uList);
// Add another OrderedListItem to the OrderedList
// after the nested UnorderedList.
oList.addListItem(olistItem3);
table.addColumnHeader(account_header);
table.addColumnHeader(name_header);
table.addColumnHeader(balance_header);
// Add rows to the table. Each customer record represents a row in the table.
int numCols = 3;
for (int rowIndex=0; rowIndex< 5; rowIndex++)
{
HTMLTableRow row = new HTMLTableRow();
row.setHorizontalAlignment(HTMLTableRow.CENTER);
row.addColumn(new HTMLTableCell(account));
row.addColumn(new HTMLTableCell(name));
row.addColumn(new HTMLTableCell(balance));
}
}
FormInput classes
The IBM Toolbox for Java FormInput class represents an input element in an HTML form.
The FormInput class allows you to:
• Get and set the name of an input element
• Get and set the size of an input element
• Get and set the initial value of an input element
The FormInput class is extended by the classes in the following list. These classes provide a way to create
specific types of form input elements and allow you to get and set various attributes or retrieve the HTML
tag for the input element:
• ButtonFormInput: Represents a button element for an HTML form
• FileFormInput: Represents a file input type, for an HTML form
• HiddenFormInput: Represents a hidden input type for an HTML form
• ImageFormInput: Represents an image input type for an HTML form.
• ResetFormInput: Represents a reset button input for an HTML form
• SubmitFormInput: Represents a submit button input for an HTML form
• TextFormInput: Represents a single line of text input for an HTML form where you define the maximum
number of characters in a line. For a password input type, you use PasswordFormInput, which extends
TextFormInput and represents a password input type for an HTML form
• ToggleFormInput: Represents a toggle input type for an HTML form. The user can set or get the text
label and specify whether the toggle should be checked or selected. The toggle input type can be one of
two:
– RadioFormInput: Represents a radio button input type for an HTML form. Radio buttons may be
placed in groups with the RadioFormInputGroup class; this creates a group of radio buttons where
the user selects only one of the choices presented.
– CheckboxFormInput: Represents a checkbox input type for an HTML form where the user may select
more than one from the choices presented, and where the checkbox is initialized as either checked or
unchecked.
FormInput Javadoc
ToggleFormInput Javadoc
RadioFormInputGroup Javadoc
Related information
ButtonFormInput Javadoc
FileFormInput class
The IBM Toolbox for Java FileFormInput class represents a file input type in an HTML form.
The following code example shows you how to create a new FileFormInput object
Related information
FileFormInput Javadoc
HiddenFormInput class
The IBM Toolbox for Java HiddenFormInput class represents a hidden input type in an HTML form.
The following code example shows how to create a HiddenFormInput object:
In an HTML page, the HiddenInputType does not display. It sends the information (in this case the
account number) back to the server.
Related information
HiddenFormInput Javadoc
ImageFormInput class
The ImageFormInput class represents an image input type in an HTML form.
You can retrieve and update many of the attributes for the ImageFormInput class by using the methods
provided.
• Get or set the source
• Get or set the alignment
• Get or set the height
• Get or set the width
Related information
ImageFormInput Javadoc
ResetFormInput class
The ResetFormInput class represents a reset button input type in an HTML form.
The following code example shows you how to create a ResetFormInput object:
Related information
ResetFormInput Javadoc
SubmitFormInput class
The SubmitFormInput class represents a submit button input type in an HTML form.
The following code example shows you how to create a SubmitFormInput object:
Related information
SubmitFormInput Javadoc
TextFormInput class
The TextFormInput class represents a single line text input type in an HTML form. The TextFormInput
class provides methods that let you get and set the maximum number of characters a user can enter in
the text field.
The following example shows you how to create a new TextFormInput object:
PasswordFormInput class
The PasswordFormInput class represents a password input field type in an HTML form.
The following code example shows you how to create a new PasswordFormInput object:
Related information
PasswordFormInput Javadoc
RadioFormInput class
The RadioFormInput class represents a radio button input type in an HTML form. The radio button may be
initialized as selected when constructed.
A set of radio buttons with the same control name make a radio button group. The RadioFormInputGroup
class creates radio button groups. Only one radio button within the group may be selected at any time.
Also, a specific button may be initialized as selected when the group is constructed.
The following code example shows you how to create a RadioFormInput object:
RadioFormInput Javadoc
RadioFormInputGroup Javadoc
CheckboxFormInput class
The IBM Toolbox for Java CheckboxFormInput class represents a checkbox input type in an HTML form.
The user may select more than one of the choices presented as checkboxes within a form.
The following example shows you how to create a new CheckboxFormInput object:
LayoutFormPanel class
The IBM Toolbox for Java LayoutFormPanel class represents a layout of form elements for an HTML form.
You can use the methods provided by the LayoutFormPanel to add and remove elements from a panel or
get the number of elements in the layout.
You may choose to use one of two layouts:
• GridLayoutFormPanel: Represents a grid layout of form elements for an HTML form
• LineLayoutFormPanel: Represents a line layout of form elements for an HTML form
LayoutFormPanel Javadoc
GridLayoutFormPanel
The GridLayoutFormPanel class represents a grid layout of form elements. You use this layout for an
HTML form where you specify the number of columns for the grid.
The following example creates a GridLayoutFormPanel object with two columns:
// Create the GridLayoutFormPanel object with two columns and add the form elements.
GridLayoutFormPanel panel = new GridLayoutFormPanel(2);
panel.addElement(sysPrompt);
panel.addElement(system);
panel.addElement(userPrompt);
panel.addElement(user);
panel.addElement(passwordPrompt);
panel.addElement(password);
Related information
GridLayoutFormPanel Javadoc
CheckboxFormInput privacyCheckbox =
new CheckboxFormInput("confidential", "yes", "Confidential", true);
CheckboxFormInput mailCheckbox =
new CheckboxFormInput("mailingList", "yes", "Join our mailing list", false);
LineLayoutFormPanel panel = new LineLayoutFormPanel();
panel.addElement(privacyCheckbox);
panel.addElement(mailCheckbox);
String tag = panel.getTag();
Related information
LineLayoutFormPanel Javadoc
TextAreaFormElement class
The TextAreaFormElement class represents a text area element in an HTML form. You specify the size
of the text area by setting the number of rows and columns. You can determine the size that a text area
element is set for with the getRows() and getColumns() methods.
You set the initial text within the text area with the setText() method. You use the getText() method to see
what the initial text has been set to.
The following example shows you how to create a TextAreaFormElement:
<form>
<textarea name="foo" rows="3" cols="40">
Default TEXTAREA value goes here
</textarea>
</form>
TextAreaFormElement Javadoc
LabelFormElement class
The LabelFormElement class represents a label for an HTML form element.
You use the LabelFormElement class to label elements of an HTML form such as a text area or password
form input. The label is one line of text that you set using the setLabel() method. This text does not
respond to user input and is there to make the form easier for the user to understand.
Account Balance
Related information
LabelFormElement Javadoc
SelectFormElement class
The SelectFormElement class represents a select input type for an HTML form. You can add and remove
various options within the select element.
SelectFormElement has methods available that allow you to view and change attributes of the select
element:
• Use setMultiple() to set whether or not the user can select more than one option
• Use getOptionCount() to determine how many elements are in the option layout
• Use setSize() to set the number of options visible within the select element and use getSize() to
determine the number of visible options.
The following example creates a SelectFormElement object with three options. The SelectFormElement
object named list, is highlighted. The first two options added specify the option text, name, and select
attributes. The third option added is defined by a SelectOption object.
<select name="list1">
<option value="opt1">Option1</option>
<option value="opt2">Option2</option>
<option value="opt3" selected="selected">Option3</option>
</select>
Related reference
“SelectOption class” on page 202
The SelectOption class represents an option in an HTML SelectFormElement. You use the option form
element in a select form.
Related information
SelectFormElement Javadoc
SelectOption class
The SelectOption class represents an option in an HTML SelectFormElement. You use the option form
element in a select form.
Methods are provided that you can use to retrieve and set attributes within a SelectOption. For instance,
you can set whether the option defaults to being selected. You can also set the input value it will use
when the form is submitted.
The following example creates three SelectOption objects within a select form. Each of the following
SelectOption objects are highlighted. They are named option1, option2 and option3. The option3 object is
initially selected.
<select name="list1">
<option value="opt1">Option1</option>
<option value="opt2">Option2</option>
<option value="opt3" selected="selected">Option3</option>
</select>
Related reference
“SelectFormElement class” on page 202
The SelectFormElement class represents a select input type for an HTML form. You can add and remove
various options within the select element.
Related information
SelectOption Javadoc
RadioFormInputGroup class
The RadioFormInputGroup class represents a group of RadioFormInput objects. A user can select only
one of the RadioFormInput objects from a RadioFormInputGroup.
The RadioFormInputGroup class methods allow you to work with various attributes of a group of radio
buttons. With these methods, you can:
• Add a radio button
• Remove a radio button
• Get or set the name of the radio group
The following example creates a radio button group:
Related information
RadioFormInputGroup Javadoc
RadioFormInput Javadoc
HTMLHead class
The IBM Toolbox for Java HTMLHead class represents an HTML head tag. The head section of an HTML
page features an opening and closing head tag that typically contains other tags. Typically, the head tag
contains a title tag and possibly meta tags.
Constructors for HTMLHead enable you to construct a head tag that is empty, that contains a title tag, or
that contains a title tag and a meta tag. You can easily add title and meta tags to the empty HTMLHead
object.
Methods for the HTMLHead class include setting and getting the page title and the meta tags. Define the
contents of the meta tags by using the HTMLMeta class.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>My main page</title>
</head>
Related reference
“HTMLMeta class” on page 208
The IBM Toolbox for Java HTMLMeta class represents meta-information used within an HTMLHead tag.
Attributes in META tags are used when identifying, indexing, and defining information within the HTML
document.
Related information
HTMLHead Javadoc
HTMLHeading class
The IBM Toolbox for Java HTMLHeading class represents an HTML heading. Each heading can have its
own alignment and level from 1 (largest font, most importance) to 6.
Methods for the HTMLHeading class include:
• Get and set the text for the heading
• Get and set the level of the heading
• Get and set the alignment of the heading
• Get and set the direction of the text interpretation
• Get and set the language of the input element
• Get a String representation of the HTMLHeading object
<h1 align="left">Heading</h1>
<h2 align="center">Subheading</h2>
<h3 align="right">Item</h3>
Related information
HTMLHeading Javadoc
// Create an HTML hyperlink to the IBM Toolbox for Java home page.
HTMLHyperlink toolbox =
new HTMLHyperlink("http://www.ibm.com/as400/toolbox", "IBM Toolbox for Java home page");
toolbox.setTarget(TARGET_BLANK);
Related information
HTMLHyperlink Javadoc
HTMLImage class
The HTMLImage class allows you to create image tags for your HTML page.
The HTMLImage class provides methods that allow you to get and set image attributes, including the
following:
• Get or set the height of the image
• Get or set the width of the image
• Get or set the name of the image
• Get or set the alternate text for the image
• Get or set the horizontal space around the image
• Get or set the vertical space around the image
• Get or set the absolute or relative reference to the image
• Retrieve a string representation of the HTMLImage object
The following example shows one way to create an HTMLImage object:
// Create an HTMLImage.
HTMLImage image = new HTMLImage("http://myWebSite/picture.gif", "Alternate text for this
graphic");
image.setHeight(94);
image.setWidth(105);
System.out.println(image);
The print statement produces the following tag on a single line. Text wrapping is for display purposes only.
<img src="http://myWebSite/picture.gif"
alt="Alternate text for this graphic"
height="94" width="105" />
HTMLList classes
The IBM Toolbox for Java HTMLList classes allow you to easily create lists within your HTML pages. These
classes provide methods to get and set various attributes of the lists and the items within the lists.
In particular, the parent class HTMLList provides a method to produce a compact list that displays items
in as small a vertical space as possible.
• Methods for HTMLList include:
– Compact the list
– Add and remove items from the list
– Add and remove lists from the list (making it possible to nest lists)
• Methods for HTMLListItem include:
– Get and set the contents of the item
– Get and set the direction of the text interpretation
– Get and set the language of the input element
Use the subclasses of HTMLList and HTMLListItem to create your HTML lists:
• OrderedList and OrderedListItem
• UnorderedList and UnorderedListItem
For coding snippets, see the following examples:
• Example: Creating ordered lists
• Example: Creating unordered lists
• Example: Creating nested lists
// Create an OrderedList.
OrderedList oList = new OrderedList(HTMLConstants.SMALL_ROMAN);
// Create the OrderedListItems.
OrderedListItem listItem1 = new OrderedListItem();
OrderedListItem listItem2 = new OrderedListItem();
// Set the data in the OrderedListItems.
listItem1.setItemData(new HTMLText("First item"));
listItem2.setItemData(new HTMLText("Second item"));
// Add the list items to the OrderedList.
oList.addListItem(listItem1);
oList.addListItem(listItem2);
System.out.println(oList.getTag());
<ol type="i">
<li>First item</li>
<li>Second item</li>
</ol>
// Create an UnorderedList.
UnorderedList uList = new UnorderedList(HTMLConstants.SQUARE);
// Create the UnorderedListItems.
UnorderedListItem listItem1 = new UnorderedListItem();
UnorderedListItem listItem2 = new UnorderedListItem();
// Set the data in the UnorderedListItems.
listItem1.setItemData(new HTMLText("First item"));
listItem2.setItemData(new HTMLText("Second item"));
// Add the list items to the UnorderedList.
uList.addListItem(listItem1);
uList.addListItem(listItem2);
System.out.println(uList.getTag());
<ul type="square">
<li>First item</li>
<li>Second item</li>
</ul>
// Create an UnorderedList.
UnorderedList uList = new UnorderedList(HTMLConstants.SQUARE);
// Create and set the data for UnorderedListItems.
UnorderedListItem listItem1 = new UnorderedListItem();
UnorderedListItem listItem2 = new UnorderedListItem();
listItem1.setItemData(new HTMLText("First item"));
listItem2.setItemData(new HTMLText("Second item"));
// Add the list items to the UnorderedList.
uList.addListItem(listItem1);
uList.addListItem(listItem2);
// Create an OrderedList.
OrderedList oList = new OrderedList(HTMLConstants.SMALL_ROMAN);
// Create the OrderedListItems.
<ol type="i">
<li>First item</li>
<li>Second item</li>
<ul type="square">
<li>First item</li>
<li>Second item</li>
</ul>
<li>Third item</li>
</ol>
HTMLList Javadoc
HTMLListItem Javadoc
HTMLMeta class
The IBM Toolbox for Java HTMLMeta class represents meta-information used within an HTMLHead tag.
Attributes in META tags are used when identifying, indexing, and defining information within the HTML
document.
Attributes of the META tag include:
• NAME - the name associated with the contents of the META tag
• CONTENT - values associated with the NAME attribute
• HTTP-EQUIV - information gathered by HTTP servers for response message headers
• LANG - the language
• URL - used to redirect users from the current page to another URL
For example, to help search engines determine the contents of a page, you might use the following META
tag:
You can also use HTMLMeta to redirect a user from one page to another.
Methods for the HTMLMeta class include:
• Get and set the NAME attribute
• Get and set the CONTENT attribute
• Get and set the HTTP-EQUIV attribute
• Get and set the LANG attribute
• Get and set the URL attribute
Related information
HTMLMeta Javadoc
HTMLParameter class
The HTMLParameter class represents the parameters you can use with the HTMLServlet class. Each
parameter has its own name and value.
Methods for the HTMLParameter class include:
• Get and set the name of the parameter
• Get and set the value of the parameter
Example: Creating HTMLParameter tags
The following example creates an HTMLParameter tag:
// Create an HTMLServletParameter.
HTMLParameter parm = new HTMLParameter ("age", "21");
System.out.println(parm);
Related information
HTMLParameter Javadoc
HTMLServlet class
The HTMLServlet class represents a server-side include. The servlet object specifies the name of the
servlet and, optionally, its location. You may also choose to use the default location on the local system.
The HTMLServlet class works with the HTMLParameter class, which specifies the parameters available to
the servlet.
Methods for the HTMLServlet class include:
• Add and remove HTMLParameters from the servlet tag
• Get and set the location of the servlet
• Get and set the name of the servlet
• Get and set the alternate text of the servlet
// Create an HTMLServlet.
HTMLServlet servlet = new HTMLServlet("myServlet", "http://server:port/dir");
// Create the alternate text if the Web server does not support the servlet tag.
servlet.setText("The Web server providing this page does not support the SERVLET tag.");
System.out.println(servlet);
HTMLServlet Javadoc
“HTMLParameter class” on page 209
The HTMLParameter class represents the parameters you can use with the HTMLServlet class. Each
parameter has its own name and value.
HTMLTableCell class
The HTMLTableCell class takes any HTMLTagElement object as input and creates the table cell tag with
the specified element. The element can be set on the constructor or through either of two setElement()
methods.
Many cell attributes can be retrieved or updating using methods that are provided in the HTMLTableCell
class. Some of the actions you can do with these methods are:
• Get or set the row span
• Get or set the cell height
• Set whether the cell data will use normal HTML line breaking conventions
The following example creates an HTMLTableCell object and displays the tag:
HTMLTableRow class
The HTMLTableRow class creates a row within a table. This class provides various methods for getting and
setting attributes of a row.
The methods of the HTMLTableRow class allow you to:
• Add or remove a column from the row
• Get column data at the specified column Index
• Get column index for the column with the specified cell.
• Get the number of columns in a row
• Set horizontal and vertical alignments
The following is an example for HTMLTableRow:
row.addColumn(new HTMLTableCell(account));
row.addColumn(new HTMLTableCell(name));
row.addColumn(new HTMLTableCell(balance));
// Add the row to an HTMLTable object (assume that the table already exists).
table.addRow(row);
Related information
HTMLTableRow Javadoc
HTMLTableHeader class
The HTMLTableHeader class inherits from the HTMLTableCell class. It creates a specific type of cell, the
header cell, giving you a <th> cell instead of a <td> cell. Like the HTMLTableCell class, you call various
methods in order to update or retrieve attributes of the header cell.
The following is an example for HTMLTableHeader:
// Add the table headers to an HTMLTable object (assume that the table already exists).
table.addColumnHeader(account_header);
table.addColumnHeader(name_header);
table.addColumnHeader(balance_header);
HTMLTableCaption class
The HTMLTableCaption class creates a caption for your HTML table. The class provides methods for
updating and retrieving the attributes of the caption. For example, you can use the setAlignment() method
to specify to which part of the table the caption should be aligned.
The following is an example for HTMLTableCaption:
// Add the table caption to an HTMLTable object (assume that the table already exists).
table.setCaption(caption);
Related information
HTMLTableCaption Javadoc
<font size="5"><b>IBM</b></font>
When you use this tag in an HTML page, it looks like this:
IBM
Related information
HTMLText Javadoc
HTMLTree classes
The HTMLTree class allows you to easily set up a hierarchical tree of HTML elements that you can use in
HTML pages.
This class provides methods to get and set various attributes of the tree, in addition to methods allowing
you to:
• Get and set the HTTP Servlet Request
• Add an HTMLTreeElement or FileTreeElement to the tree
• Remove an HTMLTreeElement or FileTreeElement from the tree
HTMLTreeElement class
The HTMLTreeElement class represents an hierarchical element within an HTMLTree or other
HTMLTreeElements.
Many tree element attributes can be retrieved or updating using methods that are provided in the
HTMLTreeElement class. Some of the actions you can do with these methods are:
• Get or set the visible text of the tree element
• Get or set the URL for the expanded and collapsed icon
• Set whether the tree element will be expanded
The following example creates an HTMLTreeElement object and displays the tag:
// Create an HTMLTree.
HTMLTree tree = new HTMLTree();
The getTag() method in the above example generates HTML tags like the following:
<tr>
<td> </td>
<td>
<table cellpadding="0" cellspacing="3">
<tr>
<td><font color="#0000FF"><u>-</u></font> </td>
<td><font color="#0000FF"><u>Another Web Page</u></font> </td>
</tr>
</table>
</td>
Related information
HTMLTreeElement Javadoc
FileTreeElement class
The IBM Toolbox for Java FileTreeElement class represents the Integrated File System within an
HTMLTree view.
Many tree element attributes can be retrieved or updating using methods that are provided in the
HTMLTreeElement class. You can also get and set the name and path of NetServer shared drives.
Some of the actions these methods enable you to perform are:
• Get or set the URL for the expanded and collapsed icon (inherited method)
• Set whether the tree element will be expanded (inherited method)
• Get or set the name of the NetServer shared drive
• Get or set the path of the NetServer shared drive
// Create an HTMLTree.
HTMLTree tree = new HTMLTree();
// Create a FileTreeElement.
FileTreeElement node = new FileTreeElement(dirList[i]);
System.out.println(tree.getTag());
FileListElement class
The IBM Toolbox for Java FileListElement class allows you to create a file list element, which represents
the contents of an integrated file system directory.
You can use the FileListElement object to represent the contents of a NetServer shared drive by getting
and setting the name and path of NetServer shared drives.
FileListRenderer class
The IBM Toolbox for Java FileListRenderer class renders any field for File objects (directories and files) in
a FileListElement.
The FileListRenderer class offers methods that allow you to perform the following actions:
• Get the name of the directory
• Get the name of the file
• Get the name of the parent directory
• Return the row data that you want to display in the FileListElement
This example creates an FileListElement object with a renderer:
// Create a FileListElement.
FileListElement fileList = new FileListElement(sys, httpservletrequest);
If you don't want to use the default renderer, you can extend FileListRenderer and override methods or
create new ones. For example, you might want to ensure that you prevent passing the names of specific
directories or files with certain extensions to the FileListElement. By extending the class and overriding
the appropriate method, you can return null for these files and directories, ensuring that they are not
displayed.
To fully customize the rows within a FileListElement, use the getRowData() method. An example of
customizing row data using getRowData() might be adding a column to the row data or rearranging
the columns. When the default behavior of FileListRenderer is satisfactory, you need no additional
programming because the FileListElement class creates a default FileListRenderer.
Related reference
“FileListElement class” on page 214
ReportWriter classes
The com.ibm.as400.util.reportwriter package provides classes that enable you to easily access and
format data from an XML source file or data produced by servlets or JavaServer Pages.
The reportwriter package is a convenient way to name three different but related packages:
• com.ibm.as400.util.reportwriter.pclwriter
• com.ibm.as400.util.reportwriter.pdfwriter
• com.ibm.as400.util.reportwriter.processor
These packages include a variety of classes that allow you to format XML data streams and generate
reports in those formats. Make sure you have the necessary JAR files in your CLASSPATH, including an
XML parser and an XSLT processor. For more information, see the following pages:
• JAR files
Context classes (in the pclwriter and pdfwriter packages) define methods that the ReportProcessor
classes need to render XML and JSP data in the chosen format:
• Use PCLContext in combination with a ReportWriter class to generate a report in the Hewlett Packard
Printer Control Language (PCL) format.
• Use PDFContext in combination with a ReportWriter class to generate a report in the Adobe Portable
Document Format (PDF).
ReportProcessor classes (in the processor package) enable you to generate formatted reports from
information your application gathers from Java servlets and JavaServer Pages (JSPs).
• Use the JSPReportProcessor class to retrieve data from servlets and JSP pages to produce reports in
the available formats (contexts).
Context classes
The IBM Toolbox for Java context classes support specific data formats, that, in combination with the
OutputQueue and SpooledFileOutputStream classes, enable the ReportWriter classes to generate reports
in that format and put those reports in a spool file.
Your application only has to create an instance of the Context class, which the ReportWriter classes then
use to generate the reports. Your application never directly calls any of the methods in either Context
class. The PCLContext and PDFContext methods are meant to be used internally by the ReportWriter
classes.
Constructing an instance of the Context class requires an OutputStream (from the java.io package) and
a PageFormat (from the java.awt.print package). Example: Using JSPReportProcessor with PDFContext
show how you can construct and use the Context classes with other ReportWriter classes to generate
reports.
OutputQueue Javadoc
SpooledFileOutputStream Javadoc
“ReportWriter classes” on page 216
The com.ibm.as400.util.reportwriter package provides classes that enable you to easily access and
format data from an XML source file or data produced by servlets or JavaServer Pages.
“Example: Using XSLReportProcessor with PCLContext” on page 473
This example should not be used as the XSLReportProcessor class is no longer supported.
“Example: Using JSPReportProcessor with PDFContext” on page 469
JSPReportProcessor class
The JSPReportProcessor class enables you to create a document or report from the contents of a
JavaServer Page (JSP) or Java servlet.
Use this class to obtain a JSP or servlet from a given URL and create a document from the contents. The
JSP or servlet must provide the document data, including XSL formatting objects. You must specify the
output context and the JSP input data source before you can generate any pages of the document. You
can then convert the report data to a specified output data stream format.
The JSPReportProcessor class allows you to:
• Process the report
• Set a URL as the template
The following examples show how you can use the JSPReportProcessor and the PDFContext classes to
generate a report. The examples include both the Java and the JSP code, which you can view by using the
following links. You can also download a ZIP file that contains the example JSP, XML, and XSL source files
for the JSPReportProcessor examples:
• “Example: Using JSPReportProcessor with PDFContext” on page 469
• “Example: JSPReportProcessor sample JSP file” on page 471
Java Server Pages technology
XSLReportProcessor class
The XSLReportProcessor class is no longer supported and should not be used.
The XSLReportProcessor class enables you to create a document or report by transforming and formatting
your XML source data using an XSL stylesheet. Use this class to create the report by using an XSL
stylesheet that contains XSL formatting objects (FOs), which must conform to the XSL specification. You
then use a Context class to convert the report data to a specified output data stream format.
The XSLReportProcessor class allows you to:
• Set the XSL stylesheet
• Set the XML data source
• Set the XSL FO source
• Process a report
Examples
The following examples show how you can use the XSLReportProcessor and the PCLContext classes to
generate a report. The examples include the Java, XML, and XSL code, which you can view by using the
following links. You can also download a zip file that contains the example XML, XSL, and JSP source files
for both the XSLReportProcessor and JSPReportProcessor examples:
• Example: Using XSLReportProcessor with PCLContext
• Example: XSLReportProcessor sample XML file
• Example: XSLReportProcessor sample XSL file
For more information about XML and XSL, see the XML Toolkit topic in the Information Center.
Using SSL to encrypt data between IBM Toolbox for Java and IBM i servers
You can use SSL to encrypt data exchanged between IBM Toolbox for Java classes and IBM i servers.
On the client side, use JSSE to encrypt the data. On the server side, you must use the IBM i digital
certificate manager to configure the IBM i servers to exchange encrypted data.
Setting up your client and server to use SSL
To encrypt data flowing between the IBM Toolbox for Java classes and IBM i servers, complete the
following tasks:
1. Set up your servers to exchange encrypted data.
2. Use the SecureAS400 object to force IBM Toolbox for Java to encrypt data.
Note: Completing the first two steps above only creates a secure path between the client and the
server. Your application must use the SecureAS400 object to tell the IBM Toolbox for Java which data
to encrypt. Data that flows through the SecureAS400 object is the only data that is encrypted. If you
use an AS400 object, data is not encrypted and the normal path to the server is used.
Authentication services
Classes are provided by the IBM Toolbox for Java that interact with the security services provided by IBM
i.
Specifically, support is provided to authenticate a user identity, sometimes referred to as a principal, and
password against the IBM i user registry. A credential representing the authenticated user can then be
established. You can use the credential to alter the identity of the current IBM i thread to perform work
under the authorities and permissions of the authenticated user. In effect, this swap of identity results in
the thread acting as if a signon was performed by the authenticated user.
Example
Refer to this code for an example of how to use a profile token credential to swap the IBM i thread identity
and perform work on behalf of a specific user.
AS400 Javadoc
ProfileTokenCredential Javadoc
“Long description of
Figure 1: How servlets work (rzahh585.gif)” on page 221
Note: The jt400Servlet.jar file includes both the HTML and Servlet classes. You must update
your CLASSPATH to point to both jt400Servlet.jar and jt400.jar if you want to use classes in the
com.ibm.as400.util.html and com.ibm.as400.util.servlet packages.
For more information about servlets in general, see the reference section.
Description
The figure is composed of the following:
• An image on the left of a personal computer, labeled 'Browser,' that represents an instance of a browser
running on a personal computer.
• An image of an IBM i server on the right, labeled 'IBM i Data,' that represents the location of the data
that you want the servlet to access.
• An image of an IBM i server in the middle (between the other two images), labeled 'WebServer,' that
represents the Web server. Several labeled shapes on the WebServer image indicate files or functions
that reside on the Web server:
– A green oval labeled Servlet that represents the location of the servlet code.
– A tan circle labeled jt400Servlet that indicates the location of the jt400Servlet.jar file.
– A tan circle labeled jt400 that indicates the location of the jt400.jar file.
Note: The Web server does not have to be on an IBM i server, but it can be, and can even be the same
server as that indicated by the IBM i Data image.
• Lines that connect the images together.
A line labeled HTML connects the Browser (the left image) to a Servlet (the green oval) on the Web server
(middle image). The line is labeled HTML because servlets most often use HTML to 'serve' data to the
browser.
Authentication classes
Two classes in the servlet package perform authentication for servlets, AuthenticationServlet and
AS400Servlet.
AuthenticationServlet class
AuthenticationServlet is an HttpServlet implementation that performs basic authentication for servlets.
Subclasses of AuthenticationServlet override one or more of the following methods:
• Override the validateAuthority() method to perform the authentication (required)
• Override the bypassAuthentication() method so that the subclass authenticates only certain requests
• Override the postValidation() method to allow additional processing of the request after authentication
The AuthenticationServlet class provides methods that allow you to:
• Initialize the servlet
• Get the authenticated user ID
• Set a user ID after bypassing authentication
• Log exceptions and messages
AS400Servlet class
The AS400Servlet class is an abstract subclass of AuthenticationServlet that represents an HTML servlet.
You can use a connection pool to share connections and manage the number of connections to the server
that a servlet user can have.
The AS400Servlet class provides methods that allow you to:
• Validate user authority (by overriding the validateAuthority() method of the AuthenticationServlet class)
• Connect to a system
• Get and return connection pool objects to and from the pool
• Close a connection pool
• Get and set the HTML document head tags
• Get and set the HTML document end tags
For more information about servlets in general, see the reference section.
AuthenticationServlet Javadoc
AS400Servlet Javadoc
RowData class
The RowData class is an abstract class that provides a way to describe and access a list of data.
The RowData classes allow you to:
• Get and set the current position
• Get the row data at a given column using the getObject() method
• Get the meta data for the row
• Get or set the properties for an object at a given column
• Get the number of rows in the list using the length() method.
RowData position
Related information
RowData Javadoc
ListRowData class
The IBM Toolbox for Java ListRowData class represents a list of data in table form. In the table, each row
contains a finite number of columns determined by the ListMetaData object and each column within a row
contains an individual data item. The data can be a directory in the integrated file system, a list of jobs, a
list of printers, or a variety of other data.
The ListRowData class allows you to do the following:
• Add and remove rows to and from the result list.
• Get and set the row
• Get information about the list's columns with the getMetaData() method
• Set column information with the setMetaData() method
The ListRowData class represents a list of data. ListRowData can represent many types of information,
including the following, through IBM Toolbox for Java access classes:
• A directory in the integrated file system
• A list of jobs
• A list of messages in a message queue
• A list of users
• A list of printers
Example
The following example shows how the ListRowData and HTMLTableConverter classes work. The example
shows the Java code, HTML code, and HTML look and feel.
“Example: Using ListRowData” on page 485
ListRowData Javadoc
RecordListRowData class
The IBM Toolbox for Java RecordListRowData class allows you to do the following:
• Add and remove rows to and from the record list.
• Get and set the row
• Set the record format with the setRecordFormat method
• Get the record format
The RecordListRowData class represents a list of records. A record can be obtained from the server in
different formats, including:
• A record to be written to or read from a server file
ResourceListRowData class
The IBM Toolbox for Java ResourceListRowData class represents a resource list of data. Use
ResourceListRowData objects to represent any implementation of the ResourceList interface.
Resource lists are formatted into a series of rows, where each row contains a finite number of columns
determined by the number of column attribute IDs. Each column within a row contains an individual data
item.
The ResourceListRowData class offers methods that enable you to perform the following actions:
• Get and set column attribute IDs
• Get and set the resource list
• Retrieve the number of rows in the list
• Get the column data for the current row
• Get the property list of the data object
• Get the metadata for the list
Example: Presenting a resource list in a servlet
SQLResultSetRowData class
The SQLResultSetRowData class represents an SQL result set as a list of data. This data is generated by
an SQL statement through JDBC. With methods provided, you can get set the result set metadata.
This example shows you how ListRowData and HTMLTableConverter work. It shows the Java code, HTML
code, and HTML look and feel.
Related reference
“JDBC classes” on page 54
JDBC is an application programming interface (API) included in the Java platform that enables Java
programs to connect to a wide range of databases.
Related information
SQLResultSetRowData Javadoc
ListMetaData class
The IBM Toolbox for Java ListMetaData class lets you get information about and change settings for the
columns in a ListRowData class. It uses the setColumns() method to set the number of columns, clearing
any previous column information. Alternatively, you can also pass the number of columns when you set
the constructor's parameters.
Example
The following example shows how ListMetaData, ListRowData and HTMLTableConverter work. It shows
the Java code, HTML code, and HTML look and feel.
“Example: Using ListRowData” on page 485
ListMetaData Javadoc
“ListRowData class” on page 223
The IBM Toolbox for Java ListRowData class represents a list of data in table form. In the table, each row
contains a finite number of columns determined by the ListMetaData object and each column within a row
contains an individual data item. The data can be a directory in the integrated file system, a list of jobs, a
list of printers, or a variety of other data.
RecordFormatMetaData class
The RecordFormatMetaData makes use of the IBM Toolbox for Java RecordFormat class. It allows you
to provide the record format when you set the constructor's parameters or use the get set methods to
access the record format.
The following example shows you how to create a RecordFormatMetaData object:
Related information
RecordFormatMetaData Javadoc
RecordFormat Javadoc
SQLResultSetMetaData Javadoc
“SQLResultSetRowData class” on page 224
The SQLResultSetRowData class represents an SQL result set as a list of data. This data is generated by
an SQL statement through JDBC. With methods provided, you can get set the result set metadata.
Converter classes
You use the IBM Toolbox for Java converter classes to convert row data into formatted string arrays.
The result is in HTML format and ready for presentation on your HTML page. The following classes take
care of the conversion for you:
StringConverter class
The StringConverter class is an abstract class that represents a row data string converter. It provides a
convert() method to convert row data. This returns a string array representation of that row's data.
Related information
StringConverter Javadoc
HTMLFormConverter class
The IBM Toolbox for Java HTMLFormConverter classes extend StringConverter by providing an additional
convert method called convertToForms(). This method converts row data into an array of single-row HTML
tables. You can use these table tags to display the formatted information on a browser.
You can tailor the appearance of the HTML form by using the various get and set methods to view or
change the attributes of the form. For example, some of the attributes that you can set include:
• Alignment
• Cell spacing
• Header hyper links
• Width
Example: Using HTMLFormConverter
The following example illustrates using HTMLFormConverter. (You can compile and run this example with
a webserver running.)
Using HTMLFormConverter
HTMLTableConverter class
The HTMLTableConverter class extends StringConverter by providing a convertToTables() method. This
method converts row data into an array of HTML tables that a servlet can use to display the list on a
browser.
You can use the getTable() and setTable() methods to choose a default table that will be used during
conversion. You can set table headers within the HTML table object or you can use the meta data for the
header information by setting setUseMetaData() to true.
The setMaximumTableSize() method allows you to limit the number of rows in a single table. If the row
data does not all fit within the specified size of table, the converter will produce another HTML table
object in the output array. This will continue until all row data has been converted.
Examples
The following examples illustrate how to use the HTMLTableConverter class:
• Example: Using ListRowData
• Example: Using RecordListRowData
• Example: Using SQLResultSetRowData
• Example: Presenting ResourceList in a servlet
Utility classes
The utility classes enable you to do administrative tasks, such as using the AS400JarMaker class.
IBM Toolbox for Java offers the following utilities:
AS400ToolboxJarMaker
While the JAR file format was designed to speed up the downloading of Java program files, the
AS400ToolboxJarMaker generates an even faster loading IBM Toolbox for Java JAR file through its ability
to create a smaller JAR file from a larger one.
Also, the AS400ToolboxJarMaker class can unzip a JAR file for you to gain access to the individual content
files for basic use.
Flexibility of AS400ToolboxJarMaker
All of the AS400ToolboxJarMaker functions are performed with the JarMaker class and the
AS400ToolboxJarMaker subclass:
• The generic JarMaker tool operates on any JAR or Zip file; it splits a JAR file or reduces the size of a JAR
file by removing classes that are not used.
• The AS400ToolboxJarMaker customizes and extends JarMaker functions for easier use with IBM
Toolbox for Java JAR files.
According to your needs, you can invoke the AS400ToolboxJarMaker methods from within your own
Java program or from a command line. Call AS400ToolboxJarMaker from the command line by using the
following syntax:
where
• options = one or more of the available options
For a complete set of options available to run at a command line prompt, see the following in the Javadoc:
• Options for the JarMaker base class
• Extended options for the AS00ToolboxJarMaker subclass
Using AS400ToolboxJarMaker
You can use AS400ToolboxJarMaker to work with JAR files in several ways:
• Uncompress one file bundled within a JAR file
• Split a large JAR file into smaller JAR files
• Exclude any IBM Toolbox for Java files that your application does not need to run
Uncompressing a JAR file
Suppose you wanted to uncompress just one file bundled within a JAR file. AS400ToolboxJarMaker allows
you to expand the file into one of the following:
• Current directory (extract(jarFile))
• Another directory (extract(jarFile, outputDirectory))
Additionally, if it is unnecessary to convert text strings between Unicode and the double byte character
set (DBCS) conversion tables, you can create a 400KB byte smaller JAR file by omitting the unneeded
conversion tables with the -ccsid option:
Note: Conversion classes are not included with the program call classes. When including program call
classes, you must also explicitly include the conversion classes used by your program by using the -ccsid
option.
JarMaker Javadoc
AS400ToolboxJarMaker Javadoc
CommandHelpRetriever class
The CommandHelpRetriever class retrieves help text for IBM i control language (CL) commands
and generates that text either in HTML or User Interface Manager (UIM) format. You can run
CommandHelpRetriever from a command line or embed the functionality into your Java program.
To use CommandHelpRetriever, your server must have an XML parser and XSL processor in the
CLASSPATH environment variable. For more information, see “XML parser and XSLT processor” on page
311.
Additionally, the Generate Command Documentation (GENCMDDOC) CL command uses the
CommandHelpRetriever class. So you can simply use the GENCMDDOC command to take advantage
of the functionality offered by the CommandHelpRetriever class. For more information, see Generate
Command Documentation (GENCMDDOC) in the CL reference topic.
Related information
CommandHelpRetriever Javadoc
CommandPrompter class
The IBM Toolbox for Java CommandPrompter class prompts for the parameter on a given command.
The CommandPrompter class offers functionality that is similar to the CL command prompt (pressing F4).
Using CommandPrompter requires that you have the following JAR files in your CLASSPATH:
• jt400.jar
• jui400.jar
• util400.jar
• jhall.jar
You must also have an XML parser in your CLASSPATH. For more information about using a suitable XML
parser, see the following page:
“XML parser and XSLT processor” on page 311
All of the JAR files, except for jhall.jar, are included in IBM Toolbox for Java. For more information about
IBM Toolbox for Java JAR files, see Jar files. For more information about downloading jhall.jar, see the
Sun JavaHelp Web site .
To construct a CommandPrompter object, you pass it parameters for the parent frame that launches
the prompter, the AS400 object on which the command will be prompted, and the command string. The
command string can be a command name, a full command string, or a partial command name, such as
crt*.
RunJavaApplication
The RunJavaApplication and VRunJavaApplication classes are utilities to run Java programs on the IBM i
JVM.
Unlike JavaApplicationCall and VJavaApplicationCall classes that you call from your Java program,
RunJavaApplication and VRunJavaApplication are complete programs.
The RunJavaApplication class is a command line utility. It lets you set the environment (CLASSPATH
and properties, for example) for the Java program. You specify the name of the Java program and its
parameters, then you start the program. Once started, you can send input to the Java program which it
receives via standard input. The Java program writes output to standard output and standard error.
The VRunJavaApplication utility has the same capabilities. The difference is VJavaApplicationCall uses a
graphical user interface while JavaApplicationCall is a command line interface.
RunJavaApplication Javadoc
VRunJavaApplication Javadoc
“JavaApplicationCall class” on page 54
The JavaApplicationCall class provides you with the ability to have your client use the server JVM to run a
Java program that resides on the server.
JPing
The JPing class is a command line utility that allows you to query your servers to see which services
are running and which ports are in service. To query your servers from within a Java application, use the
AS400JPing class.
See the JPing Javadoc for more information about using JPing from within your Java application.
Call JPing from the command line by using the following syntax:
where:
• System = the system that you want to query
• [options] = one or more of the available options
Options
You can use one or more of the following options. For options that have abbreviations, the abbreviation is
listed in parenthesis.
-help (-h or -?)
Displays the help text.
-service i_Service (-s i_Service)
Specifies one specific service to ping. The default action is to ping all services. You can use this option
to specify one of the following services: as-file, as-netprt, as-rmtcmd, as-dtaq, as-database, as-ddm,
as-central, and as-signon.
-ssl
Specifies whether or not to ping the ssl ports. The default action is not to ping the ssl ports.
-timeout (-t)
Specifies the timeout period in milliseconds. The default setting is 20000, or 20 seconds.
Related information
JPing Javadoc
AS400JPing Javadoc
Examples
The following examples show how to use JavaBeans in your program and how to create a program from
JavaBeans by using a visual bean builder:
“Example: IBM Toolbox for Java bean code” on page 434
“Example: Creating beans with a visual bean builder” on page 436
JDBC
JDBC is an application programming interface (API) included in the Java platform that enables Java
programs to connect to a wide range of databases.
The IBM Toolbox for Java JDBC driver allows you to use JDBC API interfaces to issue structured query
language (SQL) statements to and process results from databases on the server. You can also use IBM
Developer Kit for Java JDBC driver, called the 'native' JDBC driver:
• Use the IBM Toolbox JDBC driver when the Java program is on one system and the database files are on
another system, as in a client/server environment
• Use the native JDBC driver when both the Java program and database files are on the same server
Enhancements to IBM Toolbox for Java JDBC support for IBM i 7.1
Many additions were made to JDBC support in IBM i 7.1.
The enhancements to IBM Toolbox for Java JDBC support are detailed in the following sections:
• “XML data type support” on page 239
• “Database metadata updates” on page 240
• “Currently committed support” on page 240
• “Array type support” on page 241
• “Long schema name support” on page 241
Enhancements to IBM Toolbox for Java JDBC support for IBM i 6.1
Many additions were made to JDBC support in IBM i 6.1.
The enhancements to IBM Toolbox for Java JDBC support are detailed in the following sections:
• “Support for JDBC 4.0” on page 243
setQueryStorageLimit()
public void setQueryStorageLimit(int limit);
Specifies the query storage limit value to be used when statements in a connection are executed. Valid
values are -1 to 2 147 352 578. The default is value -1, indicating a special value of *NOMAX.
getQueryStorageLimit()
public int getQueryStorageLimit()
Returns the query storage limit value used when statements in a connection are executed. The default
value is -1, indicating a special value of *NOMAX.
Systems that run a release of IBM i prior to V6R1 will ignore the getQueryStorageLimit property.
setDecfloatRoundingMode()
public void setDecfloatRoundingMode(int String mode)
getDecfloatRoundingMode()
public intString getDecfloatRoundingMode()
This method sets the value of the client info property specified by name to the value specified by value.
See the DatabaseMetadata.getClientInfoProperties method description for the client info properties
supported by the IBM Toolbox for Java JDBC driver.
This method sets the value of the connection's client info properties. The Properties object contains the
names and values of the client info properties to be set. The set of client info properties contained in the
properties list replaces the current set of client info properties on the connection. If a property that is
currently set on the connection is not present in the properties list, that property is cleared. Specifying an
empty properties list will clear all of the properties on the connection.
This method returns the value of the client info property specified by name. This method may return null
if the specified client info property has not been set and does not have a default value.
Properties AS400JDBCConnection.getClientInfo()
This method returns a list containing the name and current value of each client info property supported
by the driver. The value of a client info property may be null if the property has not been set and does not
have a default value.
ResultSet AS400JDBCDatabaseMetaData.getClientInfoProperties()
This method retrieves a list of the client info properties that the driver supports. The IBM Toolbox for Java
JDBC driver returns a result set with the following information:
Enhancements to IBM Toolbox for Java JDBC support for IBM i 5.4
Several JDBC functions were enhanced for IBM i 5.4.
The enhancements to IBM Toolbox for Java JDBC support are detailed in the following sections:
• “2 MB statement size” on page 246
• “128 byte column name support” on page 246
• “Database host server trace support” on page 246
• “eWLM Correlator support” on page 247
2 MB statement size
Prior to V5R4, the limit on SQL statement size was 65 535 bytes. This corresponds to 65 535 characters
when the statement text is represented using a single-byte CCSID, and 32 767 characters when the
statement text is represented using a double-byte CCSID. Some customers, particularly those using
applications that automatically generate SQL statements, were affected by this limit.
In V5R4, the IBM i statement size limit has been increased to two megabytes, or 2 097 152 bytes.
The IBM Toolbox for Java JDBC driver always sends statement text in two byte Unicode. Therefore, the
maximum statement length in characters will be one megabyte or 1 048 576 characters.
Sets the eWLM Correlator. It is assumed a valid correlator value is used. If the value is null, all ARM/eWLM
implementation will be turned off. eWLM correlators require i5/OS V5R3 or later servers. This request is
ignored when running to V5R2 or earlier servers.
Parameters:
• bytes: The eWLM correlator value
• SQLException: See the Class SQLException Javadoc.
General properties
General properties are system attributes that specify the user, password, and whether a prompt is
necessary to connect to the server.
Server properties
Server properties specify attributes that govern transactions, libraries, and databases.
"decfloat Specifies the rounding mode to use when no "half even" "half even"
rounding mode" working with the decfloat data type. This "half up"
property is ignored when connecting to
"down"
systems running IBM i 5.4 and earlier.
"ceiling"
"floor"
"half down"
"up"
"package ccsid" Specifies the character encoding to use for no "1200" "13488"
the SQL package and any statements sent (UCS-2)
to the server. "13488"
(UTF-16)
"read committed"
"repeatable
read"
"serializable"
Format properties
Format properties specify date and time formats, date and decimal separators, and table naming
conventions used within SQL statements.
"date separator" Specifies the date separator used in no "/" (slash) (server job)
date literals within SQL statements. "-" (dash)
This property has no effect unless
"." (period)
the "date format" property is set to
"julian", "mdy", "dmy" or "ymd". "," (comma)
"b" (space)
"time separator" Specifies the time separator used in no ":" (colon) (server job)
time literals within SQL statements. "." (period)
This property has no effect unless the
"," (comma)
"time format" property is set to "hms".
"b" (space)
Performance properties
Performance properties are attributes that include caching, data conversion, data compression, and
prefetching that affect performance.
"block size" Specifies the block size (in kilobytes) to no "0" "32"
retrieve from the server and cache on "8"
the client. This property has no effect
"16"
unless the "block criteria" property is
non-zero. Larger block sizes reduce "32"
the frequency of communication to "64"
the server, and therefore may improve "128"
performance. "256"
"512"
"query storage limit" Limits the storage used by a query. This no -1 (*NOMAX) to -1, which
property compares the storage limit 2 147 352 578 indicates a
you specify to the estimated storage special value
usage of the query. If the estimated of *NOMAX
storage usage exceeds the specified
storage limit, the query is not allowed
to execute.
"receive buffer size" Specifies the buffer size used to receive no "1" - max size (platform
data through the socket connection dependent)
between the front-end driver and the
system.
Note: This does not specify the actual
receive buffer size. It is only used as a
hint by the underlying socket code.
"send buffer size" Specifies the buffer size used to send no "1" - max size (platform
data through the socket connection dependent)
between the front-end driver and the
system.
Note: This does not specify the actual
send buffer size. It is only used as a
hint by the underlying socket code.
"use block update" This property allows the toolbox JDBC no "true" "false"
driver to use a block update mode "false"
when updating blocks of data into the
database. This is an optimized version
of the batch update.
"variable field Specifies whether variable-length fields no "true" "true"
compression" should be compressed. "false"
Sort properties
Sort properties specify how the server performs stores and performs sorts.
Other properties
Other properties are those properties not easily categorized. These properties determine which JDBC
driver is used, and specify options related to level of database access, bidirectional string type, data
truncation and so on.
"full open" Specifies whether the server fully opens a file no "true" "false"
for each query. By default the server optimizes "false"
open requests. This optimization improves
performance but may fail if a database monitor
is active when a query is run more than once.
Set the property to true only when identical
queries are issued when monitors are active.
"remarks" Specifies the source of the text for no "sql" (SQL object "system"
REMARKS columns in ResultSets returned by comment)
DatabaseMetaData methods. This property is "system" (IBM i
only used if the "metadata source" property is object description)
set to "0".
"secondary Specifies the URL to be used for a connection no JDBC URL (current
URL" on the middle-tier's DriverManager in a JDBC URL)
multiple tier environment, if it is different than
already specified. This property allows you to
use this driver to connect to other databases.
Use a backslash as an escape character before
backslashes and semicolons in the URL.
"secure" Specifies whether a Secure Sockets Layer no "true" (encrypt "false"
(SSL) connection is used to communicate with all client/server
the server. communication)
"false" (encrypt
only the password)
Related reference
“Registering the JDBC driver” on page 71
Before using JDBC to access data in a server database file, you need to register the IBM Toolbox for Java
JDBC driver with the DriverManager.
Basic Rules Only one library is searched. The job's library list is updated
with the libraries on the libraries
• If a default SQL schema is specified on
property. If a default SQL schema
the URL, it is used. It becomes the default
is specified on the URL then that
library.
becomes the default library.
• If no default SQL schema is specified on
the URL, the first library in the "libraries"
property is used. It becomes the default
library.
• If no default SQL schema is specified
on URL and if no "libraries" property is
specified, the library with the same name
as the signed-on user profile is used.
The job's library list is updated with the
libraries in the libraries property. This
may affect the behavior of some triggers
and stored procedures. It does not affect
unqualified names in statements.
1. No default SQL Default SQL schema is the user profile No default SQL schema. Job's
schema specified on name. library list is searched.
URL and "libraries"
property is not
specified
2. Default SQL Default SQL schema is what is specified in Default SQL schema is what is
schema specified the URL. specified in the URL. Library list is
on URL and not searched to resolve unqualified
"libraries" property name in SQL statements.
not specified
3. Default SQL Default SQL schema is first library specified No default SQL schema. All libraries
schema not specified in property. specified in property are searched.
on URL and
"libraries" property is
specified
4. Default SQL Default SQL schema is what is specified in Default SQL schema is what is
schema specified on the URL. Property is ignored. specified in the URL. Library list is
URL and "libraries" not searched to resolve unqualified
property specified name in SQL statements.
5. No default SQL Default SQL schema is first library specified No default SQL schema. The library
schema specified on in property. list can not be changed because
URL, the "libraries" one of the libraries in the list is
property is specified not found so the job's library list is
and a library in the used.
list is not valid
6. No default SQL Default SQL schema is first library specified If all libraries exist , then no default
schema specified in property, rest of libraries ignored. SQL schema, all libraries on list
on URL, "libraries" searched, list replaces job's library
property specified, list.
file found in second
If one of the libraries on the list
library in list
does not exist, the job's library list
is not changed.
7. No default SQL Default SQL schema is user profile. No default SQL schema, all libraries
schema specified on on list searched, list replaces job's
URL, the "libraries" library list.
property is specified,
list starts with a
comma
8. No default SQL Default SQL schema is user profile. No default SQL schema, all libraries
schema specified on list searched, libraries specified
on URL, "libraries" added to end of list
property specified,
list starts with a
*LIBL
9. No default SQL Default SQL schema is first library specified No default SQL schema, all libraries
schema specified in property, rest of libraries ignored. on list searched, libraries specified
on URL, "libraries" added to beginning of job's library
property specified, list
list ends with a *LIBL
10. Default SQL No default SQL schema, user profile used. No default SQL schema, job's
schema specified on library list is used
URL not valid
Note: When a default SQL schema is specified on the URL and the libraries property is not used, the
default SQL schema is appended before the current library list
Proxy Support
IBM Toolbox for Java includes proxy support for some classes. Proxy support is the processing that IBM
Toolbox for Java needs to carry out a task on a Java virtual machine (JVM) when the application is on a
different JVM.
The proxy classes reside in jt400Proxy.jar, which ships with the rest of the IBM Toolbox for Java. The
proxy classes, like the other classes in the IBM Toolbox for Java, comprise a set of platform independent
Java classes that can run on any computer with a Java virtual machine. The proxy classes dispatch all
method calls to a server application, or proxy server. The full IBM Toolbox for Java classes are on the
proxy server. When a client uses a proxy class, the request is transferred to the proxy server which creates
and administers the real IBM Toolbox for Java objects.
Figure 1 shows how the standard and proxy client connect to the server. The proxy server can be the IBM i
server that contains the data.
Figure 1: How a standard client and a proxy client connect to a server
• HTTP tunneling is where the proxy client and proxy server communicate by way of the HTTP server. The
IBM Toolbox for Java provides a servlet that handles the proxy request. The proxy client calls the servlet
by way of the HTTP server. The advantage of tunneling is that you are not required to open an additional
port through the firewalls, because communication is by way of the HTTP port. The disadvantage of
tunneling is that it is slower than standard proxy.
IBM Toolbox for Java uses the proxy server name to determine if standard proxy or tunneling proxy is
being used:
• For standard proxy, just use the server name. For example:
• For tunneling, use a URL to force the proxy client to use tunneling. For example:
com.ibm.as400.access.AS400.proxyServer=http://myServer
When running standard proxy, a socket connection exists between the client and server. If that connection
fails, the server cleans up resources associated with that client.
When using HTTP tunneling, using the HTTP protocol makes proxy connectionless. That is, a new
connection is made for each data flow. Because the protocol is connectionless, the server does not
know if the client application is no longer active. Consequently, the server does not know when to clean
up resources. The tunneling server solves this problem by using a thread to clean up resources at a
predetermined interval (which is based on a timeout value).
At the end of the predetermined interval, the thread runs and cleans up resources that have not been
used lately. Two system properties govern the thread:
• com.ibm.as400.access.TunnelProxyServer. clientCleanupInterval is how often, in seconds, the cleanup
thread runs. The default is every two hours.
• com.ibm.as400.access.TunnelProxyServer. clientLifetime is how long, in seconds, a resource can be idle
before it is cleaned up. The default is 30 minutes.
java com.ibm.as400.access.ProxyServer
• For tunneling proxy, configure your HTTP server to use the proxy servlet. The servlet class name is
com.ibm.as400.access.TunnelProxyServer and it is contained in jt400.jar.
6. On the client, set a system property to identify the proxy server. IBM Toolbox for Java uses this system
property to determine if standard proxy or tunneling proxy is being used.
• For standard proxy, the property value is the name of the machine that runs the proxy server. For
example:
com.ibm.as400.access.AS400.proxyServer=myServer
• For tunneling proxy, use a URL to force the proxy client to use tunneling. For example:
com.ibm.as400.access.AS400.proxyServer=http://myServer
1. Choose a machine to act as the proxy server. Applets can initiate network connections only to the
machine from which they were originally downloaded; therefore, it works best to run the proxy server
on the same machine as the HTTP server. The Java environment and CLASSPATH on the proxy server
machine includes the jt400.jar file.
2. Start the proxy server on this machine by typing: java com.ibm.as400.access.ProxyServer
-verbose Specifying verbose will allow you to monitor when the client connects and disconnects.
3. Applet code needs to be downloaded before it runs so it is best to reduce the size of the code as much
as possible. The AS400ToolboxJarMaker can reduce the jt400Proxy.jar significantly by including only
the code for the components that your applet uses. For instance, if an applet uses only JDBC, reduce
the jt400Proxy.jar file to include the minimal amount of code by running the following command:
4. The applet must set the value of the com.ibm.as400.access.AS400.proxyServer system property to
be the name of your proxy server. A convenient way to do this for applets is using a compiled
Properties class (Example). Compile this class and place the generated Properties.class file in the
com/ibm/as400/access directory (the same path your html file is coming from). For example, if the
html file is /mystuff/HelloWorld.html, then Properties.class is in /mystuff/com/ibm/as400/access.
5. Put the jt400ProxySmall.jar in the same directory as the html file (/mystuff/ in step 4).
6. Refer to the applet like this in your HTML file:
Note: The proxy client code creates the correct servlet URL by concatenating "servlet" and the
servlet name to the server name. In this example, it converts http://psMachineName to http://
psMachineName/servlet/TunnelProxyServer
For more information about JSSE, see the Sun JSSE Web site .
JSSE provides the ability to perform server authentication, enable secure communications, and encrypt
data. Using JSSE, you can provide for secure data exchange between clients and servers that run any
application protocol (for example, HTTP and FTP) over TCP/IP.
If you have previously used sslight, you should migrate to JSSE. As of IBM i 5.4, JSSE is the only package
supported, and sslight is no longer shipped.
When your application constructs the ProgramCallDocument object, the XML parser reads and parses the
PCML source file. For more information about using an XML parser with IBM Toolbox for Java, see XML
parser and XSLT processor.
After the ProgramCallDocument class has been created, the application program uses the
ProgramCallDocument class's methods to retrieve the necessary information from the server through
the IBM i distributed program call (DPC) server.
To improve run-time performance, the ProgramCallDocument class can be serialized during your product
build time. The ProgramCallDocument is then constructed using the serialized file. In this case, the XML
parser is not used at run-time. Refer to Using serialized PCML files.
The ProgramCallDocument object will look for your PCML source in a file called myPcmlDoc.pcml. Notice
that the .pcml extension is not specified on the constructor.
If you are developing a Java application in a Java package, you can package-qualify the name of the PCML
resource:
This method is helpful for having batch processes to build your application.
• From within a Java program:
If your PCML is in a source file named myDoc.pcml, the result of serialization is a file named
myDoc.pcml.ser.
The ProgramCallDocument constructor will first try to find a serialized PCML file named
myPcmlDoc.pcml.ser in the com.mycompany.mypackage package in the Java CLASSPATH. If a serialized
PCML file does not exist, the constructor will then try to find a PCML source file named myPcmlDoc.pcml
in the com.mycompany.mypackage package in the Java CLASSPATH. If a PCML source file does not exist,
an exception is thrown.
<pcml version="1.0">
<program name="polytest" path="/QSYS.lib/MYLIB.lib/POLYTEST.pgm">
<!-- Parameter 1 contains a count of polygons along with an array of polygons -->
<struct name="parm1" usage="inputoutput">
<data name="nbrPolygons" type="int" length="4" init="5" />
<!-- Each polygon contains a count of the number of points along with an array of points
-->
<struct name="polygon" count="nbrPolygons">
<data name="nbrPoints" type="int" length="4" init="3" />
<struct name="point" count="nbrPoints" >
<data name="x" type="int" length="4" init="100" />
<data name="y" type="int" length="4" init="200" />
</struct>
</struct>
</struct>
</program>
</pcml>
Note: All public methods in the PcmlMessageLog class, including tracing, were deprecated in V5R2.
The Trace setFileName() method enables you to send the following types of information to specific log
files or, by default, to System.out:
• A dump of the hexadecimal data being transferred between the Java application and the IBM i program.
This shows the program input parameters after character data is converted to EBCDIC and integers are
converted to big-endian. It also shows the output parameters before they are converted to the Java
environment.
The data is shown in a typical hexadecimal dump format with hexadecimal digits on the left and a
character interpretation on the right. The following is an example of this dump format. (The following
example was altered to allow for width restrictions)
qgyolobj[6]
Offset : 0....... 4....... 8....... C....... 0....... 4....... 8....... C.......
0...4...8...C...0...4...8...C...
0 : 5CE4E2D9 D7D9C640 4040
**USRPRF *
In the above example, the dump shows the seventh parameter has 10 bytes of data set to "*USRPRF ".
• For output parameters, following the hexadecimal dump is a description of how the data has been
interpreted for the document. (The following example was altered to allow for width restrictions)
/QSYS.lib/QGY.lib/QGYOLOBJ.pgm[2]
Offset : 0....... 4....... 8....... C....... 0....... 4....... 8....... C.......
0...4...8...C...0...4...8...C...
0 : 0000000A 0000000A 00000001 00000068 D7F0F9F9 F0F1F1F5 F1F4F2F6 F2F5F400
*................P09901151426254.*
20 : 00000410 00000001 00000000 00000000 00000000 00000000 00000000 00000000
*................................*
40 : 00000000 00000000 00000000 00000000
*................ *
Reading data -- Offset: 0 Length: 4 Name: "qgyolobj.listInfo.totalRcds"
Byte data: 0000000A
Reading data -- Offset: 4 Length: 4 Name: "qgyolobj.listInfo.rcdsReturned"
Byte data: 0000000A
Reading data -- Offset: 8 Length: 4 Name: "qgyolobj.listInfo.rqsHandle"
Byte data: 00000001
Reading data -- Offset: c Length: 4 Name: "qgyolobj.listInfo.rcdLength"
Byte data: 00000068
Reading data -- Offset: 10 Length: 1 Name: "qgyolobj.listInfo.infoComplete"
Byte data: D7
Reading data -- Offset: 11 Length: 7 Name: "qgyolobj.listInfo.dateCreated"
Byte data: F0F9F9F0F1F1F5
Reading data -- Offset: 18 Length: 6 Name: "qgyolobj.listInfo.timeCreated"
Byte data: F1F4F2F6F2F5
Reading data -- Offset: 1e Length: 1 Name: "qgyolobj.listInfo.listStatus"
Byte data: F4
Reading data -- Offset: 1f Length: 1 Name: "qgyolobj.listInfo.[8]"
Byte data: 00
Reading data -- Offset: 20 Length: 4 Name: "qgyolobj.listInfo.lengthOfInfo"
Byte data: 00000410
Reading data -- Offset: 24 Length: 4 Name: "qgyolobj.listInfo.firstRecord"
Byte data: 00000001
Reading data -- Offset: 28 Length: 40 Name: "qgyolobj.listInfo.[11]"
Byte data: 00000000000000000000000000000000000000000000000000000000000000000000000000000000
PCML syntax
PCML consists of the following tags, each of which has its own attribute tags.
• The program tag begins and ends code that describes one program
• The struct tag defines a named structure which can be specified as an argument to a program or as a
field within another named structure. A structure tag contains a data or a structure tag for each field in
the structure.
• The data tag defines a field within a program or structure.
In the following example the PCML syntax describes one program with one category of data and some
isolated data.
<program>
<struct>
<data> </data>
</struct>
<data> </data>
</program>
<program name="name"
[ entrypoint="entry-point-name" ]
[ epccsid="ccsid" ]
[ path="path-name" ]
[ parseorder="name-list" ]
[ returnvalue="{ void | integer }" ]
[ threadsafe="{ true | false }" ]>
</program>
The following table lists the program tag attributes. Each entry includes the attribute name, the possible
valid values, and a description of the attribute.
returnvalue= void The program does not return Specifies the type of value, if any,
a value. that is returned from a service
program call. This attribute is not
integer The program returns a 4-
allowed for *PGM object calls.
byte signed integer.
Note: This attribute is only
allowed when the PCML version
is 2.0 or higher. (For example
<pcml version="2.0">)
<struct name="name"
[ count="{number | data-name }"]
[ maxvrm="version-string" ]
[ minvrm="version-string" ]
[ offset="{number | data-name }" ]
[ offsetfrom="{number | data-name | struct-name }" ]
[ outputsize="{number | data-name }" ]
[ usage="{ inherit | input | output | inputoutput }" ]>
</struct>
The following table lists the struct tag attributes. Each entry includes the attribute name, the possible
valid values, and a description of the attribute.
<pcml version="1.0">
<program name="myprog" path="/QSYS.lib/MYLIB.lib/MYPROG.pgm">
<!-- receiver variable contains a path -->
<struct name="receiver" usage="output" outputsize="2048">
<data name="pathType" type="int" length="4" />
<data name="offsetToPathName" type="int" length="4" />
<data name="lengthOfPathName" type="int" length="4" />
<data name="pathName" type="char" length="lengthOfPathName"
offset="offsetToPathName" offsetfrom="0"/>
</struct>
</program>
</pcml>
For displacements, since the distance is from the beginning of another structure, you specify the name
of the structure to which the offset is relative. The following is an example of an displacement from the
beginning of a named structure:
<pcml ="1.0">
<program name="myprog" path="/QSYS.lib/MYLIB.lib/MYPROG.pgm">
<!-- receiver variable contains an object -->
<struct name="receiver" usage="output" >
<data name="objectName" type="char" length="10" />
<data name="libraryName" type="char" length="10" />
<data name="objectType" type="char" length="10" />
<struct name="pathInfo" usage="output" outputsize="2048" >
<data name="pathType" type="int" length="4" />
<data name="offsetToPathName" type="int" length="4" />
<data name="lengthOfPathName" type="int" length="4" />
<data name="pathName" type="char" length="lengthOfPathName"
offset="offsetToPathName" offsetfrom="pathInfo"/>
</struct>
</struct>
</program>
</pcml>
<data type="{ char | int | packed | zoned | float | byte | struct | date | time | timestamp }"
[ bidistringtype="{ ST4 | ST5 | ST6 | ST7 | ST8 | ST9 | ST10 | ST11 | DEFAULT }"]
[ ccsid="{ number | data-name }" ]
[ chartype="{ onebyte | twobyte }"]
[ count="{ number | data-name }" ]
[ init="string" ]
[ length="{ number | data-name }" ]
[ maxvrm="version-string" ]
[ minvrm="version-string" ]
[ name="name" ]
[ offset="{ number | data-name }" ]
[ offsetfrom="{ number | data-name | struct-name }" ]
[ outputsize="{ number | data-name | struct-name }" ]
[ passby= "{ reference | value }" ]
[ precision="number" ]
[ struct="struct-name" ]
The following table lists the data tag attributes. Each entry includes the attribute name, the possible valid
values, and a description of the attribute.
Specifying offsets
Some programs return information with a fixed structure followed by one or more variable length fields
or structures. In this case, the location of a variable length element is typically specified as an offset or
displacement within the parameter.
An offset is the distance in bytes from the beginning of the parameters to the beginnings of a field or
structure. A displacement is the distance in bytes from the beginning of one structure to the beginning of
another structure.
For offsets, since the distance is from the beginning of the parameter, you must specify offsetfrom="0".
The following is an example of an offset from the beginning of the parameter:
<pcml version="1.0">
<program name="myprog" path="/QSYS.lib/MYLIB.lib/MYPROG.pgm">
<!-- receiver variable contains a path -->
<struct name="receiver" usage="output" outputsize="2048">
<data name="pathType" type="int" length="4" />
<data name="offsetToPathName" type="int" length="4" />
<data name="lengthOfPathName" type="int" length="4" />
<data name="pathName" type="char" length="lengthOfPathName"
offset="offsetToPathName" offsetfrom="0"/>
</struct>
</program>
</pcml>
For displacements, since the distance is from the beginning of another structure, you specify the name
of the structure to which the offset is relative. The following is an example of an displacement from the
beginning of a named structure:
<pcml version="1.0">
<program name="myprog" path="/QSYS.lib/MYLIB.lib/MYPROG.pgm">
<!-- receiver variable contains an object -->
<struct name="receiver" usage="output" >
<data name="objectName" type="char" length="10" />
<data name="libraryName" type="char" length="10" />
type="packed" or "zoned" The number of numeric digits of The number of decimal digits for
data for this element. You must the element. This number must
specify a literal number. be greater than or equal to zero
and less than or equal to the total
number of digits specified on the
length attribute.
type="float" The number of bytes, 4 or 8, of Not applicable
data for this element. You must
specify a literal number.
<pcml version="1.0">
<program name="polytest" path="/QSYS.lib/MYLIB.lib/POLYTEST.pgm">
<!-- Parameter 1 contains a count of polygons along with an array of polygons -->
<struct name="parm1" usage="inputoutput">
<data name="nbrPolygons" type="int" length="4" init="5" />
<!-- Each polygon contains a count of the number of points along with an array of points
-->
<struct name="polygon" count="nbrPolygons">
<data name="nbrPoints" type="int" length="4" init="3" />
<struct name="point" count="nbrPoints" >
<data name="x" type="int" length="4" init="100" />
<data name="y" type="int" length="4" init="200" />
</struct>
</struct>
</struct>
</program>
</pcml>
<rfml version="4.0">
<struct name="polygon">
<!-- Each polygon contains a count of the number of points along with an array of points.
-->
<data name="nbrPoints" type="int" length="4" init="3" />
<data name="point" type="struct" struct="point" count="nbrPoints" />
</struct>
<struct name="point" >
<data name="x" type="int" length="4" init="100" />
<data name="y" type="int" length="4" init="200" />
</struct>
<recordformat name="polytest">
<!-- This format contains a count of polygons along with an array of polygons -->
<data name="nbrPolygons" type="int" length="4" init="5" />
<data name="polygon" type="struct" struct="polygon" count="nbrPolygons" />
</recordformat>
</rfml>
Example: Using RFML compared to using IBM Toolbox for Java Record classes
This example illustrates the differences between using RFML and using the IBM Toolbox for Java Record
classes.
Using the traditional Record classes, you interweave the data format specifications with the business logic
of your application. Adding, changing, or deleting a field means that you must edit and recompile your
Java code. However, using RFML isolates the data format specifications into RFML source files that are
entirely separate from the business logic. Accommodating field changes means modifying the RFML file,
often without having to change or recompile your Java application.
The example assumes that your application deals with customer records, which you have defined in
an RFML source file and named qcustcdt.rfml. The source file represents the fields that compose each
customer record.
The listing below shows how a Java application might interpret a customer record using the IBM Toolbox
for Java Record, RecordFormat, and FieldDescription classes:
By comparison, here is how the same record might be interpreted using RFML.
The Java code to interpret the contents of the customer data record using RFML might look like this:
RecordFormatDocument class
The RecordFormatDocument class enables your Java programs to convert between RFML representations
of data and Record and RecordFormat objects for use with other IBM Toolbox for Java components.
RecordFormatDocument class
<rfml>
<recordformat>
<data> </data>
</recordformat>
<struct>
<data> </data>
</struct>
</rfml>
<!--
Record Format Markup Language (RFML) Document Type Definition.
<!-- Note: RFML does not support nested struct declarations. -->
<!-- All struct elements are direct children of the root node. -->
<!ELEMENT struct (data)+>
<!ATTLIST struct
name ID #REQUIRED
>
<data type="{ char | int | packed | zoned | float | byte | struct }" ]
[ bidistringtype="{ ST4 | ST5 | ST6 | ST7 | ST8 | ST9 | ST10 | ST11 | DEFAULT }"]
[ ccsid="{ number | data-name }" ]
[ count="{ number | data-name }" ]
[ init="string" ]
[ length="{ number | data-name }" ]
[ name="name" ]
[ precision="number" ]
[ struct="struct-name" ]>
</data>
The following table lists the data tag attributes. Each entry includes the attribute name, the possible valid
values, and a description of the attribute.
ccsid= number where number defines Specifies the host coded character set
a fixed, never-changing CCSID. identifier (CCSID) for character data
data-name where data-name for the <data> element. The ccsid
defines the name that will attribute can be specified only for
contain, at runtime, the CCSID <data> elements with type="char".
of the character data. The If this attribute is omitted, character
data-name specified can be data for this element is assumed to
a fully qualified name or a be in the default CCSID of the host
name that is relative to the environment.
current element. In either
case, the name must reference
a <data> element that is
defined with type="int". See
Resolving Relative Names for
more information about how
relative names are resolved.
length= number where number defines Specifies the length of the data
a fixed, never-changing length. element. Usage of this attribute varies
depending on the data type. For more
data-name where data-name
information, see the Values for length
defines the name of a
and precision.
<data> element within the
RFML document that will
contain, at runtime, the
length. A data-name can be
specified only for <data>
elements with type="char"
or type="byte". The data-
name specified can be a
fully qualified name or a
name that is relative to the
current element. In either
case, the name must reference
a <data> element that is
defined with type="int". See
Resolving Relative Names for
more information about how
relative names are resolved.
Related information
BidiStringType Javadoc
<rfml version="version-string"
[ ccsid="number" ]>
</rfml>
The following table lists the rfml tag attributes. Each entry includes the attribute name, the possible valid
values, and a description of the attribute.
<recordformat name="name"
[ description="description" ]>
</recordformat>
The following table lists the recordformat tag attributes. Each entry includes the attribute name, the
possible valid values, and a description of the attribute.
<struct name="name">
</struct>
The following table lists the struct tag attributes. Each entry includes the attribute name, the possible
valid values, and a description of the attribute.
XML parser
If the package or function requires an XML parser, you must include an XML parser in the CLASSPATH at
run-time. The XML parser must meet the following requirements:
• Be JAXP-compliant
• Extend class org.apache.xerces.parsers.SAXParser
• Support full schema validation
Note: The parser only needs to support full schema validation if use intend to use XPCML. If you are only
using PCML, full schema validation is not necessary.
The Java 2 Software Developer Kit (J2SDK), version 1.4, includes a suitable XML parser. If you use a
previous version of J2SDK, use any of the following methods to access a suitable XML parser:
• Use x4j400.jar (an IBM version of the Xerces XML parser from Apache)
• Download the Xerces XML parser from the Apache Web site
• Use any compatible XML parser in the /QIBM/ProdData/OS400/xml/lib directory on your system
Note: Consider using the latest versions of the parsers that reside in /QIBM/ProdData/OS400/xml/
lib. For example, xmlapis11.jar and xerces411.jar are both fully validating parsers.
You can use these parsers on your server or copy them to a workstation.
XSLT processor
If the package or function requires an XSLT processor, you must include an XSLT processor in the
CLASSPATH at run-time. The XSLT processor must meet the following requirements:
• Be JAXP-compliant
• Contain the class javax.xml.transform.Transformer
The Java 2 Software Developer Kit (J2SDK), version 1.4, includes a suitable XSLT processor. If you use a
previous version of J2SDK, use any of the following methods to access a suitable XSLT processor:
• Use xslparser.jar (an IBM version of the Xalan XSLT processor from Apache)
• Download the Xalan XSLT processor from the Apache Web site
• Use any compatible XSLT processor in the /QIBM/ProdData/OS400/xml/lib directory on your
system
You can use these processors on your system or copy them to a workstation.
Note: If you do not run the previous command from the directory that contains jt400.jar, you can specify a
fully qualified path to jt400.jar.
You can place the default schema file (or any schema file) in any directory. The only requirement is that
you specify the location of the schema file by using the xsi:noNamespaceSchemaLocation attribute in the
<xpcml> tag.
You can specify the location of the schema as a file path or as a URL.
Note: Although the following examples use xpcml.xsd as the schema file, you can specify any schema
that extends xpcml.xsd.
• To specify the same directory as the XPCML file, use xsi:noNamespaceSchemaLocation='xpcml.xsd'
<pcml version="4.0">
<program name="prog1" path="QSYS.LIB/MYLIB.LIB/PROG1.PGM">
<data name="parm1" type="char" usage="input" length="10" init="Parm1"/>
<data name="parm2" type="int" usage="input" length="4" init="5"/>
<data name="parm3" type="int" usage="input" length="2" precision="16" init="3"/>
</program>
</pcml>
<pcml version="4.0">
<program name="prog2" path="QSYS.LIB/MYLIB.LIB/PROG2.PGM">
<data name="parm1" type="char" usage="input" length="20" count="3"/>
<data name="parm2" type="int" usage="input" length="8" init="5"/>
<data name="parm3" type="zoned" usage="input" length="5" precision="2" init="32.56"/>
</program>
</pcml>
<!--///////////////////////////////////////////////////////////////////////////
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:annotation>
<xs:documentation>
Schema for xpcml (eXtended Program Call Markup Language).
</xs:documentation>
</xs:annotation>
<xs:element name="xpcml">
<xs:complexType>
<xs:sequence>
<xs:element ref="structOrProgram" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="version" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="4.0"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:group>
<xs:complexType name="stringElementType">
<xs:simpleContent>
<xs:extension base="xs:string">
<!-- The index into the array. -->
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="intElementType">
<xs:simpleContent>
<xs:extension base="xs:int">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="unsignedIntElementType">
<xs:simpleContent>
<xs:extension base="xs:unsignedInt">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="shortElementType">
<xs:simpleContent>
<xs:extension base="xs:short">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="unsignedShortElementType">
<xs:simpleContent>
<xs:extension base="xs:unsignedShort">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="longElementType">
<xs:simpleContent>
<xs:extension base="xs:long">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="zonedDecimalElementType">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="packedDecimalElementType">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="floatElementType">
<xs:simpleContent>
<xs:extension base="xs:float">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="doubleElementType">
<xs:simpleContent>
<xs:extension base="xs:double">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
<xs:complexType name="hexBinaryElementType">
<xs:simpleContent>
<xs:extension base="xs:hexBinary">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="structElementType">
<xs:complexContent>
<xs:extension base="structureParmArray">
<xs:attribute name="index" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<!-- Attributes that are common to all data field types. -->
<xs:attributeGroup name="commonParmAttrs">
<!-- Specifies whether this is an input, output, or input-output parameter ('usage' in
PCML). -->
<!-- The default value if none is specified is 'inherit'. -->
<xs:attribute name="passDirection" type="passDirectionType"/>
<!-- Specifies whether the parameter is passed by reference or value ('passby' in PCML).
-->
<!-- The default value if none is specified is 'reference'. -->
<xs:attribute name="passMode" type="passModeType" />
<!-- The offset to the element within an output parameter. -->
<!-- The default value if none is specified is 0. -->
<xs:attribute name="offset" type="xs:string" />
<!-- The base location from which the 'offset' attribute is relative. -->
<xs:attribute name="offsetFrom" type="xs:string" />
<!-- The number of bytes to reserve for output data for the element. -->
<xs:attribute name="outputSize" type="xs:string" />
<!-- The lowest version of IBM i to which this field applies. -->
<!-- If not specified, we assume this field applies to all versions. -->
<xs:attribute name="minvrm" type="string10" />
<!-- The highest version of IBM i to which this field applies. -->
<!-- If not specified, we assume this field applies to all versions. -->
<xs:attribute name="maxvrm" type="string10" />
</xs:attributeGroup>
<xs:simpleType name="passDirectionType">
<xs:restriction base="xs:string">
<xs:enumeration value="in"/>
<xs:enumeration value="inout"/>
<xs:enumeration value="out"/>
<xs:enumeration value="inherit"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="passModeType">
<xs:restriction base="xs:string">
<xs:enumeration value="value"/>
<xs:enumeration value="reference"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="charType">
<xs:restriction base="xs:string">
<xs:enumeration value="onebyte"/>
<xs:enumeration value="twobyte"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="trimType">
<xs:restriction base="xs:string">
<xs:enumeration value="none"/>
<xs:enumeration value="left"/>
<xs:enumeration value="right"/>
<xs:enumeration value="both"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="returnValueType">
<xs:restriction base="xs:string">
<xs:enumeration value="void"/>
<xs:enumeration value="integer"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="structureParmArray">
<xs:sequence>
<xs:group ref="structureParm" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="string50"/>
<xs:attribute name="passDirection" type="passDirectionType"/>
<xs:attribute name="offset" type="xs:string" />
<xs:attribute name="offsetFrom" type="xs:string" />
<xs:attribute name="outputSize" type="xs:string" />
<xs:attribute name="minvrm" type="string10" />
<xs:attribute name="maxvrm" type="string10" />
</xs:complexType>
<xs:complexType name="zonedDecimal">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="totalDigits" type="xs:positiveInteger" />
<xs:attribute name="fractionDigits" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="packedDecimal">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="totalDigits" type="xs:positiveInteger" />
<xs:attribute name="fractionDigits" type="xs:nonNegativeInteger" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="structureFieldArray">
<xs:sequence>
<xs:group ref="structureField" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="string50"/>
<!-- 'count' is required if you want to input and/or output array data as XPCML. -->
<xs:attribute name="count" type="xs:string"/>
</xs:complexType>
<!-- Attributes that are common to all data field types. -->
<xs:attributeGroup name="commonFieldAttrs">
<xs:attribute name="name" type="string50"/>
<xs:attribute name="columnHeading1" type="string20"/>
<xs:attribute name="columnHeading2" type="string20"/>
<xs:attribute name="columnHeading3" type="string20"/>
<xs:attribute name="description" type="string50"/>
<xs:attribute name="defaultValue" type="xs:string"/><!-- Max length of string is 65535
characters. -->
<xs:simpleType name="ccsidType">
<xs:restriction base="xs:nonNegativeInteger">
<xs:maxInclusive value="65535"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string10">
<xs:restriction base="xs:string">
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string20">
<xs:restriction base="xs:string">
<xs:maxLength value="20"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string50">
<xs:restriction base="xs:string">
<xs:maxLength value="50"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
XPCML syntax
The XPCML schema defines several element tags, and each element tag contains attribute tags.
The following table lists the different elements that you can declare and define in your XPCML source
files. Each entry in the first column links to the appropriate section of the XPCML schema.
Using XPCML
Using XPCML is similar to using PCML. The following steps serve as a general outline for the actions that
you need to perform to use XPCML.
1. Use XPCML to describe the specification for the program call
2. Create a ProgramCallDocument object
3. Use ProgramCallDocument.callProgram() to run the program
Despite the similarities to using PCML, using XPCML offers enhanced functionality:
• Have the parser automatically validate parameter values
• Specify and pass values for program parameters
• Retrieve the results of a program call to your server in XPCML
• Transform an existing PCML document into the equivalent XPCML document
• Extend the XPCML schema to define new simple and complex elements and attributes
For example, IBM Toolbox for Java enables you to extend the XPCML schema to create new parameter
and data types. You can use this XPCML capability to condense your XPCML source files, which makes the
files easier to read and code easier to use.
For more information about using XPCML, see the following pages:
try {
InputStream pcmlStream = new FileInputStream("myPCML.pcml");
OutputStream xpcmlStream = new FileOutputStream("myXPCML.xpcml");
ProgramCallDocument.transformPCMLToXPCML(pcmlStream, xpcmlStream);
}
catch (Exception e) {
System.out.println("error: - "+e.getMessage());
e.printStackTrace();
}
For more information about transformPCMLToXPCML() and the ProgramCallDocument class, see the
following page:
ProgramCallDocument javadoc information
// Call PROG1
boolean rc = xpcmlDoc.callProgram("PROG1");
Examples
The following examples illustrate how to condense an existing XPCML document.
The first example is simple and includes original XPCML source, the resulting condensed XPCML, and the
extended schema. The second example is longer and more complex, so it includes the Java code that
calls condenseXPCML() and only a few of the newly generated type definitions in the extended schema:
Example
A fully validating XML parser generates an error for any numeric parameter type that does not have a
value. The following example shows sample XPCML source and the resulting non-fatal parse error:
XPCML source
<program name="prog1"/>
<parameterList>
<intParm name="parm1"/>
</parameterList>
</program>
Resulting error
To prevent logging this kind of error, add the nil=true attribute to the intParm element. The nil=true
atttribute signals to the parser that you have deliberately left the element empty.. Here is the previous
XPCML source with the nil=true atttribute added:
<program name="prog1"/>
<parameterList>
<intParm xsi:nil="true" name="parm1"/>
</parameterList>
</program>
• IBM Toolbox for Java FAQ : Find answers to many types of questions, including improving
performance, using IBM i, performing troubleshooting, and more.
• IBM Toolbox for Java JDBC FAQ : Find answers to questions about using JDBC with IBM Toolbox for
Java.
Follow these conditions when determining and specifying the integrated file system name:
• The forward slash (/) is the path separator character.
• The root-level directory, called QSYS.LIB, contains the server library structure.
/QSYS.LIB/object.type
/QSYS.LIB/library.LIB/object.type
• The object type extension is the server abbreviation used for that type of object.
To see a list of these types, enter a CL command that has object type as a parameter and press F4
(Prompt) for the type. For example, the Work with Objects (WRKOBJ) command has an object type
parameter.
The following table is a list of some commonly used object types and the abbreviation for each type:
Use the following descriptions to help you determine how to specify integrated file system path names:
Path name component Traditional format IBM Toolbox for Java format
Library name *ALL %ALL%
*ALLUSR %ALLUSR%
*CURLIB %CURLIB%
*LIBL %LIBL%
*USRLIBL %USRLIBL%
Object name *ALL %ALL%
Member name *ALL %ALL%
*FILE %FILE%
*FIRST %FIRST%
*LAST %LAST%
See the QSYSObjectPathName class for information about building and parsing integrated file system
names.
For more information about integrated file system concepts, see Integrated file system concepts.
To conserve server resources, create only one AS400 object as shown in Figure 2. This approach reduces
the number of connections, which reduces the amount of resource used on the server.
Figure 2: Java program creating a single AS400 object and socket connection for the same system
Note: Although creating more connections increases the amount of resource used on the server,
creating more connections can have a benefit. Having more connections enables your Java program to
process things in parallel, which can give better throughput (transactions-per-second) and speed up your
application.
You can also choose to use a connection pool to manage connections as shown in Figure 3. This approach
reduces the amount of time it takes to connect by reusing a connection previously established for the
user.
Figure 3: Java program getting a connection from an AS400ConnectionPool to a server
Example 2: In the following example, two CommandCall objects are created that send commands to the
same system. Because the CommandCall objects use different AS400 objects, two connections to the
server are created.
Example 3: In the following example, a CommandCall object and an IFSFileInputStream object are
created using the same AS400 object. Because the CommandCall object and the IFSFileInput Stream
object use different services on the server, two connections are created.
Example 4: In the following example, an AS400ConnectionPool is used to get an IBM i connection. This
example (like Example 3 above) does not specify a service, so the connection to the command service is
made when the command is run.
// Create an AS400ConnectionPool.
AS400ConnectionPool testPool1 = new AS400ConnectionPool();
// Create a connection.
AS400 newConn1 = testPool1.getConnection("myAS400", "myUserID", "myPassword");
Example 5: The following example uses AS400ConnectionPool to connect to a particular service when
requesting the connection from the pool. This eliminates the time required to connect to the service when
the command is run (see Example 4 above). If the connection is returned to the pool, the next call to get
a connection can return the same connection object. This means that no extra connection time is needed,
either on creation or use.
// Create an AS400ConnectionPool.
AS400ConnectionPool testPool1 = new AS400ConnectionPool();
// Create a connection to the AS400.COMMAND service. (Use the service number constants
// defined in the AS400 class (FILE, PRINT, COMMAND, DATAQUEUE, and so on.))
AS400 newConn1 = testPool1.getConnection("myAS400", "myUserID", "myPassword",
AS400.COMMAND);
// Get another connection to command service. In this case, it will return the same
// connection as above, meaning no extra connection time will be needed either now or
// when the command service is used.
AS400 newConn2 = testPool1.getConnection("myAS400", "myUserID", "myPassword",
AS400.COMMAND);
Example 2: Once a connection is started, the Java program is responsible for disconnecting, which
is done either implicitly by the AS400 object, or explicitly by the Java program. A Java program
disconnects by calling the disconnectService() method on the AS400 object. To improve performance,
the Java program must disconnect only when the program is finished with a service. If the Java program
disconnects before it is finished with a service, the AS400 object reconnects, if it is possible to reconnect,
when data is needed from the service.
Figure 4 shows how disconnecting the connection for the first integrated file system object connection
ends only that single instance of the AS400 object connection, not all of the integrated file system object
connections.
Figure 4: Single object using its own service for an instance of an AS400 object is disconnected
Example 3: Multiple objects that use the same service and share the same AS400 object share a
connection. Disconnecting ends the connection for all objects that are using the same service for each
instance of an AS400 object as is shown in Figure 5.
Figure 5: All objects using the same service for an instance of an AS400 object are disconnected
Example 4: Not all IBM Toolbox for Java classes automatically reconnect. Some method calls in the
integrated file system classes do not reconnect because the file may have changed. While the file was
disconnected, some other process may have deleted the file or changed its contents. In the following
example, two file objects use the same AS400 object. When disconnectService() is called, the connection
is ended for both file objects. The read() for the second IFSFileInputStream object fails because it no
longer has a connection to the server.
Comparing the IBM i Java virtual machine and the IBM Toolbox for Java
classes
You always have at least two ways to access a server resource when your Java program is running on the
IBM Developer Kit for Java (IBM i) Java virtual machine (JVM).
You can use either of the following interfaces:
• Facilities built into Java
• An IBM Toolbox for Java class
When deciding which interface to use, consider the following factors:
• Location - Where a program runs is the most important factor in deciding which interface set to use.
Does the program do the following:
– Run only on the client?
– Run only on the server?
– Run on both client and server, but in both cases the resource is an IBM i resource?
– Run on one IBM i JVM and access resources on another IBM i server?
– Run on different kinds of servers?
If the program runs on both client and server (including an IBM i server as a client to a second IBM i
server) and accesses only IBM i resources, it may be best to use the IBM Toolbox for Java interfaces.
If the program must access data on many types of servers, it may be best to use Java native interfaces.
• Consistency / Portability - The ability to run IBM Toolbox for Java classes on the IBM i server means
that the same interfaces can be used for both client programs and server programs. When you have only
one interface to learn for both client programs and server programs, you can be more productive.
Writing to IBM Toolbox for Java interfaces makes your program less server portable, however.
If your program must connect to an IBM i server as well as other servers, you may find it better to use
the facilities that are built into Java.
• Complexity - The IBM Toolbox for Java interface is built especially for easy access to an IBM i resource.
Often, the only alternative to using the IBM Toolbox for Java interface is to write a program that
accesses the resource and communicates with that program through Java Native Interface (JNI).
You must decide whether it is more important to have better Java neutrality and write a program to
access the resource, or to use the IBM Toolbox for Java interface, which is less portable.
• Function - The IBM Toolbox for Java interface often provides more function than the Java interface.
For example, the IBM Toolbox for Java IFSFileOutputStream class has more function than the
Running IBM Toolbox for Java classes on the IBM i Java virtual machine
There are some special considerations for running the IBM Toolbox for Java classes on the IBM Developer
Kit for Java (IBM i) Java virtual machine (JVM).
Command call
Two common ways to call a command are to use one of the following:
• The IBM Toolbox for Java CommandCall class
• The java.lang.Runtime.exec method
The CommandCall class generates a list of messages that are available to the Java program once the
command completes. This list of messages is not available through java.lang.Runtime.exec().
The java.lang.Runtime.exec method is portable across many platforms, so if your program must access
files on different types of servers, java.lang.Runtime.exec() is a better solution.
JDBC
Two IBM-supplied JDBC drivers are available to programs running on the IBM i JVM:
• The IBM Toolbox for Java JDBC driver
• The IBM Developer Kit for Java JDBC driver
The IBM Toolbox for Java JDBC driver is best to use when the program is running in a client/server
environment.
Program call
Two common ways to call a program are as follows:
• The ProgramCall class of the IBM Toolbox for Java
• Through a Java Native Interface (JNI) call
The IBM Toolbox for Java ProgramCall class has the advantage that it can call any server program.
You may not be able to call your server program through JNI. An advantage of JNI is that it is more
portable across server platforms.
Setting system name, user ID, and password with an AS400 object in the IBM
i Java virtual machine
The AS400 object allows special values for system name, user ID, and password when the Java program
is running on the IBM Toolbox for Java (IBM i) Java virtual machine (JVM).
When you run a program on the IBM i JVM, be aware of some special values and other considerations:
• User ID and password prompting is disabled when the program runs on the server. For more information
about user ID and password values in the server environment, see Summary of user ID and password
values on an AS400 object.
• If system name, user ID, or password is not set on the AS400 object, the AS400 object connects to
the current server by using the user ID and password of the job that started the Java program. When
connecting to a v4r4 or later machine, it can extend the signed-on user's password like the rest of the
IBM Toolbox for Java components.
• The special value, localhost, can be used as the system name. In this case, the AS400 object connects
to the current server.
• The special value, *current, can be used as the user ID or password on the AS400 object. In this case,
the user ID or password (or both) of the job that started the Java program is used.
• The special value, *current, can be used as the user ID or password on the AS400 object when the Java
program is running on the IBM i JVM of one server, and the program is accessing resources on another
IBM i server. In this case, the user ID and password of the job that started the Java program on the
source system are used when connecting to the target system.
Examples
The following examples show how to use the AS400 object with the IBM i JVM.
Example: Creating an AS400 object when the IBM i JVM is running a Java program
When a Java program is running in the IBM i JVM, the program does not need to supply a system name,
user ID, or password.
Note: You must supply a password when using record-level access.
If these values are not supplied, the AS400 object connects to the local system by using the user ID and
password of the job that started the Java program.
When the program is running on the IBM i JVM, setting the system name to localhost is the same as not
setting the system name. The following example shows how to connect to the current server:
Example: Connecting to the current server with a different user ID and password from the program
that started the job The Java program can set a user ID and password even when the program is running
on the IBM i JVM. These values override the user ID and password of the job that started the Java
program.
In the following example, the Java program connects to the current server, but the program uses a user ID
and password that differs from those of the job that started the Java program.
Example: Connecting to a different server by using the user ID and password of the job that started
the Java program
A Java program that is running on one server can connect to and use the resources of other systems.
If *current is used for user ID and password, the user ID and password of the job that started the Java
program is used when the Java program connects to the target server.
In the following example, the Java program is running on one server, but uses resources from another
server. The user ID and password of the job that started the Java program are used when the program
connects to the second server.
Exceptions
The IBM Toolbox for Java access classes throw exceptions when device errors, physical limitations,
programming errors, or user input errors occur. The exception classes are based upon the type of error
that occurs instead of the location where the error originates.
Most exceptions contain the following information:
• Error type: The exception object that is thrown indicates the type of error that occurred. Errors of the
same type are grouped together in an exception class.
• Error details: The exception contains a return code to further identify the cause of the error that
occurred. The return code values are constants within the exception class.
• Error text: The exception contains a text string that describes the error that occurred. The string is
translated in the locale of the client Java virtual machine.
// All the setup work to delete a file on the server through the
// IFSFile class is done. Now try deleting the file.
try
{
aFile.delete();
// Get the return code out of the exception and display additional
// information based on the return code.
int rc = e.getReturnCode()
switch (rc)
{
case ExtendedIOException.FILE_IN_USE:
System.out.println("Delete failed, file is in use "):
break;
case ExtendedIOException.PATH_NOT_FOUND:
System.out.println("Delete failed, path not found ");
break;
default:
System.out.println("Delete failed, rc = ");
System.out.println(rc);
}
}
Trace class
The Trace class allows the Java program to log trace points and diagnostic messages. This information
helps reproduce and diagnose problems.
Note: You can also set tracing by using the trace system properties.
The Trace class logs the following categories of information:
The IBM Toolbox for Java classes also use the trace categories. When a Java program enables logging,
IBM Toolbox for Java information is included with the information that is recorded by the application.
Examples
Note: Read the Code example disclaimer for important legal information.
The following examples show how to use the Trace class.
Example Using setTraceOn() and writing data to a log by using the log method
// Send IBM Toolbox for Java and the component trace data each to separate files.
// The trace will contain all trace information, while each
// Trace.setFileName("c:\\bit.bucket");
// Trace.setFileName(myComponent1, "c:\\Component1.log");
// Trace.setFileName(myComponent2, "c:\\Component2.log");
// Log component specific trace data or general IBM Toolbox for Java
// trace data.
Trace.setFileName("c:\\bit.bucket");
Trace.setFileName(myComponent1, "c:\\Component1.log");
Related information
Trace Javadoc
IBM i optimization
There exists two versions of the IBM Toolbox for Java software, one that is optimized when running on the
IBM i JVM, and another that runs the same way no matter where the IBM Toolbox for Java is run.
Sign-on behavior and performance are improved when using the optimized version of the IBM Toolbox for
Java software and running on the IBM i JVM and connecting to the same server.
Sign-on considerations
The version of the IBM Toolbox for Java that contains optimizations adds additional options for providing
server (system) name, user ID and password information to the IBM Toolbox for Java.
When accessing an IBM i resource, the IBM Toolbox for Java classes must have a system name, user ID
and password.
• When running on a client, the system name, user ID and password are provided by the Java program,
or the IBM Toolbox for Java retrieves these values from the user through a sign-on dialog.
• When running within the IBM i Java virtual machine, the IBM Toolbox for Java has one more option.
It can send requests to the current (local) server using the user ID and password of the job that started
the Java program.
With the IBM Toolbox for Java that contains optimizations, the user ID and password of the current job
also can be used when a Java program that is running on one IBM i server accesses the resources on
another IBM i server. In this case, the Java program sets the system name, then uses the special value
"*current" for the user ID and password.
is the same as
Examples
The following examples show how to sign on to a server by using optimized classes.
Example: Signing on when using different AS400 constructors
Two AS400 objects are created in the following example. The two objects have the same behavior: they
both run a command to the current server using the user ID and password of the job. One object uses the
special value for the user ID and password, while the other uses the default constructor and does not set
user ID or password.
// Create two command call objects that use the AS400 objects.
CommandCall cmd1 = new CommandCall(sys1,"myCommand1");
CommandCall cmd2 = new CommandCall(sys2,"myCommand2");
Example: Signing on by using the user ID and password of the current job
In the following example an AS400 object is created that represents a second IBM i server. Since
"*current" is used, the job's user ID and password from the server running the Java program are used on
the second (target) server.
Faster communication
For all IBM Toolbox for Java functions except JDBC and integrated file system access, Java programs
running on the Java virtual machine for IBM i will run faster. The programs run faster because less
communication code is used when communicating between the Java program and the server program on
the server that does the request.
JDBC and integrated file system access were not optimized because facilities already exist that make
these functions run faster. When running on the IBM i server, you can use the JDBC driver for IBM i
instead of the JDBC driver that comes with the IBM Toolbox for Java. To access files on the server, you can
use java.io instead of the integrated file system access classes that come with the IBM Toolbox for Java.
Converters
Two classes allow faster, more efficient conversion between Java and the system:
• Binary Converter: Converts between Java byte arrays and Java simple types.
• Character Converter: Converts between Java String objects and IBM i code pages.
Also, the IBM Toolbox for Java now incorporates its own conversion tables for over 100 commonly used
CCSIDs. Previously, the IBM Toolbox for Java either deferred to Java for nearly all text conversion. If Java
did not possess the correct conversion table, IBM Toolbox for Java downloaded the conversion table from
the server.
The IBM Toolbox for Java performs all text conversion for any CCSID of which it is aware. When it
encounters an unknown CCSID, it attempts to let Java handle the conversion. At no point does the IBM
Toolbox for Java attempt to download a conversion table from the server. This technique greatly reduces
the amount of time it takes for an IBM Toolbox for Java application to perform text conversion. No action
is required by the user to take advantage of this new text conversion; the performance gains all occur in
the underlying converter tables.
Related information
AS400 Javadoc
BinaryConverter Javadoc
Character Converter Javadoc
AS400ToolboxJarMaker
While the JAR file format was designed to speed up the downloading of Java program files, the
AS400ToolboxJarMaker generates an even faster loading IBM Toolbox for Java JAR file through its ability
to create a smaller JAR file from a larger one.
Also, the AS400ToolboxJarMaker class can unzip a JAR file for you to gain access to the individual content
files for basic use.
where
• options = one or more of the available options
For a complete set of options available to run at a command line prompt, see the following in the Javadoc:
• Options for the JarMaker base class
• Extended options for the AS00ToolboxJarMaker subclass
Using AS400ToolboxJarMaker
You can use AS400ToolboxJarMaker to work with JAR files in several ways:
• Uncompress one file bundled within a JAR file
• Split a large JAR file into smaller JAR files
• Exclude any IBM Toolbox for Java files that your application does not need to run
Uncompressing a JAR file
Suppose you wanted to uncompress just one file bundled within a JAR file. AS400ToolboxJarMaker allows
you to expand the file into one of the following:
• Current directory (extract(jarFile))
• Another directory (extract(jarFile, outputDirectory))
For example, with the following code, you are extracting AS400.class and all of its dependent classes
from jt400.jar:
Additionally, if it is unnecessary to convert text strings between Unicode and the double byte character
set (DBCS) conversion tables, you can create a 400KB byte smaller JAR file by omitting the unneeded
conversion tables with the -ccsid option:
Note: Conversion classes are not included with the program call classes. When including program call
classes, you must also explicitly include the conversion classes used by your program by using the -ccsid
option.
JarMaker Javadoc
AS400ToolboxJarMaker Javadoc
IBM Toolbox for Java troubleshooting information Use this information to help you resolve
problems when using IBM Toolbox for Java.
JTOpen/IBM Toolbox for Java forum Join the community of Java programmers who use
IBM Toolbox for Java. This forum is an effective way to get assistance and advice from other
Java programmers and sometimes from the IBM Toolbox for Java developers themselves
Server support Use the IBM Server support Web site to find out about the tools and
resources that help you streamline the technical planning and support for your system.
Software support Use the IBM Software Support Services Web site to find out about the
wide array of software support services offered by IBM.
Support services for the IBM Toolbox for Java are provided under the usual terms and conditions for
software products. Support services include program services, voice support, and consulting services.
Contact your local IBM representative for more information.
Resolving IBM Toolbox for Java program defects is supported under program services and voice support,
while resolving application programming and debugging issues is supported under consulting services.
IBM Toolbox for Java application program interface (API) calls are supported under consulting services
unless any of the following are true:
• It is clearly a Java API defect, as demonstrated by re-creation in a relatively simple program.
• It is a question asking for documentation clarification.
• It is a question about the location of samples or documentation.
All programming assistance is supported under consulting services including those program samples
provided in the IBM Toolbox for Java licensed program. Additional samples may be made available on the
Internet at the IBM i home page on an unsupported basis.
Code examples
The following list provides links to entry points for many of the examples used throughout the IBM
Toolbox for Java information.
IBM grants you a nonexclusive copyright license to use all programming code examples from which you
can generate similar function tailored to your own specific needs.
SUBJECT TO ANY STATUTORY WARRANTIES WHICH CANNOT BE EXCLUDED, IBM, ITS PROGRAM
DEVELOPERS AND SUPPLIERS MAKE NO WARRANTIES OR CONDITIONS EITHER EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT, REGARDING THE PROGRAM OR
TECHNICAL SUPPORT, IF ANY.
UNDER NO CIRCUMSTANCES IS IBM, ITS PROGRAM DEVELOPERS OR SUPPLIERS LIABLE FOR ANY OF
THE FOLLOWING, EVEN IF INFORMED OF THEIR POSSIBILITY:
1. LOSS OF, OR DAMAGE TO, DATA;
2. DIRECT, SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES, OR FOR ANY ECONOMIC CONSEQUENTIAL
DAMAGES; OR
3. LOST PROFITS, BUSINESS, REVENUE, GOODWILL, OR ANTICIPATED SAVINGS.
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF DIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES, SO SOME OR ALL OF THE ABOVE LIMITATIONS OR EXCLUSIONS MAY NOT
APPLY TO YOU.
AS400JPing
• Example: Using AS400JPing within a Java program
BidiTransform
• Example: Using the AS400BidiTransform class to transform bidirectional text
CommandCall
• Example: Using CommandCall to run a command on the server
• Example: Using CommandCall to prompt for the name of the server, command to run, and print the
result
DataArea
• Example: Creating and writing to a decimal data area
DataQueue
• Example: How to create a DataQueue object, read data, and disconnect
• Example: Putting data on a queue
• Example: Reading data from a queue
• Example: Using KeyedDataQueue to put items on a queue
• Example: Using KeyedDataQueue to take items off a queue
Digital certificate
• Example: Listing digital certificates that belong to a user
EnvironmentVariable
• Example: Creating, setting, and getting environment variables
Exceptions
• Example: Catching a thrown exception, retrieving the return code, and displaying the exception text
FTP
• Example: Using the FTP class to Copy a set of files from a server directory
• Example: Using the AS400FTP class to copy a set of files from a directory
JavaApplicationCall
• Example: Running a program on the server from the client that outputs "Hello World!"
Jobs
• Example: Retrieving and changing job information using the cache
• Example: Listing all active jobs
• Example: Printing all of the messages in the job log for a specific user
• Example: Listing the job identification information for a specific user
• Example: Getting a list of jobs on the server and listing the job status and the job identifier
• Example: Displaying messages in the job log for a job that belongs to the current user
Message queue
• Example: How to use the message queue object
• Example: Printing the contents of the message queue
• Example: Retrieving and printing a message
• Example: Listing the contents of the message queue
• Example: Using AS400Message with CommandCall
• Example: Using AS400Message with ProgramCall
NetServer
• Example: Using a NetServer object to change the name of the NetServer
Print
• Example: Asynchronously listing all spooled files using the PrintObjectListListener interface
• Example: Asynchronously listing all spooled files without using the PrintObjectListListener interface
• Example: Copying a spooled file using SpooledFile.copy()
• Example: Creating a spooled file from an input stream
• Example: Generating an SCS data stream using the SCS3812Writer class
• Example: Reading an existing spooled file
• Example: Reading and transforming spooled files
• Example: Synchronously listing all spooled files
Permission
• Example: Set the authority of an AS400 object
Program call
• Example: Using ProgramCall
• Example: Using ProgramCall to retrieve system status
• Example: Passing parameter data with a Program parameter object
QSYSObjectPathName
• Example: Building an integrated file system name
Record-level access
• Example: Sequentially accessing a file
• Example: Using the record-level access classes to read a file
• Example: Using the record-level access classes to read records by key
• Example: Using the LineDataRecordWriter class
SystemStatus
• Example: Use caching with the SystemStatus class
SystemPool
• Example: Setting the maximum faults size for SystemPool
SystemValue
• Example: Using SystemValue and SystemValueList
Trace
• Example: Using the Trace.setTraceOn() method
• Example: Preferred way to use Trace
• Example: Using component tracing
UserGroup
• Example: Retrieving a list of users
• Example: Listing all the users of a group
UserSpace
• Example: How to create a user space
The following disclaimer applies to all of the IBM Toolbox for Java examples:
Code example disclaimer
IBM grants you a nonexclusive copyright license to use all programming code examples from
which you can generate similar function tailored to your own specific needs.
All sample code is provided by IBM for illustrative purposes only. These examples have
not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply
reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any
kind. The implied warranties of non-infringement, merchantability and fitness for a particular
purpose are expressly disclaimed.
//////////////////////////////////////////////////////////////////////////////////
//
// Command call example. This program prompts the user
// for the name of the server and the command to run, then
// prints the result of the command.
//
// This source is an example of "CommandCall"
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
// Declare variables to hold the system name and the command to run
String systemString = null;
String commandString = null;
// Get the system name and the command to run from the user
try
{
System.out.print("System name: ");
systemString = inputStream.readLine();
System.out.print("Command: ");
commandString = inputStream.readLine();
}
catch (Exception e) {};
try
{
// Run the command.
if (command.run(commandString))
System.out.print( "Command successful" );
else
System.out.print( "Command failed" );
System.exit(0);
}
}
////////////////////////////////////////////////////////////
//
// AS400ConnectionPooling example. This program uses an
// AS400ConnectionPool to create connections to an
// IBM i system.
// Command syntax:
// AS400ConnectionPooling system myUserId myPassword
//
// For example,
// AS400ConnectionPooling MySystem MyUserId MyPassword
//
////////////////////////////////////////////////////////////
import com.ibm.as400.access.*;
try
{
// Create an AS400ConnectionPool.
AS400ConnectionPool testPool = new AS400ConnectionPool();
System.out.println();
System.out.println("getConnection gives out an existing connection to user");
System.out.println("Number of active connections: "
+ testPool.getActiveConnectionCount(system, userId));
System.out.println("Number of available connections for use: "
+ testPool.getAvailableConnectionCount(system, userId));
System.out.println();
System.out.println("Returned a connection to pool");
System.out.println("Number of active connections: "
+ testPool.getActiveConnectionCount(system, userId));
System.out.println("Number of available connections for reuse: "
+ testPool.getAvailableConnectionCount(system, userId));
// Create a connection to the AS400.COMMAND service. This will return the same
// object as above for reuse.
AS400 newConn2 = testPool.getConnection(system, userId, password, AS400.COMMAND);
System.out.println();
System.out.println("getConnection gives out an existing connection to user");
System.out.println("Number of active connections: "
+ testPool.getActiveConnectionCount(system, userId));
System.out.println("Number of available connections for reuse: "
+ testPool.getAvailableConnectionCount(system, userId));
System.out.println();
System.out.println("getConnection creates a new connection because there are no
connections available");
System.out.println("Number of active connections: "
+ testPool.getActiveConnectionCount(system, userId));
System.out.println("Number of available connections for reuse: "
+ testPool.getAvailableConnectionCount(system, userId));
Example 1
This brief example shows the basic use of the AS400JDBCManagedConnectionPoolDataSource class.
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.ibm.as400.access.AS400JDBCManagedConnectionPoolDataSource;
import com.ibm.as400.access.AS400JDBCManagedDataSource;
// Set general datasource properties. Note that both connection pool datasource (CPDS) and
managed
// datasource (MDS) have these properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
Connection c = dataSource_.getConnection();
Example 2
This example shows more details about how to use the AS400JDBCManagedConnectionPoolDataSource
class.
import java.awt.TextArea;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Vector;
import java.util.Properties;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.*;
import java.util.Date;
import java.util.ArrayList;
import java.util.Random;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCManagedConnectionPoolDataSource;
import com.ibm.as400.access.AS400JDBCManagedDataSource;
import com.ibm.as400.access.Trace;
// If you turn this flag on, be sure to also turn on the following flag:
// AS400JDBCConnection.TESTING_THREAD_SAFETY.
private static final boolean TESTING_THREAD_SAFETY = false;
// Note: For consistency, all time values are stored units of milliseconds.
private int initialPoolSize_; // initial # of connections in pool
private int minPoolSize_; // max # of connections in pool
private int maxPoolSize_; // max # of connections in pool
private long maxLifetime_; // max lifetime (msecs) of connections in pool
private long maxIdleTime_; // max idle time (msecs) of available connections in pool
private long propertyCycle_; // pool maintenance frequency (msecs)
private boolean keepDaemonsAlive_ = true; // When this is false, the daemons shut down.
static
{
try {
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
}
catch(Exception e){
System.out.println("Unable to register JDBC driver.");
System.exit(0);
}
}
cptest.setup();
cptest.runTest();
}
if (TESTING_THREAD_SAFETY)
{
// Adjust values for performing thread-intensive stress testing.
// NOTE: This assumes that the AS400JDBCConnection class has also been modified to
// not make actual connections to an actual server.
// To do this, edit AS400JDBCConnection.java, changing its TESTING_THREAD_SAFETY
// flag to 'false', and recompile.
minPoolSize_ = 100;
maxPoolSize_ = 190;
initialPoolSize_ = 150; // this should get reset to maxPoolSize_
numDaemons_ = 75;
if (timeToRunDaemons_ == 0) {
timeToRunDaemons_ = 180*1000; // 180 seconds == 3 minutes
}
}
else
{ // Set more conservative values, as we'll be making actual connections to an
// actual server, and we don't want to monopolize the server.
minPoolSize_ = 5;
maxPoolSize_ = 15;
initialPoolSize_ = 9;
numDaemons_ = 4;
if (timeToRunDaemons_ == 0) {
timeToRunDaemons_ = 15*1000; // 15 seconds
}
}
maxLifetime_ = (int)timeToRunDaemons_ / 3;
maxIdleTime_ = (int)timeToRunDaemons_ / 4;
propertyCycle_ = timeToRunDaemons_ / 4;
poolHealthCheckCycle_ = Math.min(timeToRunDaemons_ / 4, 20*60*1000);
// at least once every 20 minutes (more frequently if shorter run-time)
daemonMaxSleepTime_ = Math.min(timeToRunDaemons_ / 3, 10*1000);
// at most 10 seconds (less if shorter run-time)
daemonMinSleepTime_ = 20; // milliseconds
if (DEBUG)
System.out.println("setup: Constructing "
+ "AS400JDBCManagedConnectionPoolDataSource (cpds0)");
AS400JDBCManagedConnectionPoolDataSource cpds0 =
new AS400JDBCManagedConnectionPoolDataSource();
// Set datasource properties. Note that both CPDS and MDS have these
// properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
ctx.rebind("mydatasource", cpds0);
// We can now do lookups on cpds, by the name"mydatasource".
if (DEBUG)
System.out.println("setup: lookup(\"mydatasource\"" + ")");
// AS400JDBCManagedConnectionPoolDataSource cpds1 =
// (AS400JDBCManagedConnectionPoolDataSource)ctx.lookup("mydatasource");
// if (DEBUG) System.out.println("setup: cpds1.getUser() == |" + cpds1.getUser() + "|");
if (DEBUG)
System.out.println("setup: Constructing AS400JDBCManagedDataSource (mds0)");
AS400JDBCManagedDataSource mds0 = new AS400JDBCManagedDataSource();
mds0.setDescription("DataSource supporting connection pooling");
mds0.setDataSourceName("mydatasource");
ctx.rebind("ConnectionPoolingDataSource", mds0);
if (DEBUG)
System.out.println("setup: lookup(\"ConnectionPoolingDataSource\"" + ")");
dataSource_ = (DataSource)ctx.lookup("ConnectionPoolingDataSource");
//dataSource_.setLogWriter(output_);
if (DEBUG)
System.out.println("setup: dataSource_.getUser() == |" +
((AS400JDBCManagedDataSource)dataSource_).getUser() + "|");
mds_ = (AS400JDBCManagedDataSource)dataSource_;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Setup error during Trace file creation.");
}
}
/**
* Gets and returns connections from and to a connection pool for a while.
**/
public void runTest()
{
boolean ok = true;
try
{
System.out.println("Started test run at " + new Date());
if (DEBUG)
System.out.println("Checking health just after datasource creation "
+ "(we expect that the pool does not exist yet) ...");
if (mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool exists prior to first getConnection().");
}
mds_.setAccess("read only");
if (!mds_.getAccess().equals("read only")) {
ok = false;
System.out.println("\nERROR: getAccess() returned unexpected value: "
+ "|" + mds_.getAccess()+"|");
}
oldBool = mds_.isKeepAlive();
newBool = (oldBool ? false : true);
mds_.setKeepAlive(newBool);
if (mds_.isKeepAlive() != newBool) {
ok = false;
System.out.println("\nERROR: isKeepAlive() returned unexpected value: "
+ "|"+mds_.isKeepAlive()+"|");
}
mds_.setKeepAlive(oldBool);
oldInt = mds_.getReceiveBufferSize();
newInt = (oldInt == 256 ? 512 : 256);
mds_.setReceiveBufferSize(newInt);
if (mds_.getReceiveBufferSize() != newInt) {
ok = false;
System.out.println("\nERROR: getReceiveBufferSize() returned unexpected value: "
+ "|"+mds_.getReceiveBufferSize()+"|");
}
mds_.setReceiveBufferSize(oldInt);
System.out.println("CONNECTION 1");
Object o = dataSource_.getConnection();
System.out.println(o.getClass());
System.out.println("******LOOK ABOVE*******");
Connection c1 = dataSource_.getConnection();
if (DEBUG)
displayConnectionType(c1, true);
if (DEBUG)
System.out.println("Checking health after first getConnection() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first getConnection().");
}
if (!TESTING_THREAD_SAFETY)
{
try
{
c1.setAutoCommit(false);
if (DEBUG)
System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c1.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG)
System.out.println(rs.getString(2));
}
rs.close();
s.close();
}
catch (Exception e) {
e.printStackTrace();
if (DEBUG)
System.out.println("Checking health after fatal connection error ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("CONNECTION 2");
Connection c2 = dataSource_.getConnection(userid, password);
if (DEBUG)
displayConnectionType(c2, false);
System.out.println("CONNECTION 3");
Connection c3 = dataSource_.getConnection();
if (DEBUG)
displayConnectionType(c3, true);
c1.close();
if (DEBUG)
System.out.println("Checking health after first close() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first close().");
}
System.out.println("CONNECTION 4");
Connection c4 = dataSource_.getConnection();
if (DEBUG) displayConnectionType(c4, true);
// Run the test daemons for a while; check pool health periodically.
if (DEBUG)
System.out.println("Checking health after connectionGetter daemons have run...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after test daemons stopped.");
}
if (!TESTING_THREAD_SAFETY)
{
System.out.println("CONNECTION 5");
Connection c = dataSource_.getConnection();
if (DEBUG) displayConnectionType(c, true);
c.setAutoCommit(false);
if (DEBUG) System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG) System.out.println(rs.getString(2));
if (DEBUG)
System.out.println("Checking health after pool closed ...");
Trace.setTraceJDBCOn(true); // make sure the final stats get printed out
Trace.setTraceOn(true);
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after pool closed.");
}
System.out.println();
if(ok==true)
System.out.println("test ran ok");
else
System.out.println("test failed");
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
finally {
System.out.println("Ended test at " + new Date());
}
}
void startThreads()
{
// Create a bunch of threads that call getConnection().
Thread[] threads = new Thread[numDaemons_];
for (int i=0; i<numDaemons_; i++)
{
ConnectionGetter getter;
// Flip a coin to see if this daemon will specify the default uid, or unique uid.
if (random_.nextBoolean())
{
getter = new ConnectionGetter(userid,password);
if (TESTING_THREAD_SAFETY) { // we can use fictional userid
getter = new ConnectionGetter("Thread"+i, "Pwd"+i);
}
else { // must use a real userid
getter = new ConnectionGetter(userid,password);
}
}
else
getter = new ConnectionGetter(null, null);
void stopThreads()
{
// Tell the threads to stop.
keepDaemonsAlive_ = false;
synchronized (daemonSleepLock_) {
daemonSleepLock_.notifyAll();
}
/**
Helper class. This daemon wakes up at random intervals and either
gets another connection from the connection pool or returns a
previously-gotten connection to the pool.
**/
private final class ConnectionGetter implements Runnable
{
private String uid_;
private String pwd_;
private boolean useDefaultUid_;
private long maxSleepTime_;
private String threadName_;
private boolean firstConnection_ = true;
ArrayList connections_ = new ArrayList();
// list of connections that this getter currently 'owns'.
try
{
while (keepDaemonsAlive_)
{
try
{
// Pick a random sleep-time, between min and max values.
long sleepTime = Math.max((long)(maxSleepTime_ * random_.nextFloat()),
daemonMinSleepTime_);
// Note: Must never call wait(0), because that waits forever.
synchronized (daemonSleepLock_) {
try {
daemonSleepLock_.wait(sleepTime);
System.out.print(".");
}
catch (InterruptedException ie) {}
}
if (!keepDaemonsAlive_) break;
if (conn == null) {
System.out.println("ConnectionGetter("+threadName_+") ERROR: "
+ "getConnection() returned null");
}
else
{
// Occasionally "forget" that we own a connection, and neglect to
// close it.
// Orphaned connections should eventually exceed their maximum
// lifetime and get "reaped" by the connection manager.
float val = random_.nextFloat();
if (firstConnection_ || val < 0.1) {
// 'orphan' a few gotten connections
}
}
// Get a record based on the format of the entries on the data queue
Record rec = entryFormat.getNewRecord();
public MessageEntryFormat()
{
// We will name this format for posterity
super("MessageEntryFormat");
// Add the field descriptions
addFieldDescription(msgNumber);
addFieldDescription(sender);
addFieldDescription(timeSent);
addFieldDescription(msgText);
addFieldDescription(replyRequired);
}
}
// Read an entry
DataQueueEntry dqEntry = null;
try
// Get a record object from our record format, initializing it with the data from the entry we
// just read.
Record rec = entryFormat.getNewRecord(dqEntry.getData());
// Output the complete entry as a String. The contents of the record are converted to Java
Objects
// based on the record format of the entry.
System.out.println(rec.toString());
// Get the contents of the individual fields of the entry. Each field's contents are
converted to
// a Java Object.
Integer num = (Integer)rec.getField(0); // Retrieve contents by index
String s = (String)rec.getField("sender");// Retrieve contents by field name
String text = (String)rec.getField(3); // Retrieve the message text
// Output the data
System.out.println(num + " " + s + " " + text);
public MessageEntryRecord()
{
super(format);
}
After adding the new getNewRecord() method, you can use the MessageEntryRecord to interpret the data
queue entry:
// Get a record object from our record format, initializing it with the data from the entry we
// just read. Note the use of the new overridden method getNewRecord().
MessageEntryRecord rec = (MessageEntryRecord)entryFormat.getNewRecord(dqEntry.getData());
// Output the complete entry as a String. The contents of the record are converted to Java
Objects
// based on the record format of the entry.
System.out.println(rec.toString());
// Get the contents of the individual fields of the entry. Each field's contents are
converted to
// a Java Object.
int num = rec.getMessageNumber(); // Retrieve the message number as an int
String s = rec.getSender(); // Retrieve the sender
String text = rec.getMessageText(); // Retrieve the message text
// Output the data
System.out.println(num + " " + s + " " + text);
///////////////////////////////////////////////////////////////////////////////
//
// Data Queue example. This program uses the DataQueue class to put
// records on a data queue.
//
// This example uses the Record and Record format classes to put data
// on the queue. String data is converted from Unicode to ebcdic
// and numbers are converted from Java to the server format. Because data
// is converted, entries can be read by a server program,
// an Access for Windows program, or another Java program.
//
// This is the producer side of the producer/consumer example. It puts work
// items on the queue for the consumer to process.
//
// Command syntax:
// DQProducerExample system
//
///////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.net.*;
import com.ibm.as400.access.*;
// if the system name was not specified, display help text and exit.
if (parameters.length >= 1)
{
try
// Create an AS400 object for the server that has the data queue.
AS400 as400 = new AS400(system);
// Build a record format for the format of the data queue entry.
// This format matches the format in the DQConsumer class. A
// record consists of:
// - a four byte number -- the customer number
// - a four byte number -- the part number
// - a 20 character string -- the part description
// - a four byte number -- the number of parts in this order
// First create the base data types.
BinaryFieldDescription customerNumber =
new BinaryFieldDescription(new AS400Bin4(), "CUSTOMER_NUMBER");
BinaryFieldDescription partNumber =
new BinaryFieldDescription(new AS400Bin4(), "PART_NUMBER");
CharacterFieldDescription partName =
new CharacterFieldDescription(new AS400Text(20, as400), "PART_NAME");
BinaryFieldDescription quantity =
new BinaryFieldDescription(new AS400Bin4(), "QUANTITY");
// Build a record format and fill it with the base data types.
RecordFormat dataFormat = new RecordFormat();
dataFormat.addFieldDescription(customerNumber);
dataFormat.addFieldDescription(partNumber);
dataFormat.addFieldDescription(partName);
dataFormat.addFieldDescription(quantity);
// Create the data queue just in case this is the first time this
// program has run. The queue already exists exception is caught
// and ignored.
try
{
dq.create(96);
}
catch (Exception e) {};
// Set the values we received from the user into the record.
data.setField("CUSTOMER_NUMBER", new Integer(customer));
data.setField("PART_NUMBER", new Integer(part));
data.setField("QUANTITY", new Integer(quantityToOrder));
data.setField("PART_NAME", description);
System.out.println("");
System.exit(0);
}
// This is the subroutine that gets a character string from the user
// and converts it into an int.
static int getInt()
{
int i = 0;
boolean Continue = true;
while (Continue)
{
try
{
String s = inputStream.readLine();
i = (new Integer(s)).intValue();
Continue = false;
}
catch (Exception e)
{
System.out.println(e);
System.out.print("Please enter a number ==>");
}
}
return i;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Data Queue example. This program uses the Data Queue classes to read
// entries off a data queue on the server. The entries were put on the
// queue with the DQProducer example program.
//
// This is the consumer side of the producer/consumer example. It reads
// entries off the queue and process them.
//
// Command syntax:
// DQConsumerExample system
//
///////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.net.*;
import com.ibm.as400.access.*;
// if a system name was not specified, display help text and exit.
if (parameters.length >= 1)
{
try
{
// The first parameter is the system that contains the data queue.
String system = parameters[0];
// Create an AS400 object for the server that has the data queue.
AS400 as400 = new AS400(system);
// Build a record format for the format of the data queue entry.
// This format matches the format in the DQProducer class. A
// record consists of:
// - a four byte number -- the customer number
// - a four byte number -- the part number
// - a 20 character string -- the part description
// - a four byte number -- the number of parts in this order
BinaryFieldDescription partNumber =
new BinaryFieldDescription(new AS400Bin4(), "PART_NUMBER");
CharacterFieldDescription partName =
new CharacterFieldDescription(new AS400Text(20, as400), "PART_NAME"
BinaryFieldDescription quantity =
new BinaryFieldDescription(new AS400Bin4(), "QUANTITY"
// Build a record format and fill it with the base data types.
RecordFormat dataFormat = new RecordFormat();
dataFormat.addFieldDescription(customerNumber);
dataFormat.addFieldDescription(partNumber);
dataFormat.addFieldDescription(partName);
dataFormat.addFieldDescription(quantity);
// Create the data queue object that represents the data queue on
// the server.
DataQueue dq = new DataQueue(as400, "/QSYS.LIB/JAVADEMO.LIB/PRODCONS.DTAQ");
while (Continue)
{
// We just read an entry off the queue. Put the data into
// a record object so the program can access the fields of
// the data by name. The Record object will also convert
// the data from server format to Java format.
Record data = dataFormat.getNewRecord(DQData.getData());
System.exit(0);
}
}
// For the output parameter we need only specify how many bytes will
// be returned
parms[0] = new ProgramParameter(135);
parms[1] = new ProgramParameter(bin4.toBytes(new Integer(135)));
parms[2] = new ProgramParameter(char8Converter.toBytes("MBRD0100"));
parms[3] = new ProgramParameter(char20Converter.toBytes("MYFILE MYLIB "));
parms[4] = new ProgramParameter(char10COnverter.toBytes("MYMEMBER "));
parms[5] = new ProgramParameter(char1Converter.toBytes("0"));
// Get the information retrieved. Note that this is raw server data.
byte[] receiverVar = parms[0].getOutputData();
The following table lists the required parameters for the QUSRMBRD API as used in the preceding
example.
The following table lists the type of information that the example retrieves (based on format MBRD0100,
as specified in the preceding example):
///////////////////////////////////////////////////////////////////////////////
//
// Data Queue example. This program uses the KeyedDataQueue class to put
// records on a data queue.
//
// The key is a number and the data is a Unicode string. This program
// shows one way to convert on int into a byte array and how to convert
// a Java string into a byte array so it can be written to the queue.
//
// This is the producer side of the producer/consumer example. It puts work
// items on the queue for the consumer to process.
//
// Command syntax:
// DQKeyedProducer system
//
///////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.net.*;
import com.ibm.as400.access.*;
// if the system name was not specified, display help text and exit.
if (parameters.length >= 1)
{
// The first parameter is the system that contains the data queue.
try
{
// Create an AS400 object for the server that has the data queue.
// Create the data queue just in case this is the first time this
// program has run. The queue already exists exception is caught
// and ignored. The length of the key is four bytes, the length
// of an entry is 96 bytes.
try
{
dq.create(4, 96);
}
catch (Exception e) {};
System.out.println("");
System.out.println("Writing record to the server...");
System.out.println("");
dq.write(byteKey, byteData);
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" DQKeyedProducter system");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" system = server that has the data queue");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" DQKeyedProducer mySystem");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
// This is the subroutine that gets a character string from the user
// and converts it into an int.
while (Continue)
{
try
{
String s = inputStream.readLine();
i = (new Integer(s)).intValue();
Continue = false;
}
catch (Exception e)
{
System.out.println(e);
System.out.print("Please enter a number ==>");
}
}
return i;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Keyed Data Queue example. This program uses the KeyedDataQueue classes to
// read entries off a data queue on the server. The entries were put on the
// queue with the DQKeyedProducer example program.
//
// The key is a number and the data is a unicode string. This program
// shows one way to convert the byte array to a Java int and to read
// a byte array and convert it into a Java string.
//
// This is the consumer side of the producer/consumer example. It reads
// entries off the queue and process them.
//
// Command syntax:
// DQKeyedConsumer system
//
///////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.net.*;
import com.ibm.as400.access.*;
// if a system name was not specified, display help text and exit.
if (parameters.length >= 1)
{
// The first parameter is the system that contains the data queue.
String system = parameters[0];
try
{
// Create an AS400 object for the server that has the data queue.
AS400 as400 = new AS400(system);
// Create the data queue object that represents the data queue
// on the server.
try
{
boolean Continue = true;
if (DQData != null)
{
processEntry(DQData);
}
if (DQData != null)
{
processEntry(DQData);
}
if (DQData != null)
{
processEntry(DQData);
}
else
{
System.out.println("Nothing to process, will check again in 30
seconds");
Thread.sleep(30000);
}
}
}
}
}
catch (Exception e)
{
// If any of the above operations failed say the data queue
// operation failed and output the exception.
}
catch (Exception e)
{
// If any of the above operations failed say the data queue
// operation failed and output the exception.
System.exit(0);
}
// The key is a byte array. Get the key out of the data queue entry
// and convert it into a number.
byte [] keyData = DQData.getKey();
}
catch (Exception e)
{
// If any of the above operations failed say the data queue operation
// failed and output the exception.
switch (rc)
{
case ExtendedIOException.FILE_IN_USE:
System.out.println("Delete failed, file is in use ");
break;
case ExtendedIOException.PATH_NOT_FOUND:
System.out.println("Delete failed, path not found ");
default:
System.out.println("Delete failed, rc = ");
System.out.println(rc);
}
}
//////////////////////////////////////////////////////////////////////////////////
//
// IFSListFiles example. This program uses the integrated file system
// classes to list the contents of a directory on the server.
//
// Command syntax:
// IFSListFiles system directory
//
// For example,
// IFSListFiles MySystem /path1
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
// if both parameters were not specified, display help text and exit.
if (parameters.length >= 2)
{
try
{
// Create an AS400 object for the server that holds the files.
if (directoryFiles == null)
{
System.out.println("The directory does not exist");
return;
}
else if (directoryFiles.length == 0)
{
System.out.println("The directory is empty");
return;
}
System.out.print(directoryFiles[i].getName());
System.out.print(" ");
if (directoryFiles[i].isDirectory())
System.out.println("");
else
System.out.println(directoryFiles[i].length());
}
}
catch (Exception e)
{
// If any of the above operations failed say the list failed
System.out.println("List failed");
System.out.println(e);
}
}
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" IFSListFiles as400 directory");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" as400 = system that contains the files");
System.out.println(" directory = directory to be listed");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" IFSListFiles mySystem /dir1/dir2");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
}
////////////////////////////////////////////////////////////////////////////
//
// The directory filter class prints information from the file object.
//
// Another way to use the filter is to simply return true or false
// based on information in the file object. This lets the mainline
// function decide what to do with the list of files that meet the
// search criteria.
//
////////////////////////////////////////////////////////////////////////////
return true;
}
catch (Exception e)
{
return false;
}
}
}
Example: Using IFS classes to copy a file from one directory to another
This program uses the installable file system classes to copy a file from one directory to another on the
server.
Note: Read the Code example disclaimer for important legal information.
//////////////////////////////////////////////////////////////////////////////////
//
// IFSCopyFile example. This program uses the installable file system classes
// to copy a file from one directory to another on the server.
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
// if all three parameters were not specified, display help text and exit.
if (parameters.length > 2)
{
system = parameters[0];
sourceName = parameters[1];
targetName = parameters[2];
try
{
// Create an AS400 object for the server that holds the files.
// While there is data in the source file copy the data from
// the source file to the target file.
source.close();
target.close();
// Get the last changed date/time from the source file and
// set it on the target file.
}
catch (Exception e)
{
// If any of the above operations failed say the copy failed
// and output the exception.
System.out.println("Copy failed");
System.out.println(e);
}
}
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" IFSCopyFile as400 source target");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" as400 = system that contains the files");
System.out.println(" source = source file in /path/path/name format");
System.out.println(" target = target file in /path/path/name format");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" IFSCopyFile myAS400 /dir1/dir2/a.txt /dir3/b.txt");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
}
//////////////////////////////////////////////////////////////////////////////////
//
// IFSListFile example. This program uses the integrated file system classes
// to list the contents of a directory on the server.
//
// Command syntax:
// IFSList system directory
//
// For example,
// IFSList MySystem /path1
//
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
// if both parameters were not specified, display help text and exit.
if (parameters.length >= 2)
{
system = parameters[0];
directoryName = parameters[1];
try
{
// Create an AS400 object for the server that holds the files.
if (directoryNames == null)
System.out.println("The directory does not exist");
else if (directoryNames.length == 0)
System.out.println("The directory is empty");
}
catch (Exception e)
{
// If any of the above operations failed say the list failed
// and output the exception.
System.out.println("List failed");
System.out.println(e);
}
}
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" IFSList as400 directory");
System.out.println("");
System.exit(0);
}
}
////////////////////////////////////////////////////////////////////////////
//
// The directory filter class prints information from the file object.
//
// Another way to use the filter is to simply return true or false
// based on information in the file object. This lets the mainline
// function decide what to do with the list of files that meet the
// search criteria.
//
////////////////////////////////////////////////////////////////////////////
System.out.print(file.getName());
System.out.print(" ");
if (file.isDirectory())
System.out.println("<DIR>");
else
System.out.println(file.length());
return true;
}
catch (Exception e)
{
return false;
}
//////////////////////////////////////////////////////////////////////////////////
//
// JDBCPopulate example. This program uses the IBM Toolbox for Java JDBC driver to
// create and populate a table.
//
// Command syntax:
// JDBCPopulate system collectionName tableName
//
// For example,
// JDBCPopulate MySystem MyLibrary MyTable
//
//////////////////////////////////////////////////////////////////////////////////
import java.sql.*;
try {
catch (Exception e) {
System.out.println ();
System.out.println ("ERROR: " + e.getMessage());
}
finally {
// Clean up.
try {
if (connection != null)
connection.close ();
}
catch (SQLException e) {
// Ignore.
}
}
System.exit (0);
}
Example 1
This brief example shows the basic use of the AS400JDBCManagedConnectionPoolDataSource class.
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.ibm.as400.access.AS400JDBCManagedConnectionPoolDataSource;
import com.ibm.as400.access.AS400JDBCManagedDataSource;
// Set general datasource properties. Note that both connection pool datasource (CPDS) and
managed
// datasource (MDS) have these properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
Connection c = dataSource_.getConnection();
Example 2
This example shows more details about how to use the AS400JDBCManagedConnectionPoolDataSource
class.
import java.awt.TextArea;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Vector;
import java.util.Properties;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.ResultSet;
// If you turn this flag on, be sure to also turn on the following flag:
// AS400JDBCConnection.TESTING_THREAD_SAFETY.
private static final boolean TESTING_THREAD_SAFETY = false;
// Note: For consistency, all time values are stored units of milliseconds.
private int initialPoolSize_; // initial # of connections in pool
private int minPoolSize_; // max # of connections in pool
private int maxPoolSize_; // max # of connections in pool
private long maxLifetime_; // max lifetime (msecs) of connections in pool
private long maxIdleTime_; // max idle time (msecs) of available connections in pool
private long propertyCycle_; // pool maintenance frequency (msecs)
private boolean keepDaemonsAlive_ = true; // When this is false, the daemons shut down.
static
{
try {
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
}
catch(Exception e){
System.out.println("Unable to register JDBC driver.");
System.exit(0);
}
}
cptest.setup();
cptest.runTest();
}
if (TESTING_THREAD_SAFETY)
{
// Adjust values for performing thread-intensive stress testing.
if (DEBUG)
System.out.println("setup: Constructing "
+ "AS400JDBCManagedConnectionPoolDataSource (cpds0)");
AS400JDBCManagedConnectionPoolDataSource cpds0 =
new AS400JDBCManagedConnectionPoolDataSource();
// Set datasource properties. Note that both CPDS and MDS have these
// properties, and they might have different values.
cpds0.setServerName(host);
cpds0.setDatabaseName(host);//iasp can be here
cpds0.setUser(userid);
cpds0.setPassword(password);
cpds0.setSavePasswordWhenSerialized(true);
ctx.rebind("mydatasource", cpds0);
// We can now do lookups on cpds, by the name"mydatasource".
if (DEBUG)
System.out.println("setup: lookup(\"mydatasource\"" + ")");
// AS400JDBCManagedConnectionPoolDataSource cpds1 =
// (AS400JDBCManagedConnectionPoolDataSource)ctx.lookup("mydatasource");
// if (DEBUG) System.out.println("setup: cpds1.getUser() == |" + cpds1.getUser() + "|");
if (DEBUG)
System.out.println("setup: Constructing AS400JDBCManagedDataSource (mds0)");
if (DEBUG)
System.out.println("setup: lookup(\"ConnectionPoolingDataSource\"" + ")");
dataSource_ = (DataSource)ctx.lookup("ConnectionPoolingDataSource");
//dataSource_.setLogWriter(output_);
if (DEBUG)
System.out.println("setup: dataSource_.getUser() == |" +
((AS400JDBCManagedDataSource)dataSource_).getUser() + "|");
mds_ = (AS400JDBCManagedDataSource)dataSource_;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Setup error during Trace file creation.");
}
}
/**
* Gets and returns connections from and to a connection pool for a while.
**/
public void runTest()
{
boolean ok = true;
try
{
System.out.println("Started test run at " + new Date());
if (DEBUG)
System.out.println("Checking health just after datasource creation "
+ "(we expect that the pool does not exist yet) ...");
if (mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool exists prior to first getConnection().");
}
mds_.setAccess("read only");
if (!mds_.getAccess().equals("read only")) {
ok = false;
System.out.println("\nERROR: getAccess() returned unexpected value: "
+ "|" + mds_.getAccess()+"|");
}
oldBool = mds_.isKeepAlive();
oldInt = mds_.getReceiveBufferSize();
newInt = (oldInt == 256 ? 512 : 256);
mds_.setReceiveBufferSize(newInt);
if (mds_.getReceiveBufferSize() != newInt) {
ok = false;
System.out.println("\nERROR: getReceiveBufferSize() returned unexpected value: "
+ "|"+mds_.getReceiveBufferSize()+"|");
}
mds_.setReceiveBufferSize(oldInt);
System.out.println("CONNECTION 1");
Object o = dataSource_.getConnection();
System.out.println(o.getClass());
System.out.println("******LOOK ABOVE*******");
Connection c1 = dataSource_.getConnection();
if (DEBUG)
displayConnectionType(c1, true);
if (DEBUG)
System.out.println("Checking health after first getConnection() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first getConnection().");
}
if (!TESTING_THREAD_SAFETY)
{
try
{
c1.setAutoCommit(false);
if (DEBUG)
System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c1.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG)
System.out.println(rs.getString(2));
}
rs.close();
s.close();
}
catch (Exception e) {
e.printStackTrace();
if (DEBUG)
System.out.println("Checking health after fatal connection error ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after fatal connection "
+ "error.");
}
}
}
System.out.println("CONNECTION 2");
Connection c2 = dataSource_.getConnection(userid, password);
if (DEBUG)
displayConnectionType(c2, false);
System.out.println("CONNECTION 3");
Connection c3 = dataSource_.getConnection();
if (DEBUG)
displayConnectionType(c3, true);
c1.close();
if (DEBUG)
System.out.println("Checking health after first close() ...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after first close().");
}
System.out.println("CONNECTION 4");
// Run the test daemons for a while; check pool health periodically.
if (DEBUG)
System.out.println("Checking health after connectionGetter daemons have run...");
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after test daemons stopped.");
}
if (!TESTING_THREAD_SAFETY)
{
System.out.println("CONNECTION 5");
Connection c = dataSource_.getConnection();
if (DEBUG) displayConnectionType(c, true);
c.setAutoCommit(false);
if (DEBUG) System.out.println("SELECT * FROM QIWS.QCUSTCDT");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM QIWS.QCUSTCDT");
while(rs.next()){
if (DEBUG) System.out.println(rs.getString(2));
}
rs.close();
s.close();
c.close();
}
if (DEBUG)
System.out.println("Checking health after pool closed ...");
Trace.setTraceJDBCOn(true); // make sure the final stats get printed out
Trace.setTraceOn(true);
if (!mds_.checkPoolHealth(true)) {
ok = false;
System.out.println("\nERROR: Pool is not healthy after pool closed.");
}
System.out.println();
if(ok==true)
System.out.println("test ran ok");
else
System.out.println("test failed");
}
void startThreads()
{
// Create a bunch of threads that call getConnection().
Thread[] threads = new Thread[numDaemons_];
for (int i=0; i<numDaemons_; i++)
{
ConnectionGetter getter;
// Flip a coin to see if this daemon will specify the default uid, or unique uid.
if (random_.nextBoolean())
{
getter = new ConnectionGetter(userid,password);
if (TESTING_THREAD_SAFETY) { // we can use fictional userid
getter = new ConnectionGetter("Thread"+i, "Pwd"+i);
}
else { // must use a real userid
getter = new ConnectionGetter(userid,password);
}
}
else
getter = new ConnectionGetter(null, null);
void stopThreads()
{
// Tell the threads to stop.
keepDaemonsAlive_ = false;
synchronized (daemonSleepLock_) {
daemonSleepLock_.notifyAll();
}
// ConnectionGetter --------------------------------------------------------------------
/**
Helper class. This daemon wakes up at random intervals and either
gets another connection from the connection pool or returns a
previously-gotten connection to the pool.
**/
private final class ConnectionGetter implements Runnable
{
private String uid_;
private String pwd_;
private boolean useDefaultUid_;
private long maxSleepTime_;
private String threadName_;
private boolean firstConnection_ = true;
ArrayList connections_ = new ArrayList();
// list of connections that this getter currently 'owns'.
try
{
while (keepDaemonsAlive_)
{
try
{
// Pick a random sleep-time, between min and max values.
long sleepTime = Math.max((long)(maxSleepTime_ * random_.nextFloat()),
daemonMinSleepTime_);
// Note: Must never call wait(0), because that waits forever.
synchronized (daemonSleepLock_) {
try {
daemonSleepLock_.wait(sleepTime);
System.out.print(".");
}
catch (InterruptedException ie) {}
}
if (!keepDaemonsAlive_) break;
if (conn == null) {
System.out.println("ConnectionGetter("+threadName_+") ERROR: "
+ "getConnection() returned null");
}
else
{
// Occasionally "forget" that we own a connection, and neglect to
// close it.
// Orphaned connections should eventually exceed their maximum
// lifetime and get "reaped" by the connection manager.
float val = random_.nextFloat();
if (firstConnection_ || val < 0.1) {
// 'orphan' a few gotten connections
firstConnection_ = false;
}
else {
connections_.add(conn);
}
if (DEBUG) displayConnectionType(conn, useDefaultUid_);
if (conn instanceof com.ibm.as400.access.AS400JDBCConnectionHandle)
{ // We got a pooled connection. Try speeding up our cycle time.
if (maxSleepTime_ > 100)
maxSleepTime_--;
else
maxSleepTime_ = 100;
}
else
{ // We didn't get a pooled connection. That means that the pool
// must be at capacity. Slow down our cycle time a bit.
maxSleepTime_ = maxSleepTime_ + 50;
}
}
}
else { // Close a connection that we currently own.
if (connections_.size() != 0) {
conn = (Connection)connections_.remove(0);
conn.close();
}
}
//////////////////////////////////////////////////////////////////////////////////
//
// JDBCQuery example. This program uses the IBM Toolbox for Java JDBC driver to
// query a table and output its contents.
//
// Command syntax:
// JDBCQuery system collectionName tableName
//
// For example,
// JDBCQuery MySystem qiws qcustcdt
//
//////////////////////////////////////////////////////////////////////////////////
import java.sql.*;
return formattedString;
}
try {
catch (Exception e) {
System.out.println ();
System.out.println ("ERROR: " + e.getMessage());
}
// Clean up.
try {
if (connection != null)
connection.close ();
}
catch (SQLException e) {
// Ignore.
}
}
System.exit (0);
}
///////////////////////////////////////////////////////////////////////////
//
// This program is an example of the Job support in the IBM Toolbox
// for Java. It lists job identification information for a specific
// user on the system.
//
// Command syntax:
// listJobs2 system userID password
//
/////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.lang.*;
import java.util.*;
import com.ibm.as400.access.*;
System.exit(0);
}
if (parameters.length > 1)
userID = parameters[1].toUpperCase();
System.out.println(" ");
try
{
if (userID != null)
as400.setUserId(userID);
if (password != null)
as400.setPassword(password);
if (userID != null)
{
if (j.getUser().trim().equalsIgnoreCase(userID))
{
System.out.println(j.getName().trim() + "." +
j.getUser().trim() + "." +
j.getNumber());
}
}
else
System.out.println(j.getName().trim() + "." +
j.getUser().trim() + "." +
j.getNumber());
}
}
catch (Exception e)
{
System.out.println("Unexpected error");
e.printStackTrace();
}
}
///////////////////////////////////////////////////////////////////////////
//
// This program is an example of the "job" classes in the
// IBM Toolbox for Java. It gets a list of jobs on the server
// and outputs the job's status followed by job identifier.
//
//
// Command syntax:
// listJobs system userID password
//
// (UserID and password are optional)
//
/////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
System.exit(0);
}
// Set up AS400 object parms. The first is the system name and must
// be specified by the user. The second and third are optional. They
// are the userid and password. Convert the userid and password
// to uppercase before setting them on the AS400 object.
String userID = null;
String password = null;
if (parameters.length > 1)
userID = parameters[1].toUpperCase();
if (parameters.length >= 2)
password = parameters[2].toUpperCase();
System.out.println(" ");
try
{
// Create an AS400 object using the system name specified by the user.
if (password != null)
as400.setPassword(password);
// Create a job list object. Input parm is the AS400 we want job
// information from.
JobList jobList = new JobList(as400);
// For each job in the list print information about the job.
while (listOfJobs.hasMoreElements())
{
printJobInfo((Job) listOfJobs.nextElement(), as400);
}
}
catch (Exception e)
{
System.out.println("Unexpected error");
System.out.println(e);
}
}
// The second parm is the size of our output data buffer (1K).
Integer iStatusLength = new Integer( 1024 );
byte[] statusLength = bin4Converter.toBytes( iStatusLength );
parmlist[1] = new ProgramParameter( statusLength );
// The fourth parm is the job name is format "name user number".
// Name must be 10 characters, user must be 10 characters and
// number must be 6 characters. We will use a text converter
// to do the conversion and padding.
byte[] jobName = text26Converter.toBytes(job.getName());
int i = text10Converter.toBytes(job.getUser(),
jobName,
10);
i = text6Converter.toBytes(job.getNumber(),
jobName,
System.out.println(job.getName().trim() + "." +
job.getUser().trim() + "." +
job.getNumber() + " ");
}
}
catch (Exception e)
{
System.out.println(e);
}
///////////////////////////////////////////////////////////////////////////
//
// This program is an example of the job log fuction of the
// IBM Toolbox for Java. It will display the messages in the job
// log for a job that belongs to the current user.
//
// Command syntax:
// jobLogExample system userID password
//
// (Password is optional)
import java.lang.*;
import java.util.*;
import com.ibm.as400.access.*;
try
{
// Create an AS400 object. The system name was passed
// as the first command line argument. If a userid
// and password were passed on the command line,
// set those as well.
AS400 system = new AS400 (args[0]);
if (args.length > 1)
{
userID = args[1];
system.setUserId(userID);
}
if (args.length > 2)
system.setPassword(args[2]);
// Look through the list to find a job for the current user.
while (list.hasMoreElements() && Continue)
{
Job j = (Job) list.nextElement();
if (j.getUser().trim().equalsIgnoreCase(userID))
{
// A job matching the current user was found. Create
// a job log object for this job.
JobLog jlog = new JobLog(system, j.getName(), j.getUser(), j.getNumber());
while (messageList.hasMoreElements())
{
AS400Message message = (AS400Message) messageList.nextElement();
System.out.println(message.getText());
}
System.exit(0);
/////////////////////////////////////////////////////////////////////////
//
// Example that shows creating a spooled file on a server from an input stream.
//
/////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
class NPExampleCreateSplf
{
// method to create the spooled file on the specified server, in the specified
// output queue from the given input stream.
public SpooledFile createSpooledFile(AS400 system, OutputQueue outputQueue, InputStream in)
{
SpooledFile spooledFile = null;
try
{
byte[] buf = new byte[2048];
int bytesRead;
SpooledFileOutputStream out;
PrintParameterList parms = new PrintParameterList();
// read from the inputstream in until end of stream, passing all data
// to the spooled file output stream.
do
{
bytesRead = in.read(buf);
if (bytesRead != -1)
{
out.write(buf, 0, bytesRead);
}
} while (bytesRead != -1);
}
catch (Exception e)
{
//...handle exception...
}
return spooledFile;
}
/////////////////////////////////////////////////////////////////////////
//
// This source is an example of IBM Toolbox for Java "SCS3812Writer".
//
/////////////////////////////////////////////////////////////////////////
import com.ibm.as400.access.*;
class NPExampleCreateSCSSplf
{
private static final String DEFAULT_SYSTEM = new String("RCHAS1");
private static final String DEFAULT_OUTQ = new String("/QSYS.LIB/QUSRSYS.LIB/PRT01.OUTQ");
/////////////////////////////////////////////////////////////////////////
//
// Example that reads an existing server spooled file.
//
// This source is an example of IBM Toolbox for Java "PrintObjectInputStream".
//
/////////////////////////////////////////////////////////////////////////
try{
byte[] buf = new byte[2048];
int bytesRead;
AS400 sys = new AS400();
SpooledFile splf = new SpooledFile( sys, // AS400
"MICR", // splf name
17, // splf number
"QPRTJOB", // job name
"QUSER", // job user
"020791" ); // job number
// open the spooled file for reading and get the input stream to
// read from it.
InputStream in = splf.getInputStream(null);
do
{
// read up to buf.length bytes of raw spool data into
// our buffer. The actual bytes read will be returned.
// The data will be a binary printer data stream that is the
// contents of the spooled file.
bytesRead = in.read( buf );
if( bytesRead != -1 )
{
in.close();
}
catch( Exception e )
{
// exception
}
Example of PrintObjectTransformedInputStream
Note: Read the Code example disclaimer for important legal information.
The following example shows how to create a PrintObjectTransformedInputStream object for reading data
formatted as TIFF. A TIFF (G4 compression) workstation customization object is used to specify the data
transform.
/////////////////////////////////////////////////////////////////////////
//
// Example that shows listing all spooled files on a server asynchronously using
// the PrintObjectListListener interface to get feedback as the list is being built.
// Listing asynchronously allows the caller to start processing the list objects
// before the entire list is built for a faster perceived response time
// for the user.
//
/////////////////////////////////////////////////////////////////////////
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.SpooledFileList;
import com.ibm.as400.access.SpooledFile;
import com.ibm.as400.access.ExtendedIllegalStateException;
import com.ibm.as400.access.PrintObjectListListener;
import com.ibm.as400.access.PrintObjectListEvent;
try
{
String strSpooledFileName;
boolean fCompleted = false;
int listed = 0, size;
fCompleted = splfList.isCompleted();
size = splfList.size();
if (fListClosed)
{
System.out.println(" The list was closed before it completed!");
break;
}
} while (!fCompleted);
catch( ExtendedIllegalStateException e )
{
System.out.println(" The list was closed before it completed!");
}
catch( Exception e )
{
// ...handle any other exceptions...
e.printStackTrace();
}
/////////////////////////////////////////////////////////////////////////
//
// This example lists all spooled files on a system asynchronously without
// using the PrintObjectListListener interface. After opening the list the caller
// can do some additional work before waiting for the list to complete.
//
import java.util.Enumeration;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.SpooledFileList;
import com.ibm.as400.access.SpooledFile;
System.out.println(
"Now receiving all spooled files Asynchronously without using a listener");
catch( Exception e )
{
// ...handle any exceptions...
e.printStackTrace();
}
}
/////////////////////////////////////////////////////////////////////////
//
// Example that shows listing all spooled files on a server synchronously.
// Listing synchronously does not return to the caller until the complete list
// is built. The user perceives a slower response time then listing asynchronously.
//
/////////////////////////////////////////////////////////////////////////
//
// This source is an example of IBM Toolbox for Java "PrintObjectList".
//
/////////////////////////////////////////////////////////////////////////
import java.util.Enumeration;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.SpooledFileList;
import com.ibm.as400.access.SpooledFile;
while( enum.hasMoreElements() )
{
SpooledFile splf = (SpooledFile)enum.nextElement();
if ( splf != null )
{
// output this spooled file's name
strSpooledFileName = splf.getStringAttribute(SpooledFile.ATTR_SPOOLFILE);
System.out.println(" spooled file = " + strSpooledFileName);
}
/////////////////////////////////////////////////////////////////////////
//
// Program call example. This program calls the QWCRSSTS server program
// to retrieve the status of the system.
//
// Command syntax:
// PCSystemStatusExample system
//
// This source is an example of IBM Toolbox for Java "ProgramCall".
//
/////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.Thread.*;
import com.ibm.as400.access.*;
if (parameters.length >= 1)
{
try
{
// Create an AS400 object for the server that contains the
// program. Assume the first parameter is the system name.
// Set the program to call and the parameter list to the program
// call object.
getSystemStatus.setProgram(programName.getPath(), parmlist );
// Run the program then sleep. We run the program twice because
// the first set of results are inflated. If we discard the first
// set of results and run the command again five seconds later the
// number will be more accurate.
getSystemStatus.run();
Thread.sleep(5000);
if (getSystemStatus.run()!=true)
{
else
{
as400.disconnectService(AS400.COMMAND);
}
catch (Exception e)
{
// If any of the above operations failed say the program failed
// and output the exception.
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" PCSystemStatusExample myServer");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" myServer = get status of this server ");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" PCSystemStatusExample mySystem");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
}
//////////////////////////////////////////////////////////////////////////////////
//
// Record level access example. This program will prompt the user
// for the name of the server and the file to display. The file must exist
// and contain records. Each record in the file will be displayed
// to System.out.
//
// Calling syntax: java RLSequentialAccessExample
//
// This source is an example of IBM Toolbox for Java "RecordLevelAccess"
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
// Declare variables to hold the system name, library, file and member names
String systemName = "";
String library = "";
String file = "";
String member = "";
// Get the system name and and file to display from the user
System.out.println();
try
{
System.out.print("System name: ");
systemName = inputStream.readLine();
System.out.println();
}
catch (Exception e)
{
System.out.println("Error obtaining user input.");
e.printStackTrace();
System.exit(0);
}
// Create AS400 object and connect for the record level access service.
AS400 system = new AS400(systemName);
try
{
system.connectService(AS400.RECORDACCESS);
}
catch(Exception e)
{
System.out.println("Unable to connect for record level access.");
System.out.println("Check the readme file for special instructions regarding record
level access");
e.printStackTrace();
System.exit(0);
}
// Create a QSYSObjectPathName object to obtain the integrated file system path name form
// of the file to be displayed.
QSYSObjectPathName filePathName = new QSYSObjectPathName(library, file, member, "MBR");
// Open the file for reading. Read 100 records at a time if possible.
theFile.open(AS400File.READ_ONLY, 100, AS400File.COMMIT_LOCK_LEVEL_NONE);
try
{
// Close the file
theFile.close();
// Make sure that the application ends; see readme for details
System.exit(0);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Record-Level Access example. This program uses the record-level
// access classes to read records from a file on the server.
//
// Command syntax:
// java RLReadFile system
//
// This program reads the records from CA/400's sample database file
// (QCUSTCDT in library QIWS). If you change this example to update
// records, make a copy of QCUSTCDT and update the copy.
//
// This source is an example of IBM Toolbox for Java "Record-level access".
//
///////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import java.math.*;
import com.ibm.as400.access.*;
if (parameters.length >= 1)
{
try
{
system = parameters[0];
// Create an AS400 object for the server that has the file.
ZonedDecimalFieldDescription customerNumber =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(6,0),
"CUSNUM");
CharacterFieldDescription lastName =
new CharacterFieldDescription(new AS400Text(8, as400), "LSTNAM");
CharacterFieldDescription initials =
new CharacterFieldDescription(new AS400Text(3, as400), "INIT");
CharacterFieldDescription city =
new CharacterFieldDescription(new AS400Text(6, as400), "CITY");
CharacterFieldDescription state =
new CharacterFieldDescription(new AS400Text(2, as400), "STATE");
ZonedDecimalFieldDescription zipCode =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(5,0),
"ZIPCOD");
ZonedDecimalFieldDescription creditLimit =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(4,0),
"CDTLMT");
ZonedDecimalFieldDescription chargeCode =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(1,0),
"CHGCOD");
ZonedDecimalFieldDescription balanceDue =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(6,2),
"BALDUE");
ZonedDecimalFieldDescription creditDue =
new ZonedDecimalFieldDescription(new AS400ZonedDecimal(6,2),
"CDTDUE");
qcustcdt.addFieldDescription(customerNumber);
qcustcdt.addFieldDescription(lastName);
qcustcdt.addFieldDescription(initials);
qcustcdt.addFieldDescription(street);
qcustcdt.addFieldDescription(city);
qcustcdt.addFieldDescription(state);
qcustcdt.addFieldDescription(zipCode);
qcustcdt.addFieldDescription(creditLimit);
qcustcdt.addFieldDescription(chargeCode);
qcustcdt.addFieldDescription(balanceDue);
qcustcdt.addFieldDescription(creditDue);
file.setRecordFormat(qcustcdt);
file.open(SequentialFile.READ_ONLY,
10,
SequentialFile.COMMIT_LOCK_LEVEL_NONE);
// Loop while there are records in the file (while we have not
// reached end-of-file).
data = file.readNext();
}
// When there are no more records to read, disconnect from the server.
as400.disconnectAllServices();
}
catch (Exception e)
{
else
{
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" RLReadFile as400");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" as400 = system that contains the file");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" RLReadFile mySystem");
System.out.println("");
System.out.println("");
System.out.println("Note, this program reads data base file QIWS/QCUSTCDT. ");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Record-Level Access example. This program uses the record-level
// access classes to read records by key from a file on the server.
import java.io.*;
import java.util.*;
import java.math.*;
import com.ibm.as400.access.*;
// Declare variables to hold the system name, library, file and member names
String systemName = "";
String library = "";
// Create AS400 object and connect for the record level access service.
AS400 system = new AS400(systemName);
try
{
system.connectService(AS400.RECORDACCESS);
}
catch(Exception e)
{
System.out.println("Unable to connect for record level access.");
System.out.println("Check the readme file for special instructions regarding record
level access");
e.printStackTrace();
System.exit(0);
}
// There is only one record format for the file, so take the first (and only) element
// of the RecordFormat array returned as the RecordFormat for the file.
System.out.println("Retrieving record format of QIWS/QCUSTCDT...");
qcustcdtFormat = recordDescription.retrieveRecordFormat()[0];
// Indicate that CUSNUM is a key field
qcustcdtFormat.addKeyFieldDescription("CUSNUM");
}
catch(Exception e)
try
{
System.out.println("Creating file " + library + "/QCUSTCDTKY...");
// Create the file using the qcustcdtFormat object
file.create(qcustcdtFormat, "Keyed QCUSTCDT file");
// Create the key for reading the records. The key for a KeyedFile
// is specified with an Object[]
Object[] key = new Object[1];
/////////////////////////////////////////////////////////////////////////
//
// User list example. This program lists all of the users in a given
// group.
//
// Command syntax:
// UserListExample system group
//
// This source is an example of IBM Toolbox for Java "UserList".
//
/////////////////////////////////////////////////////////////////////////
import com.ibm.as400.access.*;
import com.ibm.as400.vaccess.*;
import java.util.Enumeration;
try
{
// Create an AS400 object. The system name was passed
// as the first command line argument.
AS400 system = new AS400 (args[0]);
}
catch (Exception e)
{
System.out.println ("Error: " + e.getMessage ());
}
System.exit (0);
}
Examples: JavaBeans
This section lists the code examples that are provided throughout the IBM Toolbox for Java bean
information.
The following disclaimer applies to all of the IBM Toolbox for Java examples:
Code example disclaimer
IBM grants you a nonexclusive copyright license to use all programming code examples from
which you can generate similar function tailored to your own specific needs.
All sample code is provided by IBM for illustrative purposes only. These examples have
not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply
reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any
kind. The implied warranties of non-infringement, merchantability and fitness for a particular
purpose are expressly disclaimed.
//////////////////////////////////////////////////////////////////////////////////
//
// Beans example. This program uses the JavaBeans support in the
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.CommandCall;
import com.ibm.as400.access.ConnectionListener;
import com.ibm.as400.access.ConnectionEvent;
import com.ibm.as400.access.ActionCompletedListener;
import com.ibm.as400.access.ActionCompletedEvent;
class BeanExample
{
AS400 as400_ = new AS400();
CommandCall cmd_ = new CommandCall( as400_ );
BeanExample()
{
// Whenever the system is connected or disconnected print a
// comment. Do this by adding a listener to the AS400 object.
// When a system is connected or disconnected, the AS400 object
// will call this code.
as400_.addConnectionListener
(new ConnectionListener()
{
public void connected(ConnectionEvent event)
{
System.out.println( "System connected." );
}
public void disconnected(ConnectionEvent event)
{
System.out.println( "System disconnected." );
}
}
);
cmd_.addActionCompletedListener(
new ActionCompletedListener()
{
public void actionCompleted(ActionCompletedEvent event)
{
System.out.println( "Command completed." );
}
}
);
}
void runCommand()
{
try
{
// Run a command. The listeners will print comments when the
// system is connected and when the command has run to
// completion.
cmd_.run( "TESTCMD PARMS" );
}
catch (Exception ex)
{
System.out.println( ex );
}
}
be.runCommand();
System.exit(0);
}
}
• Edit the bean properties. (To edit, select the bean and then right-click to display a window, which has
Properties as an option.)
– Change the label of the Button to Run command, as shown in Figure 2.
Figure 2: Changing the label of the button to Run command
///////////////////////////////////////////////////////////////////////////////
//
// This source is an example of using the HTML
// package classes, which allow you to easily build HTML Forms.
//
///////////////////////////////////////////////////////////////////////////////
package customer;
import java.io.*;
import java.awt.Color;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.as400.access.*;
import com.ibm.as400.util.html.*;
try
{
super.init(config);
}
catch(Exception e)
{
e.printStackTrace();
}
/**
* Process the GET request.
* @param req The request.
* @param res The response.
**/
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
try
{
//Create the registration.txt file
FileWriter f = new FileWriter(regPath, true);
BufferedWriter output = new BufferedWriter(f);
}
else // read the next line
line = in.readLine();
//------------------------------------------------------------
//Getting "USE" checkbox from form
data = req.getParameter("use");
if(data != null)
{
output.write("Currently Using Toolbox: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "More Information" checkbox from form
data = req.getParameter("contact");
if (data != null)
{
output.write("Requested More Information: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "AS400 Version" from form
data = req.getParameter("version");
if (data != null)
{
if (data.equals("multiple versions"))
{
data = req.getParameter("MultiList");
output.write("Multiple Versions: " + data);
}
else
output.write("AS400 Version: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "Current Projects" from form
data = req.getParameter("interest");
if (data != null)
{
output.write("Using Java or Interested In: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "Platforms" from form
data = req.getParameter("platform");
if (data != null)
{
output.write("Platforms: " + data);
output.newLine();
if (data.indexOf("Other") >= 0)
{
output.write("Other Platforms: " + req.getParameter("OtherPlatforms"));
output.newLine();
}
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "Number of IBM i servers" from form
data = req.getParameter("list1");
if (data != null)
{
output.write("Number of IBM i servers: " + data);
//------------------------------------------------------------
//Getting "Comments" from form
data = req.getParameter("comments");
if (data != null && data.length() > 0)
{
output.write("Comments: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting "Attachment"
data = req.getParameter("myAttachment");
if (data != null && data.length() > 0)
{
output.write("Attachment File: " + data);
output.newLine();
}
//------------------------------------------------------------
//------------------------------------------------------------
//Getting Hidden "Copyright" infomation
data = req.getParameter("copyright");
if (data != null)
{
output.write(data);
output.newLine();
}
//------------------------------------------------------------
output.flush();
output.close();
}
catch (Exception e)
{
// Show error in browser
out.println("<HTML>");
out.println("<TITLE>ERROR!</TITLE>");
out.println("<META HTTP-EQUIV=\"pragma\" content=\"no-cache\"> ");
out.println("<BODY BGCOLOR=\"blanchedalmond\">");
out.println("<BR><B>Error Message:</B><P>");
out.println(e + "<P>");
e.printStackTrace();
}
}
else
{
// Output a message to the customer saying customer name &
// e-mail not entered. Please try again
out.println ("<HTML> " +
// Build the beginning of the HTML Page and add it to the String Buffer
page.append("<HTML>\n");
page.append("<TITLE> Welcome!!</TITLE>\n");
page.append("<HEAD><SCRIPT LANGUAGE=\"JavaScript\">
function test(){alert(\"This is a sample script executed with a
ButtonFormInput.\")}</SCRIPT></HEAD>");
page.append("<META HTTP-EQUIV=\"pragma\" content=\"no-cache\">\n");
page.append("<BODY BGCOLOR=\"blanchedalmond\" TEXT=\"black\"><BR>\n");
try
{
//--------------------------------------------------------------------
// Create page title using HTML Text
txt = new HTMLText("Product Registration");
txt.setSize(5);
txt.setBold(true);
txt.setColor(new Color(199, 21, 133));
txt.setAlignment(HTMLConstants.CENTER);
//--------------------------------------------------------------------
// Create a Line Layout
LineLayoutFormPanel line = new LineLayoutFormPanel();
txt = new HTMLText("Enter your name and e-mail address:");
txt.setSize(4);
line.addElement(txt);
//--------------------------------------------------------------------
// Set the HTML Form METHOD
form.setMethod(HTMLForm.METHOD_POST);
//--------------------------------------------------------------------
// Create a ImageFormInput
ImageFormInput img =
new ImageFormInput("Submit Form", "..\\images\\myPiimages/c.gif");
img.setAlignment(HTMLConstants.RIGHT);
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Create a LineLayoutFormPanel object for the name & e-mail address
LineLayoutFormPanel line2 = new LineLayoutFormPanel();
//--------------------------------------------------------------------
// Create Questions line layout
LineLayoutFormPanel line3 = new LineLayoutFormPanel();
//--------------------------------------------------------------------
// Create Version Radio Group
RadioFormInputGroup group = new RadioFormInputGroup("version");
//--------------------------------------------------------------------
// Create Grid Layout for interests
GridLayoutFormPanel grid2 = new GridLayoutFormPanel(1);
txt = new HTMLText("Current Projects or Area of Interest: " +
"(check all that apply)");
txt.setSize(4);
//--------------------------------------------------------------------
// Create Line Layout for platforms
LineLayoutFormPanel line4 = new LineLayoutFormPanel();
txt = new HTMLText("Client Platforms Used: " +
"(check all that apply)");
txt.setSize(4);
line4.addElement(other);
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Create a Line Layout for number of servers
LineLayoutFormPanel grid3 = new LineLayoutFormPanel();
//--------------------------------------------------------------------
// Create a Grid Layout for Product Comments
GridLayoutFormPanel grid4 = new GridLayoutFormPanel(1);
txt = new HTMLText("Product Comments:");
txt.setSize(4);
//--------------------------------------------------------------------
// Create a Grid Layout
GridLayoutFormPanel grid5 = new GridLayoutFormPanel(2);
txt = new HTMLText("Would you like to sign on to a server?");
txt.setSize(4);
// Add the Text inputs, password inputs, and Labels to the grid
grid5.addElement(sysLabel);
grid5.addElement(sys);
grid5.addElement(uidLabel);
grid5.addElement(uid);
grid5.addElement(pwdLabel);
grid5.addElement(pwd);
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Add the various panels created to the HTML Form
// in the order you wish them to appear
form.addElement(line2);
form.addElement(line3);
form.addElement(grid1);
form.addElement(grid2);
form.addElement(line4);
form.addElement(grid3);
form.addElement(grid4);
form.addElement(txt);
form.addElement(new LineLayoutFormPanel());
form.addElement(grid5);
form.addElement(new LineLayoutFormPanel());
form.addElement(
new HTMLText("Submit an attachment Here: <br />"));
// Add a File Input to the form
form.addElement(new FileFormInput("myAttachment"));
form.addElement(new ButtonFormInput("button",
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// This source is an example of using the IBM Toolbox for Java HTML
// package classes, which allow you to easily build HTML and File Trees.
//
///////////////////////////////////////////////////////////////////////////////
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Vector;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.Trace;
import com.ibm.as400.access.IFSJavaFile;
import com.ibm.as400.util.html.HTMLMeta;
import com.ibm.as400.util.html.HTMLTree;
import com.ibm.as400.util.html.HTMLTreeElement;
import com.ibm.as400.util.html.URLParser;
import com.ibm.as400.util.html.DirFilter;
import com.ibm.as400.util.html.FileTreeElement;
import com.ibm.as400.util.servlet.ServletHyperlink;
/**
* An example of using the HTMLTree and FileTreeElement classes in a servlet.
**/
public class TreeNav extends HttpServlet
{
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
HTMLTreeElement.setExpandedGif("/images/expanded.gif");
HTMLTreeElement.setCollapsedGif("/images/collapsed.gif");
HTMLTreeElement.setDocGif("/images/bullet.gif");
}
/**
* Process the GET request.
* @param req The request.
resp.setContentType("text/html");
out.println("</body>\n");
out.println("</html>\n");
out.close();
// Set the session tree value, so when entering this servlet for
// the second time, the FileTree object will be reused.
session.putValue("filetree", fileTree);
}
/**
* Process the POST request.
* @param req The request.
* @param res The response.
**/
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
}
/**
* This method will create the initial HTMLTree.
**/
private HTMLTree createTree(HttpServletRequest req, HttpServletResponse resp, String uri)
{
// Create an HTMLTree object.
HTMLTree tree = new HTMLTree(req);
try
{
// Create a URLParser object.
URLParser urlParser = new URLParser(uri);
return tree;
}
Example: Creating a traversable integrated file system tree (File one of three)
This IBM Toolbox for Java example code, in conjunction with the code in the other two example files,
displays an HTMLTree and FileListElement in a servlet.
The three files in the example are:
• FileTreeExample.java - this file, which generates the HTML frames and starts the servlet
• TreeNav.java - builds and manages the tree
• TreeList.java - displays the contents of selections made in the TreeNav.java class
Note: Read the Code example disclaimer for important legal information.
///////////////////////////////////////////////////////////////////////////////
//
// This source is an example of using the HTML package
// classes, which allow you to easily build HTML and File Trees.
//
///////////////////////////////////////////////////////////////////////////////
import java.io.PrintWriter;
import java.io.IOException;
import com.ibm.as400.util.html.HTMLMeta;
//
// An example of using frames to display an HTMLTree and FileListElement
// in a servlet.
//
/**
* Process the GET request.
* @param req The request.
* @param res The response.
**/
/**
* Process the POST request.
* @param req The request.
* @param res The response.
**/
Example: Creating a traversable integrated file system tree (File two of three)
This example code, in conjunction with the code in the other two example files, displays an HTMLTree and
FileListElement in a servlet.
The three files in the example are:
• FileTreeExample.java - generates the HTML frames and starts the servlet
//////////////////////////////////////////////////////////////////////////////////
//
// This source is an example of using the IBM Toolbox for Java HTML
// package classes, which allow you to easily build HTML and File Trees.
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.IFSJavaFile;
import com.ibm.as400.util.html.HTMLMeta;
import com.ibm.as400.util.html.HTMLTree;
import com.ibm.as400.util.html.HTMLTreeElement;
import com.ibm.as400.util.html.URLParser;
import com.ibm.as400.util.html.DirFilter;
import com.ibm.as400.util.html.FileTreeElement;
import com.ibm.as400.util.servlet.ServletHyperlink;
//
// An example of using the HTMLTree and FileTreeElement classes
// in a servlet.
//
// IBM Toolbox for Java uses a set of default icons to represents expanded,
// collapsed, and documents within the HTMLTree. To enhance those icons,
// IBM Toolbox for Java ships three gifs (expanded.gif, collapsed.gif, bullet.gif)
// in the jt400Servlet.jar file. Browsers do not have the ability to find
// gifs in a JAR or zip file, so you need to extract those images from the
// JAR file and place them in the appropriate webserver directory (by default
// it is the /html directory). Then change the following lines of code to
// specify the correct location in the set methods. The location can be
// absolute or relative.
HTMLTreeElement.setExpandedGif("http://myServer/expanded.gif");
HTMLTreeElement.setCollapsedGif("http://myServer/collapsed.gif");
HTMLTreeElement.setDocGif("http://myServer/bullet.gif");
}
/**
* Process the GET request.
* @param req The request.
* @param res The response.
**/
resp.setContentType("text/html");
out.println("</body>\n");
out.println("</html>\n");
out.close();
// Set the session tree value, so when entering this servlet for
// the second time, the FileTree object will be reused.
session.putValue("filetree", fileTree);
}
/**
* Process the POST request.
* @param req The request.
* @param res The response.
**/
/**
* This method will create the initial HTMLTree.
**/
try
{
// Create a URLParser object.
URLParser urlParser = new URLParser(uri);
// Create a Filter.
DirFilter filter = new DirFilter();
sys_.disconnectAllServices();
}
catch (Exception e)
{
e.printStackTrace();
}
return tree;
}
////////////////////////////////////////////////////////////////////////////////
//
// This source is an example of using the IBM Toolbox for Java HTML
// package classes, which allow you to easily build HTML and File Lists.
//
////////////////////////////////////////////////////////////////////////////////
import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.Trace;
import com.ibm.as400.access.IFSJavaFile;
import com.ibm.as400.util.html.HTMLMeta;
import com.ibm.as400.util.html.HTMLHeading;
import com.ibm.as400.util.html.HTMLConstants;
import com.ibm.as400.util.html.FileListElement;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* An example of using the FileListElement class in a servlet.
**/
public class TreeList extends HttpServlet
{
/**
* Process the GET request.
* @param req The request.
* @param res The response.
**/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
try
{
// If the path parameter is not null, then the user has selected an
// element from the FileTreeElement list in the navigation frame.
if (req.getPathInfo() != null)
{
// Create a FileListElement passing in an AS400 system object and
// the Http servlet request. The request will contain the necessary
// path information to list out the contents of the FileTreeElement
// (directory) selected.
FileListElement fileList = new FileListElement(sys_, req);
out.println(heading.getTag());
}
out.println("</body>\n");
out.println("</html>\n");
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/**
* Process the POST request.
* @param req The request.
* @param res The response.
**/
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
table.addColumnHeader(account_header);
table.addColumnHeader(name_header);
table.addColumnHeader(balance_header);
// Add rows to the table. Each customer record represents a row in the table.
int numCols = 3;
for (int rowIndex=0; rowIndex< numCustomers; rowIndex++)
{
HTMLTableRow row = new HTMLTableRow();
row.setHorizontalAlignment(HTMLTableRow.CENTER);
row.addColumn(new HTMLTableCell(account));
row.addColumn(new HTMLTableCell(name));
row.addColumn(new HTMLTableCell(balance));
The Java code example above generates the following HTML code:
The following table shows how the HTML code above displays in a Web browser.
<!-- PCML source for calling "Retrieve user Information" (QSYRUSRI) API -->
<!-- Program QSYRUSRI and its parameter list for retrieving USRI0100 format -->
<program name="qsyrusri" path="/QSYS.lib/QSYRUSRI.pgm">
<data name="receiver" type="struct" struct="usri0100" usage="output"/>
<data name="receiverLength" type="int" length="4" usage="input" />
<data name="format" type="char" length="8" usage="input"
init="USRI0100"/>
<data name="profileName" type="char" length="10" usage="input"
init="*CURRENT"/>
<data name="errorCode" type="int" length="4" usage="input"
init="0"/>
</program>
</pcml>
public qsyrusri() {
}
System.setErr(System.out);
try
{
// Uncomment the following to get debugging information
//com.ibm.as400.data.PcmlMessageLog.setTraceEnabled(true);
// Construct ProgramCallDocument
// First parameter is system to connect to
// Second parameter is pcml resource name. In this example,
// serialized PCML file "qsyrusri.pcml.ser" or
// PCML source file "qsyrusri.pcml" must be found in the classpath.
pcml = new ProgramCallDocument(as400System, "qsyrusri");
System.exit(0);
} // End main()
<!-- PCML source for calling "Open List of Authorized Users" (QGYOLAUS) API -->
<!-- Program QGYOLAUS and its parameter list for retrieving AUTU0150 format -->
<program name="qgyolaus" path="/QSYS.lib/QGY.lib/QGYOLAUS.pgm" parseorder="listInfo receiver">
<data name="receiver" type="struct" struct="autu0150" usage="output"
count="listInfo.rcdsReturned" outputsize="receiverLength" />
<data name="receiverLength" type="int" length="4" usage="input" init="16384" />
<data name="listInfo" type="struct" struct="listInfo" usage="output" />
<data name="rcdsToReturn" type="int" length="4" usage="input" init="264" />
<data name="format" type="char" length="10" usage="input"
init="AUTU0150" />
<data name="selection" type="char" length="10" usage="input" init="*USER" />
<data name="member" type="char" length="10" usage="input" init="*NONE" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
<!-- Program QGYCLST closes the list, freeing resources on the server -->
<program name="qgyclst" path="/QSYS.lib/QGY.lib/QGYCLST.pgm" >
<data name="requestHandle" type="byte" length="4" usage="input" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
</pcml>
System.setErr(System.out);
try
{
// Uncomment the following to get debugging information
//com.ibm.as400.data.PcmlMessageLog.setTraceEnabled(true);
// Construct ProgramCallDocument
// First parameter is system to connect to
// Second parameter is pcml resource name. In this example,
// serialized PCML file "qgyolaus.pcml.ser" or
// PCML source file "qgyolaus.pcml" must be found in the classpath.
pcml = new ProgramCallDocument(as400System, "qgyolaus");
// All input parameters have default values specified in the PCML source.
// Do not need to set them using Java code.
nbrUsers += nbrRcds;
}
}
System.out.println("Number of users returned: " + nbrUsers);
System.exit(0);
}
}
<struct name="receiver">
<data name="lengthOfEntry" type="int" length="4" />
<data name="dispToObjectPathName" type="int" length="4" />
<data name="lengthOfObjectPathName" type="int" length="4" />
<data name="ccsidOfObjectPathName" type="int" length="4" />
<data name="readOnlyFlag" type="int" length="4" />
<data name="nosuidFlag" type="int" length="4" />
<data name="dispToReadWriteHostNames" type="int" length="4" />
<data name="nbrOfReadWriteHostNames" type="int" length="4" />
<data name="dispToRootHostNames" type="int" length="4" />
<data name="nbrOfRootHostNames" type="int" length="4" />
<data name="dispToAccessHostNames" type="int" length="4" />
<data name="nbrOfAccessHostNames" type="int" length="4" />
<data name="dispToHostOptions" type="int" length="4" />
<data name="nbrOfHostOptions" type="int" length="4" />
<data name="anonUserID" type="int" length="4" />
<data name="anonUsrPrf" type="char" length="10" />
<data name="pathName" type="char" length="lengthOfObjectPathName"
<struct name="returnedRcdsFdbkInfo">
<data name="bytesReturned" type="int" length="4" />
<data name="bytesAvailable" type="int" length="4" />
<data name="nbrOfNFSExportEntries" type="int" length="4" />
<data name="handle" type="int" length="4" />
</struct>
</pcml>
System.setErr(System.out);
try
{
// Uncomment the following to get debugging information
// com.ibm.as400.data.PcmlMessageLog.setTraceEnabled(true);
// Construct ProgramCallDocument
// First parameter is system to connect to
// Second parameter is pcml resource name. In this example,
// serialized PCML file "qznfrtve.pcml.ser" or
// PCML source file "qznfrtve.pcml" must be found in the classpath.
pcml = new ProgramCallDocument(as400System, "qznfrtve");
if (rc == false)
{
// Retrieve list of server messages
AS400Message[] msgs = pcml.getMessageList("qznfrtve");
// Iterate and write out Read Write Host Names for this export
nbrOfReadWriteHostNames =
pcml.getIntValue("qznfrtve.receiver.nbrOfReadWriteHostNames",
indices);
for(indices[1] = 0; indices[1] < nbrOfReadWriteHostNames; indices[1]++)
{
value = pcml.getValue("qznfrtve.receiver.rwAccessList.hostName", indices);
System.out.println(" Read/write access host name = " + value);
}
// Iterate and write out Root Host Names for this export
nbrOfRootHostNames = pcml.getIntValue("qznfrtve.receiver.nbrOfRootHostNames",
// Iterate and write out Access Host Names for this export
nbrOfAccessHostnames = pcml.getIntValue("qznfrtve.receiver.nbrOfAccessHostNames",
indices);
for(indices[1] = 0; indices[1] < nbrOfAccessHostnames; indices[1]++)
{
value = pcml.getValue("qznfrtve.receiver.accessHostNames.hostName", indices);
System.out.println(" Access host name = " + value);
}
System.exit(0);
} // end main()
}
//////////////////////////////////////////////////////////////////////////////////
//
// The following example (JSPRunReport) uses the JSPReportProcessor and the
// PDFContext classes to obtain data from a specified URL and convert the data
// to the PDF format. The data is then streamed to a file as a PDF document.
//
// Command syntax:
// java JSPRunReport <jsp_Url> <output_filename>
//
//////////////////////////////////////////////////////////////////////////////////
import java.lang.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.print.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.HashMap;
import com.ibm.xsl.composer.flo.*;
import com.ibm.xsl.composer.areas.*;
import com.ibm.xsl.composer.framework.*;
import com.ibm.xsl.composer.java2d.*;
import com.ibm.xsl.composer.prim.*;
import com.ibm.xsl.composer.properties.*;
import com.ibm.as400.util.reportwriter.processor.*;
import com.ibm.as400.util.reportwriter.pdfwriter.*;
import java.io.IOException;
import java.io.Serializable;
import org.xml.sax.SAXException;
/** specify the URL that contains the data you want to use in your report **/
String JSPurl = args[0];
URL jspurl = null;
try {
jspurl = new URL(JSPurl);
}
catch (MalformedURLException e)
{}
/** create the JSPReportProcessor object and set the template to the specified JSP **/
JSPReportProcessor jspprocessor = new JSPReportProcessor(pdfcontext);
try {
jspprocessor.setTemplate(jspurl);
}
System.exit(0);
}
}
<?xml version="1.0"?>
<!--
Copyright (c) 1999 The Apache Software Foundation. All rights reserved.
-->
<%!
String[][] cust_data = new String [4][5];
cust_data[0] = cust_record_1;
cust_data[1] = cust_record_2;
cust_data[2] = cust_record_3;
cust_data[3] = cust_record_4;
}
%>
<%
// add row to table
for(int i = 0; i <= 3; i++)
{
String[] _array = cust_data[i];
%>
<fo:table-row>
<fo:table-cell column-number="1">
<fo:block space-before=".1in">
<% if(_array[0].equals("IBM")) { %>
<fo:inline background-color="blue">
<% out.print(_array[0]); %>
</fo:inline>
<% } else { %>
<% out.print(_array[0]); %>
<% } %>
</fo:block>
</fo:table-cell>
<fo:table-cell column-number="2">
<fo:block space-before=".1in">
<% out.print(_array[1]); %>
</fo:block>
</fo:table-cell>
<fo:table-cell column-number="3">
<fo:block space-before=".1in">
<% out.print(_array[2]); %>
</fo:block>
</fo:table-cell>
<fo:table-cell column-number="4">
<fo:block space-before=".1in">
<% out.print(_array[3]); %>
</fo:block>
</fo:table-cell>
<fo:table-cell column-number="5">
<fo:block space-before=".1in">
<% out.print(_array[4]); %>
</fo:block>
</fo:table-cell>
</fo:table-row>
<%
} // end row while
%>
</fo:table-body>
</fo:table>
</fo:block>
</fo:flow>
//////////////////////////////////////////////////////////////////////////////////
//
// The following example (PCLRunReport) uses the XSLPReportProcessor and the
// PCLContext classes to obtain XML data and convert the data to the PCL format.
// The data is then streamed to a printer OutputQueue.
//
// To view the contents of example XML and XSL source files that you can use
// with PCLRunReport, see realestate.xml and realestate.xsl. You can also
// download a zip file that contains the XML and XSL example files. The zip
// file also contains a JSP example file that you can use with the
// JSPReportProcessor example (JSPRunReport).
//
// Command syntax:
// java PCLRunReport <xml_file> <xsl_file>
//
//////////////////////////////////////////////////////////////////////////////////
import java.lang.*;
import java.awt.*;
import java.io.*;
import java.awt.print.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.HashMap;
import com.ibm.xsl.composer.flo.*;
import com.ibm.xsl.composer.areas.*;
import com.ibm.xsl.composer.framework.*;
import com.ibm.xsl.composer.java2d.*;
import com.ibm.xsl.composer.prim.*;
import com.ibm.xsl.composer.properties.*;
import com.ibm.as400.util.reportwriter.processor.*;
import com.ibm.as400.util.reportwriter.pclwriter.*;
import java.io.IOException;
import java.io.Serializable;
import org.xml.sax.SAXException;
import com.ibm.as400.access.*;
try{
fileout = new SpooledFileOutputStream(system, parms, null, null);
}
catch (Exception e)
{}
System.exit(0);
}
<?xml version="1.0"?>
<RESIDENTIAL-LISTINGS VERSION="061698">
</GENERAL>
<FEATURES>
<DISCLOSURES>
In your dreams.
</DISCLOSURES>
<UTILITIES>
Yes
</UTILITIES>
<EXTRAS>
Pest control included.
</EXTRAS>
<CONSTRUCTION>
Wallboard and glue
</CONSTRUCTION>
<ACCESS>
Front door.
</ACCESS>
</FEATURES>
<FINANCIAL>
<ASSUMABLE>
I assume so.
</ASSUMABLE>
<OWNER-CARRY>
Too heavy.
</OWNER-CARRY>
<ASSESMENTS>
$150,000
</ASSESMENTS>
<DUES>
$100
</DUES>
<TAXES>
$2,000
</TAXES>
<LENDER>
Fly by nite mortgage co.
</LENDER>
<EARNEST>
Burt
</EARNEST>
<DIRECTIONS>
North, south, east, west
</DIRECTIONS>
</FINANCIAL>
<REMARKS>
</REMARKS>
<CONTACTS>
<COMPANY>
<NAME>
</RESIDENTIAL-LISTING>
<MLS>
<MLS-CODE SECURITY="Restricted">
30298877
</MLS-CODE>
<MLS-SOURCE SECURITY="Public">
<NAME>
Mary the Realtor
</NAME>
<PHONE>
1-617-555-3333
</PHONE>
<FAX>
1-617-555-4444
</FAX>
<WEB>
<EMAIL>
[email protected]
</EMAIL>
<SITE>
www.bigbucks.com
</SITE>
</WEB>
</MLS-SOURCE>
</MLS>
<TYPE>
Home
</TYPE>
<PRICE>
$200,000
</PRICE>
<STRUCTURE>
<NUM-BEDS>
2
</NUM-BEDS>
<NUM-BATHS>
2
</NUM-BATHS>
</STRUCTURE>
<DATES>
<LISTING-DATE>
4/3/98
</LISTING-DATE>
</DATES>
<LAND-AREA UNITS="ACRES">
0.01
</LAND-AREA>
</GENERAL>
<FEATURES>
<DISCLOSURES>
In your dreams.
</DISCLOSURES>
<UTILITIES>
Yes
</UTILITIES>
<EXTRAS>
Pest control included.
</EXTRAS>
<CONSTRUCTION>
Wallboard and glue
</CONSTRUCTION>
<ACCESS>
Front door.
</ACCESS>
</FEATURES>
<FINANCIAL>
<ASSUMABLE>
I assume so.
</ASSUMABLE>
<OWNER-CARRY>
Too heavy.
</OWNER-CARRY>
<ASSESMENTS>
$150,000
</ASSESMENTS>
<DUES>
$100
</DUES>
<TAXES>
$2,000
</TAXES>
<LENDER>
Fly by nite mortgage co.
</LENDER>
<EARNEST>
Burt
</EARNEST>
<DIRECTIONS>
North, south, east, west
</DIRECTIONS>
</FINANCIAL>
<CONTACTS>
<COMPANY>
<NAME>
Noplace Realty
</NAME>
<ADDRESS>
12 Main Street
</ADDRESS>
<CITY>
Lowell, MA
</CITY>
<ZIP>
34567
</ZIP>
</COMPANY>
<AGENT>
<NAME>
Mary Jones
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</AGENT>
<OWNER>
<NAME>
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</OWNER>
<TENANT>
Yes.
</TENANT>
<COMMISION>
15%
</COMMISION>
</CONTACTS>
</RESIDENTIAL-LISTING>
<RESIDENTIAL-LISTING VERSION="061698" ID="ID1290">
<GENERAL>
<MLS>
<MLS-CODE SECURITY="Restricted">
20079877
</MLS-CODE>
<MLS-SOURCE SECURITY="Public">
<NAME>
Bob the Realtor
</NAME>
<PHONE>
1-617-555-1212
</PHONE>
<FAX>
1-617-555-1313
</FAX>
<WEB>
<EMAIL>
[email protected]
</EMAIL>
<SITE>
www.bigbucks.com
</SITE>
</WEB>
</MLS-SOURCE>
</MLS>
<TYPE>
Apartment
</TYPE>
<AGE UNITS="YEARS">
30
</AGE>
<STRUCTURE>
<NUM-BEDS>
3
</NUM-BEDS>
<NUM-BATHS>
1
</NUM-BATHS>
</STRUCTURE>
<DATES>
<LISTING-DATE>
3/5/97
</LISTING-DATE>
</DATES>
<LAND-AREA UNITS="ACRES">
0.05
</LAND-AREA>
</GENERAL>
<FEATURES>
<DISCLOSURES>
In your dreams.
</DISCLOSURES>
<UTILITIES>
Yes
</UTILITIES>
<EXTRAS>
Pest control included.
</EXTRAS>
<CONSTRUCTION>
Wallboard and glue
</CONSTRUCTION>
<ACCESS>
Front door.
</ACCESS>
</FEATURES>
<FINANCIAL>
<ASSUMABLE>
I assume so.
</ASSUMABLE>
<OWNER-CARRY>
Too heavy.
</OWNER-CARRY>
<ASSESMENTS>
$150,000
</ASSESMENTS>
<DUES>
$100
</DUES>
<TAXES>
$2,000
</TAXES>
<LENDER>
Fly by nite mortgage co.
</LENDER>
<EARNEST>
Burt
</EARNEST>
<REMARKS>
</REMARKS>
<CONTACTS>
<COMPANY>
<NAME>
Noplace Realty
</NAME>
<ADDRESS>
12 Main Street
</ADDRESS>
<CITY>
Lowell, MA
</CITY>
<ZIP>
34567
</ZIP>
</COMPANY>
<AGENT>
<NAME>
Mary Jones
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</AGENT>
<OWNER>
<NAME>
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</OWNER>
<TENANT>
Yes.
</TENANT>
<COMMISION>
15%
</COMMISION>
</CONTACTS>
</RESIDENTIAL-LISTING>
<RESIDENTIAL-LISTING VERSION="061698" ID="ID1291">
<GENERAL>
<MLS>
<MLS-CODE SECURITY="Restricted">
29389877
</MLS-CODE>
<MLS-SOURCE SECURITY="Public">
<NAME>
Mary the Realtor
</NAME>
<PHONE>
1-617-555-3333
</PHONE>
<FAX>
1-617-555-4444
</FAX>
<WEB>
<EMAIL>
[email protected]
</EMAIL>
<SITE>
www.bigbucks.com
</SITE>
</WEB>
</MLS-SOURCE>
<TYPE>
Home
</TYPE>
<PRICE>
$449,000
</PRICE>
<AGE UNITS="YEARS">
7
</AGE>
<STRUCTURE>
<NUM-BEDS>
7
</NUM-BEDS>
<NUM-BATHS>
3
</NUM-BATHS>
</STRUCTURE>
<DATES>
<LISTING-DATE>
6/8/98
</LISTING-DATE>
</DATES>
<LAND-AREA UNITS="ACRES">
2.0
</LAND-AREA>
</GENERAL>
<FEATURES>
<DISCLOSURES>
In your dreams.
</DISCLOSURES>
<UTILITIES>
Yes
</UTILITIES>
<EXTRAS>
Pest control included.
</EXTRAS>
<CONSTRUCTION>
Wallboard and glue
</CONSTRUCTION>
<ACCESS>
Front door.
</ACCESS>
</FEATURES>
<FINANCIAL>
<ASSUMABLE>
I assume so.
</ASSUMABLE>
<OWNER-CARRY>
Too heavy.
</OWNER-CARRY>
<ASSESMENTS>
$300,000
</ASSESMENTS>
<DUES>
$100
</DUES>
<TAXES>
$2,000
</TAXES>
<LENDER>
<REMARKS>
</REMARKS>
<CONTACTS>
<COMPANY>
<NAME>
Noplace Realty
</NAME>
<ADDRESS>
12 Main Street
</ADDRESS>
<CITY>
Lowell, MA
</CITY>
<ZIP>
34567
</ZIP>
</COMPANY>
<AGENT>
<NAME>
Mary Jones
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</AGENT>
<OWNER>
<NAME>
</NAME>
<ADDRESS>
</ADDRESS>
<CITY>
</CITY>
<ZIP>
</ZIP>
</OWNER>
<TENANT>
Yes.
</TENANT>
<COMMISION>
15%
</COMMISION>
</CONTACTS>
</RESIDENTIAL-LISTING>
</RESIDENTIAL-LISTINGS>
<?xml version="1.0"?>
<xsl:template match="RESIDENTIAL-LISTINGS">
<fo:root>
<fo:layout-master-set>
<fo:simple-page-master master-name="theMaster">
<fo:region-body region-name="theRegion"/>
</fo:simple-page-master>
</xsl:template>
</xsl:stylesheet>
Examples: RFML
This section lists the code examples that are provided throughout the documentation of the IBM Toolbox
for Java RFML component.
• Example: Using RFML compared to using IBM Toolbox for Java Record classes
• Example: RFML source file
The following disclaimer applies to all of the IBM Toolbox for Java examples:
Code example disclaimer
IBM grants you a nonexclusive copyright license to use all programming code examples from
which you can generate similar function tailored to your own specific needs.
All sample code is provided by IBM for illustrative purposes only. These examples have
not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply
reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any
kind. The implied warranties of non-infringement, merchantability and fitness for a particular
purpose are expressly disclaimed.
<recordformat name="cusrec">
</recordformat>
<recordformat name="cusrec1">
</recordformat>
<recordformat name="cusrecAscii">
</recordformat>
<struct name="balance">
<data name="amount" type="zoned" length="6" precision="2" init="7"/>
</struct>
</rfml>
Related reference
“Example: Using RFML compared to using IBM Toolbox for Java Record classes” on page 302
This example illustrates the differences between using RFML and using the IBM Toolbox for Java Record
classes.
Example: Using a profile token credential to swap the IBM i thread identity
The following code example shows you how to use a profile token credential to swap the IBM i thread
identity and perform work on behalf of a specific user.
Note: Read the Code example disclaimer for important legal information.
system.disconnectAllServices();
system2.disconnectAllServices();
HTML source generated from the Java source by the using HTMLTableConverter
Using the “HTMLTableConverter class” on page 227 in the Java source example above generates the
following HTML code.
<table>
<tr>
<th>Customer ID</th>
<th>Order Number</th>
</tr>
<tr>
<td>777-53-4444</td>
<td>12345-XYZ</td>
</tr>
<tr>
<td>777-53-4444</td>
<td>56789-ABC</td>
</tr>
</table>
HTML source generated from the Java source by the using HTMLTableConverter
Using the HTMLTableConverter class in the Java source example above generates the following HTML
code.
<table>
<tr>
<th>CNUM</th>
<th>LNAM</th>
<th>INIT</th>
<th>STR</th>
<th>CTY</th>
<th>STATE</th>
<th>ZIP</th>
<th>CTLMT</th>
<th>CHGCOD</th>
<th>BDUE</th>
<th>CTDUE</th>
</tr>
<tr>
<td>938472</td>
<td>Henning </td>
<td>G K</td>
<td>4859 Elm Ave </td>
<td>Dallas</td>
<td>TX</td>
<td align="right">75217</td>
<td align="right">5000</td>
<td align="right">3</td>
<td align="right">37.00</td>
<td align="right">0.00</td>
</tr>
<tr>
<td>839283</td>
<td>Jones </td>
<td>B D</td>
<td>21B NW 135 St</td>
93847 Henning GK 4859 Elm Ave Dallas TX 75217 5000 3 37.00 0.00
2
HTML source generated from the Java source by the using HTMLTableConverter
Using the HTMLTableConverter class in the Java source example above generates the following HTML
code.
Custom Last Initials Street City Stat Zip Credit Charge Balance Credit
er Name Address e Code Limit Code Due Due
Number
938472 Henning G K 4859 Elm Dallas TX 75217 5000 3 37.00 0.00
Ave
839283 Jones BD 21B NW Clay NY 13041 400 1 100.00 0.00
135 St
392859 Vine SS PO Box Broton VT 5046 700 1 439.00 0.00
79
938485 Johnson J A 3 Alpine Helen GA 30545 9999 2 3987.50 33.50
Way
397267 Tyron WE 13 Myrtle Hector NY 14841 1000 1 0.00 0.00
Dr
389572 Stevens KL 208 Denve CO 80226 400 1 58.75 1.50
Snow r
Pass
846283 Alison JS 787 Lake Isle MN 56342 5000 3 10.00 0.00
Dr
475938 Doe JW 59 Sutter CA 95685 700 2 250.00 100.00
Archer
Rd
693829 Thomas AN 3 Dove Caspe WY 82609 9999 2 0.00 0.00
Circle r
593029 Williams E D 485 SE 2 Dallas TX 75218 200 1 25.00 0.00
Ave
192837 Lee FL 5963 Oak Hector NY 14841 700 2 489.50 0.50
St
import java.awt.Color;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.as400.util.html.GridLayoutFormPanel;
import com.ibm.as400.util.html.HTMLConstants;
import com.ibm.as400.util.html.HTMLForm;
import com.ibm.as400.util.html.HTMLTable;
import com.ibm.as400.util.html.HTMLTableCaption;
import com.ibm.as400.util.html.HTMLText;
import com.ibm.as400.util.html.LabelFormElement;
import com.ibm.as400.util.html.LineLayoutFormPanel;
import com.ibm.as400.util.html.SubmitFormInput;
import com.ibm.as400.util.html.TextFormInput;
import com.ibm.as400.util.servlet.HTMLFormConverter;
import com.ibm.as400.util.servlet.SQLResultSetRowData;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCDriver;
/**
* An example of using the HTMLFormConverter class in a servlet.
*/
public class HTMLFormConverterExample extends HttpServlet
{
private String userId_ = "myUserId";
private String password_ = "myPwd";
private AS400 system_;
out.println(showHtmlMain());
out.close();
}
response.setContentType("text/html");
// Retrieve the row data and HTML table values for this session.
rowData = (SQLResultSetRowData) session.getValue("sessionRowData");
htmlTable = (HTMLTable[]) session.getValue("sessionHtmlTable");
if (rowData != null)
{
// Set the row data value for this session.
session.putValue("sessionRowData", rowData);
if (htmlTable != null)
{
rowData.first();
session.putValue("sessionHtmlTable", htmlTable);
out.println(showHtmlForRecord(htmlTable, 0));
}
}
}
// If the "Return To Main" button was pressed,
// go back to the main HTML form
// Save the row data value for this session so the current position
// is updated in the object associated with this session.
session.putValue("sessionRowData", rowData);
// Get all the records from the file input by the user.
private SQLResultSetRowData getAllRecords(Hashtable parameters, ServletOutputStream out)
throws IOException
{
SQLResultSetRowData records = null;
try
{
// Get the system, library and file name from the parameter list.
String sys = ((String) parameters.get("System")).toUpperCase();
String lib = ((String) parameters.get("Library")).toUpperCase();
String file = ((String) parameters.get("File")).toUpperCase();
if ((sys == null || sys.equals("")) ||
(lib == null || lib.equals("")) ||
(file == null || file.equals("")))
{
out.println(showHtmlForError("Invalid system, file or library name."));
}
else
{
// Get the connection to the server.
getDatabaseConnection (sys, out);
if (databaseConnection_ != null)
{
Statement sqlStatement = databaseConnection_.createStatement();
return records;
}
// Create the text element for the error and add it to the panel.
HTMLText text = new HTMLText(message);
text.setBold(true);
text.setColor(Color.red);
grid.addElement(text);
page.append(errorForm.toString());
}
catch (Exception e)
{
e.printStackTrace ();
}
page.append("</body></html>");
return page.toString();
}
try
{
// Create the HTML Form object
HTMLForm recForm = new HTMLForm("HTMLFormConverterExample");
page.append("</body></html>");
return page.toString();
}
// Show the main HTML form (request input for system, file,
// and library name).
private String showHtmlMain()
{
String title = "HTMLFormConverter Example";
StringBuffer page = new StringBuffer();
page.append (showHeader (title));
try
{
// Set up so that doPost() gets called when the form is submitted.
mainForm.setMethod(HTMLForm.METHOD_POST);
panel.addElement(sysPrompt);
panel.addElement(system);
panel.addElement(filePrompt);
panel.addElement(file);
panel.addElement(libPrompt);
panel.addElement(library);
page.append(mainForm.toString());
page.append("</body></html>");
return page.toString();
}
<table border="0">
<tr>
<td><b>Record number: 1</b></td>
</tr>
<tr>
<td><table border="0">
<tr>
<td><table border="3" cellpadding="2" cellspacing="4">
<tr>
<th>CUSNUM</th>
<td>839283</td>
</tr>
<tr>
<th>LSTNAM</th>
<td>Jones </td>
</tr>
<tr>
<th>INIT</th>
<td>B D</td>
</tr>
<tr>
<th>STREET</th>
<td>21B NW 135 St</td>
</tr>
<tr>
<th>CITY</th>
import java.io.IOException;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.as400.util.html.*;
import com.ibm.as400.util.servlet.*;
import com.ibm.as400.access.*;
/*
An example of using IBM Toolbox for Java classes in a servlet.
File . . . . . . LICENSES
Library . . . LIGHTSON
File . . . . . . REPORTS
Library . . . LIGHTSON
{
private AS400 system_;
private String password_; // password for the server and for the SQL database
private java.sql.Connection databaseConnection_;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(showHtmlMain());
out.close();
}
if (parameters.containsKey("askingToReport"))
out.println (showHtmlForReporting ());
else if (parameters.containsKey("askingToRegister"))
out.println (showHtmlForRegistering ());
else if (parameters.containsKey("askingToUnregister"))
out.println(showHtmlForUnregistering());
else if (parameters.containsKey("askingToListRegistered"))
out.println (showHtmlForListingAllRegistered ());
else if (parameters.containsKey("askingToListReported"))
out.println (showHtmlForListingAllReported ());
else if (parameters.containsKey("returningToMain"))
out.println (showHtmlMain ());
else { // None of the above, so assume the user has filled out a form
// and is submitting information. Grab the incoming info
// and do the requested action.
if (parameters.containsKey("submittingReport")) {
String acknowledgement = reportLightsOn (parameters, out);
else if (parameters.containsKey("submittingRegistration")) {
String acknowledgement = registerLicense (parameters, out);
out.println (showAcknowledgement(acknowledgement));
}
else if (parameters.containsKey("submittingUnregistration")) {
String acknowledgement = unregisterLicense (parameters, out);
out.println (showAcknowledgement(acknowledgement));
}
else {
out.println (showAcknowledgement("Error (internal): " +
"Neither Report, Register, " +
"Unregister, ListRegistered, or ListReported."));
}
}
// Gets the parameters from an HTTP servlet request, and packages them
// into a hashtable for convenience.
private static Hashtable getRequestParameters (HttpServletRequest request)
{
Hashtable parameters = new Hashtable ();
Enumeration enum = request.getParameterNames();
while (enum.hasMoreElements()) {
String key = (String) enum.nextElement();
String value = request.getParameter (key);
parameters.put (key, value);
}
return parameters;
}
// Removes blanks and hyphens from a String, and sets it to all uppercase.
private static String normalize (String oldString)
{
if (oldString == null || oldString.length() == 0) return null;
StringBuffer newString = new StringBuffer ();
for (int i=0; i<oldString.length(); i++) {
if (oldString.charAt(i) != ' ' && oldString.charAt(i) != '-')
newString.append (oldString.charAt(i));
}
return newString.toString().toUpperCase();
}
system_.setSystemName(sysName);
system_.setUserId(userId);
system_.setPassword(password);
password_ = password;
system_.connectService(AS400.DATABASE);
system_.connectService(AS400.FILE);
system_.addPasswordCacheEntry(sysName, userId, password_);
}
}
catch (Exception e) { e.printStackTrace (); system_ = null; }
return system_;
}
try {
super.init(config);
}
catch (Exception e) { e.printStackTrace(); }
}
}
catch (Exception e) { e.printStackTrace (); }
}
}
if (acknowledgement.length() == 0)
{
try
{
// Insert the new license number and e-mail address into the database.
getDatabaseConnection ();
Statement sqlStatement = databaseConnection_.createStatement();
if (acknowledgement.length() == 0)
{
try
{
// Remove the specified license number and e-mail address from database.
getDatabaseConnection ();
Statement sqlStatement = databaseConnection_.createStatement();
if (acknowledgement.length() == 0)
{
try
{
// Report "lights on" for a specified vehicle.
getDatabaseConnection ();
Statement sqlStatement = databaseConnection_.createStatement();
try {
HTMLForm form = new HTMLForm("LightsOn");
GridLayoutFormPanel grid = new GridLayoutFormPanel();
HTMLText text = new HTMLText(acknowledgement);
if (acknowledgement.startsWith("Error"))
text.setBold(true);
grid.addElement(text);
grid.addElement(new SubmitFormInput("returningToMain", "Home"));
form.addElement(grid);
page.append(form.toString());
}
catch (Exception e) { e.printStackTrace (); }
page.append("</body></html>");
return page.toString();
}
try {
// Set up so that doPost() gets called when the form is submitted.
mainForm.setMethod(HTMLForm.METHOD_POST);
mainForm.addElement(grid);
}
catch (Exception e) { e.printStackTrace (); }
page.append(mainForm.toString());
page.append("</body></html>");
return page.toString();
}
try {
// Set up so that doPost() gets called when the form is submitted.
reportForm.setMethod(HTMLForm.METHOD_POST);
grid.addElement(new LabelFormElement("Color:"));
grid.addElement(colorGroup);
grid.addElement(new LabelFormElement("Building:"));
grid.addElement(location);
reportForm.addElement(grid);
}
catch (Exception e) { e.printStackTrace (); }
page.append(reportForm.toString());
page.append("</body></html>");
return page.toString();
}
try {
// Set up so that doPost() gets called when the form is submitted.
registrationForm.setMethod(HTMLForm.METHOD_POST);
registrationForm.addElement(grid);
}
catch (Exception e) { e.printStackTrace (); }
page.append(registrationForm.toString());
page.append("</body></html>");
return page.toString();
}
try {
// Set up so that doPost() gets called when the form is submitted.
unregistrationForm.setMethod(HTMLForm.METHOD_POST);
unregistrationForm.addElement(grid);
}
catch (Exception e) {
e.printStackTrace ();
CharArrayWriter cWriter = new CharArrayWriter();
PrintWriter pWriter = new PrintWriter (cWriter, true);
e.printStackTrace (pWriter);
page.append (cWriter.toString());
}
page.append(unregistrationForm.toString());
page.append("</body></html>");
return page.toString();
}
try
{
// Create the HTML Form object.
HTMLForm mainForm = new HTMLForm("LightsOn");
getDatabaseConnection ();
Statement sqlStatement = databaseConnection_.createStatement();
if (rowCount == 0) {
page.append ("<font size=4 color=red>No vehicles have been reported.</font>");
}
else {
query = "SELECT LICENSE,WHEN_ADDED FROM LICENSES";
rs = sqlStatement.executeQuery (query);
SQLResultSetRowData rowData = new SQLResultSetRowData (rs);
HTMLTable[] generatedHtml = converter.convertToTables(rowData);
grid.addElement(generatedHtml[0]);
}
sqlStatement.close();
// Note: Mustn't close statement before we're done using result set.
mainForm.addElement(grid);
page.append(mainForm.toString());
}
catch (Exception e) { e.printStackTrace (); }
page.append("</body></html>");
return page.toString();
}
try
{
// Create the HTML Form object.
HTMLForm form = new HTMLForm("LightsOn");
getDatabaseConnection ();
if (rowCount == 0) {
page.append ("<font size=4 color=red>No vehicles have been reported.</font>");
}
else {
query = "SELECT LICENSE,COLOR,CATEGORY,DATE_ADDED,TIME_ADDED FROM REPORTS";
rs = sqlStatement.executeQuery (query);
SQLResultSetRowData rowData = new SQLResultSetRowData (rs);
HTMLTable[] generatedHtml = converter.convertToTables(rowData);
grid.addElement(generatedHtml[0]);
}
sqlStatement.close();
// Note: Mustn't close statement before we're done using result set.
;c:\lib\jt400.jar
3. Open a text editor and type the first simple programming example
Note: Make sure to leave out the text that refers to the Notes (for example, Note 1, Note 2, and so on).
Save the new document with the name CmdCall.java.
4. Start a command session on your workstation and use the following command to compile the simple
programming example:
javac CmdCall.java
5. In the command session, type the following command to run the simple programming example:
java CmdCall
////////////////////////////////////////////////////
//
// This source is an example of "Job List".
//
/////////////////////////////////////////////////////
//
// The access classes are in the com.ibm.as400.access.package.
// Import this package to use the IBM Toolbox for Java classes.
//
/////////////////////////////////////////////////////
import com.ibm.as400.access.*;
System.exit(0);
1. IBM Toolbox for Java uses the "AS400" object to identify the target server. If you construct the AS400
object with no parameters, IBM Toolbox for Java prompts for the system name, userid and password.
The AS400 class also includes a constructor that takes the system name, userid and password.
2. Use the IBM Toolbox for Java CommandCall object to send commands to the server. When you create
the CommandCall object, you pass it an AS400 object so that it knows which server is the target of the
command.
3. Use the run() method on the command call object to run a command.
4. The result of running a command is a list of IBM i messages. IBM Toolbox for Java represents these
messages as AS400Message objects. When the command is complete, you get the resulting messages
from the CommandCall object.
5. Print the message text. Also available are the message ID, message severity, and other information.
This program prints only the message text.
//////////////////////////////////////////////////////////////////////////////////
//
// Example using the Message Queue function of the IBM Toolbox for Java
//
// This source is an example of IBM Toolbox for Java "Message Queue".
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
System.exit(0); Note 5
}
void displayMessage()
{
}
//////////////////////////////////////////////////////////////////////////////////
//
// Example using the Message Queue function of the IBM Toolbox for Java
//
// This source is an example of IBM Toolbox for Java "Message Queue".
//
//////////////////////////////////////////////////////////////////////////////////
package examples;
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
me.Main(parameters);
System.exit(0);
}
void displayMessage()
{
}
if (parms.length > 0)
system.setSystemName(parms[0]); Note 2
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
1. A program uses the AS400 object to designate which server to connect to. With one exception, all
programs that need resources from a server must have an AS400 object. The exception is JDBC. If
your program uses JDBC, then the IBM Toolbox for Java JDBC driver creates the AS400 object for the
program.
2. This program assumes the first command line parameter is the name of the server. If a parameter is
passed to the program, the setSystemName method of the AS400 object is used to set the system
name. The AS400 object also needs server sign-on information:
• If the program is running on a workstation, the IBM Toolbox for Java program prompts the user for
a user ID and password. Note: If a system name is not specified as a command line parameter, the
AS400 object also prompts for the system name.
• If the program is running on the IBM i JVM, then the user ID and password of the user running the
Java program is used. In this case, the user does not specify a system name, but lets the system
name default to the name of the system that the program is running on.
[ Previous part | Next part ]
//////////////////////////////////////////////////////////////////////////////////
//
// Example using the Message Queue function of the IBM Toolbox for Java
//
// This source is an example of IBM Toolbox for Java "Message Queue".
//
//////////////////////////////////////////////////////////////////////////////////
package examples;
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
me.Main(parameters);
System.exit(0);
}
void displayMessage()
{
if (parms.length > 0)
system.setSystemName(parms[0]);
while (e.hasMoreElements())
{
1. The purpose of this program is to display messages in a server message queue. The MessageQueue
object of the IBM Toolbox for Java is used for this task. When the message queue object is
constructed, the parameters are the AS400 object and the message queue name. The AS400 object
indicates which server contains the resource, and the message queue name identifies which message
queue on the server. In this case, a constant is used, which tells the message queue object to access
the queue of the signed-on user.
2. The message queue object gets a list of messages from the server. A connection to the server is made
at this point.
3. Remove a message from the list. The message is in the IBM Toolbox for Java program's
QueuedMessage object.
4. Print the text of the message.
[ Previous part ]
//////////////////////////////////////////////////////////////////////////////////
//
// Record level access example. This program will prompt the user
// for the name of the server and the file to display. The file must exist
// and contain records. Each record in the file will be displayed
// to System.out.
//
// Calling syntax: java RLSequentialAccessExample
//
// This source is an example of IBM Toolbox for Java "RecordLevelAccess"
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
System.out.println();
try
{
System.out.print("System name: ");
systemName = inputStream.readLine();
System.out.println();
}
catch (Exception e)
{
System.out.println("Error obtaining user input.");
e.printStackTrace();
System.exit(0);
}
AS400FileRecordDescription recordDescription =
new AS400FileRecordDescription(system, filePathName.getPath());
try
{
RecordFormat[] format = recordDescription.retrieveRecordFormat(); Note 4
theFile.setRecordFormat(format[0]); Note 5
theFile.close(); Note 8
system.disconnectService(AS400.RECORDACCESS); Note 9
}
catch (Exception e)
{
System.out.println("Error occurred attempting to display the file.");
e.printStackTrace();
try
{
// Close the file
theFile.close();
}
catch(Exception x)
{
}
system.disconnectService(AS400.RECORDACCESS);
System.exit(0);
}
// Make sure that the application ends; see readme for details
System.exit(0);
}
}
1. This line of code creates an AS400 object and connects to the record-level access service.
2. This line creates a QSYSObjectPathName object that obtains the integrated file system path name
form of the object to be displayed.
3. This statement creates an object that represents an existing sequential file on the server you are
connected to. This sequential file is the file that will be displayed.
4. These lines retrieve the record format of the file.
5. This line sets the record format for the file.
6. This line opens the selected file for reading. It will read 100 records at a time, when it is possible.
7. This line of code reads each record in sequence.
8. This line closes the file.
9. This line disconnects from the record-level access service.
[ Next part ]
//////////////////////////////////////////////////////////////////////////////////
//
// Record level access example.
//
// Calling syntax: java RLACreateExample
//
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
import java.util.*;
import com.ibm.as400.access.*;
try
{
SequentialFile theFile = new SequentialFile(system, filePathName);
theFile.open(AS400File.READ_WRITE, 1, AS400File.COMMIT_LOCK_LEVEL_NONE);
theFile.write(newData); Note 3
// End Note Three
theFile.close();
}
catch(Exception e)
{
System.out.println("An error has occurred: ");
e.printStackTrace();
}
system.disconnectService(AS400.RECORDACCESS);
System.exit(0);
}
}
1. (args[0]) in the previous line and MYFILE.FILE are pieces of code that are prerequisites for the rest of
the example to run. The program assumes that the library MYLIB exists on the server and that the user
has access to it.
2. The text within the Java comments labeled "Begin Note Two" and "End Note Two" shows how to create
a record format yourself instead of getting the record format from an existing file. The last line in this
block creates the file on the server.
3. The text within the Java comments labeled "Begin Note Three" and "End Note Three" shows a way to
create a record and then write it to a file.
[ Previous part ]
//////////////////////////////////////////////////////////////////////////////////
//
// JDBCPopulate example. This program uses the IBM Toolbox for Java JDBC driver
import java.sql.*;
if (parameters.length != 3) {
System.out.println("");
System.out.println("Usage:");
System.out.println("");
System.out.println(" JDBCPopulate system collectionName tableName");
System.out.println("");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println("");
System.out.println(" JDBCPopulate MySystem MyLibrary MyTable");
System.out.println("");
return;
}
try {
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver()); Note 1
try {
Statement dropTable = connection.createStatement ();
dropTable.executeUpdate ("DROP TABLE " + tableName); Note 3
}
catch (SQLException e) {
}
System.exit (0);
}
1. This line loads the IBM Toolbox for Java JDBC driver. A JDBC driver is necessary to mediate between
JDBC and the database you are working with.
2. This statement connects to the database. A prompt will appear for the user ID and password. A default
SQL schema is provided so that you will not need to qualify the table name in SQL statements.
3. These lines delete the table if it already exists.
4. These lines create the table.
5. This line prepares a statement that will insert rows into the table. Because you will be executing this
statement several times, you should use a PreparedStatement and parameter markers.
6. This block of code populates the table for you; every time the loop is executed, it inserts a row into the
table.
7. Now that the table has been created and filled in, this statement closes the connection to the
database.
[ Next part ]
//////////////////////////////////////////////////////////////////////////////////
//
// JDBCQuery example. This program uses the IBM Toolbox for Java JDBC driver to
// query a table and output its contents.
//
// Command syntax:
// JDBCQuery system collectionName tableName
//
// For example,
// JDBCQuery MySystem qiws qcustcdt
//
// This source is an example of IBM Toolbox for Java JDBC driver.
//
//////////////////////////////////////////////////////////////////////////////////
import java.sql.*;
return formattedString;
}
try {
catch (Exception e) {
System.out.println ();
System.out.println ("ERROR: " + e.getMessage());
}
finally {
// Clean up.
try {
if (connection != null)
connection.close ();
}
catch (SQLException e) {
// Ignore.
}
}
System.exit (0);
}
1. This line loads the IBM Toolbox for Java JDBC driver. A JDBC driver mediates between JDBC and the
database with which you are working.
2. This line retrieves the connection's meta data, an object that describes many of the characteristics of
the database.
3. This statement executes the query on the specified table.
4. These lines retrieve information about the table.
5. These lines set the column width to either the length of the label or the length of the data, whichever is
longer.
6. This block of code iterates through all of the rows in the table and displays the contents of each
column in each row.
[ Previous part ]
Managing connections
• Example: Making a connection to the system with a CommandCall object
• Example: Making two connections to the system with a CommandCall object
• Example: Creating CommandCall and IFSFileInputStream objects with an AS400 object
• Example: Using AS400ConnectionPool to preconnect to the system
• Example: Using AS400ConnectionPool to preconnect to a specific service on the system, then reuse the
connection
Exceptions
• Example: Using exceptions
Trace
• Example: Using trace
• Example: Using setTraceOn()
• Example: Using component trace
Optimization
• Example: Creating two AS400 objects
• Example: Using an AS400 object to represent a second server
The following disclaimer applies to all of the IBM Toolbox for Java examples:
Code example disclaimer
IBM grants you a nonexclusive copyright license to use all programming code examples from
which you can generate similar function tailored to your own specific needs.
All sample code is provided by IBM for illustrative purposes only. These examples have
not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply
reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any
kind. The implied warranties of non-infringement, merchantability and fitness for a particular
purpose are expressly disclaimed.
AS/400ToolboxJarMaker
• Example: Extracting AS400.class and all its dependent classes from jt400.jar
• Example: Splitting jt400.jar into a set of 300KB files
• Example: Removing unused files from a JAR file
• Example: Creating a 400KB smaller JAR file by omitting the conversion tables with the -ccsid parameter
CommandPrompter
• Example: Using CommandPrompter to prompt for and run a command
The following disclaimer applies to all of the IBM Toolbox for Java examples:
Code example disclaimer
//////////////////////////////////////////////////////////////////////////////////
//
// CommandPrompter example. This program uses CommandPrompter, CommandCall, and
// AS400Message to prompt for a command, run the command, and display any
// messages returned if the command does not run.
//
// Command syntax:
// Prompter commandString
//
//////////////////////////////////////////////////////////////////////////////////
import com.ibm.as400.ui.util.CommandPrompter;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.CommandCall;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class Prompter
{
public static void main ( String args[] ) throws Exception
{
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
AS400 system = new AS400("mySystem", "myUserId", "myPasswd");
String cmdName = args[0];
Examples: XPCML
This section lists the code examples that are provided throughout the documentation of the IBM Toolbox
for Java XPCML component.
• “Example: Condensing an existing XPCML document” on page 528
<!-- XPCML source for calling "Open List of Authorized Users" -->
<!-- (QGYOLAUS) API -->
<!-- List information structure (common for "Open List" type APIs) -->
<struct name="listInfo">
<intParm name="totalRcds"/>
<intParm name="rcdsReturned">0</rcdsReturned>
<hexBinaryParm name="rqsHandle" totalBytes="4"/>
<intParm name="rcdLength"/>
<stringParm name="infoComplete" length="1"/>
<stringParm name="dateCreated" length="7"/>
<stringParm name="timeCreated" length="6"/>
<stringParm name="listStatus" length="1"/>
<hexBinaryParm totalBytes="1"/>
<unsignedIntParm name="lengthOfInfo"/>
<intParm name="firstRecord"/>
<hexBinaryParm totalBytes="40"/>
</struct>
<!-- Program QGYOLAUS and its parameter list for retrieving -->
<!-- AUTU0150 format -->
Java code that constructs the ProgramCallDocument object and uses the XPCML to
call program QGYOLAUS
system = new AS400();
// Create a ProgramCallDocument into which to parse the file.
ProgramCallDocument xpcmlDoc =
new ProgramCallDocument(system, "QGYOLAUS.xpcml");
// Call QGYOLAUS
boolean rc = xpcmlDoc.callProgram("QGYOLAUS");
Results of the program call, generated as XPCML and stored in file XPCMLOut.xpcml
<?xml version="1.0" ?>
<xpcml version="4.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='xpcml.xsd' >
<!-- More records here depending on how many users output. -->
<!-- In this case 89 user records are listed here. -->
<xpcml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="xpcml.xsd" version="4.0">
<struct name="s1">
<stringParm name="s1p1"/>
<structParm name="s2Ref" struct="s2"/>
</struct>
<struct name="s2">
<xpcml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="xpcml.xsd" version="4.0">
<struct name="s2">
<stringParm name="s2p1" length="10">constantVal</stringParm>
<arrayOfStringParm name="parm1" count="2">
<i>constantVal_1</i>
<i>constantVal_2</i>
</arrayOfStringParm>
</struct>
<struct name="s2">
<stringParm name="s2p1"/>
</struct>
For example, the following XPCML specifies an array of 3 intParms and sets the first element to 12, the
second to 100, and the third to 4:
Using the index attribute of the <i> and <struct_i> tags to set array values
You can use the index attribute of the <i> and <struct_i> tags to help you set array values. In the following
example, the XPCML sets the first element of the array to 4, the second to 100, and the third to 12.
Generated schema
<!-- parm1's XSD definition -->
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<!-- Link back to XPCML.xsd -->
<xs:include schemaLocation='xpcml.xsd'/>
<xs:element name="parm1_" substitutionGroup="stringParmGroup" >
<xs:complexType>
<xs:simpleContent>
<xs:restriction base="stringParmType">
<!-- Attributes defined for parm1 -->
<xs:attribute name="name" type="string50" fixed="parm1" />
<xs:attribute name="length" type="xs:string" fixed="10" />
<xs:attribute name="passMode" type="xs:string" fixed="value" />
<xs:attribute name="ccsid" type="xs:string" fixed="37" />
<xs:attribute name="minvrm" type="xs:string" fixed="V5R2M0" />
</xs:restriction>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</schema>
<struct name="qualifiedJobName">
<stringParm name="jobName" length="10">*</stringParm>
<stringParm name="userName" length="10"/>
<stringParm name="jobNumber" length="6"/>
</struct>
<struct name="jobi0100">
<intParm name="numberOfBytesReturned"/>
<intParm name="numberOfBytesAvailable"/>
<structParm name="qualifiedJobName" struct="qualifiedJobName"/>
<hexBinaryParm name="internalJobIdentifier" totalBytes="16"/>
<stringParm name="jobStatus" length="10"/>
<stringParm name="jobType" length="1"/>
<stringParm name="jobSubtype" length="1"/>
<stringParm length="2"/>
<intParm name="runPriority"/>
<intParm name="timeSlice"/>
<intParm name="defaultWait"/>
<stringParm name="purge" length="10"/>
</struct>
}
catch (Exception e) {
System.out.println("error: - "+e.getMessage());
e.printStackTrace();
}
<struct name="qualifiedJobName">
<jobName_>*</jobName_>
<userName_/>
<jobNumber_/>
</struct>
<struct name="jobi0100">
<numberOfBytesReturned_/>
<numberOfBytesAvailable_/>
<structParm name="qualifiedJobName" struct="qualifiedJobName"/>
<internalJobIdentifier_/>
<jobStatus_/>
<jobType_/>
<jobSubtype_/>
<stringParm length="2"/>
<runPriority_/>
<timeSlice_/>
<defaultWait_/>
<purge_/>
</struct>
<!-- More type definitions for each newly defined type follow here -->
</xs:schema>
Note: The XPCML code that you use to call the program (after creating the ProgramCallDocument object)
is the same as the code you would use with PCML.
boolean rc = xpcmlDoc.callProgram("qusrjobi_jobi0100");
The following code shows an example of obtaining program call results as condensed XPCML:
<xpcml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="myXSD.xsd" version="4.0">
• IBM Toolbox for Java and JTOpen : Offers information about service packs, performance tips,
examples, and much more. You can also download a zipped package of this information, including
the Javadocs.
• IBM Toolbox for Java Frequently Asked Questions (FAQ) : Provides answers to questions about
performance, troubleshooting, JDBC, and more.
• IBM Toolbox for Java and JTOpen forum : Offers an effective way to communicate with the
community of Java programmers who use IBM Toolbox for Java and the IBM Toolbox for Java
developers themselves.
Java
Java is a programming language that allows you to develop portable object-oriented applications and
applets. Use the following sites to learn more about Java:
• IBM developerWorks® Java technology zone : Offers information, education, and tool to help you use
Java, IBM products, and other technologies to create business solutions.
• The Source for Java Developers : Offers information about the various uses for Java, including new
technologies.
Servlets
Servlets are small Java programs that run on a server and mediate requests from one or many clients
(each of which runs in a browser) to one or more databases. Because servlets are programmed in Java,
they can execute requests as multiple threads within a single process, thereby saving system resources.
Use the following sites to learn more about servlets:
• Java Servlet technology : Provides technical information, instructions, and tools to help you
understand and use servlets.
XHTML
XHTML is touted as the successor to HTML 4.0. It is based on HTML 4.0, but incorporates the extensibility
of XML. Use following sites to learn more about XHTML:
• The Web Developer's Virtual Library : Offers an introduction to XHTML, including examples and links
to additional information.
XML
Extensible Markup Language (XML) is a metalanguage that allows you to describe and organize
information in ways that are easily understandable by both humans and computers. A metalanguage
allows you to define a document markup language and its structure. Use the following sites to learn more
about XML:
• IBM developerWorks XML zone : Provides a site dedicated to the work IBM does with XML and how it
works to facilitate e-commerce
• W3C XML : Offers technical resources for XML developers.
• XML.com : Offers updated information about XML in the computer industry
• XML.org : Provides news and information about the XML community, including industry news,
calendars of events, and more.
• XML Cover Pages : Provides a comprehensive online reference work for XML, SGML, and related XML
standards, like XSL and XSLT.
Other references
• IBM HTTP Server for i : Provides information, resources, and tips about the IBM HTTP Server for i.
• IBM i Access : Offers information about IBM i Access, including downloads, FAQs, and links to
additional sites.
• IBM WebSphere® Host On-Demand : Provides information about the browser-based emulator that
offers support for S/390®, IBM i, and DEC/Unix emulation.
• IBM Support and downloads : Offers a portal to IBM hardware and software support.
For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property
Department in your country or send inquiries, in writing, to:
The following paragraph does not apply to the United Kingdom or any other country where such
provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION
PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR
IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of
express or implied warranties in certain transactions, therefore, this statement may not apply to you.
This information could include technical inaccuracies or typographical errors. Changes are periodically
made to the information herein; these changes will be incorporated in new editions of the publication.
IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this
publication at any time without notice.
Any references in this information to non-IBM Web sites are provided for convenience only and do not in
any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of
the materials for this IBM product and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way it believes appropriate without
incurring any obligation to you.
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the
exchange of information between independently created programs and other programs (including this
one) and (ii) the mutual use of the information which has been exchanged, should contact:
IBM Corporation
Software Interoperability Coordinator, Department YBWA
3605 Highway 52 N
Rochester, MN 55901
U.S.A.
If you are viewing this information softcopy, the photographs and color illustrations may not appear.
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business
Machines Corp., registered in many jurisdictions worldwide. Other product and service names might be
538 Notices
trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at
"Copyright and trademark information" at www.ibm.com/legal/copytrade.shtml.
Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or
trademarks of Adobe Systems Incorporated in the United States, and/or other countries.
IT Infrastructure Library is a registered trademark of the Central Computer and Telecommunications
Agency which is now part of the Office of Government Commerce.
Intel, Intel logo, Intel Inside, Intel Inside logo, Intel Centrino, Intel Centrino logo, Celeron, Intel Xeon,
Intel SpeedStep, Itanium, and Pentium are trademarks or registered trademarks of Intel Corporation or
its subsidiaries in the United States and other countries.
Linux® is a registered trademark of Linus Torvalds in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the
United States, other countries, or both.
ITIL is a registered trademark, and a registered community trademark of the Office of Government
Commerce, and is registered in the U.S. Patent and Trademark Office.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Cell Broadband Engine is a trademark of Sony Computer Entertainment, Inc. in the United States, other
countries, or both and is used under license therefrom.
Java and all Java-based trademarks and logos are trademarks of Oracle, Inc. in the United States, other
countries, or both.
Other product and service names might be trademarks of IBM or other companies.
Notices 539
540 IBM Toolbox for Java: IBM Toolbox for Java
IBM®