docmain.css" /> Using ECL - Reflection for the Web Reference Guide highlight.css">

2.1 Using ECL

Even if you are not a Java programmer, you can still take advantage of many ECL features from JavaScript. A built-in ECL module is provided with Reflection that integrates many of the ECL features with the LiveConnect features of JavaScript. When you use this module, called JSEventNotifier, you can write JavaScript code that registers listeners to receive event notification from the Reflection ECL; in many ways, this makes your JavaScript code act similar to a Java applet.

The JSAPI is the API documented in this section. API examples are shown primarily using JavaScript and VBScript; other scripting languages are typically similar in structure.

Because the API's focus is on logon tasks, it is recommended that you set all of your other configuration options using the Reflection terminal session menus, and then save those settings to a configuration file. See Configuring Reflection for the Web Sessions for more information about creating and using configuration files.

Then, in the web pages that you use to launch Reflection terminal sessions, script only those tasks needed to perform the logon.

2.1.1 What you need to use the API

If you plan to write scripts using JavaScript, JScript, or VBScript, you need only a text editor to write your scripts and a web browser to run them. Most web browsers support JavaScript to Java communications. VBScript requires Microsoft Internet Explorer for Windows.

If you plan to write Java applets using the ECL API, you need a Java development environment, such as JetBrains Inc.'s IntelliJ IDEA, the NetBeans IDE or Eclipse. The development environment you use must also support Java version 1.6 or higher. The ECL documentation has more details about setting up your development environment.

You can learn more about language syntax and how to program in JavaScript, VBScript, and Java from the many online resources and publications available.

2.1.2 How to use the API

Regardless of the scripting language you use when accessing the Reflection for the Web API, the basics are the same.

Incorporate the code into a session

There are two methods for incorporating JavaScript into your sessions:

  • Static page

  • Frameset - With this option you benefit from dynamic session generation.

Static page

  1. Create a session in the Administrative Console, Manage Sessions panel. Launch and save the session.

  2. Open the session from the list of sessions.

  3. Under Advanced, click More and scroll down to View Session HTML. Copy the HTML and save it to the deploy folder, giving it a name with a .html extension. You are automatically given a name for the applet that you can use in your code.

  4. In the applet HTML, locate param name=configuration and view the name of the session's config file.

  5. Copy the configuration file from deploy/dyncfgs to deploy.

  6. Add code to the HTML page.

Your user’s access the HTML page and deploy the session using the URL you provide them.

Frameset

  1. Define and save the session in the Administrative Console, Manage Sessions panel.

  2. Write your code and save it in a page in the session folder.

  3. Create an HTML frameset and save it in the deploy folder.

  4. Set the source of one frame to the full URL for the session. (This is the same URL you would use to directly access the session.)

  5. Set the source of the second frame to the code page.

  6. To deploy the session, give your users the URL to the HTML frameset.

Referencing the session applet

Manipulate the Reflection session through its API methods and properties by referencing the named session applet from your JavaScript code.

For example, a JavaScript line that displays the About box for the applet above would look like this:

var api = document.IBM3287.getAPI("JSAPI","IBM3287");
   api.showDialog( "aboutBoxDialog" );

You could also perform the same task in JavaScript using the document's applets[] property, which is an array of the applets in the document (use this technique if the applet's name contains spaces or punctuation characters):

document.applets["IBM3270Applet"].getAPI("JSAPI","IBM3270").showDialog( "aboutBoxDialog" );

If you don't name an applet, you can reference it in JavaScript by its index in the applets[] array, like this:

   // If the Reflection applet is the only one on the page, its index
   // in the applets[] array is 0.
   document.applets[0].getAPI("JSAPI","IBM3270").showDialog( "aboutBoxDialog" );

HINT: Because the Reflection for the Web API is intended primarily for scripting logon tasks, it is recommended that you set all of your other Reflection session configuration options using the Manage Sessions panel. Then, in the web pages that you use to launch the Reflection session, script only those tasks needed to perform the logon.

2.1.3 Using the API from JavaScript and VBScript

To use the API from scripting languages such as JavaScript and VBScript, you need only a text editor to write your script files, and a web browser to test and run them. In addition, the web browser must support the scripting language that you use, and scripting must be enabled in the browser. If scripting is either not available or not enabled, you can display an appropriate message using the HTML tags <noscript> and </noscript>.

To use API methods from a scripting language, name the Reflection session applet on the web page, and then reference the API from your script, as described in How to use the API.

  • If the Reflection session applet and the script code are both in the same HTML file, you reference the applet's name in the current document. Many of the API examples show how this is done, including a simple example that uses JavaScript buttons to open Reflection dialog boxes.

  • If the Reflection session applet and the script code are in different HTML files--for example, the applet is in one frame of a frameset file and the script is in a different frame of the frameset--you must supply the full frame name of the applet's document from your script code. The API examples include a web page that shows how to use JavaScript in a different HTML file than Reflection.

Scripting tips

