Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

IBM FileNet eForms for P8 Java API Developer Guide

Version 1.0

P8 eForms Java API Developer Guide



SC19-3247-00
IBM FileNet eForms for P8 Java API Developer Guide
Version 1.0

P8 eForms Java API Developer Guide



SC19-3247-00
Note

Before using this information and the product it supports, read the information in “Notices” on page 59.

Edition notices
This edition applies to version 1.0 of IBM eForms Java API Developer Guide (product number 5724-R85) and to all
subsequent releases and modifications until otherwise indicated in new editions.
© Copyright IBM Corporation 2011.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
FileNet eForms for P8 Java API
Developer Guide

Introduction

IBM FileNet EForms for P8 includes a comprehensive Java API that


enables you to integrate eForms functionality into a Web application.
This feature gives your application the ability to present a custom
HTML page from which a user can initiate and interact with an
electronic form.

Use cases
The eForms Java API provides the ability to programmatically support
eForms functionality through JSP pages, servlets or standalone
desktop applications.

The following use cases illustrate some of the functionality provided by


the eForms API.

• Creating forms from a variety of template and data sources.


• Modifying a form and working on with form cells.
• Modifying and working with form data values.
• Rendering forms to a client-side browser as an editable HTML
eForm.
• Rendering form as PDF or TIFF image.

©Copyright IBM Corp. 2011 1


1.Getting Started
Importing eForms API Package

The packages for the eForms API are all com.filenet.eforms.api.*. So,
you need to include the following line in your java code:

import com.filenet.eforms.api.*;

Initialization

Before any calls can be invoked, the eForms API must be initialized for
the particular deployment. This is done using the Configuration
object with its single static method initialize(). This method should
only be called once; any succeeding calls to it are ignored.

The initialize() method takes a single parameter, the path to


where the eforms-integration.xml and other configuration files are
located. These are typically stored in the WEB-INF directory. A typical
servlet may do this with the following command:

