Previous Next Contents Index


AppLogic class (deprecated)


The AppLogic class is deprecated and is provided for backward compatibility only. AppLogics are not part of NAS's new application model, which is based on standards defined in the servlet, EJB, and JDBC specifications. The AppLogic class is provided so that existing AppLogics continue to be supported. However, new applications should avoid calling AppLogic methods whenever possible.

For information about replacing AppLogic functionality in existing applications, see the Migration Guide.

The AppLogic class is the base class for all AppLogic code. It provides a suite of useful AppLogic-related helper methods and member variables. You can, for example, use methods in your derived AppLogic class to create database connections, queries, transactions, and HTML output.

To use the AppLogic class, you must first import the com.kivasoft.applogic package at the beginning of your AppLogic file, as shown in the following example:

import com.kivasoft.applogic.*;
After you import the com.kivasoft.applogic package, you can create an instance of AppLogic and override the execute( ) method with AppLogic-specific code, as shown in the following example:

public class myAppLogic extends AppLogic {

public int execute() {
/* Override execute() method with AppLogic code */
return result("Hello, world!\n");
}
}
Package
com.kivasoft.applogic

Variables
Variable
Description
context
IContext object, which provides access to Netscape Application Server services. Some objects require services from IContext.
valIn

IValList object containing input parameters and other information. During the execute( ) method, an AppLogic can access items in the IValList to retrieve the arguments passed into the request.
valOut

IValList object containing output parameters. During the execute( ) method, the AppLogic can add or update items in the IValList to specify output values for the request.

Methods
Most methods of the AppLogic class are deprecated. Instead of calling these methods, we recommend using equivalent functionality as described with each AppLogic method.

In some cases, you may want to call AppLogic methods to access NAS features that are not currently available through the Java standards. For example, you may want to take advantage of caching or distributed state trees. In the following table, boldface type indicates a method that may be useful in NAS 4.0 applications.

Method
Description
createDataConn( )
Creates a new data connection object and opens a connection to a database or data source.
createDataConnSet( )
Creates a collection used to dynamically assign query name / data connection pairs before loading a query file.
createHierQuery( )
Creates a new query object used for building and running a hierarchical query.
createMailbox( )
Creates an electronic mailbox object used for communicating with a user through email.
createQuery( )
Creates a new query object used for building and running a flat query.
createSession( )
Creates a new session object used for tracking a user session.

createTrans( )
Creates a new transaction object used for transaction processing operations on a database.
deleteCache( )
Deletes the result cache for a specified AppLogic.
destroySession( )
Deletes a user session.
evalOutput( )
Creates an output report by merging data with a report template file.
evalTemplate( )
Creates an output report by merging data with a report template file. The report is an HTML document that can be viewed using a Web browser.
execute( )
Performs the main task of an AppLogic object, such as accessing a database, generating a report, or other operations. Should be overridden or implemented.
getAppEvent( )
Retrieves the application event object.
getSession( )
Returns an existing user session.
getStateTreeRoot( )
Returns an existing root node of a state tree or creates a new one.
isAuthorized( )
Checks a user's permission level to a specified action or AppLogic.
isCached( )
Returns true if AppLogic results are being saved in the result cache.
loadHierQuery( )
Creates a hierarchical query by loading a query file and one or more query names with associated data connections.
log( )
Writes a message to the server log.
loginSession( )
Logs an authorized user into a session with a secured application.
logoutSession( )
Logs a user out of a session with a secured application.
newRequest( )
Calls another AppLogic from within the current AppLogic.
newRequestAsync( )
Calls another AppLogic from within the current AppLogic, and runs it asynchronously.
removeAllCachedResults( )
Clears an AppLogic's result cache.
removeCachedResult( )
Clears specific results from an AppLogic's result cache.
result( )
Specifies the return value of an AppLogic.
saveSession( )
Saves changes to a session.
setCacheCriteria( )
Stores AppLogic results, such as HTML, data values, and streamed results, in a result cache.
setSessionVisibility( )
Sets the session visibility.
setVariable( )
Sets a value that is passed to later AppLogic requests that are called by the same client session.
skipCache( )
Skips result caching for the current AppLogic execution.
streamResult( )
Streams output results as a string.
streamResultBinary( )
Streams output binary data, such as a GIF file.
streamResultHeader( )
Streams output header data.

Example
The following example shows importing the com.kivasoft and Java packages, and overriding the execute( ) method with code that logs a series of messages:

import java.lang.*;

import com.kivasoft.*;
import com.kivasoft.types.*;
import com,kivasoft.util.*;
import com.kivasoft.applogic.*;

public class mySimpleAppLogic extends AppLogic {
public int execute() {
log("The execute method got called.");
log("I can do anything I want here, such as");
log("run queries, generate reports, update tables,");
log("and log messages like this one.");
return GXE.SUCCESS;
}
}
createDataConn( )
Creates a new data connection object and opens a connection to a database or data source.

createDataConn( ) is deprecated. In standard-based applications, use the getConnection( ) method in the javax.sql.DataSource interface.

Syntax 1
Use this version for most database drivers.

public IDataConn createDataConn(
int flags,
int driver,
String datasource,
String database,
String username,
String password)
Syntax 2
Use this version for database drivers requiring parameters not found in Syntax 1. Provides parameters through an IValList object instead. To use this syntax, you must first create an instance of the IValList interface and use setValString( ) to specify the connection parameter names and values.

public IDataConn createDataConn(
int flags,
int driver,
IValList prop,
IContext context)

flags. One or more optional flags used for connecting to the specified data source.

The AppLogic can pass one parameter from both mutually exclusive pairs, as shown in the following example:

(GX_DA_CONN_FLAGS.GX_DA_CACHED | GX_DA_CONN_FLAGS.GX_DA_CONN_BLOCK)

Specify 0 (zero) to use the system's default settings: GX_DA_CONN_FLAGS.GX_DA_CACHED and GX_DA_CONN_FLAGS.GX_DA_CONN_BLOCK

driver. Specify one of the following static variables in the GX_DA_DAD_DRIVERS class:

GX_DA_DRIVER_ODBC
GX_DA_DRIVER_SYBASE_CTLIB
GX_DA_DRIVER_MICROSOFT_JET
GX_DA_DRIVER_MICROSOFT_SQL
GX_DA_DRIVER_INFORMIX_SQLNET
GX_DA_DRIVER_INFORMIX_CLI
GX_DA_DRIVER_INFORMIX_CORBA
GX_DA_DRIVER_DB2_CLI
GX_DA_DRIVER_ORACLE_OCI
GX_DA_DRIVER_DEFAULT

If GX_DA_DRIVER_DEFAULT is specified, the Netscape Application Server evaluates the drivers and their associated priorities set in the registry to determine the driver to use. Specify GX_DA_DRIVER_DEFAULT if your system uses ODBC and native drivers, and if you want the Netscape Application Server to choose between an ODBC driver and a native driver at connection time.

datasource. Name of the data source to connect to. Used for databases that organize data into data source, database, and table objects and sub-objects. For example, a data source for Accounting might contain separate databases for GL, AP, and AR. Each database, such as Accounts Payable, might be a collection of individual tables, such as a vendor table, purchase order table, materials table, and so on. See your database server documentation for more information.

database. Name of the database to connect to. Used for database servers that organize data into databases and tables. See your database server documentation for more information.

username. Login user name that is valid for the specified database.

password. Login password that is valid for the specified user name and database.

props. IValList of connection-specific information required to log in to the data source. Use the following keys for the connection parameters:

context. A pointer to the IContext object, which provides access to Netscape Application Server services. Specify null.

Usage
A data connection is a communication link or session with a database or other data source. Before interacting with a data source, an AppLogic must first establish a connection with it. Each connection is represented by a data connection object, which contains all the information needed to communicate with a database or data source, such as the name of the database, database driver, user name, password, and so on. A data connection object is an instance of the IDataConn interface.

Use createDataConn( ) to set up a separate connection for each database or data source you want to access. AppLogic objects refer to the data connection object in their methods that perform subsequent operations on the database.

Rules
Tips
Return Value
IDataConn object representing the specified data connection, or null if a failure occurred. AppLogic uses the data connection object to uniquely identify this data connection in subsequent operations, such as queries and record insert, update, and delete operations.

Example
// Method to open a connection to a database

protected com.kivasoft.IDataConn getOBDataConn()
{
String username = "kdemo";
String password = "kdemo";
IDataConn newDataConn = createDataConn(0,
GX_DA_DAD_DRIVERS.GX_DA_DRIVER_ODBC,
/* Datasource name. */ "ksample",
/* Database name. */ "",
/* userName. */ username,
/* password. */ password);

if (newDataConn == null)
{
log("ERROR: Could not create database connection");
}
return newDataConn;
}
Related Topics
IDataConn interface,
IValList interface