When using the API from a scripting language, keep in mind the following:

  • Variables are typically untyped in the scripting language, but have specific data types in Reflection. If a variable cannot be converted to the appropriate type for the API method, a scripting error will occur.

  • You may find it convenient to store a reference to the Reflection API in a script variable, especially when working with a frameset (because the location of the applet can result in a long reference name). For example, instead of prefixing every API method with something like parent.rightframe.document.IBM3270Applet.getAPI("JSAPI","IBM3270"), you might create a variable called mAPI, and set it to the name of the Reflection applet like this:

     // In JavaScript
         var mAPI = parent.rightframe.document.IBM3270Applet.getAPI("JSAPI","IBM3270");

    or

    ' In VBScript
         Set mAPI = parent.rightframe.document.IBM3270Applet.getAPI("JSAPI","IBM3270")

    If you use this technique, keep in mind the scope of the variable and where in your HTML file the script is located. If you attempt to assign the variable before the applet or API exists, you may get a script error saying that the object has no properties, that the variable is not an object, or you may get a null return value for the API. Also notice the use of the Set statement in the VBScript example; the Set statement is required in VBScript to create a reference to an object.

  • The way you specify non-printing characters, such as escape sequences, control characters, etc., when waiting for strings or transmitting data to the host (for example, using transmitString), depends on your scripting language. If you're using JavaScript, you can generally use octal or hexadecimal notation; for example, the octal value \015 or the hex value \x0D for a carriage return. If you're using VBScript, you should use either a VBScript constant (such as vbCR for the carriage return character) or the Chr function to specify the character's value.

  • Most API methods do not generate specific errors (that is, they don't throw Java exceptions). However, many methods return True or False to indicate the success or failure of the method. You should check the return value of these methods before deciding how your script should proceed.

  • Depending on the scripting language you use, you may or may not be able to trap errors that occur in your script code. In JavaScript, you can trap errors with the Window.onerror event handler, to catch situations in which a JavaScript error occurs. In VBScript, you can trap errors in individual procedures with the On Error Resume Next statement.

    You might want to trap errors in cases where you're not certain that an API method is available; if a method is not available and you try to call it, a trappable error occurs. This is different than the situation described above, in which the method is available but fails to produce the desired result.

2.1.4 Accessing the ECL API from JavaScript

Even if you're not a Java programmer, you can still take advantage of many of the powerful features of the Reflection Emulator Class Library (ECL).

JSEventNotifier, a built-in module provided with Reflection for the Web, integrates many features of the Reflection ECL API with the LiveConnect features of JavaScript. When you use the JSEventNotifier module, you can write JavaScript code that registers listeners to receive event notification from the Reflection ECL; in many ways, this makes your JavaScript code act similar to a Java applet.

The JSEventNotifier module works as an ECL "attachment" class, a type of custom Java module that attaches itself to an existing Reflection session after the session has been initialized. Attachment classes usually fall into two categories:

  • Macro-like attachments, which are invoked on demand to perform a single task.

  • Monitor-like attachments, which are loaded during the session but don't perform any action until some event occurs or some screen appears, at which time they perform their task.

These types are not exclusive; an ECL attachment class may act like a macro initially, then wait and watch for a particular screen in order to perform another task.

Because the JSEventNotifier module uses LiveConnect, it can send messages to your waiting JavaScript; that means you don't have to write JavaScript code that continually polls the terminal session to determine if new data has arrived or if the connection state has changed.

Getting started with the JSEventNotifier module

If you already have installed the Reflection for the Web files on your web server, you already have the JSEventNotifier installed and ready to use. But first, you must modify the APPLET tag that controls your Reflection session, and you must write a bit of JavaScript code.

The following sections describe how to make these changes so the JSEventNotifier module gets loaded automatically when the Reflection session starts.

Modifying the Applet tag

To enable the JSEventNotifier module, add the following parameter to the APPLET tag of the web page that launches your Reflection terminal session:

<param name="onStartupJavaClass" value="com.wrq.eNetwork.ECL.modules.JSEventNotifier">

In addition, add the MAYSCRIPT attribute to the APPLET tag. The MAYSCRIPT attribute allows a Java applet (Reflection, in this case) to communicate with JavaScript, in addition to the JavaScript-to-Java communication that's always available.

Depending on how your session is generated, you might add these values using the Applet Parameters section of the Manage Sessions panel in the Administrative Console, or by manually editing the HTML page that launches your session.

An applet tag for an IBM 3270 session might look something like this:

<APPLET name="JSSession" CODE="com.wrq.rweb.Launcher" codebase="./ex"
      width=800 height=600 archive="Launcher.jar" MAYSCRIPT>
   <param name="launcher.sessions" value="IBM3270">
   <param name="prefsName" value="myIBMsession">
   <param name="hostURL" value="tn3270://myhost.mycorp.com">
   <param name="onStartupJavaClass" value="com.wrq.eNetwork.ECL.modules.JSEventNotifier">
</APPLET>

NOTE:If you use the JSEventNotifier module to receive initial notification, you can omit the parameter preloadJSAPI from the Reflection applet tag. If you do include both parameters, you should also include a JavaScript function called jsapiInitialized in your script. Some browsers, such as Firefox, will not call the ECLInitComplete function described next if the jsapiInitialized function is not also present but is called because the preloadJSAPI parameter is set.

Accessing the ECL API

When an HTML page that contains an APPLET tag like the one above is loaded by the web browser, the Reflection session launches. When the session has completed its initialization, it loads the module specified by the onStartupJavaClass parameter, in this case, JSEventNotifier.

After the JSEventNotifier module is loaded, it invokes a JavaScript function on your web page called ECLInitComplete, and it passes a reference to the JSEventNotifier class itself. (If you prefer to call the JavaScript function that receives the initial notification something different, specify the function name using the initCallback parameter in the Reflection APPLET tag.)

Once your JavaScript function receives a reference to the JSEventNotifier object, it can obtain the JavaScript API object by calling the getJSAPI() method. It can also use other methods available though the JSEventNotifier module for registering event listeners and setting up screen recognition systems.

The power in using the JSEventNotifier module is that when the ECLInitComplete function in your JavaScript gets invoked, you're assured that the Reflection terminal session is fully initialized and ready for scripting. This means you do not have to poll your Reflection session using the getInitialized() method to determine when Reflection is ready for scripting, making your scripts much more robust and efficient.

NOTE:If you want your script to receive initialization notification but do not need to use the ECL API functions available via the JSEventNotifier module, you can use the lighter-weight notification mechanism provided by the preloadJSAPI parameter. See Using Notification to Determine When Reflection Is Initialized for more information.

Example

The following example shows how to write a simple JavaScript that receives initialization notification, then sets up a listener to receive connection state changes.

<script language="JavaScript">
<!--
    var mJSNotifier = null;
    var mJSAPI = null;

    /*
     *  This function receives the initial notification when the
     *  Reflection session is initialized and the JSEventNotifier
     *  module is done loading. It stores references to the
     *  notifier module itself and the JSAPI object,
     *  sets up the connection listener, then starts the host
     *  communications.
     */
    function ECLInitComplete(jsNotifier)
    {
        mJSNotifier = jsNotifier;
        mJSAPI = mJSNotifier.getJSAPI();
        registerConnectionListener();
        mJSAPI.connect();
    }

    /*
     *  Adds a listener to receive connection state changes. The
     *  parameter "connectionCallback" specifies the name of the
     *  JavaScript function that should be invoked when the
     *  connection state listener is invoked.
     */
    function registerConnectionListener()
    {
        mJSNotifier.addConnectionCallback("connectionCallback");
    }

    /*
     *  Callback function for connection state changes. This is the
     *  function defined above in the registerConnectionListener()
     *  function. This function will be invoked by the JSEventNotifier
     *  module when the connection state changes. The "state" parameter
     *  will contain the current state of the connection, either "true"
     *  if connected, or "false" if disconnected. The parameter is a boolean,
   *  but Firefox seems to see it as a string, while Internet Explorer sees
	 *  it as a boolean.
     */
    function connectionCallback(state)
    {
	    if ( state == true || state == "true" )        // session became connected
      {
	        alert( "Session is connected!" );
      }
        else if ( state == false || state == "false" )  // session became disconnected 
	    {
          alert( "Session is disconnected!" );
	    }
    }
//-->
</script>

The JSEventNotifier module is part of the ECL API and its methods are detailed in the ECL documentation that's part of the ECL development kit.

HINT:The JSEventNotifier module also provides methods for accessing many of the ECL API objects, including ECLSession, ECLPS, ECLOIA, and others. Although you can access these objects from browser-based scripting languages, they are not fully compatible with these languages due to browser security restrictions, and invoking methods on these objects may result in script failures (as indicated by exceptions in the Java console). You should restrict your use of JSEventNotifier methods to those methods provided by the JSEventNotifier class itself, and to the methods in the JSAPI object you obtain.

2.1.5 Timing issues when scripting Reflection

When working with the API, there are situations where timing and synchronization can become an issue between your script and the Reflection terminal session applet. For example:

  • You want to perform a task automatically after a Reflection session starts, perhaps to open a dialog box for the user. In this case, you need to make sure that the Reflection session is initialized before you open the dialog box. See Determining if Reflection Is Initialized for more information.

  • You want to get information from a Reflection session dialog box before proceeding with your script. See Synchronizing Dialog Box Input for more information.

  • You want to automate a host logon procedure by transmitting a user name and password after the appropriate host prompts have been received. In this case, you need to wait for the appropriate host prompts before transmitting the responses. See Waiting for Strings and Transmitting Data for more information.

2.1.6 Browser dependencies when using the API

The two most popular Microsoft Windows-based web browsers--Microsoft Internet Explorer and Firefox--both support JavaScript (along with Java). JavaScript to Java communication is also supported in many web browsers on other platforms, including Mozilla-based browsers (various platforms) and Apple Computer's Safari browser (version 1.2 or later) on the Macintosh. Microsoft Internet Explorer for Windows also provides VBScript, a scripting language with a syntax and structure similar to Visual Basic and Visual Basic for Applications, but not similar to JavaScript. If you write scripts using VBScript, they can run only in Internet Explorer for Windows.

If you expect to have multiple instances of Reflection emulation applets running at the same time and you need to access them using the API, it is important that each applet instance have a unique name (which you can specify using the Reflection prefsName parameter in the <applet> tag), and that your script use that unique name.

If you're using static web pages, one way to generate a unique name for each applet is to generate the applet tag and the scripts that reference the applet dynamically using JavaScript, and generate a unique applet name each time the web page is loaded. You could do this by getting the current system time when the page is loaded, and using that as the applet name.

Using the Java plug-in with the API

If you're running Reflection using the Java Plug-in, you can access API methods via JavaScript (and VBScript in Internet Explorer) as you normally do, but you must also do the following:

Add the parameter preloadJSAPI to the Reflection session and set the value to "true".

For more information about using the Java Plug-in with Reflection, see.

2.1.7 API Reference

This is a list of Reflection for the Web API methods, properties, and dialog box constants. Properties are shown with their type (such as "String property") and read/write status; properties are manipulated using the "property accessor methods" listed below. Dialog box constants are used with the showDialog() method listed below. The list is arranged alphabetically.

aboutBoxDialog

Dialog box constant. When used with the showDialog method, opens the About Reflection dialog box.

public void showDialog( "aboutBoxDialog")

apiExit

Method. Closes the Reflection for the Web applet without invoking the Java class specified by an onExitJavaClass applet parameter.

public void apiExit()

apvuReceiveFile()

Method. Transfers a file from an IBM mainframe to the desktop computer, using the APVUFILE transfer protocol. This method is valid only when using a double-byte enabled version of Reflection for the Web.

public int apvuReceiveFile( String localFile, 
String hostFile,                           
int transferType,                            
boolean showStatus )

apvuSendFile()

Method. Transfers a file from the desktop computer to an IBM mainframe, using the APVUFILE transfer protocol. This method is valid only when using a double-byte enabled version of Reflection for the Web.

public int apvuSendFile( String localFile,                         String hostFile,                         
int transferType,                         
boolean showStatus )

autoPrintLineFeed

Property. This property determines whether Reflection automatically wraps to a new line if the host attempts to print a character beyond the edge of the host-defined page. Read/write.

Setter: public void setBoolean( "autoPrintLineFeed", boolean enable )

Getter: public boolean getBoolean( "autoPrintLineFeed" )

buttonPaletteConfigure

Dialog box constant. When used with the showDialog method, opens the Button Palette Setup dialog box.

cancelPrintJob()

Method. Cancels the current print job by sending a Cancel Print message to the host. The printer continues to print until all data already sent to the printer is done printing.

public void cancelPrintJob()

colorConfigure

Dialog box constant. When used with the showDialog method, opens the Color Setup dialog box.

public void showDialog( "colorConfigure" )

connect()

Method. Establishes a connection to the host computer specified in the applet parameter hostURL. Via the API, you can use the getHostURL method to specify the host URL.

public void connect()

declans

Property. Specifies the text of an answerback message that gets sent to the host in response to an ENQ character. This property is linked to the Answerback message box in the Advanced Terminal Setup dialog box. Read/write. The name of this property derives from the mnemonic for the VT terminal's "Load Answerback Message" control sequence.

Setter: public void setString( "declans", String message)
Getter: public String getString( "declans" )

deviceName

Property. Indicates the device name (also known as the LU name) that the session is currently connected to. This property is linked to the Device name box in the Session Setup dialog box. Read/write.

Setter: public void setString("deviceName", String inDevice )
Getter: public String getString("deviceName")

disconnect()

Method. Disconnects the current session.

public void disconnect()

display (string, boolean)

Method. Displays a string of text in the terminal window at the current cursor position, without sending the text to the host computer (compare this with the transmitString method). This method can be handy for displaying informational messages in the terminal window.

public void display (String inString, boolean interpret)

emulateFormFeed

Property. When this property is True (the default), a form feed in the data stream closes the current page and starts a new one. When this property is False, Reflection determines how many line feeds are required to reach the bottom of the page (as defined by the host) and then sends that many line feeds. Read/write.

Setter: public void setBoolean( "emulateFormFeed", boolean enable)
Getter: public boolean getBoolean( "emulateFormFeed" )

enableHotspots

Property. Indicates whether hotspots are enabled or not. This property is linked to the Enable hotspots check box in the Hotspot Setup dialog box. Read/write.

Setter: public void setBoolean("enableHotspots", boolean enable)
Getter: public boolean getBoolean("enableHotspots")

exit()

Method. Closes the Reflection for the Web applet.

public void exit()

exportKeymap (OutputStream)

Method. Saves the terminal session's current keymap, independent of any preference or configuration information. Keymap files can be imported using the importKeymap API. This method is for use only from Java.

public boolean exportKeymap(OutputStream outStream)

fileTransferConfigure

Dialog box constant. When used with the showDialog method, opens the File Transfer Setup dialog box.

public void showDialog( "fileTransferConfigure")

findField (int, int, int)

Method. Finds a field with the specified attributes. You can then get the location, length, and contents of the found field using other API methods.

public boolean findField(int inRow,
                             int inCol,
                             int direction,
                             int inAttribute )

findText (String, int, int, boolean)

Method. Finds a text string in the terminal window. For this method to return True, the text must already be present on the display. If your goal is to find text that's either already on the display or will appear on the display from datacomm, use the waitForDisplayString method instead.

public boolean findText(String inString,
                               int inRow,
                               int inCol,
                               boolean ignoreCase) 

fitHostPageX

Property. Reflection can mediate between the page width, as specified by the host, and the printer to assure that the printout will fit correctly on the page. Reflection does this by scaling. If the host does not define a page size, or if Override host page format is selected, the page width is derived from the Columns setting on the Page tab in the Print Setup dialog box.

Setter: public void setBoolean("fitHostPageX", boolean scaleWidth)
Getter: public boolean getBoolean("fitHostPageX")

fitHostPageY

Property. Reflection can mediate between the page height, as specified by the host, and the printer to assure that the printout will fit correctly on the page. Reflection does this by scaling. If the host does not define a page size, or if Override host page format is selected, the page height is derived from the Rows setting on the Page tab in the Print Setup dialog box.

Setter: public void setBoolean("fitHostPageY", boolean scaleHeight) 
Getter: public boolean getBoolean("fitHostPageY")

foundFieldEndColumn

Property. Indicates the last column number of a field located using the findField method. Read only.

public int getInteger( "foundFieldEndColumn")

foundFieldEndRow

Property. Indicates the last row number of a field located using the findField method. Read only.

public int getInteger("foundFieldEndRow")

foundFieldLength

Property. Indicates the length of a field located using the findField method. Read only.

public int getInteger("foundFieldLength")

foundFieldStartColumn

Property. Gets the first column number of a field located using the findField method. Read only.

public int getInteger("foundFieldStartColumn")

foundFieldStartRow

Property. Gets the first row number of a field located using the findField method. Read only.

public int getInteger("foundFieldStartRow")

foundTextStartColumn

Property. Gets the starting column number in which the text string located using the findText method was found. Read only.

public int getInteger("foundTextStartColumn")

foundTextStartRow

Property. Gets the starting row number in which the text string located using the findText method was found. Read only.

public int getInteger("foundTextStartRow")

ftpCd (String)

Method. Changes directories on the FTP server. This method is valid only after an FTP login is successful. If the FTP session is disconnected, then reconnected, the server directory must be set again. This method is useful when transferring multiple files using the ftpSendFiles and ftpReceiveFiles methods, which transfer files to and from the current local and server working directories.

public void ftpCd(String dir)

ftpConfigure

Dialog box constant. When used with the showDialog method, opens the FTP Connection Setup dialog box for configuring connections to an FTP server.

public void showDialog("ftpConfigure")

ftpDefaultFolders

Dialog box constant. When used with the showDialog method, opens the FTP Select Default Directory dialog box for configuring the default working directories.

public void showDialog("ftpDefaultFolders")

ftpDisconnect ()

Method. Disconnects the current FTP session.

public boolean ftpDisconnect()

ftpGetLastServerResponse()

Method. Returns the text message from the FTP server received as a result from the last user command.

public String ftpGetLastServerResponse()

ftpLCd (String)

Method. Changes the current working directory on the local machine. This method is valid only after an FTP login is successful. If the FTP session is disconnected, then reconnected, the local directory must be set again. This method is useful when transferring multiple files using the ftpSendFiles and ftpReceiveFiles methods, which transfer multiple files to and from the current local and server working directories.

public void ftpLCd(String dir)

ftpLogin (String, String, String, boolean)

Method. Logs into an FTP or SFTP server in preparation for transferring files. This method supports both FTP and SFTP transfers, as well as FTP transfers through the Reflection security proxy server.

public boolean ftpLogin( String HostName,
                         String userName,
                         String passWord,
                         String acct,
                         boolean usePASV )

ftpOptions

Dialog box constant. When used with the showDialog method, opens the FTP Options dialog box window for configuring FTP options.

public void showDialog("ftpOptions")

ftpProtocol

Property. Specifies the protocol to use for FTP file transfers. This property is linked to the Connection type drop-down menu in the Connection Setup dialog of the FTP client. Typically, you do not need to set this property unless you want to perform SFTP file transfers; the default value is for FTP transfers. Read/write.

Setter: public void setString("ftpProtocol", String protocol) 
Getter: public String getString("ftpProtocol")

ftpPwd()

Method. Returns the current working directory on the FTP server. This method is useful when you are sending and receiving multiple files.

public String ftpPwd()

ftpReceiveFile (String, String, Int)

Method. Receives an FTP file.

public boolean ftpReceiveFile( String remoteFile,
                               String localFile,
                               int transferMethod )

ftpReceiveFiles (String, int)

Method. Receives multiple files using FTP.

public boolean ftpReceiveFiles( String remoteFiles,
                                int transferMethod )

ftpSendFile (String, string, boolean, int)

Method. Sends a file using FTP.

public boolean ftpSendFile( String remoteFile,
                            String localFile,
                            boolean mkDirectories,
                            int transferMethod )

ftpSendFiles (String, int)

Method. Sends multiple files using FTP.

public boolean ftpSendFiles(String localFiles, int transferMethod)

ftpUI

Dialog box constant. When used with the showDialog method, opens the FTP main window for performing file transfers between the desktop computer and an FTP server.

public void showDialog("ftpUI")

getAPI()

Method. Gets a reference to the API object on which all other API methods are invoked.

getBoolean(String)

Property accessor method. Gets the value of a boolean property. This method is available in all session types, but the valid properties vary according to emulation.

public boolean getBoolean( String propName )

propName The name of the property whose value you want to get from the list of properties below.

Properties that can use this method:

  • autoPrintLineFeed

  • emulateFormFeed

  • enableHotspots

  • fitHostPageX

  • fitHostPageY

  • showHotspots

  • streamIsEncrypted

getCoordinateBase()

Method. Gets the current screen coordinate numbering base, either 0-based or 1-based coordinates.

public int getCoordinateBase()

getCursorColumn()

Method. Gets the terminal window display column in which the host cursor is currently located.

public int getCursorColumn()

getCursorPosition()

Method. Gets the terminal window display row and column in which the host cursor is currently located.

public Dimension getCursorPosition()

getCursorRow()

Method. Gets the terminal window display row in which the host cursor is currently located.

public int getCursorRow()

getDisplayText (int, int,i nt, int, boolean, string)

Method. Gets text from the display. Form 1 of getDisplayText lets you specify a starting row and column, an ending row and column, and whether the text selection should be linear or rectangular (see the Notes section below for examples of these types of selections); the text retrieved is formatted with the line ending characters you specify separating each line of display text.

Form 2 of getDisplayText lets you specify a starting row and column and the number of characters to retrieve. If the number of characters remaining on the display line is less than the number of characters you request, only the characters remaining on the line are returned.

Form 1: public String getDisplayText( int inStartRow,
                                      int inStartCol,
                                      int inEndRow,
                                      int inEndCol,
                                      boolean isRect,
                                      String inLineEnd )
                                      
Form 2: public String getDisplayText( int inStartRow,
                                      int inStartCol,
                                      int numCharacters )

getFieldText (int, int, int)

Method. Gets the contents of a host field from the display. You specify the row and column of the field whose text you want returned and the number of characters to retrieve. To use this method, first use the findField method to find a field on the display with specific attributes. After the desired field is located, use the foundFieldStartRow, foundFieldEndRow, foundFieldStartColumn, foundFieldEndColumn, and foundFieldLength properties to determine the coordinates and length of the found field, and pass the appropriate values to the getFieldText method.

public String getFieldText(int inRow, int inCol, int inChars)

getHostName()

Method. Gets the host name for the current session. This property is linked to the Host name or IP address box in the Session Setup dialog box.

public String getHostName()

getHostStatusText (int, int)

Method. Gets text the host application has displayed on the status line. Returns a value only if the Status Line control in the Options Panel for the Terminal Setup dialog box is set to Host Writeable.

public String getHostStatusText(int inStartCol, int numCharacters)

getHostURL()

Method. Gets the host URL for the current session, including the transport type, host name, and port. This lets you get all of the current host connection information with a single method. To get the individual values that comprise a host URL, use the getHostName and getPort methods, and the transportType property.

public String getHostURL()

getInitialized()

Method. Indicates whether the Reflection terminal session applet has been fully initialized. You should not attempt to make other API calls until you're sure that the session is initialized, which you can determine with this method. Read only.

public int getInitialized()

getInteger(String)

Property accessor method. Gets the value of an integer property. This method is available in all session types, but the valid properties vary according to emulation.

public int getInteger( String propName)

Properties that can use this method:

  • foundFieldEndColumn

  • foundFieldEndRow

  • foundFieldLength

  • foundFieldStartColumn

  • foundFieldStartRow

Returns the value of the specified property.

getPort()

Method. Gets the protocol port for the current session. This property is linked to the Port box in the Session Setup dialog box.

public int getPort()

getPrintToFileFolder()

Method. Gets the name of the folder to which printer output is directed when printing to a file. Use the method getPrintToFileName to get the name of the file that is to receive the print output. This method is relevant only when the printToFile property is set to True.

public String getPrintToFileFolder()

getPrintToFileName()

Method. Gets the name of the file in which printer output is saved when printing to a file. Use the method getPrintToFileFolder to get the name of the folder in which the output file is stored. This method is relevant only when the printToFile property is set to True.

public String getPrintToFileName()

getString(String)

Property accessor method. Gets the value of a String property. This method is available in all session types, but the valid properties vary according to emulation.

public String getString( String propName)

Properties that can use this method:

  • declans (load answerback message)

  • deviceName

  • printDBCSScale

  • terminalModel

  • transportType

Returns the string value of the specified property.

ignoreUserTyping

Property. Determines whether keystrokes typed by the user into the terminal display should be processed as usual or should be ignored. During lengthy scripting operations, it may be desirable to have user keystrokes ignored so they do not interfere with the operation. After the scripting operation is complete, user typing can be re-enabled. When user typing is ignored, only keystrokes entered in the terminal display are ignored; accelerator keys used to trigger menu commands are still processed. Read/write.

Setter: public void setBoolean( "ignoreUserTyping", boolean ignore)
Getter: public boolean getBoolean("ignoreUserTyping") 

importKeymap (InputStream)

Method. Opens a keymap and applies it to the current session. A keymap file can be created with the exportKeymap API. This method is for use only from Java; see the Notes section below for more information.

public boolean importKeymap( InputStream inStream)

indReceiveFile (String, string, boolean, boolean)

Method. Transfers a file from an IBM mainframe to the desktop computer, using the IND$FILE transfer protocol. Currently, only structured field IND$FILE transfers are supported.

public int indReceiveFile(String localFile, String hostFile, boolean isASCII, boolean showStatus)

indSendFile (String, string, boolean, boolean)

Method. Transfers a file from the desktop computer to an IBM mainframe, using the IND$FILE transfer protocol. Currently, only structured field IND$FILE transfers are supported.

public int indSendFile(String localFile, String hostFile, boolean isASCII, boolean showStatus) 

isConnected()

Method. Indicates whether the session currently has a host connection.

public boolean isConnected()

keyMapConfigure

Dialog box constant. When used with the showDialog method, opens the Keyboard Setup dialog box.

public void showDialog( "keyMapConfigure")

keyPaletteOptions

Dialog box constant. This constant was removed starting with Reflection for the Web version 4.1, because the Terminal Keyboard Options dialog box was removed.

loadJavaClass()

Method. Loads the specified Java class to run as an "attachment class." Java attachment classes are a feature of the Reflection Emulator Class Library (ECL) that allow Java code to attach to the currently running terminal session and perform automated tasks. This method is equivalent to the Load Java Class command in the Macro menu.

public void loadJavaClass( String className)

mouseMapConfigure

Dialog box constant. When used with the showDialog method, opens the Mouse Setup dialog box.

public void showDialog( "mouseMapConfigure")

playbackMacro (macroName)

Method. Plays back a previously recorded macro.

public boolean playbackMacro(String macroName)

printDBCSScale

Property. By default, Reflection uses enough space for two single-byte columns to print one column of double-byte data. For example, if you've set up your page for 80 columns, you'll be able to print 40 columns of double-byte data. This parameter gives you the option of printing two double-byte columns in the same amount of space as three single-byte columns. So if you set up your page for 80 columns, you'll be able to print about 53 columns of double-byte data. Read/write.

Setter: public void setString("printDBCSScale", String ratio)
Getter: public String getString("printDBCSScale")

printerConfigure

Dialog box constant. When used with the showDialog method, opens the Print Setup dialog box.

public void showDialog( "printerConfigure")

printToFile

Property. Indicates whether printer output is to be directed to a printer or to a text file. This property is linked to the Send output to printer and Send output to file options in the Print Setup dialog box. By default, Send output to printer is selected and this property is False, and printer output is directed to a printer.

Setter: public void setBoolean("printToFile", boolean enable)
Getter: public boolean getBoolean("printToFile")

requestDisplayFocus()

Method. Requests that the Reflection terminal window should receive the input focus. If you include buttons or other form elements on your web page to perform actions via the API, you can use this method to return input focus to the Reflection session so the user can type at the terminal cursor; otherwise, the input focus may remain on the form element, and a mouse click in the terminal window is required to give focus back to the Reflection session.

public void requestDisplayFocus()

resetUserPreferences()

Method. Resets the session settings in the user preference file to the defaults established by the administrator. The user preference file contains the user's personal Reflection terminal session customizations and is stored on each user's computer. The resetUserPreferences method resets the preference file for the session by replacing the file with one containing no preference information. After the preference file is reset, the Reflection session must be restarted for the default session settings to take effect.

The specific settings that can be stored in the user preference file depend on the options that the administrator has selected for user preferences; see Configuring Reflection: User Preferences for more information about user preferences.

Preference files are stored on the user's computer in the reflectionweb sub folder under the user home folder. The user home varies according to operating system, browser, and virtual machine. To find the home folder for a given operating system/browser/virtual machine combination, look for USER_HOME in the Java console.

The name of the user preference file that gets reset is based on the value of the applet's prefsName parameter, and if that doesn't exist, on the name attribute in the <applet> tag of the web page, with a ".pref" extension added. For example, if the name attribute for the applet is IBM3270Applet, the name of the preferences file will be IBM3270Applet.pref. Avoid naming an applet using characters that are invalid for the desktop platform's file naming convention; for example, Windows operating systems do not allow file names to contain these characters: \ / : * ? " < > |.

public void resetUserPreferences() throws IOException

saveUserPreferences()

Method. Saves the current session settings to the user preference file, a file contains the user's personal Reflection terminal session customizations and is stored on each user's computer.

The settings that can be stored depend on the options that the administrator has selected in Reflection's Set User Preference Rules dialog box (available from the Administration menu)--if no preference rules are configured, an empty user preference file is saved.

Preference files are stored on the user's computer in the reflectionweb sub folder under the user home folder. The user home varies according to operating system, browser, and virtual machine. To find the home folder for a given operating system/browser/virtual machine combination, look for USER_HOME in the Java console.

The name of the user preference file is based on the value of the applet's prefsName parameter, and if that doesn't exist, on the name attribute in the <applet> tag of the web page, with a ".pref" extension added. For example, if the name attribute for the applet is IBM3270Applet, the name of the preferences file will be IBM3270Applet.pref. Avoid naming an applet using characters that are invalid for the desktop platform's file naming convention; for example, Windows operating systems do not allow file names to contain these characters: \ / : * ? " < > |.

If the <applet> tag does not define a name attribute, a user preference file will not be saved.

To disable the loading of the user preference file, set the loadUserPrefs parameter in the <applet> tag of the Reflection web page to false.

public void saveUserPreferences() throws IOException

screenPrint()

Method. Prints the contents of the terminal window display, using the options selected in the Print Setup dialog box.

public void screenPrint()

sessionConfigure

Dialog box constant. When used with the showDialog method, opens the Session Setup dialog box.

public void showDialog( "sessionConfigure")

setBoolean (String, boolean)

Property accessor method. Sets the value of a boolean property. This method is available in all session types, but the valid properties vary according to session type.

public void setBoolean( String propName, boolean value)

Value - The value to set the property to--either True or False.

Properties that can use this method:

  • autoPrintLineFeed

  • emulateFormFeed

  • enableHotspots

  • fitHostPageX

  • fitHostPageY

  • ignoreUserTyping

  • showHotspots

setCoordinateBase()

Method. Specifies whether methods that perform operations using screen coordinates should use 0-based numbering or 1-based numbering.

public void setCoordinateBase( int base)

setCursorPosition (int,int)

Method. Moves the host cursor to the specified position.

public void setCursorPosition(int inRow, int inCol) 

setHostURL (String)

Method. Sets the host URL for the current session, including the transport, host name, and port. If you use this method to change the host URL after a connection has already been established, the new value does not take effect until you disconnect then reconnect.

public void setHostURL(String hostURL) throws MalformedURLException

setInteger (String, int)

Property accessor method. Sets the value of an integer property. This method is available in all session types, but the valid properties vary according to the sessions type.

public void setInteger( String propName, int value)

setPrintToFileFolder (String)

Method. Sets the name of the folder to which printer output is directed when the output is sent to a file. Use the method setPrintToFileName to set the name of the file that should receive the print output. This method is relevant only when the printToFile property is set to True.

public void setPrintToFileFolder(String folderName)

setPrintToFileName (String)

Method. Sets the name of the file to which printer output is to be sent. Use the method setPrintToFileFolder to set the name of the folder in which the output file is to be stored. This method is relevant only when the printToFile property is set to True

public void setPrintToFileName(String fileName)

setString (String, string)

Property accessor method. Sets the value of a String property. This method is available in all session types, but the valid properties vary according to session type.

Properties that can use this method:

  • declans

  • deviceName

  • printDBCSScale

  • terminalModel

public void setString(String propName,String value)

sftpAllowUnknownHost

Property. Indicates how SFTP connections should handle unknown hosts. This property is linked to the Allow unknown hosts options in the Secure Shell Client Settings dialog box for FTP. The default value of 2, "ask," causes Reflection to prompt when encountering a host whose authenticity cannot be established. If you are automating a logon procedure and do not want the user to receive any prompts during the logon, set the value of this property to 0, for "always allow." Read/write.

Setter: public void setInteger( "sftpAllowUnknownHost",int value)                                
Getter: public int getInteger("sftpAllowUnknownHost")

showDialog (String)

Method. Opens the specified dialog box. This method is available in all seesion types, but the valid dialog box names vary according to emulation

public void showDialog(String dialog)

These dialog boxes can be opened using this method:

  • aboutBoxDialog

  • buttonPaletteConfigure

  • colorConfigure

  • fileTransferConfigure

  • fileTransferUI

  • ftpConfigure

  • ftpDefaultFolders

  • ftpOptions

  • ftpUI

  • keyMapConfigure

  • mouseMapConfigure

  • printerConfigure

  • sessionConfigure

  • terminalConfigure

The showDialog method opens Reflection dialog boxes asynchronously; it does not wait for the user to close the dialog box before continuing. This means that you can issue other Reflection method calls and perform other script actions while a dialog box is open. In addition, this method does not return any result codes to indicate how the user closed the dialog box (for example, by clicking OK or Cancel).

showHotspots

Property. Indicates whether hotspots are set to show on the terminal window display or are set to be hidden. This property is linked to the Show hotspots check box in the Hotspot Setup dialog box. Read/write.

Setter: public void setBoolean( "showHotspots", boolean visible)
Getter: public boolean getBoolean( "showHotspots") 

sshAllowUnknownHost

Property. Indicates how SSH connections should handle unknown hosts. This property is linked to the Allow unknown hosts options in the Secure Shell Client Settings dialog box. The default value of 2, "ask," causes Reflection to prompt when encountering a host whose authenticity cannot be established. If you are automating a logon procedure and do not want the user to receive any prompts during the logon, set the value of this property to 0, for "always allow." Read/write.

Setter: public void setInteger( "sshAllowUnknownHost", int value)
Getter: public int getInteger( "sshAllowUnknownHost") 

streamIsEncrypted

Property. Indicates whether the terminal session has an encrypted connection. Read only.

public boolean getBoolean( "streamIsEncrypted")

terminalConfigure

Dialog box constant. When used with the showDialog method, opens the Terminal Setup dialog box.

public void showDialog("terminalConfigure")

terminalModel

Property. Indicates the terminal model of the current terminal session. This property is linked to the Terminal model list in the Session Setup dialog box. Read/write.

Setter: public void setString( "terminalModel", String model)
Getter: public String getString("terminalModel") 

transmitString (String)

Method. Transmits a string of characters to the host as if the user had typed the string at the current cursor position. (Compare this with the display method).

public void transmitString( String inString)

transportTerminalKey

Method. Transmits a single non-character keystroke to the host as if the user had pressed that key on the host keyboard

public void transmitTerminalKey( int inKey)

transportType

Property. Gets the transport type of the current session. This property is linked to the Type list in the Transport options section of the Session Setup dialog box. Read only.

public String getString( "transportType")

waitForCursorEntered (int, int, long)

Method. Waits for the cursor to enter a specific row and column location in the terminal window.

public boolean waitForCursorEntered( int inRow, int inCol, long timeout)

waitForCursorLeft (int, int, long)

Method. Waits for the cursor to leave a specific row and column location in the terminal window.

public boolean waitForCursorLeft(int inRow, int inCol, long timeout)

waitForDisplayString (String, long)

Method. Waits for a string of characters to appear in the terminal window, and optionally, at a specific row and column. For HP emulators, if you want to wait for a string to appear in the datacomm stream (which may also include non-printing characters such as control characters), use the waitForString or waitForHostPrompt methods instead. For VT emulators, if you want to wait for a string to appear in the datacomm stream (which may also include non-printing characters such as control characters), use the waitForString method instead.

Form 1: public boolean waitForDisplayString(String inString, long timeout)
Form 2: public boolean waitForDisplayString(String inString, int inRow,   int inCol, long timeout)

waitForDisplayStrings (Vector, long)

Method. Waits for one or more strings of characters to appear in the terminal window. In HP and VT sessions, waitForDisplayStrings returns true if one of the strings appears in the visible terminal window or in the text that has scrolled off the screen into the scrollback buffer. If you are using one of these emulators and want to wait for strings to appear in the datacomm stream (which may include non-printing characters such as control characters), use the waitForStrings method. For HP emulators, you can also use the waitForHostPrompt method, which waits for the specified string plus the host prompt character.

public int waitForDisplayStrings(Vector inStrings,  long timeout) 

waitForHostPrompt (String, long)

Method. Waits until the specified string plus the host prompt character is received in the incoming datastream. The HP host prompt character (typically a DC1 character that follows the MPE colon prompt) indicates that the host is ready to receive input. If no host prompt character is being used or the host prompt is disabled (with Inhibit handshake and Inhibit DC2 in the Advanced HP Terminal Items dialog box of the Terminal Setup dialog box), this method waits for only the specified string, acting exactly like the waitForString method. You can configure which host prompt character to wait for, and whether the host prompt character is used, with the Host prompt and Use host prompt options in the Advanced HP Terminal Items dialog box of the Terminal Setup dialog box.

public boolean waitForHostPrompt(String inString,long timeout)

waitForIncomingData (long)

Method. Waits until any data is received from the host. Although this method is available in any type of emulation, it is used primarily with VT and HP sessions.

public boolean waitForIncomingData(long timeout)

waitForKeyboardLock (long, long)

Method. Waits a specified time for the keyboard to be locked for a specified duration.

public boolean waitForKeyboardLock(long duration, long timeout)

waitForKeyboardUnlock (long, long)

Method. Waits a specified time for the keyboard to be unlocked for a specified duration.

public boolean waitForKeyboardUnlock(long duration, long timeout)

waitForString (String, long)

Method. Waits for a string of characters to appear in the incoming datastream. In contrast to the waitForDisplayString method, which waits for characters to appear in the terminal window, this method allows you to wait for characters that may not appear in the terminal window, such as escape sequences and other non-printing characters. For IBM sessions, use waitForDisplayString instead of this method.

public boolean waitForString(String inString,long timeout)

waitForDisplayString (String, boolean)

Method. Waits for one or more character strings to appear in the incoming datastream. In contrast to the waitForDisplayStrings method, which waits for characters to appear in the terminal window, this method allows you to wait for characters that may not appear in the terminal window, such as escape sequences and other non-printing characters. For IBM sessions, use waitForDisplayString.

public int waitForStrings(Vector inStrings,long timeout) 

waitWhileDisplayString (String, int, int, long, boolean)

Method. Waits for a string to leave the display. If the string is not already on the display when this method is called, the method returns True immediately (that is, the string has "left" the display because it was never there to begin with). This method is typically used after determining that a desired string is in place on the display; for instance, as the result of calling the waitForDisplayString or FindText method.

Form 1: public boolean waitWhileDisplayString(String inString, boolean caseSens)
Form 2: public boolean waitWhileDisplayString(String inString, long timeout)
Form 3: public boolean waitWhileDisplayString(String inString,int inRow, nt inCol,long timeout boolean caseSens)

xfr400ReceiveFile (String, string, boolean)

Method. Transfers data from an AS/400 host to the desktop computer, using the data transfer feature.

public int xfr400ReceiveFile(String localFile,String hostFile, boolean showStatus) 

xfr400SendFile (String, string, boolean)

Method. Transfers data from the desktop computer to an AS/400 host, using the data transfer feature.

public int xfr400SendFile(String localFile,String hostFile, boolean showStatus) 

2.1.8 API Examples

The examples below show how to perform different types of tasks with the Reflection for the Web API. You can cut and paste the sample code directly from the example page into a text editor, and then save the document with a .html extension.

If you store your web pages in the deploy folder that's created when you install Reflection, the examples should work with the codebase attribute set to ./ex. If you store your pages in a different folder, you'll need to first change the codebase attribute in the <applet> tag of the examples before they will work. Also, in examples that use the hostURL parameter to specify the name of a host computer, you should change the value to a host name appropriate to your network.

HINT:If the sample code is not formatted correctly after pasting it into your text editor, try reselecting the sample code, making sure that you extend your selection to the blank line after the end of the sample. Some browsers, such as Internet Explorer, do not copy all of the code formatting unless an ending paragraph mark is also selected. You can ensure that the paragraph mark is included in the selection by including the blank line after the last line of code.

Basic JavaScript Examples

Using JavaScript in the same HTML file as Reflection

In this example, JavaScript is used to interact with an IBM 3270 applet embedded in the browser window, where both the applet and the JavaScript code are in the same HTML file. Comments in the JavaScript explain the action. Also see the example of using JavaScript in a different HTML file than Reflection.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>API Sample: JavaScript in the Same HTML File as Reflection</title>
</head>
<body>

<!--
   The <applet> tag defines a simple Reflection applet for
   IBM 3270 emulation. To use this example, change the hostURL
   parameter to one appropriate for your network.
-->
<applet mayscript name="IBM3270Applet"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="800" height="500"
        archive="Launcher.jar">
    <param name="hostURL" value="tn3270://payroll">
    <param name="autoconnect" value="true">
    <param name="frame" value="false">
    <param name="launcher.sessions" value="IBM3270">
    <param name="preloadJSAPI" value="true">
</applet> 
<!-- 
   <Form> buttons give the user access to the Color Setup and
   Button Palette Setup dialog boxes. The onClick event handler
   is used to invoke the API methods without requiring separate
   JavaScript functions. The Reflection applet is referenced
   on the page using the same name as defined above in the <applet> tag.
-->
<form>
<input type="button" Name="ColorSetup" Value="Color Setup"
       onClick='document.IBM3270Applet.getAPI("JSAPI","IBM3270").showDialog( "colorConfigure" )'>
<input type="button" Name="ButtonPalette" Value="Button Palette Setup"
       onClick='document.IBM3270Applet.getAPI("JSAPI","IBM3270").showDialog( "buttonPaletteConfigure" )'>
</form>
</body>
</html>

Using JavaScript in a different HTML file than Reflection

In this example, JavaScript is used to interact with a Reflection terminal session applet embedded in a browser window frameset. The applet is in one HTML file, which is displayed in the lower frame of the frameset file, and the JavaScript code is in a different HTML file, which is displayed in the upper frame. Comments in the JavaScript explain the action. Also see the example of using JavaScript in the same HTML file as Reflection.

First, here's the HTML for the frameset file:

   <html>
   <frameset rows="50,*">
       <frame name="codeframe" src="codeframe.html">
       <frame name="appletframe" src="appletframe.html">
   </frameset>
   </html>

Next, here's the HTML for the codeframe.html file, which is the upper frame of the frameset and contains the JavaScript code:

   <html>
   <head>
   <title>Code Frame</title>
   <script language="JavaScript">
   <!--
         /*
          The variable "target" holds a reference to the terminal session
          applet in the lower frame. When the script first runs, the setTarget() function
          executes to set the target variable.
       */
       var target;
       setTarget();

       /*
          This function sets the variable "target" to refer to the terminal
          session applet in the lower frame. The full window and document hierarchy
          that identifies the location of the applet is required. If the applet is
          not yet loaded and the target is null, a timeout is used to continually
          check for the applet again, waiting 1 second between tries.
       */
       function setTarget()
       {
           target = parent.appletframe.document.IBM3270Applet;
           if ( target == null )
           {
               setTimeout( "setTarget()", 1000 );
           }
       }
      
       /*
          This function opens Reflection's Color Setup dalog box
          when the user clicks the Color Setup button. The notation
          "target.showDialog( "colorConfigure" )" uses the target variable
          defined earlier, providing an easier way of specifying
          "parent.appletframe.document.IBM3270Applet.getAPI("JSAPI","IBM3270").showDialog( "colorConfigure" )".
       */
       function doColorSetup()
       {
           target.getAPI("JSAPI","IBM3270").showDialog( "colorConfigure" );
       }
   
       /*
          This function opens Reflection's Button Palette Setup dialog box when the user clicks the Button Setup button. The notation
          "target.showDialog( "buttonPaletteConfigure" )" uses the target variable
          defined earlier, providing an easier way of specifying
          "parent.appletframe.document.IBM3270Applet.getAPI("JSAPI","IBM3270").showDialog( "buttonPaletteConfigure" )".
       */
       function doButtonSetup()
       {
           target.getAPI("JSAPI","IBM3270").showDialog( "buttonPaletteConfigure" );
       }
   // -->
   </script>
   </head>
   <body>
   
   <!-- 
      <Form> buttons give the user access to the Color Setup and
      Button Palette Setup dialog boxes. When the onClick event handler
      is invoked, one of the JavaScript functions defined above is
      called.
   -->
   <form>
   <input type="button" Name="ColorSetup" Value="Color Setup" onClick="doColorSetup()">
   <input type="button" Name="ButtonSetup" Value="Button Setup" onClick="doButtonSetup()">
   </form>
    </body>
   </html>

Lastly, here's the HTML for the appletframe.html file, which appears in the lower frame of the frameset and contains the Reflection terminal session applet--make sure to change the hostURL parameter in the <applet> tag to a host appropriate for your network:

   <html>
   <head>
   <title>Applet Frame</title>
   </head>
   <body>
   
   <!-- 
      The <applet> tag defines a simple Reflection applet for
      IBM 3270 emulation. To use this example, change the hostURL
      parameter to one appropriate for your network.
   -->
   <applet mayscript name="IBM3270Applet"
           codebase="./ex/" 
           code="com.wrq.rweb.Launcher.class" width="800" height="500"
           archive="Launcher.jar">
       <param name="hostURL" value="tn3270://payroll">
       <param name="autoconnect" value="true">
       <param name="frame" value="false">
     <param name="launcher.sessions" value="IBM3270">
       <param name="preloadJSAPI" value="true">
   </applet> 
   
   </body>
   </html>

Advanced JavaScriptExamples

Using an onLoad handler to determine when Reflection is initialized

If you want to automate a task immediately after a Reflection terminal session loads, you must first ensure that the session is available and initialized before invoking other API methods. You can do this by using the JavaScript onLoad event handler in the web page's BODY tag, or by waiting for notification when the session is done with initialization. (See Timing issues when scripting Reflection for more information about script timing.)

The following JavaScript example shows how to use an onLoad handler to determine if a Reflection session is initialized. It also uses an error handler, so if Reflection is not initialized enough to access the getInitialized method, the function that performs the initialization check can retry the check after a short delay. Once Reflection is initialized, the Session Setup dialog box opens so the user can enter connection information and proceed with the session. In this example, both the Reflection terminal session applet and the JavaScript code are in the same HTML file.

See Using notification to determine when Reflection is initialized for an example of the notification method.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>Example of an onLoad Handler to Determine Reflection Initialization</title>
<script language="JavaScript">
<!--
    /*
       Set an error handler for the window.
    */
    window.onerror = errHandler;

    /*
       Create a few variables to hold the target applet, the API, the 
       initialization state, and a couple of counters.
    */
    var appletTarget = null;
    
    var inited = 0;
    var count = 0;
    var errcount = 0;
    
    /*
       The error handler is invoked if an attempt to get the applet
       initialization state fails (because Reflection is not yet available),
       or if the api is null and the getInitialized() method is invoked.
       The handler will retry the attempt to get the session's 
       initialization state up to 10 more times, waiting 2 seconds between
       attempts. By returning a value of true from the error handler, no
       JavaScript error alert appears.
    */
    function errHandler( msg, url, line )
    {
        // To ensure that the error handler was invoked because the
        // initialization state is not available and not because some
        // other code failed, first check the "inited" variable before
        // setting the timeout.
        if ( inited <= 0 ) {
            if ( errcount < 10 ) {
                errcount++;
                setTimeout( "tryInit()", 2000 );
            }
            else {
                alert( "Unable to initialize Reflection." );
            }
        }
        return true;
    }

    /*
       This function first gets a reference to the Reflection applet on the
       page and stores it in "appletTarget". Then the function tries to get
       the Reflection API, and then the initialization state, using the getAPI()
       and getInitialized() methods. It then sets the "inited" variable 
       to the return value of getInitialized(). If the "inited" variable 
       is true, the function that opens the Session Setup dialog box is called. 
       If the call to Reflection's getInitialized method fails (because the session 
       or API isn't available yet), the error handler is invoked to repeat the 
       attempt. If the session is available but not yet initialized, a timeout 
       is set to retry this same function every 2 seconds, for up to 10 
       attempts or until "inited" is true.
    */
    function tryInit()
    {
        appletTarget = document.IBM3270;
        api = appletTarget.getAPI("JSAPI","IBM3270");
        inited = api.getInitialized();
        if ( inited > 0 )
        {
            doSessionSetup();
        }
        else if ( inited < 0 )
        {
            alert( "Reflection initialization failed." );
        }
        else if ( count < 10 )
        {
            count++;
            setTimeout( "tryInit()", 2000 );
        }
        else
        {
            alert( "Unable to initialize Reflection." );
        }
    }

    /*
       This function calls Reflection's showDialog method to
       open the Session Setup dialog box. This function is invoked
       only after the terminal session has been initialized.
    */
    function doSessionSetup()
    {
       api.showDialog( "sessionConfigure" );
    }
// -->
</script>
</head>
<!-- 
   The onLoad event handler is used to execute the JavaScript code
   after the page is loaded.
-->
<body onLoad="tryInit()">
<!--
   This is the tag that launches a Reflection IBM 3270 applet.
   To use this example, change the hostURL parameter to one
   appropriate for your network.
-->
<applet mayscript name="IBM3270"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="666" height="448"
        archive="Launcher.jar">
    <param name="hostURL" value="tn3270://accounts">
    <param name="autoconnect" value="false">
    <param name="launcher.sessions" value="IBM3270">
    <param name="preloadJSAPI" value="true">
</applet>

</body>
</html>

Using notification to determine when Reflection is initialized

If you want to automate a task immediately after a Reflection terminal session loads, you must first ensure that the session is available and initialized before invoking other API methods. You can do this using some built-in features of the API in which the Reflection session sends notification to a JavaScript function on your web page when session initialization is complete, or by using an onLoad event handler in the web page's BODY tag. (See Timing issues when scripting Reflection for more information about script timing.)

Allowing Reflection to send a notification message to your JavaScript is much simpler and is more reliable than using an onLoad event handler, but there are some situations, such as when using VBScript, where the event handler method is needed. See Using an onLoad Handler to Determine When Reflection Is Initialized for an example of the polling method from an onLoad event handler.

There are two ways to use notification to determine Reflection's initialization state:

  • If you plan to use only those API methods available from the JavaScript API, add the parameter preloadJSAPI with a value of true to the Reflection applet tag. When this parameter is present, Reflection invokes a JavaScript function called jsapiInitialized when it has completed its initialization, passing the function a reference to the JavaScript API. Once your script receives this reference, you are guaranteed that the Reflection terminal session is initialized, and your JavaScript can proceed with any tasks it needs to perform. An example of this method is shown below.

  • If you plan to use both JavaScript API and ECL API functions from JavaScript, you can add an applet parameter to the Reflection session that specifies a built-in ECL module to run after the session is finished with initialization. When the API module runs, it calls a predefined JavaScript function on your web page, and as above, once your script receives this reference, you are guaranteed that the session is initialized. See Accessing the ECL API from JavaScript for more information about accessing ECL API methods from JavaScript.

Unless you need access to ECL API functions, the first method described above is recommended, since it requires a smaller download from the Reflection Management Server than when using the JSEventNotifier module.

The following JavaScript example shows how to use the jsapiInitialized function to receive notification when Reflection initialization is complete. Once notification is received, the Session Setup dialog box opens so the user can enter connection information and proceed with the session. In this example, both the Reflection terminal session applet and the JavaScript code are in the same HTML file.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>Example of using Notification to Determine Reflection Initialization</title>
<script language="JavaScript">
<!--

   /*
      Variable to hold the API reference when it is retrieved.
   */
   var api = null;
   
   /*
      jsapiInitialized is the name of the function that Reflection calls when
      Reflection initialization is complete. It passes a reference to the
      JSAPI, which is stored in a variable for subsequent use by other script
      functions.
   */
   function jsapiInitialized( inapi )
   {
      api = inapi;
      if ( api == null )
      {
         alert( "Reflection API initialization failed." );
      }
      else
      {
         doSessionSetup();
      }
   }

    /*
       This function calls Reflection's showDialog method to
       open the Session Setup dialog box. This function is invoked
       only after notification is received that the terminal 
       session has been initialized.
    */
    function doSessionSetup()
    {
       api.showDialog( "sessionConfigure" );
    }
// -->
</script>
</head>
<!-- 
   The onLoad event handler is used to execute the JavaScript code
   after the page is loaded.
-->
<body>
<!--
   This is the tag that launches a Reflection IBM 3270 applet.
   To use this example, change the hostURL parameter to
   one appropriate for your network.
-->
<applet mayscript name="IBM3270"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="666" height="448"
        archive="Launcher.jar">
    <param name="hostURL" value="tn3270://accounts">
    <param name="autoconnect" value="false">
    <param name="launcher.sessions" value="IBM3270">
    <param name="preloadJSAPI" value="true">
</applet>

</body>
</html>

Logging on to an IBM host

In this example, JavaScript is used to launch an IBM 3270 session and log on to the host computer.

The logon procedure for an AS/400 computer is quite similar to an IBM mainframe, and you could easily modify this script to use an IBM 5250 session.

Two <form> fields on the web page are used to get the user's ID and password before creating the Reflection session applet and performing the logon. The Reflection session is created in a new browser window that has only a status bar. This is done so the JavaScript writeln statements don't replace the contents of the current window and make the rest of the script unavailable. A related example shows a VBScript version of this script for Internet Explorer.

To use this example, you must change the hostURL parameter in the <applet> tag that's part of the writeApplet() function below to a host appropriate for your network.

<html>
<head>
<title>Sample Logon Script for IBM 3270 (JavaScript)</title>
<script language="JavaScript">
<!--
    var userid;
    var pword;
    var targetdoc;
    var targetwin;
    var appletTarget = null;
    var api = null;
    var count = 0;
    var errcount = 0;
    var inited = 0;

    /* 
       Copy relevant symbolic constants from
       api_ibm3270_constants.js and modify as needed for VBScript.
    */
    var ANY_COLUMN = -1;
    var IBM3270_ENTER_KEY = 35;
    var IBM3270_TAB_KEY = 52;
    
    /*
       Set an error handler. The error handler function is at the end of
       the script.
    */
    window.onerror = errHandler;

    /*
       This is the main function that performs the logon tasks.
    */
    function handleLogonButton()
    {
        // Validate the userid and password.
        if ( validateInputs() )
        {
            writeApplet();
        }
    }

    /*
       This function checks for a user ID and password, and if either is
       not present, displays an alert message.
    */
    function validateInputs()
    {
        userid = document.LogonForm.UserID.value;
        pword = document.LogonForm.Password.value;
        if ( userid == "" )
        {
            alert( "You must enter a User ID to log on!" );
            document.LogonForm.UserID.focus();
            return false;
        }
        if ( pword == "" )
        {
            alert( "You must enter a Password to log on!" );
            document.LogonForm.Password.focus();
            return false;
        }
        return true;
    }

    /*
       This function writes the applet tag to launch an IBM 3270 session in
       a new browser window called "IBM3270Applet."
    */
    function writeApplet()
    {
        targetwin = window.open( "", "IBM3270Applet", 
                                 "status=yes, width=650, height=550" );
        targetdoc = targetwin.document;
        
        // Use the "with (object)" statement to simplify the following lines.
        with ( targetdoc ) {
            writeln( '<html>' );
            writeln( '<body onLoad="window.opener.doLogon()">' );
            writeln( '<h1>Reflection for the Web -- IBM 3270</h1>' );
            writeln( '<applet mayscript name="IBM3270"' );
            writeln( '       codebase="./ex/"' );
            writeln( '       code="com.wrq.rweb.Launcher.class"' );
            writeln( '       width="600" height="400"' );
            writeln( '       archive="Launcher.jar">' );
            // Change the hostURL to a value appropriate for your network.
            writeln( '   <param name="hostURL" value="tn3270://payroll">' );
            writeln( '   <param name="autoconnect" value="false">' );
            writeln( '   <param name="frame" value="false">' );
            writeln( '   <param name="launcher.sessions" value="IBM3270">' );
            writeln( '   <param name="preloadJSAPI" value="true">' );
            writeln( '</applet>' );
            writeln( '<form>' );
            writeln( '<input type="button" ' );
            writeln( '       name="Close" value="Close Window" ' );
            writeln( '       onClick="window.close()"></form>' );
            writeln( '</body>' );
            writeln( '</html>' );
            close();
        }
    }

    /*
       This function is called by the applet window's onLoad event 
       handler after the new child window has been loaded. This function
       is the main entry point for the rest of the logon processing. It 
       works similar to the tryInit() function in the example
       Using an onLoad Handler to Determine When Reflection Is Initialized.
       Once Reflection is initialized, the logon procedure continues.
    */
    function doLogon()
    {
        appletTarget = targetdoc.IBM3270;
        api = appletTarget.getAPI("JSAPI","IBM3270");
        if ( api != null )
        {
            inited = api.getInitialized();
            if ( inited > 0 )
            {
                doConnect();
            }
            else if ( inited < 0 )
            {
                alert( "Reflection initialization failed." );
            }
        }
        else
        {
            if ( count < 10 )
            {
                count++;
                setTimeout( "doLogon()", 1000 );
            }
            else
            {
                alert( "Unable to initialize Reflection." );
            }
        }
    }
    
    /*
       This function starts the actual logon tasks. It determines if the session
       is connected, and if so, calls the function that finds the userid and 
       password prompts on the display and transmits the user's data.
    */
    function doConnect()
    {
        // If there's no connection, try to connect.
        if ( !api.isConnected() )
        {
            targetwin.status = "Connecting...";
            api.connect();
        }
        else
        {
            alert( "You're already connected!" );
            return;
        }

        // Use the status line to display an informational message, and then
        // wait 5 seconds for the USERID prompt to appear on the display.
        // The coordinates in which to start looking are any column in 
        // row 19. The API uses 0-based coordinates, in contrast to
        // the 1-based coordinates that are used for the status line.
        targetwin.status = "Finding USERID prompt.";
        if ( !api.waitForDisplayString( "USERID", 19,
                               ANY_COLUMN, 5000 ) )
        {
            targetwin.alert( "Unable to find USERID prompt. The " +
                   "script will stop, but you may continue manually." );
            return;
        }
        
        // Wait 5 seconds for the cursor to appear in row 19, column 16.
        // This is the location for the user's ID.
        targetwin.status = "Waiting for cursor to enter USERID field.";
        if ( !api.waitForCursorEntered( 19, 16, 5000 ) )
        {
            targetwin.alert( "Cursor was not found in the USERID field. " +
                   "The script will stop, but you can try completing the " +
                   "logon manually." );
            return;
        }
        
        // userid field was found, and cursor is in place, so transmit the 
        // user's ID, followed by the Tab key to move to the next field.
        api.transmitString( userid );
        api.transmitTerminalKey( IBM3270_TAB_KEY );
        
        // Wait for the cursor to enter the password field.
        targetwin.status = "Waiting for the cursor to enter the Password field.";
        if ( !api.waitForCursorEntered( 20, 16, 5000 ) )
        {
            targetwin.alert( "Cursor was not found in the Password field. " +
                     "The script will stop, but you can try completing " + 
                     "the logon manually." );
            return;
        }

        // Cursor is in Password field, so transmit the user's password, 
        // followed by the Enter key.
        api.transmitString( pword );
        api.transmitTerminalKey( IBM3270_ENTER_KEY );
        
        // Wait 5 seconds for the "Ready" message to appear on the display.
        // If the "Ready" message is not found, display an alert message.
        targetwin.status = "Waiting for Ready prompt.";
        if ( !api.waitForDisplayString( "Ready;", 5000 ) )
        {
            targetwin.alert( "Ready signal not found. The session may not " +
                             "be ready for input." );
            targetwin.status = "";
            return;
        }

        // Done with logon, so display final status message and set
        // focus to the terminal display.
        targetwin.status = "Ready to proceed.";
        api.requestDisplayFocus();
    }
    
    /*
       This is the error handler function that will catch script errors.
       The error we're most interested in may occur when trying to
       get Reflection's initialized state in the doLogon() function.
    */
    function errHandler( msg, url, line )
    {
        if ( inited <= 0 ) {
            if ( errcount < 10 ) {
                errcount++;
                setTimeout( "doLogon()", 2000 );
            }
            else {
                alert( "Unable to initialize Reflection." );
            }
        }
        return true;
    }
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- IBM 3270 Logon</h1>
<!--
   Use <form> items to accept the User ID and Password, and to create
   a Logon button.
-->
<form name="LogonForm">
<p>User ID: <input type="text" name="UserID" default size="25"></p>
<p>Password: <input type="password" name="Password" size="25"></p>
<p><input type="button" Name="Logon" value="Logon" onClick="handleLogonButton()"></p>
</form>
</body>
</html>

Logging on to a VMS host

In this example, a VT terminal session is embedded in the browser window, and JavaScript is used to log on to the host computer. Two <form> fields on the web page are used to get the user's name and password before performing the logon. A related example shows a VBScript version of this script for Internet Explorer.To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>Sample Logon Script for VT (JavaScript)</title>
<script language="JavaScript">
<!--
    var uname;
    var pword;
    var api = null;

    /*
       The jsapiInitialized function is called by Reflection
       when it has finished its initialization. Reflection
       passes the function a reference to the JavaScript API.
    */
    function jsapiInitialized( jsapi )
    {
       api = jsapi; 
    }

    /*
       This is the main function that performs the logon tasks.
    */
    function handleLogonButton()
    {
        // Validate the username and password.
        if ( validateInputs() )
        {
            doConnect();
        }
    }

    /*
       This function checks for a username and password, and if either is
       not present, displays an alert message.
    */
    function validateInputs()
    {
        uname = document.LogonForm.Username.value;
        pword = document.LogonForm.Password.value;
        if ( uname == "" )
        {
            alert( "You must enter a Username to log on!" );
            document.LogonForm.Username.focus();
            return false;
        }
        if ( pword == "" )
        {
            alert( "You must enter a Password to log on!" );
            document.LogonForm.Password.focus();
            return false;
        }
        return true;
    }
    
    /*
       This function starts the actual logon tasks. It determines if the session
       is connected, and if so, calls the function that finds the Username and 
       Password prompts on the display and transmits the user's data.
    */
    function doConnect()
    {
        // If there's no connection, try to connect.
        if ( !api.isConnected() )
        {
            self.status = "Connecting...";
            api.connect();
        }
        else
        {
            alert( "You're already connected!" );
            return;
        }

        // Wait 5 seconds for the Username prompt.
        self.status = "Waiting for Username prompt.";
        if ( !api.waitForString( "Username:", 5000 ) )
        {
            alert( "Unable to find Username prompt. The script will stop, " + 
                   "but you may continue manually." );
            return;
        }
        
        // Username prompt was found, so transmit the user's username,
        // followed by a carriage return. The octal representation of the
        // carriage return character--which is decimal 13--is used. You 
        // can also use the carriage return symbol \r or the hex value
        // \x0D. You CANNOT use the decimal value 13, because this will be
        // converted to a string and appended to the username.
        api.transmitString( uname + "\015" );
        
        // Wait 5 seconds for the Password prompt.
        self.status = "Waiting for Password prompt.";
        if ( !api.waitForString( "Password:", 5000 ) )
        {
             alert( "Unable to find Password prompt. The script will stop, " + 
                   "but you can try completing the logon manually." );
            return;
        }

        // Password prompt was found, so transmit the user's password,
        // followed by a carriage return. As above, the octal
        // representation of the carriage return character is used.
        api.transmitString( pword + "\015" );
        
        // Done with logon, so display final status message, and set
        // focus to the terminal display.
        self.status = "Ready to proceed.";
        api.requestDisplayFocus();
    }
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- VT Logon</h1>
<p>
<!--
   Create a basic VT applet on the page, but don't connect until
   the user fills in the username and password information. 
   To use this example, change the hostURL parameter to one 
   appropriate for your network.
-->
<applet mayscript name="VT"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="600" height="400"
        archive="Launcher.jar">
    <param name="hostURL" value="telnet://accounts">
    <param name="autoconnect" value="false">
    <param name="frame" value="false">
    <param name="launcher.sessions" value="VT">
    <param name="preloadJSAPI" value="true">
</applet>
</p>
<!--
   Use <form> items to accept the Username and Password, and to create
   a Logon button.
-->
<form name="LogonForm">
<p>Username: <input type="text" name="Username" default size="25"></p>
<p>Password: <input type="password" name="Password" size="25"></p>
<p><input type="button" name="Logon" value="Logon" onClick="handleLogonButton()"></p>
</form>
</body>
</html>

Logging on to an HP3000 host

In this example, an HP terminal session applet is embedded in the browser window, and JavaScript is used to log on to the host computer. Four <form> fields on the web page are used to get the user's name, group, account, and password before performing the logon.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>Sample Logon Script for HP (JavaScript)</title>
<script language="JavaScript">
<!--
    var uname, group, account, pword;
    var api = null;

    /*
       The jsapiInitialized function is called by Reflection
       when it has finished its initialization. Reflection
       passes the function a reference to the JavaScript API.
    */
    function jsapiInitialized( jsapi )
    {
       api = jsapi; 
    }

    /*
       This is the main function that performs the logon tasks.
    */
    function handleLogonButton()
    {
        // Validate the username and password.
        if ( validateInputs() )
        {
            doConnect();
        }
    }

    /*
       This function checks for a group, account, and password, and 
       if any of these is not present, displays an alert message.
    */
    function validateInputs()
    {
        uname = document.LogonForm.Username.value;
        pword = document.LogonForm.Password.value;
        group = document.LogonForm.Group.value;
        account = document.LogonForm.Account.value;

        // For the host in this example, a username is not required, 
        // but a group and account are.
        if ( group == "" )
        {
            alert( "You must enter a Group to log on!" );
            document.LogonForm.Group.focus();
            return false;
        }
        if ( account == "" )
        {
            alert( "You must enter an Account to log on!" );
            document.LogonForm.Account.focus();
            return false;
        }
        
        if ( pword == "" )
        {
            alert( "You must enter a Password to log on!" );
            document.LogonForm.Password.focus();
            return false;
        }
        return true;
    }
    
    /*
       This function starts the actual logon tasks. It determines if the session
       is connected, and if so, calls the function that finds the Username and 
       Password prompts on the display and transmits the user's data.
    */
    function doConnect()
    {
        // If there's no connection, try to connect.
        if ( !api.isConnected() )
        {
            self.status = "Connecting...";
            api.connect();
        }
        else
        {
            alert( "You're already connected!" );
            return;
        }

        // Wait 5 seconds for the MPE XL prompt to appear in the datacomm stream.
        // By using the HP-specific waitForHostPrompt method, the wait will be 
        // for the string "MPE XL" plus the DC1 host prompt character.
        self.status = "Waiting for host prompt.";
        if ( !api.waitForHostPrompt( "MPE XL:", 5000 ) )
        {
            alert( "Unable to find MPE XL prompt. The script will stop, " + 
                   "but you may continue manually." );
            return;
        }
        
        // MPE XL prompt was found, so transmit the username, group, and
        // account, followed by a carriage return. The octal representation
        // of the carriage return character--which is decimal 13--is used. You
        // can also use the carriage return symbol \r or the hex value
        // \x0D. You CANNOT use the decimal value 13, because this will be
        // converted to a string and appended to the username.
        var helloStr = "hello ";
        if ( uname != "" )
        {
            helloStr += uname + ",";
        }
        helloStr += group + "." + account;
        api.transmitString( helloStr + "\015" );
        
        // Wait 5 seconds for the Password prompt.
        self.status = "Waiting for Password prompt.";
        if ( !api.waitForHostPrompt( "Password:", 5000 ) )
        {
             alert( "Unable to find Password prompt. The script will stop, " + 
                   "but you can try completing the logon manually." );
            return;
        }

        // Password prompt was found, so transmit the user's password,
        // followed by a carriage return. As above, the octal
        // representation of the carriage return character is used.
        api.transmitString( pword + "\015" );
        
        // Done with logon, so display final status message, and set
        // focus to the terminal display.
        self.status = "Ready to proceed.";
        api.requestDisplayFocus();
    }
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- HP Logon</h1>
<p>
<!--
   Create a basic HP applet on the page, but don't connect until
   the user fills in the username, group, account, and password 
   information. A default group (DOCS) and account (WRITERS) are 
   already in the text fields, so the minimum information the
   user needs to supply is the password, because the username is
   optional for the host in this example.
   
   To use this example, change the hostURL parameter to one 
   appropriate for your network, and change the default group and
   account in the form fields.
-->
<applet mayscript name="HP"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="640" height="400"
        archive="Launcher.jar">
    <param name="hostURL" value="nsvt://techpubs">
    <param name="autoconnect" value="false">
    <param name="frame" value="false">
    <param name="launcher.sessions" value="HP">
    <param name="preloadJSAPI" value="true">
</applet>
</p>
<!--
   Use <form> items to accept the Username, Group, Account, and Password, 
   and to create a Logon button.
-->
<form name="LogonForm">
<p>Username: <input type="text" name="Username" default size="25">
Group: <input type="text" name="Group" value="Docs" default size="25">
Account: <input type="text" name="Account" value="Writers" default size="25"></p>
<p>Password: <input type="password" name="Password" size="25">
<input type="button" name="logon" value="Logon" onClick="handleLogonButton()"></p>
</form>
</body>
</html>

Connecting a printer session

In this example, an IBM 3270 Printer session is embedded in the browser window, and JavaScript is used to connect to the host computer. An HTML form list lets the user select the name of the printer device to which to connect, and two buttons let the user connect and disconnect the session.

This example can easily be modified to connect to an AS/400 Printer session. One difference is that it is not necessary to specify a device name when connecting to an AS/400 Printer session (although the AS/400 Printer applet can be configured to require a device name from the user by setting the promptForDeviceName parameter to True).

To use this example, you must change the hostURL parameter (including the port number) in the <applet> tag below to a host appropriate for your network. You must also change the device names in the <form> tag to appropriate device names.

<html>
<head>
<title>Sample Script for IBM 3270 Printer Emulation (JavaScript)</title>
<script language="JavaScript">
<!--
    var api = null;
    var deviceName = "";

   /*
       The jsapiInitialized function is called by Reflection
       when it has finished its initialization. Reflection
       passes the function a reference to the JavaScript API.
    */
    function jsapiInitialized( jsapi )
    {
       api = jsapi;
    }

    /*
       This function handles a click in the Connect button.  If there's no
       connection already established, it calls the doConnect() function to
       make a connection attempt. If there is a connection already, an alert
       message is displayed.
    */
    function handleConnectButton()
    {
        if ( api.isConnected() )
        {
            alert( "You already have a connection to '" +
                   api.getString( "deviceName" ) + "'. You must first\n" +
                   "disconnect the current connection before " +
                   "establishing a new\nconnection.");
            return; 
        }
        doConnect();
    }

    /*
       This function handles a click in the Disconnect button. If there is
       no current connection, it does nothing. Otherwise, it disconnects
       the current session and displays a message in the form field.
    */
    function handleDisconnectButton()
    {
        if ( api.isConnected() )
        {
            api.disconnect();
            document.DevicePicker.ConnectedDevice.value = "<disconnected>";
        }
    }

    /*
       This function establishes the connection. It gets the name of the
       item selected in the form list, sets the Reflection session's device
       name to the same name, and then opens the connection. After the connection
       is opened, a timer is set to check the connection status after 2
       seconds (2000 milliseconds), using the setTimeout() method.
    */
    function doConnect()
    {
        var deviceList = document.DevicePicker.DeviceName;
        deviceName = deviceList.options[deviceList.selectedIndex].text;
        api.setString( "deviceName", deviceName );
        api.connect();
        setTimeout( "checkConnected()", 2000 );
    }

    /*
       This function checks whether the connection to the host using the
       selected device name was successful or not. If the connection failed,
       Reflection will display an alert message. This function will update
       the document's text field with either a success or failure message.
    */
    function checkConnected()
    {
        var isConnected = api.isConnected();
        var theDevice = document.DevicePicker.ConnectedDevice;
        if ( !isConnected )
        {
            theDevice.value = "<failed>";
        }
        else if ( isConnected )
        {
            theDevice.value = api.getString( "deviceName" );
        }
    }
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- IBM 3270 Printer: Session Picker</h1>
<p>
<!--
   Create a basic IBM 3270 Printer applet on the page, but don't
   connect until the user selects a device name and clicks the
   Connect button. 
   
   To use this example, change the hostURL parameter to one 
   appropriate for your network (including the port number), and
   change the names of the devices to devices for your host.
-->
<applet mayscript name="IBM3287"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="450" height="160"
        archive="Launcher.jar">
    <param name="hostURL" value="tn3270e://ibmprinter:5002">
    <param name="autoconnect" value="false">
    <param name="frame" value="false">
    <param name="launcher.sessions" value="IBM3287">
    <param name="preloadJSAPI" value="true">
</applet>
</p>
<!--
   Use <form> items to display a list from which the user
   can select a device to connect to and buttons to connect and
   disconnect the session.
-->
<form name="DevicePicker">
<p>
Device name: <select name="DeviceName">
<option selected>PRINTDEV1</option>
<option>PRINTDEV2</option>
<option>PRINTDEV3</option>
<option>PRINTDEV4</option>
</select>
<input type="button" name="Connect" value="Connect" onClick="handleConnectButton()">
<input type="button" name="Disconnect" value="Disconnect"
                     onClick="handleDisconnectButton()">
</p>
<p>
Connection established to device: <input type="text" 
            name="ConnectedDevice" value="<disconnected>" disabled>
</p>
</form>
</body>
</html>

Transferring files to an IBM mainframe using FTP

In this example, an IBM 3270 session is in a separate browser window, and HTML form elements are used to provide controls for performing FTP file transfers between the desktop computer and the mainframe. The Transfer type radio buttons allow users to choose the method for sending or receiving files. Because the user is given access only to the basic menus, the administrator may want to preconfigure transfer options in the Connection Setup dialog box, then save those settings to a configuration file.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>FTP API Example</title>
<script language="JavaScript">
<!--

    var api = null;

    /*
        Copy relevant symbolic constants from file server_root/webapps/rweb/admin/en/html/advanced/api_constants/api_all_constants.js
    */
    var FTP_ASCII      = 0;
    var FTP_BINARY     = 1;
    var FTP_SMART      = 2;
    
    /*
        Returns the JSAPI for the terminal session.
    */
    function getJSAPI()
    {
       if ( api == null )
       {
         if ( document.ibm3270 != null )
         {
            api = document.ibm3270.getAPI( "JSAPI", "IBM3270" );
         }
       }  
       return api;
    }

    /*
        This function performs the login to the FTP server. It first checks for
        the presence of a hostname, username, and password, and displays an alert
        message if any of these entries is missing. An alert message displays
        the status of the login attempt.
    */
    function doftpLogin()
    {
        var hostname = document.ftp.hostname.value;
        var username = document.ftp.username.value;
        var password = document.ftp.password.value;
        if ( hostname == "" || username == "" || password == "" )
        {
            alert( "You must enter a hostname, username, and " +
                   "password to login. One of these entries is missing." );
            return;
        }
        var result = getJSAPI().ftpLogin(hostname, username, password, null, true);
        if ( result )
            alert( "FTP login was successful." );
        else
            alert( "FTP login failed." );
    }

    /*
        This function disconnects from the FTP server. An alert message
        displays the status of the disconnect attempt.    
     */
    function doftpDisconnect()
    {
        var result = getJSAPI().ftpDisconnect();
        if ( result ) 
            alert( "FTP disconnect was successful." );
        else
            alert( "FTP disconnect failed." );
    }

    /*
        This function sends a file to the FTP server. It does not perform any 
        validity checking of the file names other than ensuring that there
        are entries in the local and remote file name fields. The transfer 
        is performed as either ASCII, binary, or smart transfer, depending 
        on the state of the Transfer type radio buttons, and server directories 
        are created automatically if the "Automatically create directory" check
        box is selected. An alert message displays the status of the transfer.
     */
    function doftpSendFile()
    {
        var remotefile = document.ftp.remoteFile.value;
        var localfile = document.ftp.localFile.value;
        if ( !validateXferInputs(remotefile, localfile) )
            return;
        var makedir = document.ftp.makeDirectory.checked ? true : false;
        var xfertype = FTP_ASCII;   // default to ASCII
        if ( document.ftp.AsciiBinary[1].checked )
            xfertype = FTP_BINARY;   // binary
        else if ( document.ftp.AsciiBinary[2].checked )
            xfertype = FTP_SMART;   // smart transfer
        var result = getJSAPI().ftpSendFile(remotefile,localfile,makedir,xfertype);
        if ( result ) 
            alert( "FTP transfer to host was successful." );
        else
            alert( "FTP transfer to host failed." );
    }

    /*
        This function transfers a file from the FTP server to the local machine.
        No validity checking of file names is performed other than ensuring that
        there are entries in the local and remote file name fields. The transfer 
        is performed as either ASCII, Binary or smart transfer, depending on the
        state of the Transfer type radio buttons. An alert message displays the
        status of the transfer.
     */
    function doftpReceiveFile()
    {
        var remotefile = document.ftp.remoteFile.value;
        var localfile = document.ftp.localFile.value;
        if ( !validateXferInputs(remotefile, localfile) )
            return;
        var xfertype = FTP_ASCII;   // default to ASCII
        if ( document.ftp.AsciiBinary[1].checked )
            xfertype = FTP_BINARY;   // binary
        else if ( document.ftp.AsciiBinary[2].checked )
            xfertype = FTP_SMART;   // smart transfer
        var result = getJSAPI().ftpReceiveFile(remotefile,localfile,xfertype);
        if ( result ) 
            alert( "FTP transfer from host was successful." );
        else
            alert( "FTP transfer from host failed." );
    }

    /*
        This function validates the entries in the Local File and Remote File
        text fields. There must be entries in both of these fields before you
        can transfer files.
    */
    function validateXferInputs(remotefile, localfile)
    {
        if ( remotefile == "" || localfile == "" )
        {
            alert( "You must specify both a remote file name and a local file " +
                   "name before starting the transfer." );
            return false;
        }
        return true;
    }

    /*
        This function gets the last response from the FTP server. If one of the
        other functions fails to complete successfully, the last server response 
        contains the specific message.
     */
    function doftpGetLastServerResponse()
    {
        var result = getJSAPI().ftpGetLastServerResponse();
        alert( "Last response from FTP server:\n" + result );
    }

//-->
</script>
</head>
<body>
<h1>Reflection for the Web: FTP API Example</h1>
<hr>
<!-- 
    Use form items to collect the information needed to perform the FTP API
    functions.
-->
<form name="ftp">
<table>
    <tr>
        <td><b>Connection:</b></td>
        <td> </td>
    </tr>
    <tr>
        <td>Host name:</td>
        <td><input type="text" value="" name="hostname"></td>
    </tr>
    <tr>
        <td>User name:</td>
        <td><input type="text" value="" name="username"></td>
    </tr>
    <tr>
        <td>Password:</td>
        <td><input type="password" value="" name="password"></td>
    </tr>
</table>
<p><input type="button" name="ftplogin" value="Log In" onClick="doftpLogin()">
<input type="button" name="ftpdisconnect" value="Disconnect" onClick="doftpDisconnect()">
</p>
<table>
    <tr>
        <td><b>File to transfer:</b></td>
        <td> </td>
    </tr>
    <tr>
        <td>Local file:</td>
        <td><input type="text" value="" name="localFile"></td>
    </tr>
    <tr>
        <td>Remote file:</td>
        <td><input type="text" value="" name="remoteFile"></td>
    </tr>
    <tr>        
        <td> </td>
        <td><input type="checkbox" value="makeDirectory" 
            name="makeDirectory">Automatically create directory</td>
    </tr>
    <tr>
        <td>Transfer type:</td>
        <td><input type="radio" value="ascii" name="AsciiBinary" checked>ASCII 
            <input type="radio" value="binary" name="AsciiBinary">Binary 
            <input type="radio" value="smart" name="AsciiBinary">Smart</td> 
    </tr>
</table>
<p>
<input type="button" name="ftpSendFile" value="Send File" onClick="doftpSendFile()">
<input type="button" name="ftpReceiveFile" value="Receive File" onClick="doftpReceiveFile()">
</p>
<p>
<b>Last server response:</b><br>
<input type="button" name="ftpGetLastServerResponse" value="Display" onClick="doftpGetLastServerResponse()">
</p>
</form>
<p>
<!--
   Create a basic IBM 3270 applet in a separate frame, with Advanced user
   menus. To establish a connection, you need to change the hostURL
   parameter to one appropriate for your network.
-->   
<applet mayscript name="ibm3270" codebase="./ex" 
    code="com.wrq.rweb.Launcher.class" 
    width=0 height=0 archive="Launcher.jar">
    <param name="frame" value="true">
    <param name="menuType" value="advanced">
    <param name="hostURL" value="tn3270://mymainframe:23">
    <param name="ftpenabled" value="true">
    <param name="launcher.sessions" value="IBM3270">
    <param name="preloadJSAPI" value="true">
</applet>
</p>
</body>
</html>

Transferring files to an IBM mainframe using IND$FILE

In this example, an IBM 3270 session is embedded in the browser window, and HTML form elements are used to provide controls for performing IND$FILE file transfers between the desktop computer and the mainframe. A "file" type input field is used on the form; this provides both a text field and a Browse button for selecting the local file to send to the host. Because the user is not given access to any of the Reflection menus or dialog boxes in this example, the administrator may want to preconfigure all file transfer settings in the File Transfer Setup dialog box, then save those settings to a configuration file.

To use this example, you must change the hostURL parameter in the <applet> tag below to a host appropriate for your network.

<html>
<head>
<title>Example of Transferring Files to an IBM Mainframe Using IND$FILE</title>
<script language="JavaScript">
<!--
    /*
       This function handles a click in either the Send File or Receive
       File button. It first ensures that Reflection is available and
       initialized, and then it gets the values of the <form> elements into an
       array, determines the direction of the transfer, and transfers the
       specified file.
    */
    function transferFile( direction )
    {
       // Get the Reflection session applet and make sure it is initialized.
       var rw;
       if ( (rw = getRWebAPI()) == null )
       {
          alert( "Unable to find Reflection, or Reflection is not initialized." );
          return;
       }

       // Create an Array object to store the <form> values, and get
       // the values. If any of the required values could not be
       // returned, exit the function without transferring the file.
       var fields = new Array();
       if ( getFields( fields ) )
       {
          // Determine the direction of the transfer, and then issue the
          // appropriate API method, passing the four field values
          // as parameters.
          if ( direction == "send" )
             rw.indSendFile( fields[0], fields[1], fields[2], fields[3] );
          else if ( direction == "receive" )                    
             rw.indReceiveFile( fields[0], fields[1], fields[2], fields[3] );
          else
             alert( "Invalid parameter specified for transfer direction." );
        }

        // After the transfer, request the display focus for the session,
        // so the user can type in the terminal session window.
        rw.requestDisplayFocus();
    }

    /*
       This function gets a reference to the IBM 3270 applet on the
       page, and then gets a reference to the JSAPI for the session,
       and then ensures that it is initialized. The function returns
       the API reference if the session is available, or null if either
       the session or API is not available or not initialized.
    */
    function getRWebAPI()
    {
       var targetApplet = document.IBM3270;
       if ( targetApplet == null ) return null;
       var api = targetApplet.getAPI( "JSAPI", "IBM3270" );
       if ( api == null ) return null;
       if ( api.getInitialized() <= 0 ) return null;
       return api;
    }

    /*
       This function fills in the array object with the values from
       the <form> elements. The function returns true if all of the values
       are valid, or false if the data is not valid. In this example,
       both the local file and the host file are required information,
       so if either is missing, an alert message is displayed.
    */
    function getFields( fields )
    {
       var localFile, hostFile, isAscii, showStatus;
        
       if ( (localFile = document.FileTransfer.localfile.value) == "" )
       {
          alert( "You must enter a local file name." );
          return false;
       }
       if ( (hostFile = document.FileTransfer.hostfile.value) == "" )
       {
          alert( "You must enter a host file name." );
          return false;
       }

       var typeList = document.FileTransfer.FileType;
       isAscii = (typeList.options[typeList.selectedIndex].index == 0) ? true : false;

       showStatus = true; // Currently unused; can be either true or false.
                
       // Fill in the array with the valid data.
       fields[0] = localFile;
       fields[1] = hostFile;
       fields[2] = isAscii;
       fields[3] = showStatus;

       return true;
    }
//-->
</script>
</head>
<body>
<h1>Reflection for the Web -- IBM 3270</h1>
<p>
<!--
   This is the tag that launches an IBM 3270 terminal session.
   To use this example, change the hostURL parameter to one
   appropriate for your network.
-->
<applet mayscript name="IBM3270"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="600" height="400"
        archive="Launcher.jar">
   <param name="hostURL" value="tn3270://payroll">
   <param name="launcher.sessions" value="IBM3270">
   <param name="preloadJSAPI" value="true">
</applet>
</p>
<!--
   A series of <form> elements are created to let the user enter
   the name of the local file, the name of the host file, and
   the format for transferring the file (either ASCII or Binary).
   Two buttons trigger the file transfer. By using an INPUT type
   of "FILE", the local file name field looks like a text field,
   but also gets a Browse button for browsing for a local file.
   Note, however, that the Browse dialog box cannot be used to
   specify a file to save when receiving a file from the host.
-->
<form name="FileTransfer">
<p>Local File Name:&nbsp;<input type="file" size="40" name="localfile"></p>
<p>Host File Name:&nbsp;&nbsp;<input type="text" value="" size="40" name="hostfile"></p>
<p>File type: <select name="FileType">
<option selected>ASCII</option>
<option>Binary</option>
</select>
</p>
<p>
<input type="button" name="RecvFile" value="<< Receive File"       onClick="transferFile( 'receive' )">&nbsp;
<input type="button" name="SendFile" value="Send File >>"       onClick="transferFile( 'send' )">
</p>
</form>
</body>
</html>

Logging out of the host when closing a session

When a user closes a Reflection session window without first logging out of the host, a process may remain running on the host computer, preventing the user from logging on again. This example shows how to prevent this problem; it creates the Reflection session in a separate JavaScript window containing a script that logs the user out of the host computer when the new window is closed. In this example, the script simply checks whether the session is connected, and if it is, transmits the "logout" string.

To use this example, you must change the hostURL parameter in the <applet> tag that's part of the JavaScript function that writes out the Reflection session to a host appropriate for your network. You may also need to modify the code that transmits the "logout" string.

<html>
<head>
<title>Sample Logout on Close Script</title>
<script language="JavaScript">
<!--
    /* 
       Copy relevant symbolic constants from .js file.
    */
    var IBM3270_ENTER_KEY = 35;
    var VT_RETURN_KEY = 2;

    /*
       This function writes the applet tag to launch an IBM 3270 session in
       a new browser window called "IBM3270Applet." In addition to the 
       IBM 3270 session applet, some JavaScript functions are written to the
        tag in the new window: an "onLoad" event handler is added to
       give the terminal session the input focus when it is ready, and an
       "onUnload" event handler is added to logout of the host when the
       browser window is closed.
    */
    function launchIBMSession()
    {
        var targetwin = window.open( "", "IBM3270Applet", 
                                 "status=yes, width=650, height=550" );
        var targetdoc = targetwin.document;
        
        // Use the "with (object)" statement to simplify the following lines.
        with ( targetdoc ) {
            writeln( '<html>' );
            writeln( '<body onLoad="setSessionFocus()" onUnload="doDisconnect()">' );
            writeln( '<script language="JavaScript">' );
            writeln( '   window.onerror = errHandler;' );
            writeln( '   var api = null;' );
            writeln( '   function errHandler(msg, url, line) {' );
            writeln( '      setTimeout("setSessionFocus()",1000);' );
            writeln( '      return true;' );
            writeln( '   }' );
            writeln( '   function setSessionFocus() {' );
            writeln( '      api = document.IBM3270.getAPI("JSAPI","IBM3270");' );
            writeln( '      if ( api.getInitialized() <= 0  )' );
            writeln( '         setTimeout("setSessionFocus()",1000);' );
            writeln( '      else' );
            writeln( '         api.requestDisplayFocus();' );
            writeln( '   }' );
            writeln( '   function doDisconnect() {' );
            writeln( '      if ( api.isConnected() ) {' );
            writeln( '         api.transmitString("logout");' );
            writeln( '         api.transmitTerminalKey(" + IBM3270_ENTER_KEY + ");' );
            writeln( '      }' );
            writeln( '   }' );
            writeln( '</script>' );
            writeln( '<h1>Reflection for the Web -- IBM 3270</h1>' );
            writeln( '<applet mayscript name="IBM3270"' );
            writeln( '       codebase="./ex/"' );
            writeln( '       code="com.wrq.rweb.Launcher.class"' );
            writeln( '       width="600" height="400"' );
            writeln( '       archive="Launcher.jar">' );
            // Change the hostURL to a value appropriate for your network.
            writeln( '   <param name="hostURL" value="tn3270://payroll">' );
            writeln( '   <param name="autoconnect" value="true">' );
            writeln( '   <param name="frame" value="false">' );
            writeln( '   <param name="launcher.sessions" value="IBM3270">' );
            writeln( '</applet>' );
            writeln( '</body>' );
            writeln( '</html>' );
            close();
        }
    }

    /*
       This function writes the applet tag to launch a VT session in
       a new browser window called "VTApplet." In addition to the 
       VT session applet, some JavaScript functions are written to the
        tag in the new window: an "onLoad" event handler is added to
       give the terminal session the input focus when it is ready, and an
       "onUnload" event handler is added to logout of the host when the
       browser window is closed.
    */
    function launchVTSession()
    {
        var targetwin = window.open( "", "VTApplet", 
                                 "status=yes, width=650, height=550" );
        var targetdoc = targetwin.document;
        
        // Use the "with (object)" statement to simplify the following lines.
        with ( targetdoc ) {
            writeln( '<html>' );
            writeln( '<body onLoad="setSessionFocus()" onUnload="doDisconnect()">' );
            writeln( '<script language="JavaScript">' );
            writeln( '   window.onerror = errHandler;' );
            writeln( '   var api = null;' );
            writeln( '   function errHandler(msg, url, line) {' );
            writeln( '      setTimeout("setSessionFocus()",1000);' );
            writeln( '      return true;' );
            writeln( '   }' );
            writeln( '   function setSessionFocus() {' );
            writeln( '      api = document.VT.getAPI("JSAPI","VT");' );
            writeln( '      if ( api.getInitialized() <= 0  )' );
            writeln( '         setTimeout("setSessionFocus()",1000);' );
            writeln( '      else' );
            writeln( '         api.requestDisplayFocus();' );
            writeln( '   }' );
            writeln( '   function doDisconnect() {' );
            writeln( '      if ( api.isConnected() ) {' );
            writeln( '         api.transmitString("logout");' );
            writeln( '         api.transmitTerminalKey(" + VT_RETURN_KEY + ");' );
            writeln( '      }' );
            writeln( '   }' );
            writeln( '</script>' );
            writeln( '<h1>Reflection for the Web -- VT</h1>' );
            writeln( '<applet mayscript name="VT"' );
            writeln( '       codebase="./ex/"' );
            writeln( '       code="com.wrq.rweb.Launcher.class"' );
            writeln( '       width="600" height="400"' );
            writeln( '       archive="Launcher.jar">' );
            // Change the hostURL to a value appropriate for your network.
            writeln( '   <param name="hostURL" value="telnet://accounts">' );
            writeln( '   <param name="autoconnect" value="true">' );
            writeln( '   <param name="frame" value="false">' );
            writeln( '   <param name="launcher.sessions" value="VT">' );
            writeln( '</applet>' );
            writeln( '</body>' );
            writeln( '</html>' );
            close();
        }
    }
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- Logout on Close Example</h1>
<p>

<form name="LaunchSession">
<input type="button" name="LaunchIBM" value="Launch IBM 3270" onClick="launchIBMSession()">
<input type="button" name="LaunchVT" value="Launch VT" onClick="launchVTSession()">
</p>
</form>
</body>
</html>

VBScript Examples

Logging on to an IBM 3270 host (VBScript)

In this example, which runs only in Internet Explorer, Microsoft's VBScript is used to launch an IBM 3270 session and log on to the host computer. Two <form> fields on the web page are used to get the user's name and password before creating the Reflection session applet and performing the logon. The Reflection session is created in a new browser window that has only a status bar. This is done so the VBScript WriteLn statements don't replace the contents of the current window and make the rest of the script unavailable. A related example shows a JavaScript version of this script.

To use this example, you must change the hostURL parameter in the <applet> tag that's part of the DoWriteApplet() function below to a host appropriate for your network. In addition, the HTML page must be placed in the session folder rather than in the ReflectionData/deploy folder. If the session were delivered from the deploy folder as a protected session, dynamically generated code that gets added to the applet tag written out by the WriteLn statements would contain nested double quotation marks and would generate a syntax error.

<html>
<head>
<title>Sample Logon Script for IBM 3270 (VBScript)</title>
<script language="VBScript">
<!--
    ' Script-level variables shared by various functions.
    Dim strUserid
    Dim strPword
    Dim intInited
    Dim intCount
    Dim objAppletTarget
    Dim objAPI
    Dim objTargetdoc
    Dim objTargetwin

    ' Copy relevant symbolic constants from
    ' api_ibm3270_constants.js and modify as needed for VBScript.
    Dim ANY_COLUMN
    Dim IBM3270_ENTER_KEY
    Dim IBM3270_TAB_KEY
    ANY_COLUMN = -1
    IBM3270_ENTER_KEY = 35
    IBM3270_TAB_KEY = 52

    '****************************************************
    ' Handle a click on the Logon button. This first
    ' initializes the script-level variables, and then validates
    ' the form inputs. If the form inputs are okay, the
    ' procedure DoWriteApplet is called to write the applet
    ' tag to a new browser window.
    '****************************************************
    Sub Logon_OnClick()
        Call DoInitVariables()
        If blnValidateInputs() = True Then
            Call DoWriteApplet()
        End If
    End Sub
    
    '****************************************************
    ' Initialize the script-level variables.
    '****************************************************
    Sub DoInitVariables()
        strUserid = ""
        strPword = ""
        intInited = 0
        intCount = 0
        objAppletTarget = Null
        objAPI = Null
        objTargetdoc = ""
        objTargetwin = ""
    End Sub
    
    '****************************************************
    ' Check for a username and password, and if either is
    ' not present, display a message box and return False.
    ' If the User ID and Password are filled in, return
    ' True.
    '****************************************************
    Function blnValidateInputs()
        strUserid = Document.LogonForm.Userid.Value
        strPword = Document.LogonForm.Password.Value
        If strUserid = "" Then
            Alert "You must enter a User ID to log on!"
            Document.LogonForm.Username.Focus()
            blnValidateInputs = False
            Exit Function
        End If
        
        If strPword = "" Then
            Alert "You must enter a Password to log on!"
            Document.LogonForm.Password.Focus()
            blnValidateInputs = False
            Exit Function
        End If
        blnValidateInputs = True
    End Function

    '****************************************************
    ' This function writes the applet tag to launch an 
    ' IBM 3270 session in a new browser window called 
    ' "IBM3270Applet." When the new window is done loading
    ' the new window's onLoad event handler is invoked,
    ' which calls the DoLogon procedure in this script.
    '****************************************************
    Sub DoWriteApplet()
        Set objTargetwin = Window.Open( "", "IBM3270Applet", "status=yes, width=650, height=550" )
        Set objTargetdoc = objTargetwin.Document

        objTargetdoc.Open
        objTargetdoc.WriteLn "<html>"
        objTargetdoc.WriteLn "<body language='VBScript' OnLoad='Window.Opener.DoLogon'>"
        objTargetdoc.WriteLn "<h1>Reflection for the Web -- IBM 3270</h1>"
        objTargetdoc.WriteLn "<applet mayscript name='IBM3270'"
        objTargetdoc.WriteLn "        codebase='../ex/'"
        objTargetdoc.WriteLn "        code='com.wrq.rweb.Launcher.class'"
        objTargetdoc.WriteLn "        width='600' height='400'"
        objTargetdoc.WriteLn "        archive='Launcher.jar'>"
        ' Change the hostURL parameter to a host appropriate for your network.
        objTargetdoc.WriteLn "    <param name='hostURL' value='tn3270://payroll'>"
        objTargetdoc.WriteLn "    <param name='autoconnect' value='false'>"
        objTargetdoc.WriteLn "    <param name='frame' value='false'>"
        objTargetdoc.WriteLn "    <param name='preloadJSAPI' value='true'>" 
        objTargetdoc.WriteLn "    <param name='launcher.sessions' value='IBM3270'>"
        objTargetdoc.WriteLn "</applet>"
        objTargetdoc.WriteLn "<form><input type='button' name='Close' value='Close Window' "
        objTargetdoc.WriteLn "OnClick='Window.Close()'></form>"
        objTargetdoc.WriteLn "</body>"
        objTargetdoc.WriteLn "</html>"
        objTargetdoc.Close()
    End Sub

    '****************************************************
    ' This procedure is called by the applet window's onLoad
    ' event handler after the new child window has been loaded.
    ' It gets a reference to the Reflection Launcher applet on the
    ' web page, and if the reference is null, it shuts the 
    ' child window. Otherwise, it calls the DoGetAPI() 
    ' procedure.
    '****************************************************
    Sub DoLogon()
        On Error Resume Next
        Set objAppletTarget = objTargetdoc.IBM3270
        If objAppletTarget = Null Then
            Alert "Could not get applet reference. The script is stopping now."
            objTargetwin.Close()
            Exit Sub
        Else
            DoGetAPI
        End If
    End Sub
       
    '***************************************************
    ' This procedure gets the Reflection JSAPI object for
    ' the terminal session on the web page. If the API
    ' object is null, it rechecks every 2 seconds. When
    ' the API object is available, the procedure then
    ' gets the Reflection session's initialization status,
    ' again pausing 2 seconds between attempts, before calling
    ' DoConnect. For more information about determining 
    ' Reflection's initialization status, see Using an onLoad
    ' Handler to Determine When Reflection Is Initialized.
    '****************************************************
    Sub DoGetAPI()
       Set objAPI = objAppletTarget.getAPI("JSAPI", "IBM3270")
       If objAPI = Null Then
          SetTimeout "DoGetAPI()", 2000
       Else
          On Error Resume Next
          intInited = objAPI.getInitialized()
          If intInited = 0 Then
             If intCount < 10 Then
                intCount = intCount + 1
                SetTimeout "DoGetAPI()", 2000
             Else
                Alert "Unable to initialize Reflection."
             End If
          ElseIf intInited > 0 Then
             DoConnect
          Else
             Alert "Reflection initialization failed."
          End If
       End If
    End Sub
    
    '****************************************************
    ' This procedure starts the actual logon tasks. It 
    ' determines if the session is connected, and if so, 
    ' finds the Userid and Password prompts on the display
    ' and transmits the user's data.
    '****************************************************
    Sub DoConnect()
        ' If there's no connection, try to connect.
        If objAPI.isConnected() = False Then
            objAPI.connect()
        Else
            objTargetwin.Alert "You're already connected!"
            Exit Sub
        End If
        
        ' Use the status line to display informational messages.
        objTargetwin.Status = "Waiting for USERID prompt."

        ' Wait 5 seconds for the USERID prompt to appear on the display.
        ' The coordinates in which to start looking are any column in
        ' row 19. The API uses 0-based coordinates, in contrast to the
        ' 1-based coordinates that are used for the status line.
        If objAPI.waitForDisplayString( "USERID", 19, _
                              ANY_COLUMN, 5000 ) = False Then
            objTargetwin.Alert "Unable to find USERID prompt. The script will stop, " & _
                   "but you may continue manually."
            Exit Sub
        End If
        
        ' Wait 5 seconds for the cursor to appear in row 19, column 16.
        ' This is the location for the user's ID.
        If objAPI.waitForCursorEntered( 19, 16, 5000 ) = False Then
            objTargetwin.Alert "Cursor was not found in the USERID field. The script " & _
                   "will stop, but you may continue manually."
            Exit Sub
        End If
        
        ' USERID field was found, and cursor is in place, so transmit the user's
        ' ID, followed by the Tab key to move to the next field.
        objAPI.transmitString( strUserid )
        objAPI.transmitTerminalKey( IBM3270_TAB_KEY )
        
        ' Wait for the cursor to enter the Password field.
        objTargetwin.Status = "Waiting for Password prompt."
        If objAPI.waitForCursorEntered( 20, 16, 5000 ) = False Then
            objTargetwin.Alert "Cursor was not found in the Password field. The script will " & _
                     "stop, but you can try completing the logon manually."
            Exit Sub
        End If

        ' Cursor is in Password field, so transmit the user's password, followed
        ' by the Enter key.
        objAPI.transmitString( strPword )
        objAPI.transmitTerminalKey( IBM3270_ENTER_KEY )
        
        
        ' Wait 5 seconds for the "Ready" message. If not found, display
        ' a message box.
        objTargetwin.Status = "Waiting for Ready prompt."
        If objAPI.waitForDisplayString( "Ready;", 5000 ) = False Then
            objTargetwin.Alert "Ready signal not found. The session may not be ready for input."
            Exit Sub
        End If
        
        ' Display a final status message, and set the focus to the
        ' terminal display.
        objTargetwin.Status = "Ready to proceed."
        objAPI.requestDisplayFocus()
        
    End Sub

// -->
</script>
</head>
<body bgcolor="#FFFFFF">
<h1>Reflection for the Web -- IBM 3270 Logon</h1>
<!--
   Use <form> items to accept the User ID and Password, and to create
   a Logon button.
-->
<form name="LogonForm">
<p>User ID: <input type="text" name="UserID" default size="25"></p>
<p>Password: <input type="password" name="Password" size="25"></p>
<p><input type="button" name="logon" value="Logon"></p>
</form>
</body>
</html>

Logging on to a VMS host (VBScript)

In this example, a VT session is embedded in the browser window, and VBScript, which is available only in Internet Explorer, is used to log on to the host computer. Two <form> fields on the web page are used to get the user's name and password before performing the logon. Before the logon is actually initiated, a loop with a time delay is used to determine if Reflection is initialized and ready for additional commands. A related example shows a JavaScript version of this script.

<html>
<head>
<title>Sample Logon Script for VT (VBScript)</title>
<script language="VBScript">
<!--
    ' Script-level variables shared by various functions.
    Dim strUname
    Dim strPword
    Dim intInited
    Dim intCount
    Dim objAppletTarget
    Dim objAPI
    
    '****************************************************
    ' Handle a click on the Logon button. This first 
    ' initializes the script-level variables, and then validates
    ' the form inputs. If the form inputs are okay, 
    ' DoTryInit is called to start the action.
    '****************************************************
    Sub Logon_OnClick()
        Call DoInitVariables()
        If blnValidateInputs() = True Then
            Call DoTryInit()
        Else
            Exit Sub
        End If
    End Sub
    
    '****************************************************
    ' Initialize the script-level variables.
    '****************************************************
    Sub DoInitVariables()
        strUname = ""
        strPword = ""
        intInited = 0
        intCount = 0
        objAppletTarget = Null
        objAPI = Null
    End Sub
    
    '****************************************************
    ' Check for a username and password, and if either is
    ' not present, display a message box and return False.
    ' If the username and password are filled in, return
    ' True.
    '****************************************************
    Function blnValidateInputs()
        strUname = Document.LogonForm.Username.Value
        strPword = Document.LogonForm.Password.Value
        If strUname = "" Then
            Alert "You must enter a Username to log on!"
            Document.LogonForm.Username.Focus()
            validateInputs = False
            Exit Function
        End If
        
        If strPword = "" Then
            Alert "You must enter a Password to log on!"
            Document.LogonForm.Password.Focus()
            blnValidateInputs = False
            Exit Function
        End If
        blnValidateInputs = True
    End Function

    '****************************************************
    ' This procedure gets a reference to the Reflection
    ' applet on the page and stores it in "objAppletTarget".
    ' If that succeeds, it then calls DoGetAPI() to get
    ' the Reflection API.
    Sub DoTryInit()
        On Error Resume Next
        Set objAppletTarget = Document.VT
        If objAppletTarget = Null Then
            Alert "Could not get applet reference. The script is stopping now."
            Exit Sub
        Else
            DoGetAPI
        End If
    End Sub
    
    '***************************************************
    ' This procedure gets the Reflection JSAPI object for
    ' the terminal session on the web page. If the API
    ' object is null, it rechecks every 2 seconds. When
    ' the API object is available, the procedure then
    ' gets the Reflection session's initialization status,
    ' again pausing 2 seconds between attempts, before calling
    ' DoConnect. For more information about determining
    ' Reflection's initialization status, see Using an onLoad
    ' Handler to Determine When Reflection Is Initialized.
    '****************************************************
    Sub DoGetAPI()
       Set objAPI = objAppletTarget.getAPI("JSAPI", "VT")
       If objAPI = Null Then
          SetTimeout "DoGetAPI()", 2000
       Else
          On Error Resume Next
          intInited = objAPI.getInitialized()
          If intInited = 0 Then
             If intCount < 10 Then
                intCount = intCount + 1
                SetTimeout "DoGetAPI()", 2000
             Else
                Alert "Reflection is not initialized. Unable to continue."
             End If
          ElseIf intInited > 0 Then
             DoConnect
          Else
             Alert "Reflection initialization failed. Unable to continue."
          End If
       End If
    End Sub
    
    '****************************************************
    ' This function starts the actual logon tasks. It 
    ' determines if Reflection is connected, and if so, 
    ' calls the function that finds the Username and 
    ' Password prompts on the display and transmits the 
    ' user's data.
    '****************************************************
    Sub DoConnect()

        ' If there's no connection, try to connect.
        If objAPI.isConnected() = False Then
            objAPI.connect()
        Else
            Alert "You're already connected!"
            Exit Sub
        End If

        ' Wait 5 seconds for the Username prompt.
        If objAPI.waitForString( "Username:", 5000 ) = False Then
            Alert "Unable to find Username prompt. The script will stop, " & _ 
                    "but you may continue manually."
            Exit Sub
        End If

        ' Username prompt was found, so transmit the user's username
        ' followed by a carriage return. The VBScript string constant
        ' "vbCR" is used to represent the carriage return. You can
        ' also use the expression "Chr(13)," which is the decimal 
        ' representation of the carriage return character.
        objAPI.transmitString( strUname & vbCR )

        ' Wait 5 seconds for the Password prompt.
        If objAPI.waitForString( "Password:", 5000 ) = False Then
            Alert "Unable to find Password prompt. The script will stop, " & _
                    "but you can try completing the logon manually."
            Exit Sub
        End If

        ' Password prompt was found, so transmit the user's password,
        ' followed by a carriage return. As above, the VBScript constant
        ' "vbCR" is used for the carriage return character.
        objAPI.transmitString( strPword & vbCR )
        
        ' Set the focus to the terminal display.
        objAPI.requestDisplayFocus()

    End Sub
    
// -->
</script>
</head>
<body>
<h1>Reflection for the Web -- VT Logon</h1>
<p>
<!--
   Create a basic VT applet on the page but don't connect until
   the user fills in the username and password information.
   To use this example, change the hostURL parameter to one 
   appropriate for your network.
-->
<applet mayscript name="VT"
        codebase="./ex/"
        code="com.wrq.rweb.Launcher.class"
        width="600" height="400"
        archive="Launcher.jar">
    <param name="hostURL" value="telnet://payroll">
    <param name="autoconnect" value="false">
    <param name="frame" value="false">
    <param name="launcher.sessions" value="VT">
</applet>
</p>
<!--
   Use <form> items to accept the Username and Password, and to create
   a Logon button.
-->
<form name="LogonForm">
<p>Username: <input type="text" name="Username" default size="25"></p>
<p>Password: <input type="password" name="Password" size="25"></p>
<p><input type="button" name="logon" value="Logon"></p>
</form>
</body>
</html>