Configuration.initialize(getServletContext().getRealPath("/
WEB-INF"));

A JSP page may establish the location of this folder with this
command:

Configuration.initialize(application().getRealPath("/WEB-
INF"));

application is a built-in variable that every JSP page can access. It


represents the instance of the class that implements the
javax.servlet.ServletContext object for this JSP page. That object,
in turn, is able to get the servlet path of the JSP page, which turns into
a physical path for your JSP page.

In a P8 environment, the following command must be used:

2 eForms Java API Developer Guide


Configuration.initialize(ConfigurationUtil.getConfiguration
DirPath());

Configuration Files

Name Description
This file is a deployment descriptor. It provides
web.xml configuration and deployment information for the
Web components that comprise a Web application.
eforms- This file is covered in more detail in the Integration
integration.xml section.

©Copyright IBM Corp. 2011 3


Integration

Integration is the process that allows third-party hosting to support


features that they might do better. The cornerstone of this relationship
is the eforms-integration.xml file.

eforms-integration.xml

The most important configuration file is eforms-integration.xml.


Support for different URI schemas, providers, platforms and other
configuration settings are specified within this file. It allows you to
specify Java plug-in classes to provide the support. For our purposes,
we are only interested in the URI schemas.

An eforms-integration.xml file may contain information such as:

<integration>
....
<sources>
<source scheme="p8" >
com.filenet.eforms.toolkit.server.sources.P8Source
</source>
<\sources>
....
</integration>

The <sources> tag provides a list of additional schemas that eForms


may use to get data. In this example, it specifies the location of the
java class that supports the P8 scheme. When a URI with the P8
scheme is passed in for data, it is passed to the appropriate class.

Example of a sample URI that opens a specific document:

p8:(ObjectStoreID).(ObjectID)
where the value of ObjectStoreID & ObjectID are a GUID like:
0C4F3B79-6C8A-4859-916B-93E90101CBE1

Remember that a URI needs to be URL encoded.

4 eForms Java API Developer Guide


Context

A Context object is a hash table meant to store all of the thread-


sensitive global data that is associated with the current user. Content
providers, such as IBM FileNet Application Engine, use it to pass along
information needed to access the data they are required to provide.
Because of this, it needs to be initialized with data required by the
current integration settings. For any thread this must be initialized
prior to any eForms API calls.

It is important that the context be released upon command


completion.

Default Context Provider

The default context provider supports the standard URL schemes of


http, https, and file. To support this, the context needs to have the
locale, timezone, and username specified.

For example, to initialize a context that supports the default content


provider, implement something similar to the following code:

try
{
// Initialize the context with the required data.
Hashtable context = Context.initialize();
context.put("locale", request.getLocale());
context.put("timeZone", TimeZone.getDefault());
context.put("username" , "Joe Schmeg");

// eForms java API calls would go here


...
}
finally
{
//Release the context.
context.release();
}

P8 Content Provider

If you are using P8 to support your eForms, then you will need to
implement a larger set of commands to set up the content. The

©Copyright IBM Corp. 2011 5


following is an example for setting up the context prior to making any
eForms API calls:

try
{
// Get the data store from the controller.
WcmDataStore dataStore = controller.getDataStore();
// Get the locale from the data store.
Locale locale = dataStore.getLocale();
// Get the session from the data store.
session = dataStore.getSession();
// Get the timezone from the client time zone utility.
TimeZone timeZone = null;
try
{
if(ClientTimeZoneUtil.isTimeZoneExplicit(dataStore))
timeZone =
ClientTimeZoneUtil.getClientTimeZone(dataStore, null);
else
timeZone =
ClientTimeZoneUtil.getBrowserTimeZone(dataStore);
}
catch (Throwable e)
{
timeZone = TimeZone.getDefault();
}
// Initialize the context with the required data.
Hashtable context = Context.initialize();
context.put("locale", locale);
context.put("session", session);
context.put("timeZone", timeZone);
// eForms java API calls would go here
...
}
finally
{
//Release the context.
context.release();
}

The above example may change in the future. There is a plan to


minimize the work required for a custom integration.

6 eForms Java API Developer Guide


Sample JSP for eForms Component
initialization

The following JSP page shows the initialization of the eForms and how
to use the eForms Java API to open an ITX Form Template.

<%@ Page contentType="text\html;charset=UTF-8"


language="java" %>
<%@ Page import="java.util.*" %>
<%@ Page import="com.filenet.eforms.api.*" %>
<%
try
{
// Initialize the configuration
Configuration.initialize(application.getRealPath("/WEB-
IF"));

// Initialize the Context.


Hashtable context = Context.initialize();
context.put("locale", request.getLocale());
context.put("timeZone", TimeZone.getDefault());
context.put("username", "Joe Schmeg");

// Create the form.


Template template = new
Template("file:///c:/SampleForm.itx");
Form form = new Form(template);
form.doAutoIncrements():

// Render the Form.


HtmlFormRenderer renderer = new HtmlFormRenderer(form);
renderer.setWindowTitle("This is amazing");
renderer.render(request, response);
}
catch (Throwable e)
{
FormException.toHtml(e, request, response);
}
finally
{
// Release the Context.
context.release();
}
%>

©Copyright IBM Corp. 2011 7


2. Forms
General Concepts
Form Objects

A Form object represents an instance of a form in the server


environment. You can use the Form object to obtain information about
the form and to customize the properties and behavior of the form.

Methods on the Form object enable you to:

• Obtain information about the template from which the form


instance was created.
• Access the cells and choice lists to be associated with the form.
• Create new cells and choice lists to be associated with the form.
• Execute the auto-increment, lookup and submit actions
configured for the form in eForms Designer.
• Control user navigation of the form.

Additionally, a Form object provides access to the values contained in


the form cells.

Methods on the Form object enable you to:

• Merge data from a data document into the form cells.


• Get and set cell values.
• Extract the cell values to create a data document containing the
form data.

Template Objects

A Template object represents a form template. Thus, you can use the
Template object to create an instance of a Form object.

A form template contains the framework, the intelligence and the


graphic elements of a form. Its format is ITX Form Template (.itx).

Users fill out a form by entering values in the fields (cells) on the form.

8 eForms Java API Developer Guide


After you finish creating a form template in IBM FileNet eForms
Designer, you can save it as an ITX Form Template. When users click
the icon for an ITX Form Template, a blank form opens in a browser
window.

Working with Forms


This topic provides information about creating form objects using the
template and data objects, accessing form elements, working with
form data, and modifying form objects. This topic also describes how
to define and display notifications for a form

Creating a Template Object

A Template object represents the form template from which a Form


object is instantiated. You can create a Template object implicitly
when you create a Form object by calling the fromRequest method on
the Form class. Alternatively, you can create a Template object
explicitly by calling either the Template class constructor or by calling
the fromRequest method on the Template class.

Creating a Template Object using the Constructor

To create a Template object by using the constructor, you pass the


uniform resource identifier (URI) that indicates the location of the ITX
document to be used to create the new Template object.

The eForms API supports the following URI Schemes: file, http, https
and P8. The P8 URI scheme is supported only for the P8 eForms
platform and cannot be used for the standalone application.

The following examples construct a Template object by using the file


URI scheme:

Using “file” scheme:

Template template = new


Template("file:///C:/Development/test/templates/Sample.itx"
);

Using “p8” scheme:

©Copyright IBM Corp. 2011 9


String templateUri = "p8:" +
URLEncoder.encode(templateObjectStoreID) + "." +
URLEncoder.encode(templateObjectID);
Template template = new Template(templateUri);

Creating a Template Object from a Request

To create a Template object from a request, you call the


fromRequest(HttpServletRequest, String) method on the Template
object.

The following method creates a Template object by parsing the ITX


template referenced by the "templateURI" parameter.

Template template = new Template.fromRequest(request,


"templateURI");

Creating a Form Object


A Form object represents an instance of a form in the server
environment. You can use the Form object to obtain information about
the form and to customize the properties and behavior of the form.

Creating a Form Object using the Constructor

You can create a Form object by calling the Form(Template)


constructor:

// Create the template source.


Template template = new
Template("file:///C:/Development/test/templates/Test.itx");

// Create the form.


Form form = new Form(template);

Creating a Form Object from a Request

You can create a Form object by calling one of the following methods
on the Form class:

10 eForms Java API Developer Guide


fromRequest(HttpServletRequest) - This method creates a Form
object by parsing the templateURI from the request parameter named
"template" and the form data is as follows. If a request parameter
named "data" exists, then the XML form data is parsed from
it.Otherwise, the form data is parsed from the individual request
parameters whose names match the cell names in the template.

Form form = Form.fromRequest(request);

fromRequest(HttpServletRequest, String) - This method creates a


Form object by parsing the templateURI from the request parameter
named "t" and the form data from the individual request parameters
whose names match the cell names in the template.

Form form = Form.fromRequest(request, "t");

fromRequest(HttpServletRequest, String, String) - This method


creates a Form object by parsing the templateURI from the request
parameter named "templateURI" and the XML form data from the
request parameter named "xmlData" and merge the data into the form
cells.

Form form = Form.fromRequest(request, "templateURI",


"xmlData");

The following is an example of a simple servlet that creates a Form


Object

package myapp;

import com.filenet.eforms.api.Configuration;
import com.filenet.eforms.api.Context;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.IO.Exception;
import java.util.Hashtable;

public class GetFormServlet extends HttpServlet


{

©Copyright IBM Corp. 2011 11


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
getForm(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
getForm(request, response);
}

private void getForm(HttpServletRequest request,


HttpServletResponse response)
{
try
{
//Initialize the Configuration

Configuration.initialize(getServletContext().getRealPath("/
WEB-INF"));

//Initialize the context


Hashtable context = Context.initialize();
context.put("locale", request.getLocale());

//create a Form Object


Form form = Form.fromRequest(request,
"templateURI");
}
catch (Exception e)
{
//Handle any exception thrown
System.out.println(e);
}
finally
{
//Release the Context.
Context.release();
}
}
}

12 eForms Java API Developer Guide


Merging Data into a Form Object
You can prefill the cells on the form by merging one or more Data
objects into the Form object.

Form form = Form.fromRequest(request, "templateURI");


Data data = Data.fromRequest(request, "xmlData");

form.merge(data, true);

The following sample code creates a Form Object by parsing the


Template and FormData from a request. You can submit a request
using either the Javascript HttpRequest object or using the Java
HttpCommand object.

//Create a HTTP Request using Javascript


var request = new HttpRequest();
request.setMethod(HttpMethod.Post);
request.setUrl("http://server:9080/Workplace/Sample.jsp");
request.setXmlDataIncluded(true);
request.setXmlDataParameterName("xmlData");
request.addParameter("templateURI",
"file:///C:/development/test/templates/simple_form.itx");

//Create a HTTPCommand Object using Java

HttpCommand newDataCmd = new HttpCommand("XMLData");


newDataCmd.setUrl(("http://server:9080/Workplace/Sample.jsp
");
newDataCmd.setMethod(HttpMethod.Post);
newDataCmd.setXmlDataIncluded(true);
newDataCmd.setXmlDataParameterName("xmlData");
newDataCmd.addParameter("templateURI",
"file:///C:/development/test/templates/simple_form.itx");

HtmlFormRenderer renderer = new HtmlFormRenderer();


renderer.getCommands().add(newDataCmd);

In the Sample JSP page, you can parse the Template and Data object
to create a new Form:

//Create a template object


Template template = Template.fromRequest(request,
"templateURI");

©Copyright IBM Corp. 2011 13


//Create a data object
Data data = Data.fromRequest(request, "xmlData");

//Create a Form and merge the data


Form form = new Form(template);
form.merge(data);

Getting Information about the Form


Template
You can use the following methods on the form to obtain information
about the form template from which the electronic form was rendered.

NOTE The eForms Java™ API does not enable you to modify the
template properties

Method Template Information Returned


getAuthor The name of the author of the form template from
which this form was created.
getDescription The description of the form template from which this
form was created.
getHelpUrl The URL for the help defined for the form template
from which this form was created.
getOrganization The organization to which the author of the form
template belongs.
getRevision The revision number of the form template for this
form.
getTemplateID The unique template ID of the form template for this
form.
getTemplateName The name of the form template for this form.

Accessing Form Elements


Using the Form Object you can access some of the elements that are
rendered with the electronic form. These form elements are
maintained in collections that are associated with the form as follows:

CellCollection — Contains the template cells rendered with the


electronic form and any non-template cells that your script creates for
the form.
ChoiceListCollection — Contains both the choice lists defined by

14 eForms Java API Developer Guide


the form template and rendered with the electronic form and any
choice lists that are created using the JavaAPI for the form.
PageCollection — Contains the pages rendered with the electronic
form.

You can also use the form variable to access these collections and the
objects they contain. For example, you call the getPage method on the
form to access the PageCollection object.

To access a specific object from a collection you can call the get or
find method on the appropriate collection object. In addition, you can
access a specific object directly using the form variable. For example,
to access a specific cell, you can call the findCell(string),
getCell(string), or getCell(number) method on the form.

Modifying Form Settings


Setting the Current Cell

When an electronic form is rendered to a web browser, the first


editable cell in the tab order is selected by default. The Form object
provides methods for overriding this behavior:

// Select the cell "FirstName".


Cell firstNameCell = form.getCell("FirstName");
form.setCurrentCell(firstNameCell);

The Form object also allows you to set the current cell to the first
editable cell on a particular page:

// Select the first editable cell on the "Inventory" page.


Page inventoryPage = form.getPage("Inventory");
form.setCurrentPage(inventoryPage);

Submitting Form Data


Automated data submission provides a mechanism for submitting form
data to another information system. You configure the data submit
action for the form template in eForms Designer by specifying the type
of connection for the data destination and the linking parameters.

©Copyright IBM Corp. 2011 15


To execute the data submit action from a Custom JSP page, call the
doSubmit method on the form. This method submits the form data to
the Web server to be processed as specified in eForms Designer.

The following example calls the doSubmit to execute the submit action
configured for the Form.

//create the form


Form form = new Form(template);
// create the QueryResponse Object
QueryResponse resp;

// Iterate through the cells and set values


Iterator it = form.getCells().iterator();
while (it.hasNext())
{
Cell cell = (Cell) it.next();
if (cell.getName().equalsIgnoreCase("lastName"))
cell.setValue(new Value("Smith"));
else if
(cell.getName().equalsIgnoreCase("firstName"))
cell.setValue(new Value("John"));}

// Submit the data to the DB


queryResponse = form.doSubmit();

Getting Form Data


You can also use an HttpRequest object to submit form data for
processing. Unlike the data submit action, which is configured in
eForms Designer, using an HttpRequest object to submit form data
enables your code to determine where the form data is to be
submitted.

To collect the form data to be submitted by an HttpRequest object,


call one of the following methods:

getData — Returns a Data object containing the cell values.


getDataXml — Returns a string containing the cell values in XML
format.

16 eForms Java API Developer Guide


Auto-incrementing all the cells in a Form
You can set a template cell value by executing the auto-increment
action. To do so, the auto-increment action must be configured for the
cell in eForms Designer. The auto-increment action enables your
application to assign a new number to a cell automatically each time a
new form is filled out using numbers obtained from an external
application or data source. The mechanism for obtaining the number is
determined by the way in which the auto-increment action was
configured in eForms Designer.

You can execute the auto-increment action for a specific cell or for all
cells.

To execute the auto-increment action for a specific cell, call the


doAutoIncrement method on the Cell object. This method returns a
QueryResponse object of type Data from which you then extract the
incremented number.

To execute the auto-increment action for all cells, call the


doAutoIncrements method on the Form object. The service configured
to assign incremented values issues the next available value in the
sequence. Depending on the number of users requesting incremented
values, two calls to the doAutoIncrements method might not return
sequential values.

The following example increments the values in all cells that have been
configured in eForms Designer to hold an auto-incrementing value:

Form myForm = new Form(template);


myForm.doAutoIncrements();

NOTE Exceptions are not thrown to the user indicating the failure of
any particular Auto-Increment set up on a cell. This is a design feature
as a Form can have multiple Auto-increments configured, so even if
one of them fails the others can function.

©Copyright IBM Corp. 2011 17


3. Pages
Page Concepts

Every form contains one or more numbered pages, a work page, and a
master page. The PageCollection object for a form contains a Page
object for the work page and for each numbered page. The work page
is always the first element in the 0-based page collection.

NOTE The master page is not represented by a Page object, so is not


included in the PageCollection object. You must access cells and
other form elements on the master page through the form.

The Page object enables you to access information about the page,
such as whether the form user can access the page or is the page tab
visible or is it printable. This object also enables you to work
specifically with the cells that appear only on that page.

Working with Pages

This topic describes how to get information about the page properties
defined in eForms Designer and how to access cells on a specific page.

Getting Information about a Page

You can use the following methods on the Page object to obtain
information about the page.

Method Page Information Returned


getDescription The description of this page as specified in eForms
Designer
getLabel The label that appears on the tab for this page as
specified in eForms Designer.
getName The unique ID number assigned to this page by
eForms Designer.
true if this page is accessible to users on the
isAccessible
electronic form; false otherwise.
true if users can print this page when the electronic
isPrintable form is rendered; false otherwise.
NOTE Use the setPrintable method on the Page

18 eForms Java API Developer Guide


object to enable or prevent a form user from printing
a page. A Work Page cannot be printed.

true if the tab for this page is visible to users when


isTabVisible
the electronic form is rendered; false otherwise.

Accessing Page Cells

Your code can access the cells that are defined for the work page or
for a specific numbered page through the CellCollection object
maintained for that page. To access the CellCollection object, call
the getCells command on the Page object.

To access a specific cell for a page, call one of the the following
methods on the Page object:

• findCell(string) or getCell(string) — These methods


access a cell by name.
• getCell(number) — This method accesses a cell by its index
within the cell collection for the page.

To access a published cell for a page, call getPublishedCells


methods on the Page object.

Returns the collection of published cells associated with this page. A


published cell is specified in eForms Designer by selecting the Publish
cell checkbox on the Cell Settings dialog box. A published cell
appears in the Published Form Fields list in the mapping wizards, which
enables the cell to be mapped to step data fields and document class
properties.

The following example finds a page from the page collection and gets
all the published cells for that particular page

Iterator it = form.getPages().iterator();
while (it.hasNext())
{
Page page = (Page) it.next();
if (page.getName() == "MyPage")
{
page.setTabVisible(true);
CellCollection cells = page.getPublishedCells();
Cell mycell = cells.getCell("test");
myCell.setValue("Just for testing");

©Copyright IBM Corp. 2011 19


}
}

Setting a Page as a start page


Using the Form object you can set a particular page as a start page.

Page inventoryPage = form.getPage("Inventory");


inventoryPage.setAccessible(true);
form.setCurrentPage(inventoryPage);

20 eForms Java API Developer Guide


4. Cells
General Concepts
A Cell object represents either a field cell or a column cell that was
defined as part of a form template. These template cells are defined in
eForms Designer. A template field cell is the single-value cell created
when a new field is drawn on the form template. A template column
cell is the multiple-value cell created when a new column is added to a
table on the form template.

Working with Cells


This topic provides information about creating non-template cells,
enabling or disabling cells, getting and setting cell values, executing
lookup actions on cells, and working with signature cells.

Creating a Non-template Cell

You can create a non-template cell for a form. Like a template cell, a
non-template cell is either a field cell or a column cell. The multiplicity
of a non-template cell is determined by the createCell method you
call.

To create a non-template cell, call one of the following methods on the


form:

• createCell(string, Value) — This method creates a non-


template field cell .
• createCell(string, array) — This method creates a non-
template column cell.

As with a template cell, you cannot change a non-template field cell


into a column cell or a non-template column cell into a field cell.

Both createCell methods add the new non-template cell to the cell
collection for the form. You get and set the value of the new non-
template cell as you would for a template cell. However, the non-
template cell does not have template-specific properties such as a
display name.

©Copyright IBM Corp. 2011 21


You can determine whether a cell is a template cell or a non-template
cell by calling the hasTemplateCell method on the Cell object. This
method returns true for a template cell or false for a non-template
cell.

Enabling and Disabling Cells

In eForms Designer, you can specify whether a cell is required,


recommended, optional, or display only. The Cell object provides
methods for overriding these settings:

// Make the "Approval" cell required.


Cell approvalCell = form.getCell("Approval");
approvalCell.setEntryType(EntryType.Required);

// Disable the "ForOfficeUseOnly" cell.


Cell forOfficeUseOnlyCell =
form.getCell("ForOfficeUseOnly");
forOfficeUseOnlyCell.setEnabled(false);
In eForms Designer, you can specify the choice list
associated with a cell and whether or not other values are
permitted in the cell. The Cell object provides methods for
overriding these settings.

// Set the choice list for the "Country" cell.


Cell countryCell = form.getCell("Country");
ChoiceList countryChoiceList =
form.getChoiceList("Countries");
countryCell.setChoices(countryChoiceList);

Setting a Cell Value

To set a value to a cell object, you need to know whether you are
working with a field cell or a column cell and whether you are using a
Value object or a string to set the cell value.

NOTE To determine whether you are working with a field cell or a


column cell, call the isColumn method on the Cell object. This
method returns true for a column cell and false for a field cell.

Setting the Value of a Field Cell


To set the value of a field cell using a Value object, call the
setValue(Value) method on the Cell object.

22 eForms Java API Developer Guide


To set the value of a field cell using a string, call one of the following
methods on the Cell object:

• setValueFromString(string) — If this cell is a template cell,


you must format the string according to the Cell's format style.
If this cell is a non-template cell, you must format the string
according to the General format style.
• setValueFromString(string, FormatStyle) — You must
format the string according to the specified FormatStyle value.

Setting the Value of a Column Cell


To set the value of a specific row in a column cell using a Value object,
call the setValue(string, number) method on the Cell object. To
set all the values in the cell using an array of Value objects, call the
setValues(array) method on the Cell object.

To set the value of a specific row in a column cell from a string, call
one of the following methods on the Cell object:

• setValueFromString(string, number) — If this cell is a


template cell, you must format the string according to the cell
format style. If this cell is a non-template cell, you must format
the string according to the General format style.
• setValueFromString(string, FormatStyle, number) - You
must format the string according to the specified FormatStyle
value.

To set all the values in a column cell from an array of strings, call one
of the following methods on the Cell object:

• setValuesFromStrings() — If this cell is a template cell, you


must format the string according to the cell format style. If this
cell is a non-template cell, you must format the string according
to the General format style.
• setValuesFromStrings(array, FormatStyle) — You must
format the string according to the specified FormatStyle value.

Auto-incrementing a Cell Value

You can set a template cell value by executing the auto-increment


action. To do so, the auto-increment action must be configured for the
cell in eForms Designer. The auto-increment action enables your
application to assign a new number to a cell automatically each time a

©Copyright IBM Corp. 2011 23


new form is filled out using numbers obtained from an external
application or data source. The mechanism for obtaining the number is
determined by the way in which the auto-increment action was
configured in eForms Designer.

NOTE In P8 environment, you cannot see the Auto-incremented value


while running in the FormTemplate Test mode. You need to create a
Document/Workflow Policy

You can execute the auto-increment action for a specific cell or for all
cells.

To execute the auto-increment action for a specific cell, call the


doAutoIncrement method on the Cell object. This method returns a
QueryResponse object of type Data from which you then extract the
incremented number.

To execute the auto-increment action for all cells, call the


doAutoIncrements method on the Form object. The service configured
to assign incremented values issues the next available value in the
sequence. This method then merges the incremented values into the
cells as configured.

The following example calls the doAutoIncrement to execute the auto-


increment action configured for a cell named autoincrementCell. The
example then extracts the incremented number from the data
returned by the doAutoIncrement method, and sets the value of the
autoincrementCell cell to the incremented number.

Cell myCell = myForm.findCell("autoincrementCell");


QueryResponse myResponse = myCell.doAutoIncrement();
Data myData;

//The QueryResponse object contains an array of Data


objects.
if (myResponse.getType() == QueryResponseType.Data)
myData = myResponse.getData(); //this is an array of
Data objects

//In this example, we assume that the QueryResponse


returned a single element array.
Value myValue = myData[0].getValue("autoincrementCell");

//The value extracted from the array is assigned to the


cell configured to be auto-incrementing

24 eForms Java API Developer Guide


myCell.setValue(myValue);

Performing a Lookup

You can perform a lookup of information from any information systems


such as databases. For doing this, the lookup action needs to be
configured in a field cell in the eForms Designer.

If this cell is configured to perform a lookup, the value entered in this


cell is used as a key to look up information in information systems
such as databases. If the lookup action is triggered by the user
entering data in this cell, the data returned is merged into the form
automatically. However, if the lookup action is triggered by an explicit
call to this method, the application logic determines how the data that
is returned in the QueryResponse object is to be processed.

The following example calls the doLookup to execute the lookup action
configured for a cell named lookupCell. The example then extracts the
lookup data returned by the doLookup method from any data sources,
and merges the data to the appropriate fields in the Form Template:

// create the QueryResponse Object


QueryResponse resp;

Iterator it = form.getCells().iterator();
while (it.hasNext())
{
Cell cell = (Cell) it.next();
if (cell.getName().equalsIgnoreCase("lookupCell"))
{
// perform lookup
cell.setValue(new Value("John Smith"));
resp = cell.doLookup();
}
}

// Merge the data into the Form


if (resp.getType == QueryResponseType.Data )
{
for (int i=0; i < resp.getData().length; i++)
form.merge(resp.getData(),true);
}

©Copyright IBM Corp. 2011 25


Working with a Signature Cell

You can use the verifySignature method on the Cell object to verify
the user's signature. This method sends a request to the signing
service to verify the user's signature.

The following example calls the verifySignature method to verify a


signature while opening FormData. If the signature is not valid, a
message is displayed in the Form Notification bar:

String result;
SignatureState status =
form.findCell("Signature").verifySignature();
if (status == SignatureState.Invalid)
result = "Invalid signature.";
else if (status == SignatureState.NotSigned)
result = "Please enter a signature.";
else if (status == SignatureState.NotVerified)
result = "The signature has not been verified.";

// Render the form.


HtmlFormRenderer renderer = new HtmlFormRenderer();
renderer.setForm(form);
renderer.setNotification(new Notification(result,
NotificationLevel.Notice));

26 eForms Java API Developer Guide


5.Values
Concepts
A Value object represents the single value that is stored in a field cell
or in a row of a column cell. You can use a Value object for a value
stored in a template or non-template cell contained in a Form object or
for a cell contained in a Data object.

When you create a Value object, the ValueType property is set to


indicate the type of data contained in the object as Boolean, Date,
Null, Number, Picture, Signature, String, or Time. When you use a
Value object to get or set the value of a template cell, the value type
of the Value object must match the FormatType of the Cell object.

The value type of a Value object is immutable; however, you can cast
the Value object to a Value object of a compatible type. To determine
the value type, call the getType method on the Value object.

Working with Values


This topic provides information about creating Value objects and
casting Value objects to objects of different types.

Creating Value Objects

You can create Value objects directly by calling one of the constructors
or parse methods defined on the Value object. You can create Value
objects indirectly by calling methods such as getValue on Cell objects
or findValue on Data objects.

Creating Value objects using constructors

You can create a new Value object of a given type by calling the Value
constructor. The argument you pass to the constructor determines the
value type of the new object. If you do not pass an argument to the
Value constructor, the constructor creates an empty Value object with
the ValueType property set to Null.

©Copyright IBM Corp. 2011 27


To create a Value object of type Date, Picture, Signature, or Time, you
must pass as the argument a DateDetail, PictureDetail,
SignatureDetail, or TimeDetail object, respectively. These objects
provide the structure information required to create the new Value
object.

Examples

The following example creates a Value object of type Null, and sets the
value of the new object to true:

Value myValue = new Value();

The following example creates a Value object of type Boolean, and


sets the value of the new object to true:

Value myBool = new Value(true);

The following example creates a Value object of type Date, and sets
the value of the new object to 2004-06-10:

Value myDate = new Value(new DateDetail(2004,06,10));

Creating a Value Object from a String

You can create a Value object of any type and use a string to set the
value. To do so, pass a string to the appropriate parse method for the
type. For example, the following call creates a new Value object of type
Boolean with the value set to true:

Value myBoolean = Value.parseBoolean("true");

The Value object provides two parse methods for each value type. The
method you choose depends on the format of the string to be used to
set the value. To create a Value object from a localized string in the
general format style, call a plain parse method such as parseBoolean
or parseSignature. To create a Value object from a string in the
canonical format, call a parseCanonical method such as
parseCanonicalBoolean or parseCanonicalSignature.

You can also create a Value array object and assign any specific value
object types like boolean, string , DateDetail or TimeDetail. The

28 eForms Java API Developer Guide


following example creates a Value object array for DateDetail type
objects:

Value myValueArray[] = new Value[3];


myValueArray[0]= new Value (new DateDetail(1960, 11,
6));
myValueArray[1]= new Value (new DateDetail(1981, 30,
5));
myValueArray[2]= new Value();

The following example creates a Value object and appends the value
to a particular field/column in the Form and the Data object.

Form form = new Form(template);


form.getCell("IsSigned").setValue(new Value(true));

Data data = new Data();


data.setValue("Name", new Value("John"));
if (data.findValue("Age") != null)
data.appendValue("Age", new Value(48));
data.appendValue("Column1,new Value("First Row"));

Casting a Value Object to a Different Type

You can cast a Value object to another Value object or to another kind
of object. Both cases require the resulting object to be of a type that is
compatible with the Value object on which the method is called.

To cast a Value object to another Value object, you call one of the as
methods on the Value object. The following example calls the
asString method to cast a Value object of type Number to a Value
object of type String:

Value myStringValue = myNumberValue.asString();

To cast a Value object to another kind of object, you call one of the to
methods on the Value object. The following example calls the toTime
method to cast a Value object of type Time to a TimeDetail object:

Value myTimeValue = new Value(new TimeDetail(10,30,20));


TimeDetail myTimeDetail = myTimeValue.toTime();

©Copyright IBM Corp. 2011 29


6.Choice Lists
Choice List Concepts
A choice list provides the form user with a list of allowable values for a
cell. You can create a choice list either in eForms Designer or by using
the eForms JavaScript API. You can use the API to associate a choice
list with any template cell except a signature cell, a picture cell, or a
checkbox.

You can use the eForms JavaScript API to define the choices in a
choice list. In addition, you can specify whether the form user can
enter a value not contained in the choice list.

Working with Choice Lists

This topic provides information on creating a new choice list, getting a


reference to an existing choice list, associating a choice list with a cell,
and setting the values in a choice list.

Creating a Choice List

You create a choice list by calling one of the following methods on the
form:

• Call the createChoiceList(string) method to create an empty


choice list. You then assign choices to this choice list by calling
one of the setChoices method as described in Getting and
Setting Choices.
• Call the createChoiceList(string, array) method to create a
choice list with the specified values.

The following example creates a new choice list named ColorList with
three values: orange, purple, and green:

form.createChoiceList("ColorList", new Array("orange",


"purple", "green");

The createChoiceList method adds the new choice list to the


ChoiceListCollection object for the form. You can then associate
this choice list with a template cell on the form as described in
Associating a Choice List with a Cell.

30 eForms Java API Developer Guide


Obtaining a Choice List

You can obtain a reference to a choice list using the form, the choice
list collection, or the cell object.

To obtain a reference to a choice list using the form, call one of the
following methods on the form:

• findChoiceList(string) or getChoiceList(string) — These


methods obtain the choice list by name.
• getChoiceList(number) — This method obtains the choice list
by its index position within the 0-based ChoiceListCollection
object for the form.

To obtain a reference to the choice list collection for a form, call the
getChoiceLists method on the form. You can then obtain a reference
to a choice list using the choice list collection, by calling one of the
following methods on the ChoiceListCollection object:

• find(string) or get(string) — These methods obtain the


choice list by name.
• get(number) — This method obtains the choice list by its index
position within the 0-based collection.

To obtain a reference to the choice list associated with a specific cell,


call the getChoiceList method on the Cell object.

Associating a Choice List with a Cell

You can associate a choice list with any template cell except for a
picture or signature cell or a cell defined as a checkbox. To do so, call
one of the setChoiceList methods on the Cell object as follows:

• setChoiceList(ChoiceList) — This method assigns the choice


list to the cell and sets the allowOtherValues property for the
cell to false.
• setChoiceList(ChoiceList, boolean) — This method assigns
the choice list to the cell and sets the allowOtherValues
property for the cell to the specified value.

The following example associates the choice list ColorList with a cell
named ColorChoice:

©Copyright IBM Corp. 2011 31


form.findCell("ColorChoice").setChoiceList(ColorList);

If a choice list is already associated with a cell, the choice list specified
by the setChoiceList method supersedes the existing choice list.
However, the original choice list is not deleted from the choice list
collection. The setChoiceList method also overrides the
allowOtherValues property set for the cell.

Setting the Choices in a Choice List

You call the setChoices(array) method on the ChoiceList object to


set the choices for a choice list. Doing so deletes any existing choices
from the list.

The following example replaces the choices in the ColorList choice list
with the specified new values:

ColorList.setChoices(new Array("blue", "red", "yellow",


"white"));

32 eForms Java API Developer Guide


7. Script Command
Concepts
A Command object represents a preconfigured action that can be
invoked from an electronic form. The command can be one of the
built-in commands—help, pdf, or submit—or an HTTP command or a
script command that can created using the eForms Java™ API.

A Script command represents executable JavaScript™ code that is run


when the command is invoked from an electronic form.

For a command to be available from an electronic form, you must add


the command to the command collection for that form. Once the
command is added to the command collection, it can be invoked from
a client-side script, form button, or toolbar button.

Working with Commands


This topic provides information on creating a new command, obtaining
a reference to a command and executing a command.

Creating a new Script Command

You can create a new command using the ScriptCommand object. You
can specify the javascript code that needs to be executed while
invoking this type of command.

The following example creates a simple script command that alerts the
user with a message when invoked.

ScriptCommand scriptCmd = new ScriptCommand("Alert");


scriptCmd.setCode("alert('Hello');");

The newly created command needs to be added into the command


collection in order to be invoked in the rendered form. You can create
a Toolbarbutton or Form Button or use Client-side script to call the
command. The following example adds the command to the command
collections and creates a new toolbar button to invoke the command.

ScriptCommand scriptCmd = new ScriptCommand("Alert");

©Copyright IBM Corp. 2011 33


scriptCmd.setCode("alert('Hello');");

HtmlFormRenderer renderer = new HtmlFormRenderer();


renderer.getCommands().add(scriptCmd);

ToolbarButton cmdButton = new


ToolbarButton("ScriptCommand");
cmdButton.setLabel("Alert Message");
cmdButton.setCommandName(scriptCmd.getName());

renderer.getToolbarItems().add(cmdButton);
renderer.setToolbarPosition(ToolbarPosition.Top);

34 eForms Java API Developer Guide


8.Toolbar Buttons
Concepts
A ToolbarButton object represents a button displayed on the toolbar of
an electronic form. You can create custom toolbar buttons and you can
customize the behavior of any toolbar button using the eForms Java
API.

A toolbar button can invoke

1. one of the built-in commands provided by the eForms Java API


2. A custom HttpCommand or ScriptCommand object
3. A custom event handler configured using the eForms JavaScript
API.

Working with Toolbar Buttons


This topic provides information about creating a toolbar button,
obtaining a reference to a toolbar button and enabling/disabling a
toolbar button.

Creating a Toolbar Button

You can create a toolbar button with a specific name and add that
button to the toolbar collection object in order to get that button
displayed in the form. The toolbar button can be assigned a command
object so it can invoke specific operations.

The following example creates a new toolbar button that can invoke to
a Script command when rendered in a form.

ToolbarButton testButton = new ToolbarButton("TestButton");


testButton.setLabel("TEST");
testButton.setEnabledIconUrl("forms/images/test.gif");
testButton.setCommandName("ScriptCommand");

renderer.getToolbarItems().add(testButton);

©Copyright IBM Corp. 2011 35


Obtaining a Toolbar Button

You can obtain a reference to a toolbar button through the


ToolbarItemCollection object for the form. A
ToolbarItemCollection object represents a collection of toolbar
items that can be displayed for an electronic form. The ToolbarItem
objects contained in the collection can include both toolbar buttons and
toolbar separators, which are used to group toolbar buttons.

To obtain a reference to the toolbar item collection for an electronic


form, call the getToolbarItems method on the HtmlFormRenderer
object. The following example gets the toolbar button from toolbar
item collection:

HtmlFormRenderer renderer = new HtmlFormRenderer(form)


ToolbarItemCollection tblCollection =
renderer.getToolbarItems();
ToolbarItem tblItem = tblCollection.find("PDF");

tblCollection.add(new ToolbarButton("TEST"));
tblCollection.add(new ToolbarSeparator("Blank");

Enabling and Disabling a ToolbarButton

By default, a toolbar button is enabled and available to the user on the


electronic form. You can disable or enable a toolbar button by calling
the setEnabled(boolean) method on the ToolbarButton object.
Depending on how the toolbar button was defined in eForms Designer,
its appearance might change when it is disabled.

To determine whether a toolbar button is currently enabled, call the


isEnabled method on the ToolbarButton object. This method returns
true if the toolbar button is enabled.

36 eForms Java API Developer Guide


9. Query Response
QueryResponse Concepts
A QueryResponse object represents the response returned by an auto-
increment, a lookup, or a submit action. These actions can return form
data as Data objects, an HTML page or plain text that indicates the
status of the operation, or JavaScript code to update the form as
desired. The type of data contained in the QueryResponse object is
determined by the handler for the action that initiated the query.

Working with QueryResponse object


This topic provides information about getting the Data objects
contained in a query response.

Getting Data Objects

When a query response contains an Array of Data objects, you can


process on the returned data by analyzing the type of data returned.

The following example executes the doLookup method on a Cell


object and analyses the QueryResponse object and based on the
response sets the data to a specific cell:

QueryResponse myResponse = myCell.doLookup();


if (myResponse.getType == QueryResponseType.Data)
{
for (int i=0; i < myResponse.getData().length; i++)
form.merge(myResponse.getData(),true);
}

Getting text content

Calling the getText method from the Queryresponse object returns


the HTML page, JavaScript code, or plain text contained in this query
response as a String. If this query response is not type Html,
JavaScript, or Plain, this method returns null.

The following example get the javascript response from a lookup and
executes the script through a Scriptcommand object

©Copyright IBM Corp. 2011 37


QueryResponse myResponse = myCell.doLookup();
if (myResponse.getType == QueryResponseType.JavaScript)
{
String script = myResponse.getText();
ScriptCommand scriptCmd = new ScriptCommand("Alert");
scriptCmd.setCode(script);
}

38 eForms Java API Developer Guide


10.Print Renderer
PrintRenderer Concepts
The PrintRenderer object provides mechanism for printing a Form
object to a network printer.

Working with PrintRenderer object


This topic will guide you to create a PrintRenderer object and to print
a form using this object

Creating a PrintRenderer Object


You can call the constructor to create a new PrintRenderer object and
you can either assign a form directly or you can attach the form later.
The following methods create a new PrintRenderer object

PrintRenderer print = new PrintRenderer();


print.setForm(form);

PrintRenderer printForm = new PrintRenderer(form);

Printing a Form
You can print a form to a specific network printer, if the printername
is set to null, then the form is rendered to the default printer. You can
also set the number of copies to be printed using the PrintRenderer
object.

The following sample prints a form to a network printer.

Form form = new Form(templateSource);


PrintRenderer printForm = new PrintRenderer(form);
printForm.setPrinterName("HP123");
printForm.setCopies(3);
printForm.render();

©Copyright IBM Corp. 2011 39


11.Data
Concepts
The Data object is a collection containing the cell values. It can be
created from an IFX Form Data file (.ifx) which is obtained by saving
the ITX form template.

Working with Data Objects


Creating a Data Object

A Data object represents a collection containing the cell values. The


Data object is used to populate cells on a form or to retrieve values
entered on a form.

Creating a Data Object using the constructor

Data() - This method creates an empty Data object. Data can be


populated by calling the setValue methods:

Data data = new Data();


data.setValue("cell1", "Test");
data.appendValue("cell2", "NewValue");
String[] str = new String("1","2","3");
data.setValues("cell3",str);

Data(java.io.InputStream inputStream) - This method creates a


Data object containing the form data from the IFX file passed as the
input stream.

Data(String uri) - This method creates a Data object containing the


form data from the IFX document referenced by the specified data
source.The uri is a string containing the location of the IFX document.
The eForms API supports the following URI Schemes: file, http, https
and P8. The P8 URI scheme is supported only for the P8 eForms
platform and cannot be used for the standalone application.

The following examples creates Data object using the file & P8 URI
schemes.

// Create the data source.

40 eForms Java API Developer Guide


Data data = new Data("file:///C:/test/SampleData.ifx");

String dataUri = "p8:" +


URLEncoder.encode(ObjectStoreID) + "." +
URLEncoder.encode(dataObjectID);
Data data = new Data(dataUri);

Creating a Data Object from a request

You can create a Data object by calling one of the following methods
on the Data class

fromRequest(HttpServletRequest, Template) - This method creates


a Data object by parsing the individual parameters that correspond to
the cells defined in the template, from the HTTP request XML form
data. Otherwise, the form data is parsed from the individual request
parameters whose names match the cell names in the template.

Data data = Data.fromRequest(request);

fromRequest(HttpServletRequest, String) - This method creates a


Form object by parsing the templateURI from the request parameter
named t and the form data from the individual request parameters
whose names match the cell names in the template.

Data data = Data.fromRequest(request, "t");

Merging Data into a Form Object

You can pre-fill the cells on the form by merging one or more Data
objects into the Form object.

Form form = Form.fromRequest(request, "templateURI");


Data data = Data.fromRequest(request, "xmlData");

form.merge(data, true);

The following sample code creates a Form object by parsing the


template and form data from a request. You can submit a request using
either the Javascript HttpRequest object or using the Java
HttpCommand object.

//Create a HTTP Request using Javascript


var request = new HttpRequest();
request.setMethod(HttpMethod.Post);

©Copyright IBM Corp. 2011 41


request.setUrl("http://server:9080/Workplace/Sample.jsp");
request.setXmlDataIncluded(true);
request.setXmlDataParameterName("xmlData");
request.addParameter("templateURI",
"file:///C:/development/test/templates/simple_form.itx");

//Create a HTTPCommand Object using Java

HttpCommand newDataCmd = new HttpCommand("XMLData");


newDataCmd.setUrl(("http://server:9080/Workplace/Sample.jsp
");
newDataCmd.setMethod(HttpMethod.Post);
newDataCmd.setXmlDataIncluded(true);
newDataCmd.setXmlDataParameterName("xmlData");
newDataCmd.addParameter("templateURI",
"file:///C:/development/test/templates/simple_form.itx");

HtmlFormRenderer renderer = new HtmlFormRenderer();


renderer.getCommands().add(newDataCmd);

In the Sample JSP page, you can parse the Template and Data object to
create a new form

//Create a template object


Template template = Template.fromRequest(request,
"templateURI");

//Create a data object


Data data = Data.fromRequest(request, "xmlData");

//Create a Form and merge the data


Form form = new Form(template);
form.merge(data);

Modifying Data Settings

You can set a value to a field cell or a column cell after checking the
type of the cell. Also you can remove a specific cell from the Data
object:

Data data = new Data();


data.setValue("Name", new Value("John"));
data.appendValue("Birthdate", new Value(new
DateDetail(1970, 11, 6)));
if (data.isColumn("Details"))
{

42 eForms Java API Developer Guide


data.appendValue("Details",new Value("Software
Professional"));
data.appendValue("Details",new Value("Working in Canada"));
}

Value myValueArray[] = new Value[3];


myValueArray[0]= new Value (new DateDetail(2009, 11, 5));
myValueArray[1]= new Value (new DateDetail(2008, 30, 4));
myValueArray[4]= new Value();

data.setValues("Column1", myValueArray);

if (data.hasCell("Column2"))
data.remove("Column2");

©Copyright IBM Corp. 2011 43


12. HtmlFormRenderer
HtmlFormRenderer Concepts
The HtmlFormRenderer object provides methods for rendering an
editable electronic form to the web browser and handling its automatic
callback requests.

You can use the methods on the HtmlFormRenderer object to inspect


or customize usability features of the electronic form such as the
toolbar, the notification bar, automatic window resizing , or whether or
not the form is editable.

You can also use the methods on the Forms, Page, Cell, and
ChoiceList object to customize the behavior of the electronic form
itself.

Working with HtmlFormRenderer Object


This topic provides information about creating an HtmlRenderer
object, modifying the renderer projects, rendering an electronic form
and handling automatic callback requests.

Creating an HtmlFormRenderer Object


The HtmlFormRenderer object requires a Form object to render. This
may be provided in the constructor or may be provided later by the
setForm method.

You can call the following constructors for creating the


HtmlFormRenderer object.

HtmlFormRenderer(Form) - This Constructor creates an


HtmlFormRenderer object to render the specified form.

HtmlFormRenderer renderer = new HtmlFormRenderer(form);

HtmlFormRenderer() - This constructor creates an HtmlFormRenderer


object. You must identify the form to be rendered by making a
subsequent call to the setForm method.

44 eForms Java API Developer Guide


HtmlFormRenderer renderer = new HtmlFormRenderer();
renderer.setForm(form);

NOTE The following methods on the HtmlFormRenderer object


dependent on the form attribute.

• getBuiltInCommands
• getBuiltInToolbarItems
• getHeight
• getOfflineDom
• getWidth
• render

If you do not pass the Form object as an argument to the constructor,


you must call the setForm method before calling any of these
methods.

Modifying HtmlFormRenderer Properties


Methods on the HtmlFormRenderer object enable you to inspect or
customize properties of an electronic form. You can use these methods
to

• Customize Commands and Toolbar items that are to be available


for use with the electronic form in the client environment.
• Define a Notification message to be displayed for the form.
• Open the electronic from in a read-only state.
• Specify the position of the toolbar for the rendered form.
• Specify whether the Page Tabs are to be visible.
• Automatically resize the form when it opens.

Adding commands

A Command object defines a named action to be executed in the client


environment. Such a command can be associated with a toolbar or an
on-form button, or it can be invoked directly from a script that uses
the eForms Javascript API.

The HtmlFormRenderer object provides a collection of built-in


commands. You may also create your own custom commands.
Two types of commands are supported. The ScriptCommand object
provides an arbitrary block of JavaScript code to be executed in the
browser when the command is executed. Any valid JavaScript
including the eforms JavaScript API is supported. The HttpCommand

©Copyright IBM Corp. 2011 45


object describes an arbitrary HTTP request to be submitted when the
command is executed.

Regardless of whether they are built-in or custom, commands are not


automatically included when the form is rendered unless they are
explicitly added to the renderer's command collection.

The following example adds the built-in "pdf" command and a custom
script command called "helloWorld" to the command collection.

// Add the built-in command.


Command pdfCmd = renderer.getBuiltInCommands().get("pdf");
renderer.getCommands().add(pdfCmd);

// Create and add the custom command.


ScriptCommand helloWorldCmd = new
ScriptCommand("helloWorld");
helloWorldCmd.setCode("alert('Hello World!')");
renderer.getCommands().add(helloWorldCmd);

//To Add all built-in commands to the command collection.


renderer.getCommands().add(renderer.getBuiltInCommands());

Adding Toolbar Items

A ToolbarItem object describes a named item to be added to the


toolbar. The HtmlFormRenderer object provides a collection of built-in
toolbar items. You may also create your own custom toolbar items.

Two types of toolbar items are supported. The ToolbarButton object


describes a toolbar button. Typically, the toolbar item is associated by
name to a built-in or custom Command object. Alternatively, you may
omit the command association and later configure an eForm JavaScript
API event handler for the toolbar button. The ToolbarSeparator
object is used to visually separate the toolbar into logical groups of
toolbar buttons.

Regardless of whether they are built-in or custom, toolbar items are


not automatically included when the form is rendered unless they are
explicitly added to the renderer's toolbar item collection.

The following example adds the built-in "pdf" toolbar button and the
custom toolbar command to the toolbar item collection.

46 eForms Java API Developer Guide


// Add the built-in toolbar item.
ToolbarItem pdfBtn =
renderer.getBuiltInToolbarItems().get("pdf");
renderer.getToolbarItems().add(pdfBtn);

// Create and add the custom toolbar button.


ToolbarButton helloWorldBtn = new
ToolbarButton("helloWorld");
helloWorldBtn.setLabel("Hello World");
helloWorldBtn.setToolTip("Displays the message \"Hello
World!\".");
helloWorldBtn.setEnabledIcon(myIconPath);
helloWorldBtn.setCommandName("helloWorld"); // Associates
the command.
renderer.getToolbarItems().add(helloWorldBtn);

//To add all built-in toolbar items to the toolbar item


collection.
renderer.getToolbarItems().add(renderer.getBuiltInToolbarIt
ems());

Adding a Notification

The HtmlFormRenderer object provides methods for adding a custom


notification message with a particular notification level.

String message = "This is amazing!";


renderer.setNotification(message,
NotificationLevel.Warning);

Additional Settings.

The HtmlFormRenderer object provides additional methods for


customizing the manner in which the form is rendered.

//Read-only - Open the form in a read-only state.


renderer.setReadOnly(true);

//Auto-resize - Automatically resize the form when it


opens.
renderer.setAutoResize(true);

//Adjust the toolbar settings


renderer.setToolbarPosition(ToolbarPosition.Bottom);
renderer.setToolbarButtonStyle(ToolbarButtonStyle.Icon);

©Copyright IBM Corp. 2011 47


//Set the browser window title
renderer.setTitle("Hello");

//Hide PageTabs
renderer.setPageTabsVisible(false);

Rendering the Form

Once the HtmlFormRenderer object has been created and all its
properties are modified, then the form can be rendered to the web
browser using the following command:

//render the form to the browser


renderer.render(request, response);

The following is a complete sample page for rendering a form using


different commands and toolbar buttons:

// Render the form.


HtmlFormRenderer renderer = new HtmlFormRenderer();

renderer.setForm(form);

// Set sample notification


renderer.setNotification(new Notification("This is
amazing", NotificationLevel.Notice));

renderer.getCommands().add(renderer.getBuiltInCommands());
renderer.getToolbarItems().add(renderer.getBuiltInToolbarIt
ems());

// Create pdf command


ScriptCommand pdfCommand = new ScriptCommand("pdf");
pdfCommand.setCode("self.frames[0].frm.$renderPdf();");
renderer.getCommands().add(pdfCommand);

// Create toolbar button and add it to the toolbar


ToolbarButton pdfButton = new ToolbarButton("pdf");
pdfButton.setLabel("PDF");
pdfButton.setEnabledIconUrl("forms/images/pdf.gif");
pdfButton.setCommandName(pdfCommand.getName());
renderer.getToolbarItems().add(pdfButton);

HttpCommand subCommand3 = new HttpCommand("submitGet");


subCommand3.setMethod(HttpMethod.Post);
subCommand3.setSynchronous(true);
subCommand3.setUrl("http://localhost:8080/sample.jsp");

48 eForms Java API Developer Guide


renderer.getCommands().add(subCommand3);

ToolbarButton testButton = new


ToolbarButton("TestCommand");
testButton.setLabel("TEST");
testButton.setEnabledIconUrl("forms/images/help.gif");
testButton.setCommandName(subCommand3.getName());
renderer.getToolbarItems().add(testButton); */

TargetFeatures features = new TargetFeatures();


features.setLeft(new Integer(550));
features.setTop(new Integer(300));
features.setWidth(new Integer(800));
features.setHeight(new Integer(600));

HttpCommand filenetCmd = new HttpCommand("filenet");


filenetCmd.setUrl("http://www.filenet.com");
filenetCmd.setTarget(new Target("new", features));
renderer.getCommands().add(filenetCmd);

ToolbarButton testButton = new ToolbarButton("Filenet");


testButton.setLabel("File");
testButton.setEnabledIconUrl("forms/images/help.gif");
testButton.setCommandName(filenetCmd.getName());
renderer.getToolbarItems().add(testButton);

renderer.setToolbarPosition(ToolbarPosition.Top);
renderer.render(request, response);

Handling Automatic Callback Requests


Once the electronic form is rendered to the web browser, it is ready to
a make automatic call back requests to the web server. The
HtmlFormRenderer object provides two methods, one for handling all
automatic callback requests and another for handling all exceptions
encountered while handling the callback requests.

Any custom application should have a callback servlet for handling


these requests. This servlet must handle both the Get and Post
requests and it must be registered in the eforms-integration.xml file.

The implementation of the callback servlet will vary depending on the


authentication and other requirements of a specific web application. A
typical implementation of the callback servlet is as follows:

©Copyright IBM Corp. 2011 49


package myapp;

import com.filenet.eforms.api.Configuration;
import com.filenet.eforms.api.Context;
import com.filenet.eforms.api.HtmlFormRenderer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Hashtable;

public class CallbackServlet extends HttpServlet


{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IO Exception
{
handleRequest(request, response);
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
handleRequest(request, responseA);
}

private void handleRequest(HttpServletRequest request,


HttpServletResponse response)
{
try
{
//Initialize the Configuration

Configuration.initialize(getServletContext().getRealPath("/
WEB-INF");

//Initialize the Context


Hashtable context = Context.initialize();
context.put("locale", request.getLocale());
context.put("timeZone", TimeZone.getDefault());
context.put("username", "John Smith");

//Handle the request

50 eForms Java API Developer Guide


HtlFormRenderer.handleCallback(request,
response);
}
catch (Throwable e)
{
//Handle any exception thrown
HtmlFormRenderer.handleCallbackException(e,
request, response);
}
finally
{
//Release the context
Context.release();
}
}
}

For registering the callback servlet in the eforms-integration.xml file,


include the following.

<integration>
<callback page="formCallback" formUrl="forms/" />
</integration>

©Copyright IBM Corp. 2011 51


13. ImageRenderer
ImageRenderer Concepts
The ImageRenderer object is the abstract base for rendering a static
image of a Form object. The following are the two methods for
rendering an image of a Form

PdfImageRenderer - Renderers the specific Form as a PDF document

TiffImageRenderer - Rendered a form as a TIFF image. The TIFF


format enables the form image to be viewed and annotated using the
P8 Image Viewer.

Working with ImageRenderer


This topic explains the methods involved in rendering the Form object
as a PDF and as TIFF image.

Creating a PDFImageRenderer object


You can create a PDFImageRenderer object by calling it constructors.

PdfImageRenderer newPDF = new PdfImageRenderer();

You can then associate a form with the new PdfImageRenderer object
by calling the setForm method of the ImageRenderer class.

newPDF.setForm(form);

You can also create a new PdfImageRenderer object for a specific


form:

PdfImageRenderer newPDF = new PdfImageRenderer(form);

Rendering a Form as a PDF

You can render the form image represented by the ImageRenderer


object either to a specified HTTP Servlet response or to a specified
output stream.

52 eForms Java API Developer Guide


The following method call renders the form image to the specified Http
servlet response.

render(request, response, filename, asAttachment)

In the above method the form image is downloaded as a document


with the specified filename. If a filename is not specified, then it uses
default untitled filename when downloading the document containing
the form image.

The asAttachment parameter determines whether the form user is


given the opportunity to save the downloaded document without
opening it. If this parameter is set to false, the document is rendered
directly in the target browser window. If this parameter is set to true,
the form user is presented with a standard Open/Save/Cancel dialog
box.

NOTE Setting the asAttachment parameter to true adds the keyword


attachment to the HTTP content-disposition header. The attachment
keyword enables the document to be downloaded to the browser as an
attachment.

The following example renders the form image to the specified HTTP
servlet response:

Form form = new Form(templateSource);


PdfImageRenderer pdfrenderer = new PdfImageRenderer(form);
pdfrenderer.render(request,response,"TestPDF",true);

The following example renders the form image to the specified output
stream

Form form = new Form(templateSource);


PdfImageRenderer pdfrenderer = new PdfImageRenderer(form);
File myPDFFile = new File("c:\\Temp\\Test.pdf");
FileOutputStream myOutputStream = new
FileOutputStream(myPDFFile);
pdfrenderer.render(myOutputStream);
myOutputStream.close();

Creating a TIFFImageRenderer Object.


You can create a TIFFImageRenderer object by calling its constructors.

©Copyright IBM Corp. 2011 53


TiffImageRenderer newTIFF = new TiffImageRenderer();

You can then associate a form with the new TiffImageRenderer


object by calling the setForm method of the ImageRenderer class.

newTiff.setForm(form);

You can also create a new TiffImageRenderer object for a specific


form:

TiffImageRenderer newTiff = new TiffImageRenderer(form);

Rendering a Form as a TIFF Image

You can render the form image represented by the ImageRenderer


object either to a specified HTTP Servlet response or to a specified
output stream. You can set the Tiff compression type, as the bitmap
used to create a TIFF image can be very large, which in turn causes
the TIFF image to be very large. Therefore, the TIFF document format
supports a variety of compression algorithms to reduce the size of the
image.

The following example renders the form image to the specified HTTP
servlet response, using the the LZW compression algorithm:

Form form = new Form(templateSource);


TiffImageRenderer tiffRenderer = new
TiffImageRenderer(form);
tiffRenderer.setCompressionType(TiffCompressionType.LZW);
tiffRenderer.setResolution(120);
tiffRenderer.render(request,response,"TestTiff",true);

54 eForms Java API Developer Guide


14.HTTP Commands
Http Command Concepts
A Command object represents a preconfigured action that can be
invoked from an electronic form. The command can be one of the
built-in commands — help, pdf, or submit — or an HTTP command or a
script command that can created using the eForms Java™ API.

An HttpCommand submits an HTTP request and handles the response to


that request. The way in which the response is handled depends on
whether you set a target window for the HttpCommand object.

For a command to be available from an electronic form, you must add


the command to the Command collection for that form. Once the
command is added to the Command collection, it can be invoked from a
client-side script, form button, or toolbar button.

Working with HTTP Commands


This topic provides information on creating a new HTTP command,
making post back requests and executing a command.

Creating an HTTP Command

An HttpCommand submits an HTTP request and handles the response to


that request. The way in which the response is handled depends on
whether you set a target window for the HttpCommand object.

If you set a target window, the HTTP request handler is expected to


return viewable content, such as HTML, an image, etc. The content is
then rendered in the target window.

If you do not set a target window, then the HTTP request handler is
expected to return a response that is to be processed by the calling
script. The following table lists the valid types of content for such a
response and describes the behavior of the HttpCommand object when
a given type of response is received.

©Copyright IBM Corp. 2011 55


Content Format HttpCommand Behavior
The JavaScript code is executed at the client. If the
text/x-eforms-
script- request is synchronous, the resulting value is passed
javascript to the caller. If the request is asynchronous, the
resulting value is discarded.
If the request is synchronous, the XML is parsed and
text/xml returned as a DOM object to the caller. If the
request is asynchronous, the resulting value is
discarded.
If the request is synchronous, the text is returned as
text/plain a string to the caller. If the request is asynchronous,
the resulting value is discarded.

The following example creates a new HTTPCommand object to execute a


specific JSP page and returns an HTML response to a new window.

HttpCommand testCommand = new HttpCommand("Submit");


testCommand.setTarget(new Target("new"));
testCommand.addParameters("extra",extraValue);

testCommand.setUrl("http://TestSuite:8080/sample.jsp");

The newly created HTTP command needs to be added into the Command
collection in order to be invoked from the rendered Form. You can
create a Toolbar button or a Form Button to call the command from
the rendered electronic form.

The following example creates new HTTPCommand object, sets the


command to direct the response to a newly created target object, adds
the command to the Command collection and finally creates a new
Toolbar button to invoke the command from the rendered Form.

HttpCommand httpCmd= new HttpCommand("TestCommand");


httpCmd.setUrl("http://TestSuite:8080/sample.jsp");

TargetFeatures myTarget= new TargetFeatures("MyWindow");


myTarget.setLeft(new Integer(550));
myTarget.setTop(new Integer(300));
myTarget.setWidth(new Integer(800));
myTarget.setHeight(new Integer(600));

httpCmd.setTarget(myTarget);

56 eForms Java API Developer Guide


renderer.getCommands().add(httpCmd);

ToolbarButton testButton = new ToolbarButton("MyButton");


testButton.setLabel("My Test Button");
testButton.setEnabledIconUrl("forms/images/help.gif");
testButton.setCommandName(httpCmd.getName());
renderer.getToolbarItems().add(testButton);

Handling Custom Postback Requests

When you render an electronic form, you can configure a custom


HttpCommand object to submit an HTTP request to a custom servlet or
JSP page. Alternatively, you can use the eForms JavaScript API's
HttpRequest object to configure such a request.

With such a request you may choose to include the form data in the
request. If so, the eForm Java API provides convenience methods for
parsing the form data from the request parameters. Many such
scenarios are supported. This section describes the most common or
important.

Posting the Form Data as a Single XML Parameter

An HttpCommand object can be configured as follows to post the form


data as a single request parameter whose value represents the form
data as an XML document in IFX format. By default, the request
parameter name is "data", but a custom request parameter name may
be specified as shown below:

// Create the HttpCommand object.


HttpCommand xmlDataCmd = new HttpCommand("XMLData");
xmlDataCmd.setUrl(url);
xmlDataCmd.setMethod(HttpMethod.Post);
xmlDataCmd.setXmlDataIncluded(true);
xmlDataCmd.setXmlDataParameterName("xmlData");
renderer.getCommands().add(xmlDataCmd);

You can parse the form data submitted from the above request and
create a Data object as follows:

// Parse the data parameter.


Data data = Data.fromRequest(request, "xmlData");

©Copyright IBM Corp. 2011 57


Posting the Form Data as Individual Request
Parameters

Traditional HTML forms post form data to a server as individual form


parameters. Similarly, an HttpCommand object can be configured to
post cell values as individual request parameters using the
HTTPMethod.Post method.

Alternatively, if you use the method HttpMethod.Get, then all


parameters are appended to the query string.

The request includes a request parameter for each cell where the
parameter name is the cell name and the parameter value is the cell
value as a string in canonical format. For column cells, multiple
request parameters with the same name are included.

// Create the HttpCommand object.


HttpCommand formDataCmd = new HttpCommand("FormData");
formDataCmd.setUrl(url);
formDataCmd.setMethod(HttpMethod.Post);
formDataCmd.setFormDataIncluded(true);
renderer.getCommands().add(formDataCmd);

Including the Template URI

Alternatively you can modify the command as follows to include the


template URI as a request parameter. By default, the request
parameter name is "template", but a custom request parameter name
may be specified as shown:

// Create the HttpCommand object.


HttpCommand formDataCmd = new HttpCommand("FormData");
formDataCmd.setUrl(url);
formDataCmd.setMethod(HttpMethod.Post);
formDataCmd.setTemplateUriIncluded(true);
formDataCmd.setTemplateUriParameterName("templateUri");
formDataCmd.setFormDataIncluded(true);
renderer.getCommands().add(formDataCmd);

You can parse the form data submitted from the above request and
create a Data object:

// Parse the data parameter.


Data data = Data.fromRequest(request, "templateUri");

58 eForms Java API Developer Guide


Notices
This information was developed for products and services offered in the U.S.A.

IBM® may not offer the products, services, or features discussed in this document
in other countries. Consult your local IBM representative for information on the
products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may
be used instead. However, it is the user's responsibility to evaluate and verify the
operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not grant you
any license to these patents. You can send license inquiries, in writing, to:

IBM Director of Licensing


IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.

For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country or send inquiries, in writing, to:

IBM World Trade Asia Corporation


Licensing
2-31 Roppongi 3-chome, Minato-ku
Tokyo 106-0032, Japan

The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law:
INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS
PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or
implied warranties in certain transactions, therefore, this statement may not apply
to you.

This information could include technical inaccuracies or typographical errors.


Changes are periodically made to the information herein; these changes will be
incorporated in new editions of the publication. IBM may make improvements
and/or changes in the product(s) and/or the program(s) described in this
publication at any time without notice.

Any references in this information to non-IBM Web sites are provided for
convenience only and do not in any manner serve as an endorsement of those Web
sites. The materials at those Web sites are not part of the materials for this IBM
product and use of those Web sites is at your own risk.

© Copyright IBM Corp. 2011 59


IBM may use or distribute any of the information you supply in any way it
believes appropriate without incurring any obligation to you.

Licensees of this program who wish to have information about it for the purpose
of enabling: (i) the exchange of information between independently created
programs and other programs (including this one) and (ii) the mutual use of the
information which has been exchanged, should contact:

IBM Corporation
J46A/G4
555 Bailey Avenue
San Jose, CA 95141-1003
U.S.A.

Such information may be available, subject to appropriate terms and conditions,


including in some cases, payment of a fee.

The licensed program described in this document and all licensed material
available for it are provided by IBM under terms of the IBM Customer Agreement,
IBM International Program License Agreement or any equivalent agreement
between us.

Any performance data contained herein was determined in a controlled


environment. Therefore, the results obtained in other operating environments may
vary significantly. Some measurements may have been made on development-level
systems and there is no guarantee that these measurements will be the same on
generally available systems. Furthermore, some measurements may have been
estimated through extrapolation. Actual results may vary. Users of this document
should verify the applicable data for their specific environment.

Information concerning non-IBM products was obtained from the suppliers of


those products, their published announcements or other publicly available sources.
IBM has not tested those products and cannot confirm the accuracy of
performance, compatibility or any other claims related to non-IBM products.
Questions on the capabilities of non-IBM products should be addressed to the
suppliers of those products.

All statements regarding IBM's future direction or intent are subject to change or
withdrawal without notice, and represent goals and objectives only.

This information contains examples of data and reports used in daily business
operations. To illustrate them as completely as possible, the examples include the
names of individuals, companies, brands, and products. All of these names are
fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.

COPYRIGHT LICENSE:

This information contains sample application programs in source language, which


illustrate programming techniques on various operating platforms. You may copy,
modify, and distribute these sample programs in any form without payment to
IBM, for the purposes of developing, using, marketing or distributing application
programs conforming to the application programming interface for the operating
platform for which the sample programs are written. These examples have not
been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or
imply reliability, serviceability, or function of these programs.

60 P8 eForms Java API Developer Guide


Trademarks
The following terms are trademarks of the International Business Machines
Corporation in the United States, other countries, or both: http://www.ibm.com/
legal/copytrade.shtml

Microsoft, Windows, and Windows NT are trademarks of Microsoft Corporation in


the United States, other countries, or both.

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.

The Oracle Outside In Technology included herein is subject to a restricted use


license and can only be used in conjunction with this application.

Other company, product, and service names may be trademarks or service marks
of others.

© Copyright IBM Corp. 2011 61


62 P8 eForms Java API Developer Guide


Program Number: 5724-R85

SC19-3247-00

You might also like