createDataConnSet( )
Creates a collection used to dynamically assign query name/data connection pairs before loading a query file.

createDataConnSet( ) is deprecated. In standard-based applications, use the JDBC API to provide similar functionality.

Syntax
public IDataConnSet createDataConnSet(
int flags)

flags. Specify 0. Internal use only.

Usage
Use createDataConnSet( ) only if you are loading a query file using loadHierQuery( ). To use a query file, an AppLogic first establishes a data connection with each database on which any queries will be run.

Next, the AppLogic calls createDataConnSet( ) to create an IDataConnSet object, then populates this collection with query name / data connection pairs. Each query name in the collection matches a named query in the query file. IDataConnSet provides a method for adding query name / data connection pairs to the collection. In this way, AppLogic can use standardized queries and select and assign data connections dynamically at runtime.

Finally, the AppLogic calls loadHierQuery( ) to create the hierarchical query object.

Return Value
IDataConnSet object that can hold a collection of data connections, or null for failure (such as insufficient memory).

Example
IDataConnSet connSet;

connSet = createDataConnSet(0);
// Specify query / db connection pairs
connSet.addConn("employee", conn_empDB);
connSet.addConn("sales", conn_salesDB);
IHierQuery hqry;
// Load the GXQ file with the db connection set
hqry = loadHierQuery("employeeReport.gxq",connSet, 0, null);

// Run the report
evalTemplate("employeeReport.html", hqry);
Related Topics
loadHierQuery( ),
IDataConnSet interface

createHierQuery( )
Creates a new query object used for building and running a hierarchical query.

createHierQuery( ) is deprecated. In standard-based applications, use the JDBC API to create join statements.

Syntax
public IHierQuery createHierQuery()
Usage
Use createHierQuery( ) for nested output or for merging query results with a template using evalOutput( ) or evalTemplate( ).

A hierarchical query can be more complex than a flat query. A hierarchical query combines one or more flat queries which, when run on the database server, returns a result set with multiple nested levels of data. The number of nested levels is limited only by system resources.

The hierarchical query is not necessarily a single query. In fact, a hierarchical query is a collection of one or more flat queries arranged in a series of cascading parent-child, one-to-many relationships. The parent query obtains the outer level of information, or summary, and the child query obtains the inner level of information, or detail. The parent level of information determines the grouping of information in its child levels. The child query is run multiple times, once for each row in the parent query's result set.

Tips
Return Value
IHierQuery object representing a hierarchical query, or null for failure. An AppLogic module uses this object to uniquely identify this hierarchical query in subsequent operations, such as defining the query criteria, executing the query, retrieving query results, and processing templates.

Example 1
// Create the flat query

IQuery qry = createQuery();
qry.setTables("CTLusers");
qry.setFields("loginName, Password, AccessLevel")
qry.setOrderBy("LoginName);

// Create the hierarchical query used for template processing
IHierQuery hqry = createHierQuery();

// Add the flat query object and data connection to hqry
hqry.addQuery(qry, conn, "USERS", "", "");

// Pass hierarchical query to evalTemplate() for reporting
if(evalTemplate("apps/template/userinfo.html", hqry)== GXE.SUCCESS)
return result("");
else
return result("Failed to Generate HTML");
}
Example 2
// Create the flat query

IQuery qry = createQuery();
qry.setTables("CTLusers");
qry.setFields("loginName, Password, AccessLevel")
qry.setWhere("UserId > 100");

// Create the hierarchical query
IHierQuery hqry = createHierQuery();
hqry.addQuery(qry, conn, "USERS", "", "");

// Execute the hierarchical query
IHierResultSet hrs = hqry.execute(0, 0, null);

// Process rows in result set
if(hrs.getRowNumber("USERS")!=0)
. . .
Related Topics
addQuery( ) in the IHierQuery interface,
createDataConn( ),
createQuery( ),
execute( ) in the IHierQuery interface,
IHierQuery interface,
IHierResultSet interface

createMailbox( )
Creates an electronic mailbox object used for communicating with a user's mailbox.

Syntax
public IMailbox createMailbox(
String pHost,
String pUser,
String pPassword,
String pUserAddr)

pHost. Address of POP and SMTP server, such as mail.myOrg.com. If the POP and SMTP servers are running on different hosts, you must use two separate createMailbox( ) calls.

pUser. Name of user's POP account, such as jdoe.

pPassword. Password for POP server.

pUserAddr. Return address for outgoing mail, such as john@myOrg.com. Usually the electronic mail address of the user sending the message.

Usage
Use createMailbox( ) to set up a mail session for sending and receiving electronic mail messages.

In the Internet electronic mail architecture, different servers are used for incoming and outgoing messages.

Rules
Tip
Once instantiated, use the methods in the IMailbox interface to open and close a mailbox, as well as send and receive mail messages.

Return Value
IMailbox object representing a mailbox, or null for failure (such as an invalid parameter).

Related Topics
IMailbox interface

createQuery( )
Creates a new query object used for building and running a flat query.

createQuery( ) is deprecated. In standard-based applications, use the createStatement( ) method in the java.sql.Connection interface.

Syntax
public IQuery createQuery()
Usage
A flat query is the simplest type of query. It retrieves data in a tabular, non-hierarchical result set. Unlike a hierarchical query, a flat query returns a result set that is not divided into levels or groups.

An AppLogic can also use createQuery( ) to create a query object to perform SELECT, INSERT, DELETE, or UPDATE operations on a database.

Tips
Return Value
IQuery object representing a query, or null for failure. AppLogic uses this object to uniquely identify this query in subsequent operations, such as defining the query criteria, executing the query, retrieving query results, and processing templates.

Example
// Create the flat query object

IQuery qry = createQuery();
// Set up the query
qry.setTables("CTLcust");
qry.setFields("CustomerID, Customer");
qry.setWhere("Customer"+"='"+String.valueOf(custId)+"'");

// Execute the query
IResultSet rs = conn.executeQuery(0, qry, null, null);

// Check for a result set with rows
if((rs!=null)&&(rs.getRowNumber()>0))
return result("Sorry, this user ("+
firstName+" "+lastName+") already exists");
// Otherwise, process the result set . . .
Related Topics
createDataConn( ),
createQuery( ),
IHierQuery interface,
IHierResultSet interface,
executeQuery( ) in the IDataConn interface

createSession( )
Creates a new session object used for tracking a user session.

createSession( ) is deprecated. In standard-based applications, use the getSession( ) method in the interface javax.servlet.http.HttpSession, and set the boolean parameter to true.

Syntax
public ISession2 createSession(
int dwFlags,
int dwTimeout,
String pAppName,
String pSessionID,
ISessionIDGen pIDGen)

dwFlags. Specify one of the following flags, or 0 to use the default system settings:

The default scope is distributed and the default timeout is 60 seconds from the time the session was last accessed.

dwTimeout. Session timeout, in number of seconds, or zero for no timeout. The meaning of timeout depends on the timeout flag specified in dwFlags. A value of 0 means the session is deleted when the AppLogic calls destroySession( ).

pAppName. Name of the application associated with the session. The application name enables the Netscape Application Server to determine which AppLogics have access to the session data. Specify null to use the application name assigned to the AppLogic during kreg registration.

pSessionID. The session ID to use. Specify null to use the default ID generated by the system.

pIDGen. The session ID generation object used to generate session IDs. Specify null.

Usage
Use createSession( ) to create a new session between a user and your application. AppLogics use sessions to store information about each user's interaction with an application. For example, a login AppLogic might create a session object to store the user's login name and password. This session data is then available to other AppLogics in the application.

Rule
If you implement a custom session class, you must override createSession( ).

Return Value
ISession2 object representing a user session, or null for failure.

Example
In the following code, getSession( ) checks if a session exists. If there isn't an existing session, createSession( ) creates a new session.

ISession2 sess;

sess = getSession(0, "Catalog", null);
if (sess == null)
{
log("Could not get session, creating a new one");
sess = createSession(GXSESSION.GXSESSION_DISTRIB, 0,
null, null, null);
Related Topics
getSession( ),
saveSession( ),
Session2 class,
ISession2 interface

createTrans( )
Creates a new transaction object used for transaction processing operations on a database.

createTrans( ) is deprecated. In standard-based applications, call setAutoCommit(FALSE), a method in the java.sql.Connection interface.

Syntax
public ITrans createTrans()
Usage
Transaction processing allows the AppLogic to define a series of operations that succeed or fail as a group. If all operations in the group succeed, then the system commits, or saves, all of the modifications from the operations. If any operation in the group fails for any reason, then the AppLogic can roll back, or abandon, any proposed changes to the target table(s).

If your application requires transaction processing, use createTrans( ) to create a transaction object. Pass this transaction object to subsequent methods, such as addRow( ) or executeQuery( ), that make up a transaction.

Tips
Return Value
ITrans object representing a transaction, or null for failure. AppLogic uses this object to uniquely identify this transaction in subsequent transaction processing operations, such as beginning, committing, or rolling back a transaction.

Example
// Create and begin a transaction

ITrans trx = createTrans();
trx.begin();

// 1) Process the credit card
if(!processCreditCard(cusId, card, number, expirationDate, trx)) {
trx.rollback();
return result("Could not process the credit card information"); }

// 2) Process the invoice record
InfoHolder info=new InfoHolder();
if(!makeInvoiceRecord(cusId, number, trx, info)) {
trx.rollback();
return result("Could not create the invoice record"); };

// 3) Process products on the invoice
if(!makeInvoiceEntries(info.invoiceId, trx)) {
trx.rollback();
return result("Can't create product records"); };

// 4) Process optional shipping information
if(shippingInfo && !makeShippingRecord(info.invoiceId, trx, addr1, addr2, city, state, zip)) {
trx.rollback();
return result("Could not create the shipping information record"); };

// 5) Process the inventory for each purchased product
if(!reduceProductInventory(trx)) {
// Problem occurred - abandon everything
trx.rollback();
return result("Could not reduce inventory");
}

// No problem occurred - save everything
trx.commit(0);
// Return success message / report
Related Topics
ITrans interface

deleteCache( )
Deletes the result cache for a specified AppLogic.

Syntax
public int deleteCache(
String guid)

guid. The guid that identifies the AppLogic whose result cache to delete. Specify null to delete the current AppLogic's cache.

Usage
To free system resources, use deleteCache( ) to clear all results from an AppLogic's cache when the results are no longer needed. This method also stops further caching of results.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
int hr;

String guid = valIn.getValString("applogic");

hr = deleteCache(guid);

if (hr == GXE.SUCCESS)
return result("Successfully deleted cache")
else
return result("Failed to delete cache");
Related Topics
removeAllCachedResults( ),
removeCachedResult( ),
setCacheCriteria( )

destroySession( )
Deletes a user session.

destroySession( ) is deprecated. In standard-based applications, use the invalidate( ) method in the interface javax.servlet.http.HttpSession.

Syntax
public int destroySession(
ISessionIDGen pIDGen)

pIDGen. The session ID generation object used to generate session IDs. Specify null .

Usage
To increase security and conserve system resources, use destroySession( ) to delete a session between a user and the application when the session is no longer required. An AppLogic typically calls destroySession( ) when the user logs out of an application.

Tip
If the AppLogic set a timeout value for the session when it was created, you need not delete the session explicitly with destroySession( ). The session is deleted automatically when the timeout expires.

Return Value
GXE.SUCCESS if the method succeeds.

Related Topics
createSession( ),
getSession( )

evalOutput( )
Creates an output report by merging data with a report template file. Depending on the client—AppLogic or web browser—evalOutput( ) returns either a self-describing data stream or HTML output.

evalOutput( ) is deprecated. In standard-based applications, similar functionality can be achieved by using the interface javax.servlet.RequestDispatcher.

Syntax 1
Merges a template with data from a hierarchical query object.

public int evalOutput(
String templatePath,
IHierQuery query,
ITemplateMap map,
IStream stream,
IValList props);
Syntax 2
Merges a template with data from an ITemplateData object or IHierResultSet object. IHierResultSet objects implement the ITemplateData interface.

public int evalOutput(
String templatePath,
ITemplateData data,
ITemplateMap map,
IStream stream,
IValList props);

templatePath. Path to the template file used to create the report. At a minimum, specify the file name. Do not specify the filename extension; for example, specify "report" instead of "report.html". The evalOutput( ) method automatically uses the correct filename extension depending on the client type. Use a relative path whenever possible. The Netscape Application Server first searches for the template using the specified path. If the template is not found, the Netscape Application Server uses the configured TEMPLATE\PATH search path to find it. For more information on configuring the search path, see Administration Guide.

query. Hierarchical query object from which evalOutput( )createTrans( ) derives the hierarchical result set to merge with the template. The Template Engine runs the query on the database server. To specify this parameter, the AppLogic must first create the specified hierarchical query, using createHierQuery( ) in the AppLogic class, and then define it using methods in the IHierQuery interface or calling loadHierQuery( ).

map. Field map that links template fields to calculated values. Fields in the template are expressed with the cell type gx tags. Additionally, the map can be used to map source data with a non-matching field name but identically-formatted data. To specify this parameter, the AppLogic should instantiate the TemplateMapBasic class, add template / field mappings using put( ) in the ITemplateMap interface, then pass the populated ITemplateMap object to evalOutput( ) for template processing.

stream. The output stream where results will be captured for subsequent retrieval and processing. Specify null to use the default stream, which sends results back to the client. To specify this parameter, an AppLogic creates a stream buffer object from IStreamBuffer, which it passes to evalOutput( ). After evalOutput( ) returns, the AppLogic calls getStreamData( ) in the IStreamBuffer interface to retrieve the contents of the buffer as an array of byte values.

data. ITemplateData object containing data. This can be a hierarchical result set from executing a hierarchical query or it can be data programmatically organized in memory. To specify this data in memory, an AppLogic must first instantiate the TemplateDataBasic class (or implement your own version of the ITemplateData interface), populate the ITemplateData object with rows of hierarchical data, then pass it to evalOutput( ) for template processing.

props. Specify null.

Usage
Use evalOutput( ) in an AppLogic that returns output to different types of clients. The evalOutput( ) method detects the client type, selects the appropriate template file to merge with the data, and generates the appropriate output, as described in the following table:

Client
Template File Used by evalOutput( )
Output Returned by evalOutput( )
Web browser
HTML
HTML page
AppLogic that passed to its newRequest( ) call the following key and value in the input IValList parameter:
key: gx_client_type
value: "ocl"
GXML
Self-describing data stream, which contains the names of the fields in the result set and their values.
AppLogic that does not specify a client type explicitly, or that passed to its newRequest( ) call the following key and value in the input IValList parameter:
key: gx_client_type
value: "http"
HTML
HTML page

Both the GXML and HTML template files contain embedded tags, called GX tags, that specify how the Template Engine merges dynamic data with the template to produce the output report. In addition, the HTML template file can contain graphics, static text, and other components, just like any HTML-formatted document.

The data that the Template Engine merges with the template can come from several sources. Most commonly, it comes from the result set of a hierarchical query. However, it can also come from an ITemplateData object containing data organized hierarchically in memory.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
// Create a hierarchical query used for template processing

IHierQuery hqry = createHierQuery();

// Add a flat query object and data connection to hqry
hqry.addQuery(qry, conn, "USERS", "", "");

// Pass hierarchical query to evalOutput() for reporting
if(evalOutput("apps/template/userinfo", hqry)== GXE.SUCCESS)
return result("");
else
return result("Failed to Generate HTML");
}
Related Topics
evalTemplate( ),
result( ),
IHierQuery interface,
TemplateDataBasic class and the ITemplateData interface,
TemplateMapBasic class and the ITemplateMap interface

evalTemplate( )
Creates an output report by merging data with a report template file. The report is an HTML document that can be viewed using a Web browser.

evalTemplate( ) is deprecated. In standard-based applications, similar functionality can be achieved by using the interface javax.servlet.RequestDispatcher.

Syntax 1
Merges an HTML report template with data from a hierarchical query object.

public int evalTemplate(
String path,
IHierQuery query)
Syntax 2
Merges an HTML report template with data from a hierarchical query object.

public int evalTemplate(
String path,
IHierQuery query,
ITemplateMap map,
IStream stream)
Syntax 3
Merges an HTML report template with data from an ITemplateData object or IHierResultSet object. IHierResultSet objects implement the ITemplateData interface.

public int evalTemplate(
String path,
ITemplateData data,
ITemplateMap map)

path. Path to the HTML template file used to create the report. At a minimum, specify the file name. Use a relative path whenever possible. The Netscape Application Server first searches for the template using the specified path. If the template is not found, the Netscape Application Server uses the configured TEMPLATE\PATH search path to find it. For more information on configuring the search path, see the Administration Guide.

query. Hierarchical query object from which evalTemplate( ) derives the hierarchical result set to merge with the HTML template. The Template Engine runs the query on the database server. To specify this parameter, the AppLogic must first create the specified hierarchical query, using createHierQuery( ) in the AppLogic class, and then define it using methods in the IHierQuery interface or calling loadHierQuery( ).

map. Field map that links template fields to calculated values. Fields in the template are expressed with the cell type gx tags. Additionally, the map can be used to map source data with a non-matching field name but identically-formatted data. To specify this parameter, the AppLogic should instantiate the TemplateMapBasic class, add template / field mappings using put( ) in the ITemplateMap interface, then pass the populated ITemplateMap object to evalTemplate( ) for template processing.

stream. The output stream where results will be captured for subsequent retrieval and processing. Specify null to use the default stream, which sends results back to the client. To specify this parameter, an AppLogic creates a stream buffer object from IStreamBuffer, which it passes to evalOutput( ). After evalTemplate( ) returns, the AppLogic calls getStreamData( ) in the IStreamBuffer interface to retrieve the contents of the buffer as an array of byte values.

data. ITemplateData object containing data. This can be a hierarchical result set from executing a hierarchical query or it can be data programmatically organized in memory. To specify this data in memory, an AppLogic must first instantiate the TemplateDataBasic class (or implement your own version of the ITemplateData interface), populate the ITemplateData object with rows of hierarchical data, then pass it to evalTemplate( ) for template processing.

Usage
Use evalTemplate( ) to create an HTML report by merging data with an HTML template file. An HTML template is an HTML document with the addition of special embedded tags, called GX tags, that specify how the Template Engine merges dynamic data with the template to produce the output report or HTML page. In addition to these dynamic links, a template can contain static text, graphics, and other components, just like any HTML-formatted document.

The data that the Template Engine merges with the template can come from several sources. Most commonly, it comes from the result set of a hierarchical query. However, it can also come from an ITemplateData object containing data organized hierarchically in memory.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
// Create the flat query

IQuery qry = createQuery();
qry.setTables("CTLusers");
qry.setFields("loginName, Password, AccessLevel");
qry.setOrderBy("LoginName");

// Create the hierarchical query used for template processing
IHierQuery hqry = createHierQuery();

// Add the flat query object and data connection to hqry
hqry.addQuery(qry, conn, "USERS", "", "");

// Pass hierarchical query to evalTemplate() for reporting
if(evalTemplate("apps/template/userinfo.html", hqry)==GXE.SUCCESS)
return result("");
else
return result("Failed to Generate HTML");
}
Related Topics
evalOutput( ),
IHierQuery interface,
TemplateDataBasic class and the ITemplateData interface,
TemplateMapBasic class and the ITemplateMap interface

execute( )
Performs the main task of an AppLogic, such as accessing a database, generating a report, or other operations. It should be overridden in your AppLogic subclass.

execute( ) is deprecated. In standard-based applications, use one of the request processing methods in the class javax.servlet.http.HttpServlet. For example, use doGet( ), doPost( ), or service( ).

Syntax
public int execute()
Usage
Netscape Application Server calls the AppLogic's execute( ) method automatically whenever a request is received for an AppLogic, such as when a user submits a form or an information request.

Rule
By default, execute( ) does nothing except return a value of zero (0). You should always write code to override this method in your AppLogic derived class.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
The following example overrides the execute( ) method to display "Hello world":

package gxApp.sample

import java.lang.*;
import com.kivasoft.*;
import com.kivasoft.types.*;
import com,kivasoft.util.*;
import com.kivasoft.applogic.*;

public class HelloWorldAppLogic extends AppLogic {
public int execute() {
// Simple code that overrides execute() method
return result("Hello world!");
}
}
Related Topics
result( ),
IValList interface

getAppEvent( )
Retrieves the application event object.

getAppEvent( ) is deprecated. See New Usage section for more information.

Syntax
public IAppEvent getAppEvent()
New Usage
This method is deprecated and is provided for backward compatibility only.

New applications should use the IAppEventMgr interface and IAppEventObj interface, along with the GetAppEventMgr( ) method in the com.kivasoft.dlm.GXContext class.

Old Usage
Use getAppEvent( )to retrieve an IAppEvent object. Through the IAppEvent interface, you can create and manage application events. An AppLogic uses application event objects to define events that are triggered at a specified time or times or when triggered explicitly.

Return Value
IAppEvent object, or null for failure.

Related Topics
IAppEvent interface,
registerEvent( ) in the IAppEvent interface

getSession( )
Returns an existing user session.

getSession( ) is deprecated. In standard-based applications, use the getSession( ) method in the interface javax.servlet.http.HttpSession.

Syntax
public ISession2 getSession(
int dwFlags,
String appName,
ISessionIDGen pIDGen)

dwFlags. Specify 0 (zero).

pAppName. Name of the application associated with the session. The application name enables the Netscape Application Server to determine which AppLogics have access to the session data. Specify null to use the application name assigned to the AppLogic during kreg registration.

pIDGen. The session ID generation object used to generate session IDs. Specify null.

Usage
Use getSession( ) to obtain an existing session. Use it also to determine if a user session exists before calling createSession( ) to create one.

Rule
If you implement a custom session class, you must implement your own method to get a session, which in turn, can call the getSession( ) method.

Return Value
ISession2 object representing a user session, or null for failure.

Example 1
In the following code, getSession( ) checks if a session exists. If there isn't an existing session, createSession( ) creates a new session.

ISession2 sess;

sess = getSession(0, "Catalog", null);
if (sess == null)
{
log("Could not get session, creating a new one");
sess = createSession(GXSESSION.GXSESSION_DISTRIB, 0,
null, null, null);
Example 2
In the following code, getSession( ) gets an existing session, then checks if the user is authorized to perform a secured task:

public class ProductRestock extends AppLogic

{
public int execute()
{
try {
ISession2 mySess;
mySess = getSession(0, null, null);
if (mySess == null) {
log("missing session");
return evalOutput("kivaapp/shop/please_login",
(ITemplateData) null,
(ITemplateMap) null, null, null);
}
// Check to see if the current role is authorized
// to update inventory.
//
if (isAuthorized("Shop_Inventory", "WRITE") !=
GXACLPERMSTATUS.GXACL_ALLOWED)
{
log("unauthorized access: Shop_Inventory");
return evalOutput("kivaapp/shop/no_access",
(ITemplateData) null,
(ITemplateMap) null, null, null);
}
// Record the inventory restock transaction.
Related Topics
createSession( ),
loginSession( ),
saveSession( ),
Session2 class,
ISession2 interface

getStateTreeRoot( )
Returns an existing root node of a state tree or creates a new one.

Syntax
public IState2 getStateTreeRoot(
int dwFlags,
String pName)

dwFlags. Specify one of the following flags or zero to use the default settings:

pName. The name of the root node. If a node with this name doesn't already exist, a new node is created.

Usage
Use getStateTreeRoot( ) to create a state tree. A state tree is a hierarchical data storage mechanism. It is used primarily for storing application data that needs to be distributed across server processes and clusters.

Return Value
IState2 object representing the root node, or null for failure.

Example
The following code shows how to create a state tree and a child node:

IState2 tree = getStateTreeRoot(GXSTATE.GXSTATE_DISTRIB, "Grammy");


if (tree!=null)
{
IState2 child = tree.getStateChild("Best Female Vocal");
if (child == null)
{
child = tree.createStateChild("Best Female Vocal", 0,
GXSTATE.GXSTATE_DISTRIB);
Related Topics
IState2 interface

isAuthorized( )
Checks a user's permission level to a specified action or AppLogic.

isAuthorized( ) is deprecated. As of the 2.1 servlet specification, there is no standard security model for servlets. However, NAS provides a security model. In servlets, use the equivalent isAuthorized( ) method, available from the HttpSession2 interface in package com.netscape.server.servlet.extension.

Syntax 1
Use in most cases.

public int isAuthorized(
String pTarget,
String pPermission)
Syntax 2
Contains several parameters that are placeholders for future functionality.

public int isAuthorized(
String pDomain,
String pTarget,
String pPermission,
int method,
int flags,
ICred pCred,
IObject pEnv)

pDomain. The type of Access Control Lists (ACL). An ACL (created by the server administrator) defines the type of operations, such as Read or Write, that a user or group can perform. There are two types of ACLs: AppLogic and general. For this parameter, specify one of the following strings, which specifies the type of ACL to check for this user:

"kiva:acl,logic"

"kiva:acl,general"

pTarget. The name of the ACL, if the ACL is a general type. If the ACL is an AppLogic ACL, specify the AppLogic name or GUID string.

pPermission. The type of permission, for example, "EXECUTE."

method. Specify 0.

flags. Specify 0.

pCred. Specify null.

pEnv. Specify null.

Usage
Use isAuthorized( ) in portions of the code where application security is enforced through Access Control Lists (ACL). This method lets an application check if a user has permission to execute an AppLogic or perform a particular action. The application can use the result of isAuthorized( ) as a condition in an If statement. It can, for example, return a message to users who are denied access to an AppLogic.

Application developers should obtain the list of registered ACLs, users and groups from the server administrator who created these items. ACLs are created through the Enterprise Administrator tool or through the kreg tool.

Rule
Before calling isAuthorized( ), the application must create a session with createSession( ) and a user must be logged in with loginSession( ).

Return Value
One of the following:

Value
Description
GXACLPERMSTATUS.GXACL_ALLOWED
The specified permission is granted to the user.
GXACLPERMSTATUS.GXACL_NOTALLOWED
The specified permission is not granted to the user.
GXACLPERMSTATUS.GXACL_DONTKNOW
The specified permission is unlisted or there is conflicting information.

Example
if (isAuthorized("MonthlyForecast", "READ") != 
GXACLPERMSTATUS.GXACL_ALLOWED)

return result("<html><body>sorry no access</body></html>);
else
// run monthly forecast report
Related Topics
loginSession( )

isCached( )
Returns true if AppLogic results are being saved in the result cache.

Syntax
public boolean isCached()
Usage
Call isCached( ) to determine whether caching is enabled for the current AppLogic. You should, for example, call isCached( ) before calling setCacheCriteria( ) to avoid inadvertently overwriting the current contents of the result cache.

Return Value
A boolean true if caching is enabled, or a boolean false if not.

Example
// Determine whether AppLogic is cached

// before setting cache criteria
if(!isCached()) {
log("Setting agent cache criteria");
if(setCacheCriteria(60, 3, "category")!=0)
log("Could not set agent cache criteria");
else
log("Succeeded in setting agent cache criteria");
}
else
log("Not setting agent cache criteria");
Related Topics
skipCache( )

loadHierQuery( )
Creates a hierarchical query by loading a query file containing one or more query names and associated data connections.

loadHierQuery( ) is deprecated. In standard-based applications, use the JDBC API to execute a join statement.

Syntax
public IHierQuery loadHierQuery(
String pFileName,
IDataConnSet pDataConnSet,
int flags,
IValList pParams)

pFileName. Name of the query (.GXQ) file, including the path. Use a relative path when possible.

A query file is an ASCII text file containing one or more SQL statements. You can create the file using any ASCII text editor. Use the following syntactical guidelines:

pDataConnSet. Collection of query name/data connection pairs. The query names in the collection must match the named queries in the query file. The associated IDataConn object identifies the data connection for the query.

flags. Specify 0 (zero). Internal use only.

pParams. IValList of query file parameters, or null. A collection of placeholders for the WHERE clause. A placeholder may be a name or a number. It is prefixed by a colon (:) character. The placeholders can be replaced by specifying replacement values in the ValList parameter.

Usage
Use loadHierQuery( ) to create a hierarchical query object. An AppLogic can retrieve standardized queries stored in a data file and, at runtime, can dynamically select and assign the data sources on which the query is run. You create the query file separately using the Query Designer or an ASCII text editor, ANSI 89 standard SQL SELECT statements, and specialized syntax. A query file can define both flat and hierarchical queries.

To use a query file, the AppLogic first establishes a data connection with each database on which any queries will be run. Next, the AppLogic calls createDataConnSet( ) in the AppLogic class to create an IDataConnSet collection, then populates this collection with query name / data connection pairs. Each query name in the collection matches a named query in the query file.

IDataConnSet provides a method for adding query name / data connection pairs to the collection. In this way, AppLogic can use standardized queries and assign data connections dynamically at runtime. Finally, the AppLogic calls loadHierQuery( ) to create the hierarchical query object.

Rules
Return Value
IHierQuery object representing a hierarchical query, or null for failure (such as query file not found). The AppLogic uses this object to uniquely identify this hierarchical query in subsequent operations, such as defining the query criteria, executing the query, retrieving query results, and processing templates.

Example
The following example shows a query (GXQ) file and a section of an AppLogic that loads the hierarchical query file and creates an HTML report:

Query file:

/* STATES */

query STATES using (ODBC, kstates, kuser) is
select STATES.STATE as STATES_STATE
from STATES
where (STATES.REGION = ':REGION')
order by STATES.STATE asc

/* DETAILS */
query DETAILS using (ODBC, kdetails, kuser) is
select COUNTIES.COUNTYNAM as COUNTIES_COUNTYNAM,
COUNTIES.POP as COUNTIES_POP,
COUNTIES.STATE as COUNTIES_STATE
from COUNTIES
order by COUNTIES.COUNTYNAM asc

join DETAILS to parent STATES
where DETAILS.COUNTIES.STATE = 'STATES.STATES_STATE'
AppLogic code snippet:

IDataConnSet connSet;

connSet = createDataConnSet(0);

// Create database connections
IDataConn conn_detailDB = createDataConn(0, GX_DA_DAD_DRIVERS.GX_DA_DRIVER_DEFAULT, "kdetails", "", "kuser", "kpassword");

IDataConn conn_statesDB = createDataConn(0, GX_DA_DAD_DRIVERS.GX_DA_DRIVER_ODBC, "kstates", "", "kuser", "kpassword");

// Specify query / db connection pairs
connSet.addConn("DETAILS", conn_detailDB);
connSet.addConn("STATES", conn_statesDB);

// Create IValList that contains the REGION parameter
// value to pass to the hierarchical query
IValList param = GX.CreateValList();
param.setValString("REGION", "WEST");

IHierQuery hqry;
// Load the GXQ file with the db connection set and
// parameter value
hqry = loadHierQuery("state.gxq", connSet, 0, param);

// Run the report
evalTemplate("state.html", hqry);
Related Topics
createDataConnSet( ),
IDataConnSet interface,
IHierQuery interface

loadQuery( )
Creates a flat query by loading a query file.

loadQuery( ) is deprecated. Instead, use loadQuery( ) from the class com.kivasoft.util.SqlUtil.

Syntax
public IQuery loadQuery(
String pFileName,
String pQueryName,
int flags,
IValList pParams)

pFileName. Name of the query (.GXQ) file, including the path. Use a relative path when possible.

A query file is an ASCII text file containing one or more SQL statements. You can create the file using any ASCII text editor. Use the following syntactical guidelines:

pQueryName. Name of the query in the query file.

flags. Specify 0 (zero). Internal use only.

pParams. IValList of query file parameters, or null. A collection of placeholders for the WHERE clause. A placeholder may be a name or a number. It is prefixed by a colon (:) character. The placeholders can be replaced by specifying replacement values in the IValList parameter.

Usage
Use loadQuery( ) to create a flat query object by loading a query (.GXQ) file. An AppLogic can retrieve standardized queries stored in a data file and, at runtime, can dynamically select and assign the data source on which the query is run.

You create the query file separately using the Query Designer or an ASCII text editor, ANSI 89 standard SQL SELECT statements, and special syntax.

To run the flat query, call executeQuery( ) in the IDataConn interface (deprecated).

Return Value
IQuery object, or null for failure (such as query file not found).

Example
The following example shows a query (GXQ) file and a section of an AppLogic that loads and executes the query:

Query file:

/* STATES */

query STATES using (ODBC, kstates, kuser) is
select STATES.STATE as STATES_STATE
from STATES
where (STATES.REGION = ':REGION')
order by STATES.STATE asc
AppLogic code snippet:

// Create database connection

IDataConn conn = createDataConn(0, GX_DA_DAD_DRIVERS.GX_DA_DRIVER_DEFAULT, "kstates", "", "kuser", "kpassword");

// Create IValList that contains the REGION parameter
// value to pass to the query
IValList param = GX.CreateValList();
param.setValString("REGION", "WEST");

IQuery qry;
// Load the query file with the parameter value
qry = loadQuery("state.gxq", "STATES", 0, param);

// Execute the query
IResultSet rs = conn.executeQuery(
GX_DA_EXECUTEQUERY_FLAGS.GX_DA_RS_BUFFERING, qry, null, null);
Related Topics
IQuery interface (deprecated)

log( )
Writes a message to the server log.

log( ) is deprecated. In standard-based applications, use one of the log( ) methods available from the javax.servlet package. For example, refer to the GenericServlet class or the ServletContext interface.

Syntax 1
Logs a message (type = GXLOG.GXEVENTTYPE_INFORMATION and category = 0).

public int log(
String msg)
Syntax 2
Logs an event with a message, specifying the type and category of event.

public int log(
int type,
int category,
String msg)

msg. Message text to log.

type. Message type. Use one of the following variables:

category. User-defined message category. Do not use the range of values reserved for the Netscape Application Server systems, which is 0 to 65535, inclusive.

Usage
Use log( ) for displaying or storing simple messages or for debugging. The output can be directed to the console, to a text file, or to a database table. To direct output, use the Netscape Application Server Administrator. For more information, see the Administration Guide.

Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Log a message

log("This is the message text saved to the log");
Example 2
// Log messages that include String variables

log(firstName+lastName+password+" "+String.valueOf(cusId));
log(GXLOG.GXEVENTTYPE_ERROR", -1, Cannot find table: "+"Shipping");
loginSession( )
Logs an authorized user into a session with a secured application.

loginSession( ) is deprecated. As of the 2.1 servlet specification, there is no standard security model for servlets. However, NAS provides a security model. In servlets, use the equivalent loginSession( ) method, available from the HttpSession2 interface in package com.netscape.server.servlet.extension.

Syntax 1
Use in most cases.

public int loginSession(
String name,
String password)
Syntax 2
Contains several parameters that are placeholders for future functionality.

public int loginSession(
String pDomain,
int dwMethod,
int dwFlags,
String pName,
byte[] pAuthData,
int nAuthData)

name. The login user name.

password. The user password.

pDomain. Specify null.

dwMethod. Specify 0.

dwFlags. Specify 0.

pName. The login user name.

pAuthData. The user password.

nAuthData. The size of the password.

Usage
Call loginSession( ) after creating a user session with createSession( ) or after retrieving a user session with getSession( ). loginSession( ) checks the passed in login name and password against the user names and passwords stored in the Netscape Application Server (the administrator sets up and manages this information) and logs the user into the session if the login name and password are valid.

If login is successful, a security credential object is created and associated with the session. The server checks this security credential object each time it receives an AppLogic request, and verifies if the user has execute permission for the AppLogic.

Using loginSession( ) in conjunction with isAuthorized( ), an application can ensure that only authorized users can execute certain AppLogics or take certain actions.

Tip
The server administrator creates users and passwords and manages access to AppLogics and specified resources, such as sales or forecast reports. During the development and debugging phases, application developers can use the ldapmodify tool to create users, groups, and ACLs in the LDIF file. These tasks cannot be done programmatically.

Return Value
GXE.SUCCESS if the method succeeds.

Example
public class Welcome extends AppLogic

{
public int execute()
{
try {

// Check user login
if (valIn.getValString("NAME") == null ||
valIn.getValString("PASSWORD") == null) {
log("missing login NAME/PASSWORD");
return evalOutput("kivaapp/shop/login_again",
(ITemplateData) null,
(ITemplateMap) null, null, null);
}
// If login succeeds, create a session
ISession2 mySess;
mySess = getSession(0, null, null);
if (mySess == null) {
mySess=createSession(0, 60000, null, null, null);
log("created session: " + String.valueOf(mySess != null));
} else
log("got session");

// Now, look up user NAME/PASSWORD in database
// and see what role the user has. The database
// should have a user table which tracks all the
// users of the online shop application.
//
String role;
role = /* Database lookup here. */ "Shop_Customer";

// Call loginSession() to set up the session with
// that role. Future requests to AppLogics in this
// session will now operate under the right role.
//
loginSession(role, "");
saveSession(null);

// Check to see if the current role is authorized
// against some of the more advanced operations,
// and choose the appropriate main menu page to
// return to the user.
//
if (isAuthorized("Shop_Inventory", "READ") ==
GXACLPERMSTATUS.GXACL_ALLOWED ||
isAuthorized("Shop_Daily_Forecast", "READ") ==
GXACLPERMSTATUS.GXACL_ALLOWED ||
isAuthorized("Shop_Weekly_Forecast", "READ") ==
GXACLPERMSTATUS.GXACL_ALLOWED)
return evalOutput("mainmenu_advanced",
(ITemplateData) null,
(ITemplateMap) null, null, null);
return evalOutput("kivaapp/shop/mainmenu_regular",
(ITemplateData) null,
(ITemplateMap) null, null, null);
} finally {
}
}
}
Related Topics
isAuthorized( ),
logoutSession( )

logoutSession( )
Logs a user out of a session with a secured application.

logoutSession( ) is deprecated. As of the 2.1 servlet specification, there is no standard security model for servlets. However, NAS provides a security model. In servlets, use the equivalent isAuthorized( ) method, available from the HttpSession2 interface in package com.netscape.server.servlet.extension.

Syntax
public int logoutSession(
int dwFlags)

dwFlags. Specify 0.

Usage
If the AppLogic called loginSession( ) to log into a session with a secured application, call logoutSession( )when the user exits the application, or the secured portion of it.

Rule
Call getSession( ) before calling logoutSession( ).

Return Value
GXE.SUCCESS if the method succeeds.

Related Topics
getSession( ),
isAuthorized( ),
loginSession( )

newRequest( )
Calls another AppLogic from within the current AppLogic.

Syntax 1
Passes in the ValIn and ValOut of the current AppLogic to the called AppLogic. If the called AppLogic streams results, the calling AppLogic streams the same results.

public int newRequest(
String guidSTR)
Syntax 2
Passes in the specified valIn and valOut.

public int newRequest(
String guidSTR,
IValList vIn,
IValList vOut)
Syntax 3
Use to explicitly specify the location of AppLogic execution.

public int newRequest(
String guidSTR,
IObject vIn,
IObject vOut,
int host,
int port,
int flag)

guidSTR . String GUID or name of the AppLogic to execute.

vIn. IValList object containing input parameters to pass to the called AppLogic.

vOut. IValList object containing result values of the called AppLogic.

host. IP address of the Internet host of the Netscape Application Server where the AppLogic is to be executed. Specify 0 to execute the AppLogic locally.

port. Internet port of the Netscape Application Server where the AppLogic is to be executed. Specify 0 to execute the AppLogic locally.

flag. Specify zero.

Usage
Use newRequest( ) to call another AppLogic from within the current AppLogic. When it calls newRequest( ), the AppLogic passes to the Netscape Application Server the GUID or name of the AppLogic to execute and, optionally, any input and output parameters.

Netscape Application Server constructs a request using the parameters specified and processes it like any other request, by instantiating the AppLogic and passing in its parameters. The results from the called AppLogic module are returned to the calling AppLogic.

The AppLogic that newRequest( ) invokes can do one of the following tasks:

If the called AppLogic uses evalOutput( ) to stream results, evalOutput( ) returns HTML results by default. The current AppLogic can, however, specify that evalOutput( ) return a non-HTML data stream by setting the gx_client_type key to "ocl" in the input IValList of newRequest( ). For example:

vallist.setValString("gx_client_type", "ocl");
Rule
The specified GUID string, input parameters, and output parameters must be valid for the specified AppLogic.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Call specified AppLogic and pass parameters

newRequest("{E5CA1000-6EEE-11cf-96FD-0020AFED9A65}",
paramsToModule, paramsReturned);
Example 2
// Use DisplayBasket AppLogic to display the contents

if(newRequest("DisplayBasket", valIn, valOut)==0){
return 0;
}
else
return result("Cannot execute DisplayBasket AppLogic");
Related Topics
GUID class,
IValList interface

newRequestAsync( )
Calls another AppLogic from within the current AppLogic, and runs it asynchronously.

Syntax 1
Passes in the ValIn and ValOut of the AppLogic.

public IOrder newRequestAsync(
String guidSTR)
Syntax 2
Passes in the specified valIn and valOut.

public IOrder newRequestAsync(
String guidSTR,
IValList vIn,
IValList vOut)
Syntax 3
Use to explicitly specify the location of AppLogic execution.

public IOrder newRequest(
String guidSTR,
IObject vIn,
IObject vOut,
int host,
int port,
int flag)

guidSTR . String GUID or name of the AppLogic to execute.

vIn. IValList object containing input parameters to pass to the called AppLogic.

vOut. IValList evalOutput( ) object containing result values of the called AppLogic.

host. IP address of the Internet host of the Netscape Application Server where the AppLogic is to be executed. Specify 0 to execute the AppLogic locally.

port. Internet port of the Netscape Application Server where the AppLogic is to be executed. Specify 0 to execute the AppLogic locally.

flag. Specify 0.

Usage
Use newRequestAsync( ) to call another AppLogic from within the current AppLogic, and run it asynchronously. Executing an AppLogic asynchronously is useful if the AppLogic performs a lengthy operation, or if the AppLogic acts as a monitor or remains persistent. For example, an asynchronous AppLogic may perform a lengthy database query to produce a complex result set that it sends an e-mail to a destination address. Another AppLogic module may run continuously and re-index HTML pages every 24 hours.

When an AppLogic calls newRequestAsync( ), it passes to the Netscape Application Server the GUID of the AppLogic module to execute and, optionally, any input and output parameters.

The Netscape Application Server constructs a request using the parameters specified and processes it like any other request, by instantiating the AppLogic and passing in its parameters. The results from the called AppLogic module are returned to the calling AppLogic.

The AppLogic that newRequestAsync( ) invokes can do one of the following tasks:

Rules
Tips
Return Value
IOrder object, or null for failure.

Example
Orders[] = new IOrder[1];

int nOrder;

Orders[0] = newRequestAsync(asyncGUIDStr, valIn, valOut);
if (Orders[0] != null)
{
log("Successfully invoked async AppLogic\n");

// wait for async applogic to finish (max 100 seconds)
nOrder = GX.WaitForOrder(Orders, context, 100);
if (nOrder >= 0)
{
return result("Error in executing async request:
order wait returned an error");
}
else
{
getStateIOrder state = Orders[0].getState();
if (state == null || state.pdwState != GXE.SUCCESS)
return result("Error in executing async
request");
}
}
else
{
log("Failed to invoke async AppLogic\n");
}
Related Topics
GUID class,
IOrder interface,
IValList interface

removeAllCachedResults( )
Clears an AppLogic's result cache.

Syntax
public int removeAllCachedResults(
String guid)

guid. The guid that identifies the AppLogic whose result cache to clear. Specify null to clear the current AppLogic's cache.

Usage
To free system resources, use removeAllCachedResults( ) to clear an AppLogic's result cache when the results are no longer needed. This method clears the cache, but does not disable caching.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
int hr;

String guid = valIn.getValString("applogic");

hr = removeAllCachedResults(guid);
if (hr == GXE.SUCCESS)
return result("Successfully cleared cached results")
else
return result("Failed to clear cached results");
Related Topics
deleteCache( ),
removeCachedResult( ),
setCacheCriteria( )

removeCachedResult( )
Clears a specific result from an AppLogic's result cache.

Syntax
public int removeCachedResult(
String guid,
IValList criteria)

guid. The guid that identifies the AppLogic whose cached result to clear. Specify null to clear the current AppLogic's cached result.

criteria. An IValList object that contains the criteria for selecting the result to remove. In the IValList object, set a specific value that matches the cache criteria passed to setCacheCriteria( ). For example, if the cache criteria passed to setCacheCriteria( ) was "Salary=40000-60000"), you can remove results where salary is 50000 by setting in the IValList object a "Salary" key to a value of "50000".

Usage
Use removeCachedResult( ) to clear a specific result from an AppLogic's cache when the result is no longer needed.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example
int hr;

String guid = valIn.getValString("applogic");

IValList resultList = GX.CreateValList();
resultList.setValString("Salary", "50000");

hr = removeCachedResult(guid, resultList);

if (hr == GXE.SUCCESS)
return result("Successfully deleted specified result")
else
return result("Failed to delete specified result");
Related Topics
deleteCache( ),
removeAllCachedResults( ),
setCacheCriteria( )

result( )
Specifies the return value of an AppLogic.

result( ) is deprecated. In standard-based applications, use similar functionality as defined in the Servlet API. For example, refer to javax.servlet.ServletOutputStream or javax.servlet.http.HttpServletResponse.

Syntax
public int result(
String result)

result. Text representing the result value of the current AppLogic.

Usage
Use result( ) in conjunction with the execute( ) method to define a return value for an AppLogic. In general, use result( )in an AppLogic that services HTTP or HTML requests and returns a simple HTML string that does not require streaming.

In the execute( ) method, the AppLogic can call result( )in conjunction with the return statement to send data results directly back to the entity that called the AppLogic.

Rule
An AppLogic can stream results using streamResultHeader( ) or streamResult( ) . If the AppLogic streams results, call result( ) only after finishing streaming.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Return a simple HTML string

public class HelloWorld extends AppLogic {
public int execute() {
return result("Hello, world!\n");
}
}
Example 2
// Dynamically create the return string

public int execute() {
String resultStr;
String text;
text = valIn.getValString("Incoming Text");
if (text == null)
resultStr = "No input text.";
else if (text.indexOf('-') >= 0)
resultStr = "Input text has a hyphen.";
else
resultStr = "Input text has no hyphen.";
resultStr = "<HTML>" + resultStr + "</HTML>";
return result(resultStr);
}
Related Topics
execute( ),
streamResult( ),
streamResultHeader( )

saveSession( )
Saves changes to a session.

saveSession( ) is deprecated. In standard-based applications, this method is unnecessary because the functionality is automatically provided.

Syntax
public int saveSession(
ISessionIDGen pIDGen)

pIDGen. The session ID generation object used to generate session IDs. Specify null.

Usage
Use saveSession( ) to ensure that changes are saved in the distributed state storage area, which stores the session information for subsequent use if any other AppLogics are invoked within the same session.

The saveSession( ) method uses a cookie—if the Web browser supports cookies— to pass the session ID back and forth between the Web browser and Netscape Application Server. It transfers only the session ID, not the session information itself, to provide better information security.

Because saveSession( ) uses streamResultHeader( ) to register the cookie, be sure to call saveSession( ) before calling streamResult( ), evalTemplate( ), or any other HTTP body streaming methods.

Tip
Return Value
GXE.SUCCESS if the method succeeds.

Related Topics
createSession( ),
getSession( ),
Session2 class ,
ISession2 interface

setCacheCriteria( )
Stores AppLogic results, such as HTML, data values, and streamed data, in a result cache.

setCacheCriteria( ) is deprecated. In NAS 4.0 applications, this functionality is controlled using the setCacheCriteria property in the servletInfo.ntv file.

Syntax
public int setCacheCriteria(
int timeout,
int cachesize,
String criteria)

timeout. Number of seconds the AppLogic result remains in the result cache after the last access. To clear the result cache after a specified time from its creation, use the GXREPOSIT.GXREPOSIT_TIMEOUT_CREATE flag, as shown in the following example: setCacheCriteria(GXREPOSIT.GXREPOSIT_TIMEOUT_CREATE | 300, ...). In this example, the cache is cleared 300 seconds after it is created. Set timeout to zero to clear the result cache and disable caching for this AppLogic.

cachesize. Maximum number of results to be cached for the AppLogic at any time. The result cache stores distinct AppLogic output up to the cachesize limit. If the AppLogic generates another output to cache, the least accessed member of the cache is dropped. Setting cachesize to zero clears the result cache and disables caching for this AppLogic.

criteria. Criteria expression containing a string of comma-delimited descriptors. Each descriptor defines a match with one of the input parameters to the AppLogic. Use the following syntax:

Syntax
Description
arg
Test succeeds for any value of arg in the input parameter list. For example:
setCacheCriteria(3600,1,"EmployeeCode");
arg=v
Test whether arg matches v (a string or numeric expression). For example:
"stock=NSCP"
Assign an asterisk (*) to the argument to cache a new set of results every time the AppLogic module runs with a different value. For example:
setCacheCriteria(3600,1,"EmployeeCode=*");
arg=v1|v2
Test whether arg matches any values in the list (v1, v2, and so on). For example:
"dept=sales|marketing|support"
arg=n1-n2
Test whether arg is a number that falls within the range. For example:
"salary=40000-60000"

Usage
Use to specify caching for the results from an AppLogic. An AppLogic can cache any type of result. Caching improves performance for time-consuming operations such as queries and report generation.

When caching is enabled for an AppLogic, the Netscape Application Server stores its input parameter values and its results in the cache so that, if the AppLogic is called again with the same parameters (matching the cache criteria), the Netscape Application Server retrieves its results directly from the cache instead of running the AppLogic again. If the AppLogic is called with different parameters, the Netscape Application Server runs the AppLogic again and saves its result in the cache as well.

Each AppLogic has only one cache but it can contain multiple sets of results if the AppLogic was run multiple times with different parameters for each call.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Verify AppLogic caching before setting cache criteria

if(!isCached()) {
log("Set criteria to save output from 3 deptcodes");
if(setCacheCriteria(60, 3, "deptcode")!=0)
log("Could not set criteria");
else
log("Succeeded in setting criteria");
}
else
log("Not Setting Criteria");
Example 2
// Cache multiple results for up to 100 values of Department

setCacheCriteria(3600,100,"Department");
Example 3
// Cache single result for given matching value of Department

setCacheCriteria(3600,1,"Department=Operations");
Example 4
// Cache multiple results for two matching values of dept

setCacheCriteria(3600,2,"Department=Research | Engineering");
Example 5
// Cache one result for salary in a range

setCacheCriteria(3600,1,"Salary=40000-60000");
Example 6
// Cache two results for several parameters

setCacheCriteria(3600, 2,
"Department=Sales,Salary=40000-60000");
Related Topics
deleteCache( ),
removeAllCachedResults( ),
removeCachedResult( ),
isCached( ),
skipCache( )

setSessionVisibility( )
Sets the session visibility.

setSessionVisibility( ) is deprecated. It provides functionality that does not apply to standard-based applications.

Syntax
public int setSessionVisibility(
String domain,
String path,
boolean isSecure)

domain. The domain in which the session is visible.

path. The path to which this session must be visible.

isSecure. If TRUE, the session is visible only to secure servers (HTTPS).

Usage
Because of the way cookies are used to identify sessions, NAS sessions are, by default, accessible only within the same URL name space where they were created. As a result, if you call only the saveSession( ) method, then your session is not visible to any other domain or URL.

However, if you call setSessionVisibility( ) before calling saveSession( ), you can control the visibility of the session. The setSessionVisibility( ) method internally controls the attributes of the cookie used in transmitting the session ID.

You must be part of the domain to set the domain attribute. For example, if the domain is set to netscape.com, then the session is visible to foo.netscape.com, bar.netscape.com, and so on. Domains must have at least two periods (.) in them. For example, .net is an invalid domain attribute.

By default, the session is visible only to the URL that created the session cookie. Use the path parameter to specify different URLs that will be visible. For example, the path /phoenix would match "/phoenixbird" and "/phoenix/bird.html". To make the entire server root visible, specify a path of "/", the most general value possible.

Both the domain and path parameters are null-terminated character strings. They are not modified within the setSessionVisibility( ) method.

Rule
For the session visibility to take effect, you must invoke setSessionVisibility( ) before a call to saveSession( ). The saveSession( )method uses the visibility attributes set from setSessionVisibility( ).

Return Value
GXE.SUCCESS if the method succeeds.

Related Topics
saveSession( )

setVariable( )
Sets a value that is passed to later AppLogic requests that are called by the same client. If the client is a browser, cookies are used to transfer variable values.

setVariable( ) is deprecated. In standard-based applications, use the addCookie( ) method in the interface javax.servlet.http.HttpServletResponse.

Syntax 1
public int setVariable(
String name,
String value)
Syntax 2
public int setVariable(
String name,
String value,
int timeout,
String urlPath,
String urlDomain,
boolean secure)

name. The name of the value to record for this browser session. The value will appear on any future AppLogic's input IValList under this name.

value. The string value to record.

timeout. Number of seconds before the cookie expires. Applies to HTTP clients only.

urlPath. The subset of URLs in a domain for which the cookie is valid. Applies to HTTP clients only.

urlDomain. The domain for which the cookie is valid. Applies to HTTP clients only.

secure. If a cookie is marked secure, it will be sent only if the communications channel with the host is a secure one. Currently, this means that secure cookies will be sent only to HTTPS (HTTP over SSL) servers. Applies to HTTP clients only.

Usage
Use setVariable( ) to store information specific to a client that you want to pass to other AppLogics invoked by the same client. The values set with setVariable( ) are passed to the input IValList (valIn) of the called AppLogics.

In the case of an HTTP client, setVariable( ) streams the variable out in an HTTP header. The HTTP header registers a cookie, which is the mechanism used to pass data back and forth between the browser and the Netscape Application Server.

Rule
Because setVariable( ) streams information in an HTTP header, call itbefore calling any HTTP body streaming methods, such as streamResult( ), evalOutput( ), and evalTemplate( ).

Tip
If your application requires more security, you should use Netscape Application Server's session mechanism instead of cookies to maintain session information. With a Netscape Application Server session, data is stored on the server and only a session ID is passed between the client and the server. For more information about the session mechanism, see ISession2 interface.

Return Value
GXE.SUCCESS if the method succeeds.

skipCache( )
Skips result caching for the current AppLogic execution.

Syntax
public int skipCache()
Usage
Use skipCache( ) to prevent results from the current request from being saved in the results cache if an error occurs during AppLogic execution.

Rule
For skipCache( ) to have any effect, you must first enable caching by calling setCacheCriteria( ).

Return Value
GXE.SUCCESS if the method succeeds.

Example
// Skip result caching if an error occurs 

// during AppLogic execution
public class produceReport extends AppLogic {
public int execute() {
if (isCached == false)
// Set up results cache
setCacheCriteria(3600, 1, "");
String result;
if (. . . Input arguments are not valid . . .) {
result = "Please enter your employee id...";

// We don't want the above error prompt to be
// put into the result cache, so we must
// call skipCache.
skipCache();
else {
result = [. . . Generate report . . .];
}
return result(result);
}
}
Related Topics
deleteCache( ),
removeAllCachedResults( ),
removeCachedResult( ),
isCached( ),
setCacheCriteria( ),
IValList interface

streamResult( )
Streams results as a string.

streamResult( ) is deprecated. In standard-based applications, use similar functionality as defined in the Servlet API. For example, refer to javax.servlet.ServletOutputStream or javax.servlet.http.HttpServletResponse.

Syntax
public synchronized int streamResult(
String res)

res. The body data to stream. If returning HTML body data, you can use HTML formatting following HTTP body conventions. See your HTTP documentation for more information.

Usage
Use streamResult( ) to stream data as soon as it is available. With streaming, an AppLogic can make the first portion of the data available for use immediately, even if the remainder of the stream has not yet been processed. This is especially useful with large volumes of data, such as a query that takes a while for the database server to process completely. An AppLogic can process and display those rows in the result set that have been returned. Without streaming, AppLogic must prepare the entire result first before returning any data.

The streamResult( ) method is typically used to stream HTTP body content. Before calling streamResult( ), the AppLogic must call streamResultHeader( ) to return the HTTP header data first. The HTTP protocol separates data streams into header and body data, and specifies that the header data and body data are returned in that order. For details about HTTP header and body data, see your HTTP documentation.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Stream header and body, passing the header and body data

// as variables.
streamResultHeader(headerVariable);
streamResult(bodyVariable);
Example 2
// Stream header or body in several parts, using several

// method calls, starting with the header
streamResultHeader(startHeader);
streamResultHeader(finishHeader);
streamResult(bodyStart);
streamResult(bodyMiddle);
streamResult(bodyEnd);
Related Topics
streamResultBinary( ),
streamResultHeader( )

streamResultBinary( )
Streams binary data, such as a GIF file.

streamResultBinary( ) is deprecated. In standard-based applications, use similar functionality as defined in the Servlet API. For example, refer to javax.servlet.ServletOutputStream or javax.servlet.http.HttpServletResponse.

Syntax
public synchronized int streamResultBinary(
byte[] buf,
int offset,
int length)

buf. The array from which binary data is streamed.

offset. Index in the array. The starting position in the array to start streaming binary body data.

length. Number of bytes to stream from the array, starting at the specified offset position.

Usage
Use streamResultBinary( ) to stream binary data as soon as it is available. With streaming, an AppLogic can make the first portion of the data available for use immediately, even if the remainder of the stream has not yet been processed. This is especially useful with large volumes of data, such as a query that takes a while for the database server to process completely. An AppLogic can process and display those rows in the result set that have been returned. Without streaming, AppLogic must prepare the entire result first before returning any data.

The streamResultBinary( ) method is used to stream HTTP body data of binary type, such as an image (GIF) file. Before calling streamResultBinary( ), the AppLogic should call streamResultHeader( ) to return the HTTP header data first. The HTTP protocol separates data streams into header and body data, and specifies that the header data and body data are returned in that order. For details about HTTP header and body data, see your HTTP documentation.

Tips
Return Value
GXE.SUCCESS if the method succeeds.

Related Topics
streamResult( ),
streamResultHeader( )

streamResultHeader( )
Streams header data.

streamResultHeader( ) is deprecated. In standard-based applications, use similar functionality as defined in the Servlet API. For example, refer to javax.servlet.ServletOutputStream or javax.servlet.http.HttpServletResponse.

Syntax
public synchronized int streamResultHeader(
String hdr)

hdr. The header data to stream. If returning HTTP header data, use the HTTP header conventions, such as the following:

"Content-Type: text/html"

"Location: <redirect url>"
See your HTTP documentation for more information.

Usage
Use streamResultHeader( ) to return header data before streaming body data. With streaming, an AppLogic can make the first portion of the data available for use immediately, even if the remainder of the stream has not yet been processed. This is especially useful with large volumes of data, such as a query that takes a while for the database server to process completely. An AppLogic can process and display those rows in the result set that have been returned. Without streaming, AppLogic must prepare the entire result first before returning any data.

The streamResultHeader( ) method is typically used in conjunction with streamResult( ) to stream HTTP data. Before calling streamResult( ), the AppLogic should call streamResultHeader( ) to return the HTTP header data first. The HTTP protocol separates data streams into header and body data, and specifies that the header data and body data are returned in that order. For details about HTTP header and body data, see your HTTP documentation.

Return Value
GXE.SUCCESS if the method succeeds.

Example 1
// Stream header and body, passing the header and body data

// as variables.
StreamResultHeader(headerVariable);
StreamResult(bodyVariable);
Example 2
// Stream header or body in several parts, using several

// method calls, starting with the header
StreamResultHeader(startHeader);
StreamResultHeader(finishHeader);
StreamResult(bodyStart);
StreamResult(bodyMiddle);
StreamResult(bodyEnd);
Related Topics
streamResult( ),
streamResultBinary( )

 

© Copyright 1999 Netscape Communications Corp.