You are on page 1of 112

ORACLE APPLICATION

DEVELOPMENT
FRAMEWORK (ADF)
Assorted Notes

Compiled by: Deepak Bhagat


Fusion Functional Consultant,
Solution Architect & ADF Trainer
Oracle Application Development Framework (ADF) Assorted Notes

Table of Contents
1 Overview of Fusion Middleware and ADF ................................................................... 1
2 Understanding Development Tool: JDeveloper ........................................................... 2
3 Modeling Database Schema ...................................................................................... 5
4 Building Business Service with Default ADF Business Components ............................. 14
5 Persisting Data using Entity Object .......................................................................... 17
6 Querying Data using View Object ............................................................................ 19
7 Exposing Business Service through the Application Module ....................................... 20
8 Declaratively Customizing Business Services ............................................................ 28
9 Validating Business Services ................................................................................... 29
10 Introducing User Interface Technologies .............................................................. 31
11 Getting Started with Rich User Interface ............................................................... 33
12 Planning Pages using Layout Components ............................................................ 34
13 Designing User Interfaces and Page Flows............................................................ 36
14 Interactively Controlling with Navigation Components ........................................... 37
15 Ensuring Reusability in Web Applications .............................................................. 39
16 Working with Scopes, Parameters and Partial Page Refresh ................................... 42
17 Responding to Managed Beans, Events and Listeners ............................................ 44
18 Binding Model Layer with Business Services and Databound View .......................... 52
19 Querying Data with Search Components ............................................................... 53
20 Implementing Transactions ................................................................................. 58
21 Understanding Data Controls and Bindings ........................................................... 75
22 Programmatically Customizing Business Services................................................... 83
23 Deploying ADF Applications ................................................................................. 90
24 Securing ADF Applications ................................................................................... 94
25 Debugging and Troubleshooting ADF Applications ................................................. 95
26 ADF Best Practices .............................................................................................. 98
27 Miscellaneous ..................................................................................................... 99
28 Advance ADF .................................................................................................... 100
29 Integrating ADF with Web Service ...................................................................... 101

i
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

30 Integrating ADF with EJB................................................................................... 103


31 Integrating ADF with SOA.................................................................................. 104
32 Integrating ADF with Mobile Application Framework (MAF) .................................. 105
33 Integrating ADF with Cloud Service .................................................................... 106
34 Integrating ADF with WebCenter........................................................................ 107
35 Tools ................................................................................................................ 108

ii
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

1 Overview of Fusion Middleware and ADF


1. What is JSR?
Java Specification Request (JSR) the future of web programming languages is already going to
have acceptance from all over the world. In simple words, JSR is the actual description of the
proposed and final specifications for the Java platform. At any one time, numerous JSRs are
moving through the review and approval process. JSR’s are reviewed by the JCP and the public
before a final release of a specification is made.
The JSR projects found here are led by Specified leads who have decided to leverage java.net’s
infrastructure for JSR development and collaboration. You will also find other JSR discussions that
may or may not be led by Specifications leads or those involved in the JSR development. Each
java.net hosted JSR Project has a public area where discussions will take place between the
community and those involved in the JSR development project.
“Write Content Once, Deliver It to Any Device!”
What is JSR 227? In one sentence we say that JSR-227 defines a standard way for tools
to implement the interactions between user interfaces and services, doing this in a way that
will work for any user interface and any service technology. In the world of MVC applications,
the View and Controller layers need to interact with the Model layer. Until this JSR came
along, the developer had to learn the specific API for the technology that implemented its
Model layer to build his View and Controller layers. With JSR 227 there is a single standard
API that works with any implementation of a Model layer – regardless of the implementing
technology which can be EJB, SDO, XML, JavaBeans, etc – as well as with any
implementation of the View layer, such as JSP, JSF, Struts, Swing or any new technology
that might pop up.
What is JSR 241? JSR-241: Groovy – A New Standard Programming Language for the Java
Platform. Posted by Monson-Haefel on March 16, 2004, at 5:23 AM PST. JSR-241: The
Groovy Programming Language proposes the standardization of a new programming
language for the Java Platform – one that is on equal footing with the Java programming
language

1/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

2 Understanding Development Tool: JDeveloper


1. What is Oracle Fusion Middleware?
Oracle Fusion Middleware is the platform that provides various capabilities to develop deploy and
test enterprise business applications. It has a sound architecture that supports different
technologies at a single point. Oracle says it's built with the 4 unique design principles 'Complete
Integrated Hot-Pluggable and Best of Breed'.

2. Oracle Fusion Middleware Architecture


Oracle Fusion Middleware is a collection of standards-based software products that includes a
range of tools and services including developer tools, integration services, business intelligence,
collaboration, and content management. Oracle Fusion Middleware offers complete support for
development, deployment, and management.
Specifically, Oracle Fusion Middleware offers the following solutions through its middleware
design:
Development Tools: A unified SOA development tool and framework. An integrated, but
modular, set of development tools to build complete applications, rather than using lots of
specialized tools. The design tool includes a single design environment for the user interface,
business logic, service composition, business process or workflow, business rules, and
business intelligence. The design tool enables simplified design and debugging, and to
improve productivity. Includes Oracle JDeveloper, Oracle TopLink, Oracle Application
Development Framework, and Oracle Eclipse.
User Interaction: A single, end-user environment that enables access to enterprise
applications, business processes, business intelligence and sharing information with each
other. This end-user environment is multi-channel allowing it to be accessed from a variety
of different clients (mobile clients, desktop clients, Voice-over IP (VOIP) clients) with Oracle
WebCenter Portal.
Business Intelligence: A suite of business intelligence tools from extract, transform, and
load to integrate data into warehouses; query, analysis, and reporting tools for decision
support; scorecards to compare how the business is doing against key performance
indicators; alerting to drive notifications to users about problems in the business software.
Content Management: A repository within which to manage documents, digital assets,
scanned images and other forms of content; to integrate this content with a company's
enterprise applications, Web sites, and business processes.
SOA: A means of using existing investments in applications and systems most efficiently to
be able to focus more resources and budget on innovation and on delivering new business
services.
Application Server: A standards-based Java EE application server to run the enterprise
applications and provide the Web services infrastructure for interoperability.
Integration and Business Process Management (BPM): A standards-based service
bus to connect applications with each other and with legacy systems using messaging; a
BPM or workflow engine to connect the application into a business process or workflow; and
business activity monitoring and optimizes business processes in real-time.
Security and Identity Management: Security administration across multiple applications
and systems in an enterprise, by centralizing how users are created and provisioned, their
identities, and roles and by enabling them to have single sign-on access. Includes Oracle
Internet Directory, Oracle Virtual Directory, Oracle Directory Integration Platform, Oracle
Identity Federation. Identity Management provides a shared infrastructure for all
applications, enabling developers to incorporate identity management into applications.

2/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Enterprise Management: Operations and administration by running on a grid architecture
with grouping, backup, and other high availability technologies, and integrating with Oracle
Enterprise Manager for systems management. Includes Fusion Middleware Control, Oracle
WebLogic Server Administration Console, Oracle WebLogic Scripting Tool, Oracle Process
Manager and Notification Server.

3. BAM
Oracle Business Activity Monitoring (Oracle BAM) gives business executives the ability to monitor
their business services and processes in the enterprise, to correlate KPIs down to the actual
business process themselves, and most importantly, to change business processes quickly or to
take corrective action if the business environment changes.
Overview:
Creates dashboards, alerts, and reports in real-time with no coding
Provides the ability to close the loop with corrective actions
Delivers more than 35 different event visualizations
Provides integrated historical event correlation
Benefits:
Gain real-time visibility into critical business processes through push-based dashboards and
alerts powered by event-driven architecture
Ensure real-time awareness of SLA and KPI performance
Provide visibility into existing SOA, BPM, and EDA investments, as well as third-party
infrastructures such as databases, JMS servers, and Web services
Gain efficiency through pre-built integration with Oracle SOA Suite, Oracle BPM Suite, Oracle
Business Intelligence, and more

4. BPEL
BPEL (Business Process Execution Language) is an XML-based language that allows Web services
in a service-oriented architecture (SOA) to interconnect and share data. Business processes can
be described in two ways:
Executable business processes model the actual behavior of a participant in a business
interaction.
Business protocols, in contrast, use process descriptions that specify the mutually visible
message exchange behavior of each of the parties involved in the protocol, without revealing
their internal behavior. The process descriptions for business protocols are called abstract
processes.
BPEL is used to model the behavior of both executable and abstract processes. The scope
includes:
 Sequencing of process activities, especially Web Service interactions
 Correlation of messages and process instances
 Recovery behavior in case of failures and exceptional conditions
 Bilateral Web Service based relationships between process roles

5. Business Process
A business process is a collection of linked tasks that find their end in the delivery of a service or
product to a client. A business process has also been defined as a set of activities and tasks that,
once completed, will accomplish an organizational goal.

3/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

6. Agile Management
Agile management or agile project management is an iterative and incremental method
of managing the design and build activities for engineering, information technology, and new
product or service development projects in a highly flexible and interactive manner, for
example, agile software development.

7. WebCenter Portal framework includes:


page hierarchies, navigation models, delegated security (pages.xml), customization,
personalization, portlets, content management, system integration, social computing services,
search, analytics, skin configuration, configure resource catalog for task flows, navigation models,
and more.
From the perspective of an end-user, a portal is a web site with pages that are organized by tabs
or some other form of navigation. Each page can contain portlets, static content, dynamic content,
and task flows. Authorized users can also customize their view of a portal by adding their own
pages, adding portlets of their choosing, and changing the Look and Feel of the interface.
Portlets vs Pagelets: - A pagelet is a reusable user interface component similar to a
portlet, but while portlets were designed specifically for portals, pagelets can be run on any
web page, including within a portal or other web application. Pagelets can be used to expose
platform-specific portlets in other web environments.
Task flows vs Portlets: - You can drag and drop task flows onto any customizable
WebLogic Portal application page. In this sense, you can think of a task flow as a "local
portlet" that can be reused and dropped into an ADF application.
You must first add the Page Customizable, then a Layout Customizable, and then the required
hierarchy of Panel Customizable and Show Detail Frame components. Drag each of the existing
components and drop them onto suitable locations inside the Page Customizable.

8. Portlet Types
Web Clipping Allows the Portal Page Designer to clip page content from existing Web sites
Producer and deliver it as a portlet.
Omni PortletProvides a wizard-based experience to allow Page Designers to publish data
Producer from SQL, XML, Web Services, Spreadsheets and Web Page as customizable
charts, tables or lists.
Sample Portlet Provides sample portlets built with Omni Portlet for demonstration purposes
Producer only. Developers should not use them to create real-use portlet instances.

4/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3 Modeling Database Schema


1. DB Synonyms
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects. They can be used to hide ownership and location of the
database objects they refer to and minimize the impact of moving or renaming the database
objects.
There are two types of synonyms:
Private: Private synonyms exist only in a specific user schema. The owner of the synonym
maintains control over availability to other users.
Public: A public synonym is available to all users in the database
You generally use synonyms when you are granting access to an object from another schema
and you don't want the users to have to worry about knowing which schema owns the object.
For example:
CREATE PUBLIC SYNONYM suppliers FOR app.suppliers;
This first CREATE SYNONYM example demonstrates how to create a synonym called
suppliers. Now, users of other schemas can reference the table called suppliers without
having to prefix the table name with the schema named app. For example:
SELECT * FROM suppliers;
If this synonym already existed and you wanted to redefine it, you could always use the OR
REPLACE phrase as follows:
CREATE OR REPLACE PUBLIC SYNONYM suppliers FOR
app.suppliers;
DROP SYNONYM
Once a synonym has been created in Oracle, you might at some point need to drop the
synonym. Example
DROP PUBLIC SYNONYM suppliers;
This DROP statement would drop the synonym called suppliers that we defined earlier.

2. Difference b/w Date & Time Stamp


The biggest difference: DATE is accurate to the second and doesn't have fractional
seconds. TIMESTAMP has fractional seconds. The number of decimal places in the seconds
depends on the server OS, for example, the Oracle on my Windows 7 machine returns three
decimal places for the timestamp whereas a client's huge Solaris box returns six. Timestamps
can also hold a specific time zone or be normalized to a common time zone
DATE and TIMESTAMP have the same size (7 bytes). Those bytes are used to store century,
decade, year, month, day, hour, minute and seconds. But TIMESTAMP allows storing
additional info such as fractional seconds (11 bytes) and fractional seconds with time zone
(13 bytes).
TIMESTAMP was added as an ANSI compliant to Oracle. Before that, it had DATE only.
In general cases, you should use DATE. But if precision in time is a requirement, use
TIMESTAMP.
And about Java, the oracle.sql.DATE class from Oracle JDBC driver provides conversions
between the Oracle Date/Timestamp data type and Java classes java.sql.Date,
java.sql.Time and java.sql.Timestamp. Example:
Date: 16:05:14
Timestamp: 16:05:14:000

3. Constraints
5/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Primary key: This constraint defines a column or combination of columns that uniquely
identifies each row in the table.
Syntax to define a Primary key at column level:
column name datatype [CONSTRAINT constraint_name] PRIMARY KEY
Syntax to define a Primary key at table level:
[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,
column_name2,..)
column_name1, column_name2 are the names of the columns which define the Primary
Key.
The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.
For Example: To create an employee table with Primary Key constraint, the query would
be like.

Primary Key at column level:


CREATE TABLE employee
(id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
OR
CREATE TABLE employee
(id number(5) CONSTRAINT emp_id_pk PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
OR
CREATE TABLE employee
(id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT emp_id_pk PRIMARY KEY (id)
);

Primary Key at table level:


CREATE TABLE employee
(id number(5), NOT NULL,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),

6/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
ALTER TABLE employee ADD CONSTRAINT PK_EMPLOYEE_ID PRIMARY KEY
(id)
);

Foreign key: This constraint identifies any column referencing the PRIMARY KEY in another
table. It establishes a relationship between two columns in the same table or between
different tables. For a column to be defined as a Foreign Key, it should be defined as a
Primary Key in the table which it is referring to. One or more columns can be defined as
Foreign key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCES
Referenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES
referenced_table_name(column_name);
For Example:
1) Let's use the "product" table and "order_items".
Foreign Key at column level:
CREATE TABLE product
(product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
CREATE TABLE order_items
(order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,
product_id number(5) CONSTRAINT pd_id_fk REFERENCES,
product(product_id),
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
Foreign Key at table level:
CREATE TABLE order_items
(order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
CONSTRAINT od_id_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES
product(product_id)
);
2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references
primary key 'id' within the same table, the query would be like,
CREATE TABLE employee
(id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
mgr_id number(5) REFERENCES employee(id),

7/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
salary number(10),
location char(10)
);

Not Null Constraint: This constraint ensures all rows in the table contain a definite value
for the column which is specified as not null. Which means a null value is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOT NULL
Example: To create an employee table with Null value, the query would be like
CREATE TABLE employee
(id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);

Unique Key: This constraint ensures that a column or a group of columns in each row have
a distinct value. A column(s) can have a null value but the values cannot be duplicated.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name] UNIQUE(column_name)
For Example: To create an employee table with Unique key, the query would be like,
Unique Key at column level:
CREATE TABLE employee
(id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) UNIQUE
);
or
CREATE TABLE employee
(id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) CONSTRAINT loc_un UNIQUE
);
Unique Key at table level:
CREATE TABLE employee
(id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),

8/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
CONSTRAINT loc_un UNIQUE(location)
);

Surrogate key: A surrogate key in a database is a unique identifier for either an entity in
the modeled world or an object in the database. A surrogate key is a substitution for the
natural primary key. It is just a unique identifier or number for each row that can be used
for the primary key to the table. The only requirement for a surrogate primary key is that it
is unique for each row in the table. Data warehouses typically use a surrogate, (also known
as artificial or identity key), key for the dimension tables' primary keys. They can use Infa
sequence generator, or Oracle sequence, or SQL Server Identity values for the surrogate
key. It is useful because the natural primary key (i.e. Customer Number in Customer table)
can change and this makes updates more difficult. Some tables have columns such as
AIRPORT_NAME or CITY_NAME which are stated as the primary keys (according to the
business users) but, not only can these changes, indexing on a numerical value is probably
better and you could consider creating a surrogate key called, say, AIRPORT_ID. This would
be internal to the system and as far as the client is concerned you may display only the
AIRPORT_NAME.

4. Difference between primary key and unique key


Primary Key:
Can be only one in a table
It never allows null values
The primary key is a unique key identifier and cannot be null and must be unique.

Unique Key:
It can be more than one unique key in one table.
Unique key can have null values
It can’t be candidate key
The unique key can be null and may not be unique.

5. Data types in SQL


byte:
A byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive) (2^7 -1)
Default value is 0
A byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.
Example: byte a = 100, byte b = -50

short:
A short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
A short data type can also be used to save memory as a byte data type. A short is 2 times
smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000

9/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648. (-2^31)
Maximum value is 2,147,483,647(inclusive). (2^31 -1)
Int is generally used as the default data type for integral values unless there is a concern
about memory.
The default value is 0.
Example: int a = 100000, int b = -200000

long:
A long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808. (-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L

float:
A float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f

double:
A double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally the
default choice.
The double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4

boolean:
A boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true

char:
A char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'

10/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

6. What Is DB View?
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables in
the database. A database view displays one or more database records on the same page. A view
can display some or all of the database fields. Views have filters to determine which records they
show. Views can be sorted to control the record order and grouped to display records in related
sets. Views have other options such as totals and subtotals. A View in Oracle and other database
systems is simply the representation of a SQL statement that is stored in memory so that it can
easily be re-used. For example, if we frequently issue the following query
SELECT customerid, customername FROM customers WHERE countryid='US';
To create a view, use the CREATE VIEW command as seen in this example
CREATE VIEW view_uscustomers
AS
SELECT customerid, customername FROM customers WHERE countryid='US';
This command creates a new view called view_uscustomers. Note that this command does not
result in anything being stored in the database at all except for a data dictionary entry that defines
this view. This means that every time you query this view, Oracle has to go out and execute the
view and query the database data. We can query the view like this:
SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;
And Oracle will transform the query into this:
SELECT * FROM (select customerid, customername from customers WHERE
countryid='US')
WHERE customerid BETWEEN 100 AND 200

7. Benefits of using Views:


The commonality of code being used: Since a view is based on one common set of SQLs,
this means that when it is called it’s less likely to require parsing.
Security: Views have long been used to hide the tables that contain the data you are
querying. Also, views can be used to restrict the columns that a given user has access to.

8. Trigger-Assigned Values
To synchronize when database trigger updates a column, use Refresh After Update or Refresh
After Insert. To use a database sequence to generate a primary key:
The Set data type of attribute to DBSequence
Set Updatable to Never
Refresh After Insert is selected automatically

9. Synchronizing with Trigger-Assigned Values


When a database trigger updates the underlying column value during insert or update
operations, you can select the respective Refresh After Insert or Refresh After Update
checkboxes to ensure that the framework automatically retrieves the modified value and
keeps the entity object and database row in sync. The entity object then uses the Oracle
SQL RETURNING INTO feature to return the modified column back to your application in a
single database round-trip.
One common case for Refresh After Insert occurs when a primary key attribute value is
assigned by a BEFORE INSERT FOR EACH ROW trigger. Often the trigger assigns the primary
key from a database sequence. In this case, you can set the Attribute Type to the data type
DBSequence. Setting this data type automatically enables the Refresh After Insert property.

11/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
When you create a new entity row whose primary key is a DBSequence, a unique negative
number gets assigned as its temporary value. This value acts as the primary key for the
duration of the transaction in which it is created. At transaction commit time, the entity
object issues its INSERT operation using the RETURNING INTO clause to retrieve the actual
database trigger–assigned primary key value. Any related new entities that previously used
the temporary negative value as a foreign key will get that value updated to reflect the actual
new primary key of the master. You can set the Updatable property of a DBSequence-
valued primary key to Never because the end-user never needs to update this value.

10. Materialized View


Materialized views are database objects that contain the results of a query. The FROM clause of
the query can name tables, views, and other materialized views. You can model, create, and edit
materialized views in a live database connection, and offline materialized views in an offline
database in JDeveloper. When importing materialized views from Oracle Database to a JDeveloper
project:
If a materialized view on the database specifies WITHOUT REDUCED PRECISION, when it is
imported into JDeveloper it will use reduced precision, and the Reduced Precision option on
the Properties page of the Edit Materialized View dialog is selected. If the materialized view
must not reduce precision, select No Reduced Precision in the dialog.
If a materialized view on the database specifies USING ROLLBACK SEGMENT and USING
TRUSTED CONSTRAINTS, when it is imported into JDeveloper no rollback segment is
selected on the Properties page of the Edit Materialized View dialog, and the constraint is
shown as Enforced. If necessary, change the options in the Edit Materialized View dialog

11. Derived from SQL Expression


This indicates that this attribute is derived from a SQL expression. When selected, you can enter
the column Type and an Expression.
You can base an attribute value on a SQL expression by selecting the Derived from SQL Expression
checkbox in the Entity Attribute page of the Attribute Editor or the Attribute Settings page of the
Create Entity Object Wizard. This opens a checkbox in which you can enter a SQL Expression that
will calculate the attribute’s value based on an initial SQL query.

12. Getting the DB connection from Weblogic datasource / JNDI


public static Connection getConnection(String dsName) throws
NamingException, SQLException {
Connection con = null;
DataSource datasource = null;
Context initialContext = new InitialContext();
if (initialContext == null) {
}
datasource = (DataSource)initialContext.lookup(dsName);
if (datasource != null) {
con = datasource.getConnection();
} else {
System.out.println("Failed to lookup datasource.");
}
return con;
}

12/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

13. Understanding How the SRDemo Application Sets Database State


The SRDemo application includes a simple example of setting a database state on a per-user basis.
It uses the following PL/SQL package to set and get a package-level variable that holds the name
of the currently authenticated web application user.
Example: SRDemo CONTEXT_PKG PL/SQL Package
create or replace package context_pkg as
procedure set_app_user_name(username varchar2);
function app_user_name return varchar2;
end context_pkg;
The WHERE clause of the ServiceHistories view object in the demo references
the context_pkg.app_user_name function to illustrate how your application queries might
reference the per-user state.
Note: In practice, you will typically create a database CONTEXT namespace, associate a
PL/SQL procedure with it, and then use the SYS_CONTEXT() SQL function to reference
values from the context. however, the simple PL/SQL package above was enough to
illustrate the mechanics involved in setting and referencing the user state without further
complicating the installation of the SRDemo application.
The SRApplicationModuleImpl framework extension class in
the FrameworkExtensions project includes a callStoredProcedure() helper method similar to
the ones in Section "Invoking Stored Procedure with Only IN Arguments".
The SRServiceImpl application module class extends this class and defines
the setCurrentUserInPLSQLPackage() helper method shown in Example 29-5 that uses
the callStoredProcedure() method to
invoke context_pkg.set_app_user_name() stored procedure, passing the value of the
currently authenticated user as a parameter value.
Example: Method to Call Context_Pkg.Set_App_User_Name Stored Procedure
// In SRServiceImpl.java
public void setCurrentUserInPLSQLPackage() {
String user = getUserPrincipalName();
callStoredProcedure("context_pkg.set_app_user_name(?)",new
Object[]{user});
}
With this helper method in place, the SRServiceImpl class then overrides
the prepareSession() method
Example: Overridden afterConnect() and prepareSession() to Set Database State
// In SRServiceImpl.java
protected void prepareSession(Session session) {
super.prepareSession(session);
getLoggedInUser().retrieveUserInfoForAuthenticatedUser();
setUserIdIntoUserDataHashtable();
setCurrentUserInPLSQLPackage();
}

13/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

4 Building Business Service with Default ADF Business Components


1. Interaction between EO and VO
The Entity Object
An EO represents a table in simple terms. It defines the tables attributes the data types,
validation on the data, the primary keys and what not the entire business logic that needs
to be defined for pushing data into the target table.
So the EO serves as the sink for data by validating it and finally storing it into the tables.
The View Object
The view object in simple terms is the data source. It provides data for interacting with it. A
VO can be based on EO's which in the case are similar to SQL queries used to extract data,
or it can be programmatically populated or it can be populated with a static list.
However, VO's based on EO's are mostly used. The view object is used to query data and
serve as the data source, The EO serves as the sink. While a few validations can be done
even on the VO level it’s better to have business logic on the EO's for reasons entitled below:
EO cache is the same for all VO's
When two VO's are based on an EO both of them share the same entity cache. At run time when
a VO executes a query, the resultant data is split into its respective entity object records and
stored in the entity cache. This helps multiple VO's to refer the same set of data thereby reducing
memory map and also multiple validation rules for all EO's. This is similar to normalization.
For example, let's say we have two EO's, a department EO and employee EO and their respective
VO's are department VO which queries department information and employee VO which joins
department and employee information together based on department ID.
At run time when the data is queried for an employee, record let’s say we queried
[empname,empid,deptid,deptname] (assuming employeename and empid and deptname
and deptid's are the only columns in respective tables).
Now ADF splits the employee vo record into its constituent records as [empname,empid] and
[deptname,deptid] and pushes each record into respective entity cache. This reduces memory
footprint because department VO need not bring more data into memory. Moreover id deptname
is updated then one instantly sees the same value in employee info.
Thus, having validation at EO level will help in providing a central point for all VO's dependent on
them. It's not just data that is shared across VO's there are many more which one comes to know
in future blogs

2. DB Objects vs ADFC BC
Database Table vs Entity Object (EO)
Database View vs View Object (VO)
Foreign Keys relationships vs Entity Associations
SQL Queries vs Application Module (AM) operations

14/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3. Association between Entity Objects

4. Multiple Choice Support in ADF BC View Criteria

Referenced Pool Size = 1. This means AM will support only 1 user, if there will be more users -
AM pooling will be working and AM instance will be shared between users.

15/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

5. Business Services
Functions vs Procedures: - Functions return a single variable by value whereas
procedures do not return any variable by value. Rather they return multiple variables by
passing variables by reference through their OUT parameter.
Procedures vs Trigger: - We have control over the firing of a stored procedure but we
have no control over the firing of a trigger.
A foreign key is the key i.e. Attribute which refers to another table primary key. A reference
key is a primary key to the table referred to by another table.
Math.round(((adf.currentDate - DOB)/365)*100)/100 is the Age find Groovy
Expression.
(new
oracle.jbo.server.SequenceImpl("HR.DEPT_SEQ",adf.object.getDBTr
ansaction())).getSequenceNumber()
adf.currentDate for Current date.
The FetchSize attribute defines the number of rows that will be sent to the client in one
round-trip.
By default, the access mode is set to Scrollable, which is okay as long as you are not iterating
through a large data set, but if you are then you should change the Access Mode to Range
Paging or Range Paging Incremental.
in Batches of the field – which represents the FetchSize (see source) and controls the
number of records fetched simultaneously from the database. (n+1) n is the no. of rows
that need to be displayed.
The iterator’ s RangeSize attribute defines the number of records ADFm requests from the
ADF BC layer simultaneously. Both RangeSize and FetchSize should be synchronized.
Override PostChanges method in EntityImpl to insert PK entity need to be inserted first
instead of the Foreign key reference column.

16/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

5 Persisting Data using Entity Object


1. Caching
A CPU cache is a cache used by the central processing unit (CPU) of a computer to reduce the
average time to access data from the main memory. The cache is a smaller,
faster memory which stores copies of the data from frequently used main memory locations.
Oracle ADF Business Components uses a sophisticated caching system to improve performance
and maintain consistent views of data. Understanding how the caching system works is important
for understanding how your business components will behave at runtime. Every view object
instance controls its own cache, called its view cache. This cache holds a collection of view rows.
When a view object retrieves data from the data source, it creates a view row to represent that
row of data and adds the instance to the view cache. Each view attribute of this view row is
populated, but how it's populated depends on whether or not the view attribute is mapped to an
entity attribute. EOs have their own record cache VOs can have their own cache, or share an EO
cache EO/VO caches via an Application Module are per user session

2. Alternate Key
If any table has more than one candidate key, then after choosing the primary key from those
candidate keys, the rest of the candidate keys are known as an alternate key of that table. Like
here we can take a very simple example to understand the concept of alternate key. Suppose we
have a table named Employee which has two columns EmpID and EmpMail, both have not null
attributes and unique value. So, both columns are treated as a candidate key. Now we make
EmpID as a primary key to that table then EmpMail is known as an alternate key.

3. Discriminator
Select this option if this is a discriminator column for a polymorphic entity object. A polymorphic
entity usage is one that references a base entity object in an inheritance hierarchy and is
configured to handle subtypes of that entity as well. The entity-based UserList view object has the
User entity object as its primary entity usage. The view object partitions each row retrieved from
the database into an entity row part of the appropriate entity object subtype of User. It creates
the appropriate entity row subtype based on consulting the value of the discriminator attribute.
For example, if the UserList query retrieves one row for user ngreenbe, one row for manager
sking, and one row for technician ahunold.

4. Attribute Settings:
Change the following entity object settings for attributes that you select from a drop-down list:
Name: It is a valid Java identifier.
Type: It is a Java data type.
Property Set: Select a named property set to apply to this attribute. A property set is a
version of an existing domain that is XML-only (no Java) and does not enforce a data type.
Value Type: It indicates whether the default value is a literal or an expression.
Value: This is the default value (optional). This value is not propagated from the default
value, if any, in the database table.
Persistent: Select this option if the attribute is persistent; deselect for transient attributes.
Mandatory: This is selected by default for columns with NOT NULLconstraints.
Change Indicator: Select this option if the column is a change indicator, such as a
timestamp, to be used to indicate that a row has been changed by another transaction. (If
no columns are specified as change indicators, ADF BC does a column-by-column
comparison.)

17/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Derived from SQL Expression: This indicates that this attribute is derived from a SQL
expression. When selected, you can enter the column Type and an Expression.
Discriminator: Select this option if this is a discriminator column for a polymorphic entity
object.
Primary Key: This is selected by default for columns with PRIMARY KEYconstraints.
Unique: Specify that the corresponding table column is to be generated with a UNIQUE
constraint.
Queryable: Specify that this attribute can occur in the WHEREclause of a view object
(selected by default except for LOBs).
Effective Date: The attribute is either the start or end date of a date range for which the
entity row is effective (used for a point of time snapshot to answer such questions as what
an employee’s salary was on January 30, 2004.)
History Column: Select to use this column to log changes to the database. You can log
changes only if you have implemented Java Authentication and Authorization Service (JAAS)
authentication, the selected attribute is persistent, you have not selected Primary Key,
Mandatory, or Discriminator, and the attribute is Char, Character, String, Date, Timestamp,
or Number. After you have selected History Column, you can select the history column type
(created on or modified on for a Dateor Timestamp attribute, created by or modified by for
a Char, Character, or Stringattribute, or version number for a Numberattribute).
Updatable: You can enable the attribute to always or never be updatable, or enable it to
be updated only before the entity is first posted (while new).
Refresh After: Specify whether to retrieve the value from the database after an update or
insert.
Database Column: This indicates the name and SQL data type of the column to which the
attribute is mapped.

18/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

6 Querying Data using View Object


1. Attribute Settings
Name: It is a valid Java identifier.
Type: It is a Java data type.
Property Set: Select a named property set to apply to this attribute. A property set is a
version of an existing domain that is XML-only (no Java) and does not enforce a data type.
Value Type: It indicates whether the default value is a literal or an expression.
Value: It is the default value (optional).
Mapped to Column or SQL: If selected, this attribute is mapped to a column or SQL
statement. If deselected, this attribute is not yet mapped to a table. However, you can select
the check box and provide the data in the Query Column group below.
Selected in Query: When selected for a transient attribute, this attribute appears in the
view object’s SELECTstatement. SQL-derived attributes always appear in the view object’s
SELECTstatement.
Discriminator: Select this option if this is a discriminator column for a polymorphic view
object.
Key Attribute: When selected, this attribute forms part of the view object’s key. Entity
attributes defined as primary keys will automatically be selected as a Key Attribute when
view objects based on the entity are created. You may need to modify this property to view
objects based on more than one entity object, where multiple primary keys are defined.
Queryable: It is selected if this attribute can occur in a view object’s WHEREclause. It is
selected by default except for LOBs. This option cannot be selected for LOBs.
Effective Date: It is available only for view attributes that are based on entity attributes
for which the effective date is defined. The attribute is either the start or end date of a date
range for which the view row is effective (used for a point of time snapshot to answer such
questions as what an employee’s salary was on January 30, 2004.)
Updatable: You can enable the attribute to always or never be updatable, or enable it to
be updated only before the underlying entity is first posted (while new).
Query Column:
Alias: Aliases are optional, but can be useful in SQL-derived attributes to prevent naming
conflicts.
Type: This defines the SQL data type of the query column.
Expression: An expression is required for a SQL-derived attribute.

19/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

7 Exposing Business Service through the Application Module


1. Difference between Optimistic and Pessimistic Lock
ADF BC (Application module) manages the state of data. It has two locking mechanisms -Optimistic
Lock and Pessimistic Lock. Locking is Database specific feature that prevents users from different
transactions to modify the same data concurrently.
In ADF, we will specify the locking mode either as optimistic/Pessimistic in adf-config.xml file.
We can the locking mode in Application Module -> Configuration -> AppModuleLocal/Shared ->
Properties tab. For the property jbo.locking.mode, it will show either optimistic /pessimistic.
It will take the value overridden in adf-config.xml file. It has the same concept as the
database. The database also has the same two locking mechanisms. Now understand each other.
Pessimistic Locking is when you lock the record for your exclusive use until you have
finished with it. It has much better integrity than optimistic locking but requires you to be
careful with your application design to avoid Deadlocks. To use pessimistic locking you need
either a direct connection to the database (as would typically be the case in a two-tier client-
server application) or an externally available transaction ID that can be used independently
of the connection. Example- user A (travel agent) tries to book the last flight ticket to
London. He started the transaction but before clicking book the ticket, he got a phone call
and talking. He got a lock of that data. User B (Another travel agent) tries to book the same
ticket and wanted to make a lock to that row and he will get
oracle.jbo.AlreadyLockedException. So it’s a situation of deadlock. The
disadvantage of pessimistic locking is that a resource is locked from the time it is first
accessed in a transaction until the transaction is finished, making it inaccessible to other
transactions during that time.
Optimistic Locking is a strategy where you read a record, take note of a version number
(other methods to do this involve dates, timestamps or checksums/hashes) and check that
the version hasn’t changed before you write the record back. When you write the record
back you filter the update on the version to make sure it’s atomic. (i.e. hasn’t been updated
between when you check the version and write the record to the disk) and update the version
in one hit. If the record is dirty (i.e. different versions to yours) you abort the transaction
and the user can re-start it. This strategy is most applicable to high-volume systems and
three-tier architectures where you do not necessarily maintain a connection to the database
for your session. In this situation, the client cannot maintain database locks as the
connections are taken from a pool and you may not be using the same connection from one
access to the next. Example- user A (travel agent) tries to book the last flight ticket to
London. He started the transaction but before clicking book the ticket, he got a phone call
and talking. Here it will not try to acquire the lock. User B (Another travel agent) tries to
book the same ticket and he clicks commit. Ticket booked. Changes will happen in the
Database. But now user A will try to book the ticket, he will
get oracle.jbo.RowInconsistentException.

2. Application module
Application Module Pool Behavior Configuration Parameters
Pool Configuration Parameter Description
Failover Transaction State Upon Managed Release Enables eager passivation of pending
(jbo.dofailover) transaction state each time an application
module is released to the pool in the
"Managed State" mode.

20/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Pool Configuration Parameter Description


This feature is disabled by default (false)
Disconnect Application Module Upon Release Forces the application module pool to release
(jbo.doconnectionpooling) the JDBC connection used each time the
application module is released to the pool.
This feature is disabled by default (false).
Support Dynamic JDBC Credentials Enables additional pooling lifecycle events to
(jbo.ampool.dynamicjdbccredentials) allow developer-written code to change the
database credentials (username/password)
each time a new user session begins to use
the application module.
This feature is enabled by default (true),
however, this setting is a necessary but not
sufficient condition to implement the feature.
The complete implementation requires
additional developer-written code.
Reset Non-Transactional State Upon Unmanaged Forces the application module to reset any
Release non-transactional state like view object
(jbo.ampool.resetnontransactionalstate) runtime settings, JDBC prepared statements,
bind variable values, etc. when the
application module is released to the pool in
unmanaged or "stateless" mode.
This feature is enabled by default (true).
Disabling this feature can improve
performance, however, since it does not
clear bind variable values, your application
needs to ensure that it systemically sets bind
variable values correctly. Failure to do so
with this feature disabled can mean one user
might see data with another users bind
variable values.)
Enable Application Module Pooling Enables the application module pooling
(jbo.ampool.timetolive) facility.
This feature is enabled by default (true)

3. Pool Sizing Parameters


Application Module Pool Sizing Configuration Parameters
Pool Configuration Parameter Description
Initial Pool Size The number of application module instances created
(jbo.ampool.initpoolsize) when the pool is initialized.
The default is 0 (zero) instances.
Maximum Pool Size The maximum number of application module instances
(jbo.ampool.maxpoolsize) that the pool can allocate.

21/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Pool Configuration Parameter Description


The pool will never create more application module
instances than this limit imposes. The default
is 5000 instances.
Referenced Pool Size The maximum number of application module instances
(jbo.recyclethreshold) in the pool that attempt to preserve session affinity for
the next request made by the session which used them
last before releasing them to the pool in managed-state
mode.
The referenced pool size should always be less than or
equal to the maximum pool size. The default is to
allow 10 available instances to try and remain "loyal" to
the affinity they have with the most recent session that
released them in managed state mode.
Maximum Instance Time to Live The number of milliseconds after which to consider an
(jbo.ampool.timetolive) application module instance in the pool as a candidate
for removal during the next resource cleanup regardless
of whether it would bring the number of instances in the
pool below minavailablesize.
The default is 3600000 milliseconds of total time to live
(which is 3600 seconds, or one hour)

4. Pool Cleanup Parameters


A single "application module pool monitor" per Java VM runs in a background thread and wakes
up every so often to do resource reclamation. Table below lists the parameters that affect how
resources are reclaimed when the pool monitor does one of its resource cleanup passes.
Note:
Since there is only a single application monitor pool monitor per Java VM, the value that will
effectively be used for the application module pool monitor polling interval will be the value
found in the application module configuration read by the first application module pool that
gets created. To make sure this value is set predictably, it is best practice to set all
application modules to use the same Pool Polling Interval value.

5. Application Module Resource Management Configuration Parameters


Pool Configuration Parameter Description
Pool Polling Interval The length of time in milliseconds between pool
(jbo.ampool.monitorsleepinterval) resource cleanup.
While the number of application module instances
in the pool will never exceed the maximum pool size,
available instances which are candidates for getting
removed from the pool do not get "cleaned up" until
the next time the application module pool monitor
wakes up to do its job. The default is to have the
application module pool monitor wake up

22/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Pool Configuration Parameter Description


every 600000 milliseconds (which is 600 seconds,
or ten minutes).
Maximum Available Size The ideal maximum number of application module
(jbo.ampool.maxavailablesize) instances in the pool when not under abnormal load.
When the pool monitor wakes up to do resource
cleanup, it will try to remove available application
module instances to bring the total number of
available instances down to this ideal maximum.
Instances that have been not been used for a period
longer than the idle instance time-out will always get
cleaned up at this time, then additionally available
instances will be removed if necessary to bring the
number of available instances down to this size. The
default maximum available size is 25 instances.
Minimum Available Size The minimum number of available application
(jbo.ampool.minavailablesize) module instances that the pool monitor should leave
in the pool during a resource cleanup operation. Set
to zero (0) if you want the pool to shrink to contain
no instances when all instances have been idle for
longer than the idle time-out.
The default is 5 instances.
Idle Instance Timeout The number of milliseconds after which to consider
(jbo.ampool.maxinactiveage) an inactive application module instance in the pool
as a candidate for removal during the next resource
cleanup.
The default is 600000 milliseconds of idle time
(which is 600 seconds, or ten minutes).
Maximum Instance Time to Live The number of milliseconds after which to consider
(jbo.pooltimetolive) a connection instance in the pool as a candidate for
removal during the next resource cleanup
regardless of whether it would bring the number of
instances in the pool below minavailablesize.
The default is 3600000 milliseconds of total time to
live (which is 3600 seconds, or one hour)

6. Database Connection Pool Parameters


If you are using a JDBC URL for your connection information so that the ADF database connection
pool is used, then configuration parameters listed in the Table below can be used to tune the
behavior of the database connection pool. A single "database connection pool monitor" per Java
VM runs in a background thread and wakes up every so often to do resource reclamation. The
parameters in Table below include the ones that affect how resources are reclaimed when the
pool monitor does one of its resource cleanup passes.

Note:
23/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

The configuration parameters for database connection pooling have MetaObjectManager


scope. This means their settings are global and will be set once when the first application
module pool in your application is created. To ensure the most predictable behavior, Oracle
recommends leaving the values of these parameters in the Connection Pooling section
of the Pooling and Scalability tab at their default values — so that no entry for them is
written into the bc4j.xcfg file — and to instead set the desired values for the database
connection pooling tuning parameters as Java System Parameters in your J2EE container.

7. Database Connection Pool Parameters


Pool Configuration Parameter Description
Initial Pool Size The number of JDBC connection instances created
(jbo.initpoolsize) when the pool is initialized
The default is an initial size of 0 instances.
Maximum Pool Size The maximum number of JDBC connection instances
(jbo.maxpoolsize) that the pool can allocate.
The pool will never create more JDBC connections
than this imposes. The default is 5000 instances.
Pool Polling Interval The length of time in milliseconds between pool
(jbo.poolmonitorsleepinterval) resource cleanup.
While the number of JDBC connection instances in
the pool will never exceed the maximum pool size,
available instances which are candidates for getting
removed from the pool do not get "cleaned up" until
the next time the JDBC connection pool monitor
wakes up to do its job. The default
is 600000 milliseconds of idle time (which is 600
seconds, or ten minutes).
Maximum Available Size The ideal maximum number of JDBC connection
(jbo.poolmaxavailablesize) instances in the pool when not under abnormal load.
When the pool monitor wakes up to do resource
cleanup, it will try to remove available JDBC
connection instances to bring the total number of
available instances down to this ideal maximum.
Instances that have been not been used for a period
longer than the idle instance time-out will always get
cleaned up at this time, then additionally available
instances will be removed if necessary, to bring the
number of available instances down to this size. The
default is an ideal maximum of 25 instances (when
not under load).
Minimum Available Size The minimum number of available JDBC connection
(jbo.poolminavailablesize) instances that the pool monitor should leave in the
pool during a resource cleanup operation. Set to zero
(0) if you want the pool to shrink to contain no
instances when all instances have been idle for
longer than the idle time-out.
24/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Pool Configuration Parameter Description


The default is to not let the minimum available size
drop below 5 instances.
Idle Instance Timeout The number of seconds after which to consider an
(jbo.poolmaxinactiveage) inactive JDBC connection instance in the pool as a
candidate for removal during the next resource
cleanup.
The default is 600000 milliseconds of idle time
(which is 600 seconds, or ten minutes).
Notice that since the database connection pool does not implement the heuristic of session affinity,
there is no configuration parameter for the database connection pool which controls the
referenced pool size.
You should take care not to configure the jbo.ampool.monitorsleepinterval (for the
application module pools) or the jbo.poolmonitorsleepinterval (for the DB pools) to be
too short of a time period because the chance exists — with a large number of application module
pools to cleanup — that your next pool monitor "wakeup" might occur while your previous cleanup-
cycle is still going on. The default of 10 minutes (600000 milliseconds) is reasonable. Setting it to
something like 10 seconds (10000 milliseconds) might cause trouble.

8. How Database and Application Module Pools Cooperate


How ADF application module pools use the database connection pool depends on the setting of
the jbo.doconnectionpooling application module configuration parameter. In
the Configuration Manager panel that you see in Table above, you set this parameter using
the checkbox labelled Disconnect Application Module Upon Release.
Note:
The notion of disconnecting the application module upon release to the pool better captures
what the actual feature is doing than the related configuration parameter name
(jbo.doconnectionpooling) does. The setting
ofjbo.doconnectionpooling=false does not mean that there is no database
connection pooling happening. What it means is that the application module is not
disconnected from its JDBC connection upon check in back to the application module pool.
If the default setting of jbo.doconnectionpooling=false is used, then when an application
module instance is created in any pool it acquires a JDBC connection from the appropriate
connection pool (based on the JDBC URL in the ADF case, or from the underlying JDBC data source
implementation's pool in the case of a JNDI data source name). That application module instance
holds onto the JDBC connection object that it acquired from the pool until the application module
instance is removed from the application module pool. During its lifetime, that application module
instance may service many different users, and ADF worries about issuing rollbacks on the
database connection so that different users don't end up getting a pending database state
confused. By holding onto the JDBC connection, it allows each application module instance to keep
it's JDBC PreparedStatements's open and usable across subsequent accesses by clients,
thereby providing the best performance.
If jbo.doconnectionpooling=true, then each time a user session finishes using an
application module (typically at the end of each HTTP request), the application module instance
disassociates itself with the JDBC connection it was using on that request and it returns it to the
JDBC connection pool.

25/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
The next time that application module instance is used by a user session, it will reacquire a JDBC
connection from the JDBC connection pool and use it for the span of time that application module
is checked out of the application module pool (again, typically the span of one HTTP request).
Since the application module instance "unplugs" itself from the JDBC connection object used to
create the PreparedStatements it might have used during the servicing of the current HTTP
request, those PreparedStatements are no longer usable on the next HTTP request because
they are only valid in the context of the Connection object in which they were created.
So, when using the connection pooling mode turned on like this, the trade-off is slightly more
JDBC overhead setup each time, in return for using a smaller number of overall database
connections.
The key difference is seen when many application module pools are all using the same underlying
database user for their application connection.
If 50 different application module pools each have even just a single application module
instance in them, with jbo.doconnectionpooling=false there will be 50 JDBC
application connections in use. If the application module pooling parameters are set such
that the application module pools are allowed to shrink to 0instances after an appropriate
instance idle timeout by setting jbo.ampool.minavailablesize=0, then when the
application module is removed from its pool, it will put back the connection it is holding onto.
In contrast, if 50 different application module pools each have a single application module
instance and jbo.doconnectionpooling=true, then the amount of JDBC connections
in use will depend on how many of those application modules are simultaneously being used
by different clients. If an application module instance is in the pool and is not currently being
used by a user session, then with jbo.doconnectionpooling=true it will have released
its JDBC connection back to the connection pool and while the application module instance
is sitting there waiting for either another user to need it again, or to eventually be cleaned
up by the application module pool monitor, it will not be "hanging on" to a JDBC connection.
For the highest performance, Oracle recommends not disconnecting the application module
instance from its database connection on each check in to the application module pool.
Accordingly, the default setting of the jbo.doconnectionpooling configuration
parameter is false.
The pooling of application module instances is already an effective way to optimize resource
usage, and there are runtime efficiencies that Oracle ADF can gain if you do not have to
disconnect application module instances from their associated JDBC connection after each
release to the pool. Effectively, by pooling the application modules which are related one-
to-one with a JDBC connection, you are already achieving a pooling of database connections
that is optimal for most web applications.
In contrast to Oracle's default recommendation, one situation in which it might be opportune
to use database connection pooling is when you have a large number of application module
pools all needing to use database connections from the same underlying application user at
the database level. In this case, the many application module pools can perhaps economize
on the total overall database sessions by sharing a single, underlying database connection
pool of JDBC connections, albeit at a loss of efficiency of each one. This choice would be
favored only if total overall database sessions are of maximum priority.

9. Database User State and Pooling Considerations


Sometimes you may need to invoke stored procedures to initialize database state related to the
current user's session. The correct place to perform this initialization is in an
overridden prepareSession() method of your application module.

26/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

10. How Often prepareSession() Fires When jbo.doconnectionpooling =


false
The default setting for jbo.doconnectionpooling is false. This means the application module
instance hangs onto its JDBC connection while it's in the application module pool. This is the most
efficient setting because the application module can keep its JDBC prepared statements to open
across application module checkouts/checkins. The application module instance will trigger
its prepareSession() method each time a new user session begins using it.

11. Setting Database User State When jbo.doconnectionpooling = true


If you set jbo.doconnectionpooling to true, then on each checkout of an application module
from the pool, that application module pool will acquire a JDBC connection from the database
connection pool and use it during the span of the current request. At the end of the request when
the application module is released back to the application module pool, that application module
pool releases the JDBC connection it was using back to the database connection pool.
It follows that with jbo.doconnectionpooling set to true the application module instance in
the pool may have a completely different JDBC connection each time you check it out of the pool.
In this situation, the prepareSession() method will fire each time the application module is
checked out of the pool to give you a chance to reinitialize the database state.

27/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

8 Declaratively Customizing Business Services


1. To configure the declarative runtime behavior of an entity object:
1. In the Application Navigator, double-click an entity object.
2. In the overview editor, click the General navigation tab to view the name and package of
the entity object, and configure aspects of the object at the entity level, such as its associated
schema, alternative keys, custom properties, and security.
a. The Alternate Keys section allows you to select entity object attributes mapped to the
database that can serve as an alternative primary key.
b. The Tuning section allows you to set options to make database operations more
efficient when you create, modify, or delete multiple entities of the same type in a
single transaction.
c. The Custom Properties section allows you to define custom metadata that you can
access at runtime on the entity.
d. The Security section allows you to define role-based updatability permissions for the
entity.
e. The Business Logic Groups section allows you to add and edit business logic groups.
3. Click the Attributes navigation tab to create or delete attributes that represent the data
relevant to an entity object, and configure aspects of the attribute, such as validation rules,
custom properties, and security. Select an attribute and click the Edit icon to access the
properties of the attribute.
4. Click the Business Rules navigation tab to define declarative validators for the entity object
and its attributes.
5. Click the Java navigation tab to select the classes you generate for custom Java
implementation. You can use the Java classes for such things as defining programmatic
business rules."
6. Click the Business Events navigation tab to define events that your entity object can use to
notify others of interesting changes in its state, optionally including some or all of the entity
object's attributes in the delivered event.
7. Click the View Accessors navigation tab to create and manage view accessors.

28/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

9 Validating Business Services


Types of validation
Validation rules are applied to an entity to make sure that only valid values are committed to the
database and to prevent any invalid data from getting saved to the database. In ADF, we use
validation rules for the entity object to make sure the row is valid all the time.
There are three types of validation rules that can be set for the entity objects; they are as follows:
1. Entity-level validation
2. Attribute-level validation
3. Transaction-level validation

Entity-level validation
 As we know, an entity represents a row in the database table. Entity-level validation is
the business rule that is added to the database row. For example, the validation rule
that has to be applied to a row is termed as entity-level validation.
 There are two unique declarative validators that will be available only for entity-level
validation—Collection and UniqueKey. The following diagram explains that entity-level
validations are applied on a single row in the EMP table. The validated row is
highlighted in bold.

Attribute-level validation
 Attribute-level validations are applied to attributes. Business logic mostly involves
specific validations to compare different attribute values or to restrict the attributes to
a specific range. These kinds of validations are done in attribute-level validation. Some
of the declarative validators available in ADF are Compare, Length, and Range.
 The following diagram explains that the validation is happening on the attributes in the
second row:

29/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

 There can be any number of validations defined on a single attribute or on multiple


attributes in an entity. In the diagram, Empno has a validation that is different from
the validation defined for Ename. Validation for the Job attribute is different from that
for the Sal attribute. Similarly, we can define validations for attributes in the entity
object.
Transaction-level validation
 Transaction-level validations are done after all entity-level validations are completed.
If you want to add any kind of validation at the end of the process, you can defer the
validation to the transaction level to ensure that the validation is performed only once.

30/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

10 Introducing User Interface Technologies


1. FacesContext:
FacesContext contains all of the per-request state information related to the processing
of a single Java Server Faces request and the rendering of the corresponding response. It is
passed to and potentially modified by, each phase of the request processing lifecycle.
A FacesContext instance is associated with a particular request at the beginning of request
processing, by a call to the getFacesContext() method of the FacesContextFactory
instance associated with the current web application. The instance remains active until its
release() method is called, after which no further references to this instance are allowed.
While a FacesContext instance is active, it must not be referenced from any thread other
than the one upon which the servlet container executing this web application utilizes for the
processing of this request. Class facescontext:
javax.faces.context.FacesContext

2. FacesServlet:
FacesServlet is a servlet that manages the request processing lifecycle for web applications
that are utilizing Java Server Faces to construct the user interface.
Class facesservlet: javax.faces.webapp.FacesServlet

3. View Port
A viewport is a display area that is capable of navigating independently of other viewports. A
browser window and a region are both examples of viewports. The root viewport displays the
main page in a browser window. The root viewport may have child viewports, for example, regions
on the page, but does not have a parent viewport

4. Request Context
Context holder for the request-specific state, like current web application context, current locale,
current theme, and potential binding errors. It provides easy access to localized messages and
Error instances.
Suitable for exposition to views, and usage within JSP's "useBean" tag, JSP scriptlets, JSTL EL,
Velocity templates, etc. Necessary for views that do not have access to the servlet request, like
Velocity templates. It can be instantiated manually, or automatically exposed to views as model
attribute via AbstractView's "requestContextAttribute" property.

5. Data Control Frame (DCF)


DCF is the container associated with a task flow that contains data control instances. To specify
whether data control instances are shared between the calling and called task flows, you must
set a data-control-scope value of either shared or isolated on the called bounded task flow.

6. View Layer
FacesConfig.xml contains navigations and resource bundle configuration information as follows.

resourcebundle.txt

7. To access resource bundle in bean


31/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
java.util.ResourceBundle rb =
ResourceBundle.getBundle("com/oracle/,,,,/Bundle1");
String txt = rb.getString("prop1");

8. Struts Vs ADF
Similarities:
Both of them use MVC (Model-View-Controller) architecture.
Struts have config file struts-config.xml, ADF has the config file adfc-config.xml.
Both have their own framework classes and API.
Differences:
Struts don’t have any support for declarative development.
Struts don’t have its own components to use in development whereas ADF comes with its
own Oracle ADF faces components.
Struts don't have any default persistence mechanism (i.e., default ORM) whereas ADF has a
default persistence mechanism if we use ADF BC.

9. JSF Vs ADF
BC components are not available with JSF.
Entire business logic in java code whereas in ADF declarative with minimal code.
Though you can use JSF declaratively, you need to bind the JSF components manually with
bean properties.
The Java code we write in the ADF application mainly uses the Framework's API. ADF mainly
uses ADF faces components in the development. So, we can also use other components like
JSF Core, JSF HTML and Trinidad components in ADF web application.
The main advantage of ADF is that we can blend any technology with it. For example, you
don't need to have ADF business components in your model; you can have plain java code
or EJBs as well.

32/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

11 Getting Started with Rich User Interface


1. Scalable Vector Graphics (SVG)
It is an XML-based vector image format for two-dimensional graphics with support for interactivity
and animation. The SVG specification is an open standard developed by the World Wide Web
Consortium (W3C) since 1999.

2. Stretchable components
<af:decorativeBox>
<af:panelAccordion>
<af:panelBox>
<af:panelCollection>
<af:panelGroupLayout layout="scroll">
<af:panelGroupLayout layout="vertical">
<af:panelHeader>
<af:panelSplitter>
<af:panelStretchLayout>
<af:panelTabbed>
<af:region>
<af:table>
<af:tree>
<af:treeTable>

3. Not Stretchable components


<af:panelBorderLayout>
<af:panelFormLayout>
<af:panelGroupLayout layout="default">
<af:panelGroupLayout layout="horizontal">
<af:panelLabelAndMessage>
<af:panelList>
<trh:tableLayout>

33/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

12 Planning Pages using Layout Components


1. Layout Components
Stretched by Stretch
Component Description
Parent Children
af:panelFormLayout Arranges items in columns or No No
grids.
af:panelBorderLayout Places items in fixed, peripheral No No
areas around a central area.
af:panelStretchLayout Enables automatic component Yes (when Yes
stretching in your pages. This dimensionsFrom
contains top, bottom, start, = parent)
center, and end facets to hold
child components.
af:panelSplitter Enables automatic component Yes (when Yes
stretching in your pages. This dimensionsFrom
divides a region into two parts = parent)
(the first facet and the second
facet) where you can place
contents.
af:panelDashBoard Arranges child components Yes (when Yes
column-wise. dimensionsFrom
= parent)
af:panelAccordion Creates collapsible panes. Yes (when No
dimensionsFrom
= parent)
af:panelTabbed Creates stacked tabs. Yes (when No
dimensionsFrom
= parent)
af:decorativeBox Provides a decorative box for the Yes (when Yes
child components. dimensionsFrom
= parent)
af:panelBox Provides a titled box which can Yes Yes (when
contain child components. type =
stretch)
af:showDetail Hides and displays groups of No No
content through the toggle icon.
af:panelGroupLayout Enables automatic scroll bars in Yes (when Yes (when
your pages, and arranges items layout = layout =
horizontally or vertically. scroll or scroll or
vertical) vertical)
af:panelCollection Adds menus, toolbars, and status Yes Yes
bars to data aggregation

34/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

components such as tables, trees,


and tree tables.
af:panelHeader Creates titled sections and Yes (when type Yes (when
subsections. = stretch) type =
stretch)
af:panelList Creates styled lists and content No No
boxes.
af:panelGridLayout Arranges components in columns Yes (when Yes (When
or grids using af:gridRow and dimensionsFrom af:gridCe
af:gridCell. = parent) ll is
configured
for it)
af:spacer Adds a blank space between No Not a
components. container
af:separator Adds divider line between No Not a
components. container

35/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

13 Designing User Interfaces and Page Flows


1. Important Types of Outcome
Parent Outcome: enter a literal value or write an EL expression that returns an outcome
so that the parent action activity navigates to the parent view activity. The outcome is then
used to navigate the parent view activity's task flow rather than navigating the ADF region's
bounded task flow. The parent view activity's task flow should contain a control flow case or
wildcard control flow rule that accepts the value you specify for parent-outcome.
Root Outcome: enter a literal value or write an EL expression that returns an outcome so
that the parent action activity navigates to the root page of the application.
Note: Parent Outcome and Root Outcome are mutually exclusive.
(Optional) In the Outcome field, enter a literal value that specifies an outcome for control
flow within the ADF region after the parent action activity adds parent-outcome or root-
outcome to the appropriate queue. Specifying an outcome element is useful in cases where
the parent view activity or root page does not navigate as a result of the parent-
outcome or root-outcome sent by the parent action activity. Also, the ADF region should not
continue to display the same view. If you do not specify a value for an outcome, the ADF
region's viewId remains unchanged.

2. Controller Layer
“Parent Action” and “Task flow return” activities are not available on any unbounded task flow.
Parent Outcome of “Parent Action” navigates to the associated flow (acts as control flow case).

36/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

14 Interactively Controlling with Navigation Components


1. Static Navigation
At that time, the web application analyzes the user input and must decide which JSF page to use
for rendering the response. The navigation handler is responsible for selecting the next JSF page.
You simply give each button an action attribute, for example
<h:commandButton label="Login" action="login"/>
The action must match an outcome in a navigation rule:
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</navigation-rule>
This rule simply states that the login action navigates to /welcome.jsp if it occurred inside
/index.jsp.

2. Dynamic Navigation
In most web applications, navigation is not static. The page flow doesn't just depend on which
button you click, but also on the inputs that you provide. For example, submitting a login page
may have two outcomes: success or failure. The outcome depends on a computation, namely,
whether the username and password are legitimate. To implement dynamic navigation, the submit
button must have a method reference, such as
<h:commandButton label="Login"
action="#{loginController.verifyUser}"/>
In our example, loginController references a bean of some class, and that class must have
a method named verifyUser, that which should look somewhat like this:
String verifyUser() {
if (...)
return "success";
else
return "failure";
}

3. Advanced Navigation Issues (Redirection)


If you add a redirect element after to-view-id, then the JSP container terminates the current
request and sends an HTTP redirect to the client. The redirect response tells the client which URL
to use for the next page. Redirecting the page is slower than forwarding because another round
trip to the browser is involved. However, the redirection gives the browser a chance to update its
address field.

37/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

4. Wildcards
You can use wildcards in the from-view-id element of a navigation rule, for example.
<navigation-rule>
<from-view-id>/secure/*</from-view-id>
<navigation-case>
. . .
</navigation-case>
</navigation-rule>
This rule applies to all pages that start with the prefix /secure/. Only a single * is allowed, and it
must be at the end of the ID string. If there are multiple matching wildcard rules, the longest
match is taken.
Instead of leaving out a from-view-id element, you can also use one of the following to
specify a rule that applies to all pages.

38/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

15 Ensuring Reusability in Web Applications


1. How to develop reusable task flow in ADF?
Please find the step below
Define taskflow
Define the deployment profile as ADF Library jar
Deploy adf jar file
Open a new project where you want to consume the task flow.
Add the newly created jar of taskflow project
go to component palate You can find your jar name select it.
It will show a list of taskflow you developed
Drag-drop your taskflow as a region on jsff/jspx page and run ur application

2. How to Package a Custom Task Flow in an ADF Library?


To package a custom task flow in an ADF library:
1. Create a deployment profile for the task flow:
a. Right-click ViewController and choose New.
b. In the New Gallery, expand General, select Deployment Profile, and then ADF Library
JAR File, and click OK.
c. In the Create Deployment Profile -- ADF Library JAR File dialog, enter a name for your
deployment profile and click OK.
d. In the ADF Library JAR Deployment Profile Properties dialog, click OK.
e. In the Project Properties dialog, click OK.
2. In the Application Navigator, right-click the project folder, choose Deploy, deployment profile
name, and then choose to ADF Library JAR file.
3. This creates a deploy folder including the JAR file, in the project folder located
at <Application_Root>\ViewController\deploy\.

3. Resource Catalog
Application servers - developed before the ubiquity of web-based applications -
expose back-end business logic through various protocols, sometimes including HTTP, and
manage security, transaction processing, resource pooling, and messaging.
Database is an organized collection of data. The data is typically organized to model
aspects of reality in a way that supports processes requiring information.
File system is the underlying structure a computer uses to organize data on a hard disk. If
you are installing a new hard disk, you need to partition and format it using a file
system before you can begin storing data or programs.
Universal Description, Discovery and Integration (UDDI, pronounced /ˈjʊdiː/) is a
platform-independent, Extensible Markup Language (XML)-based registry by which
businesses worldwide can list themselves on the Internet, and a mechanism to register and
locate web service applications.
URL Adapter is a turn-key ready "out of the box" URL Builder and URLRewriting Engine.
It's fast, reliable, has an amazingly simple and modern administration console and is powered
by our fanatical support scheme.
WebDAV (World Wide Web Distributed Authoring and Versioning) is the Internet
Engineering Task Force (IETF) standard for collaborative authoring on the Web: a set of
extensions to the Hypertext Transfer Protocol (HTTP) that facilitates collaborative editing
and file management between users located remotely from each.

39/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
BAM is an event-driven reporting tool that generates alerts and reports in real time, based
on a continuously changing data stream, some of whose data may not be in the database.
Oracle BI Presentation Server is a layer between Oracle BI Analytics Server and a Web server.
Presentation Server maintains a web catalog that has information for different users. It helps
Web catalog administrator to grant permissions for all users and perform other
configurations.
Oracle BPEL Process Manager is a BPEL engine that is a member of the Oracle Fusion
Middleware family of products. It enables enterprises to orchestrate disparate applications
and Web services into business processes. The Virtual Content Repository allows content
contributors to access repositories using the content tools in the WebLogic Portal
Administration Console. The Virtual Content Repository also connects your repositories to
your portal application so that developers can deliver repository content to your portal users.
Web Services Description Language (WSDL pronounced "wiz'-dul") is an XML-based
interface definition language that is used for describing the functionality offered by a web
service.
Memory Scope is a simple application to free up the unused ram of your computer and
make it always fast and reactive.

4. How to Enable the Display of Task Flows in the Resource Catalog?


To enable the display of task flows in the Resource Catalog:
1. Open the default-catalog.xml file in
2. the <Application_Root>\mds\oracle\adf\rc\metadata directory.
3. Add a <resource> element to your catalog definition similar to the following example:
4. <resource id="doclibMainView"
5. name="Document Library Task Flow"
6. description="Main view of the Document Library Service"
7. repository="application.classpath"
8. path="doclib-service-
view.jar/ADF_TaskFlow/oracle+webcenter+doclib+view+jsf+taskflows+mainView.xml#doc
lib-document-library"/>
Note: Ensure that the task flow library is in the application classpath.
9. Set the path attribute for the task flow you want to include in the catalog.
10. The path must be specified in the following format:
jar_file_name/ADF_TaskFlow/task_flow_path
where
jar_file_name is the name of the task flow JAR file. This JAR is picked up from the
application classpath.
task_flow_path is the path to the task flow within the JAR file.
11. To obtain the task flow path for any task flow exposed in the Resource Palette, including
out-of-the-box service task flows, navigate to the task flow in your ADF Library and right-
click the task flow. From the context menu, select Show Catalog Reference.
12. A message dialog displays the values of the repository and path attributes for that task flow.
Save the default-catalog.xml file.
The task flows that you have defined in default-catalog.xml are now available in the Resource
Catalog.
Note: To enable users to view the task flow's content at runtime, ensure that the task flow you
add to the Resource Catalog has a TaskFlow Permission grant in the application's jazn-
data.xml file, with at least View action provisioned. Without this, the task flow appears blank when
added to the page.
40/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Delegate Security: - pages.xml
Navigation flow: - default-navigation.xml

41/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

16 Working with Scopes, Parameters and Partial Page Refresh


1. Scopes in Fusion Web Applications:
Scope indicates the lifetime of an object. In ADF and JSF it is possible to define backing beans
with a particular scope.
Types of Scopes:
There are seven types of scopes in a Fusion web application:
Scopes listed below in descending order with the first one having the longest lifetime and last one
lowest lifetime.
Application scope: An application scope object is available for the duration of the
application and is shared among users. This scope may be used to hold static objects that
are the same for all users.
Session scope: The object is available for the duration of the session, which is user
instance-specific. A use case for a session scope bean is a user info bean that stores
information about a user, which is read from the database or an LDAP server, to avoid
unnecessary queries.
Page flow scope (Task flow scope): A pageFlow scope exists for each task flow
instance and has a lifespan between request and session scope. The lifetime of the scope
spans across all pages in a bounded task flow.
Request scope: The object is available from the time an HTTP request is made until a
response is sent back to the client. From another perspective, a request scope starts with a
request to be issued from one view to another for navigation cases that don't perform a
redirect but a default server-side forward. The scope spans across all non-view activities that
follow the view of interest to the next view activity.
Backing bean scope: The backing bean scope is comparable to the request scope, with
the difference in that it exists for a specific client component. In general, all managed beans
used in reusable components should be configured to backingBean scope. For example,
bounded task flows that are designed to be regions on a page should use the backingBean
scope if more than one instance of the task flow is expected to be on a single page.
View scope (Page Scope): The object is available until the view ID for the current view
activity changes. This becomes handy when you use partial page rendering. If you have a
dependent list box, you might send a server request to refresh the list box. When a response
is returned, the request scope will be gone but the view scope will be still there. Therefore,
view scope can be used to store data when a partial rendering request comes back. The
view scope exists not only for views that are rendered by JSPX pages but also for views
rendered by page fragments, as is the case in task flows that are built to execute in a region.
The view scope of the parent page is not accessible from components added to a page
fragment in a region, and the view scope of a view in a region is not accessible for the parent
page.
None: When you create objects (such as a managed bean) that require you to define a
scope, you can set the scope to none, meaning that it will not live within any particular
scope, but will instead be instantiated each time it is referenced. You should set a bean's
scope to none when it is referenced by another bean.
Out of these View scope, Backing bean scope and page flow scope are ADF specific. Rest
comes with JSF. This is the reason you must define ADF specific scoped backing beans ether
in "adf-config.xml" or task flow. You access objects in those scopes via expression language
with scope qualification. For instance, to reference the aaBean managed bean from
viewScope scope, your expression would be #{viewScope .aaBean}. When working in

42/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
ADF, it's always recommended to define backing beans in ether "adf-config.xml" or task flow
files.

2. Programmatically setting/getting Pageflow Scope values in ADF:


AdfFacesContext.getCurrentInstance().getPageFlowScope().put("myKey","v
alue");
AdfFacesContext.getCurrentInstance().getPageFlowScope().get("myKey ");

43/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

17 Responding to Managed Beans, Events and Listeners


1. Controlling TaskFlow Programmatically:
public static DCTaskFlowBinding getTaskFlow(String taskFlowName) {
BindingContext bindingCtx = BindingContext.getCurrent();
DCBindingContainer dcbCon =
(DCBindingContainer)bindingCtx.getCurrentBindingsEntry();
DCTaskFlowBinding taskFlow =
(DCTaskFlowBinding)dcbCon.findExecutableBinding(taskFlowName);
return taskFlow;
}

2. Static list in ADF the other way (via Taskflow parameters):


Inside your adfc-config.xml or your page-flow.xml register this list as below
<managed-bean id="__3">
<managed-bean-name>StaticBean</managed-bean-name>
<managed-bean-class>java.util.HashMap</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<map-entries>
<map-entry>
<key>deepakbhagat</key>
<value>deepbag1@gmail.com</value>
</map-entry>
<map-entry>
<key>brightwave</key>
<value>info@brightwaveprojects.com</value>
</map-entry>
</map-entries>
</managed-bean>
and access the pair in EL as #{StaticBean['deepakbhagat']}

44/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3. The JSF and ADF Page Lifecycles


The figure shows how the JSF and ADF phases integrate into the lifecycle of a page request. For
more information about how the JSF lifecycle operates on its own, see the "Understanding the JSF
and ADF Faces Lifecycles" chapter of the Oracle Fusion Middleware Web User Interface
Developer's Guide for Oracle Application Development Framework.

4. Figure Lifecycle of a Page Request in a Fusion Web Application

In a JSF application that uses the ADF Model layer, the phases in the page lifecycle are as follows:
Restore View: The URL for the requested page is passed to the bindingContext object,
which finds the page definition file that matches the URL. The component tree of the
requested page is either newly built or restored. All the component tags, event handlers,
converters, and validators on the submitted page have access to
the FacesContext instance. If the component tree is empty, (that is, there is no data from
the submitted page), the page lifecycle proceeds directly to the Render Response phase. If
any discrepancies between the request state and the server-side state are detected, an error
will is thrown and the page lifecycle jumps to the Render Response phase.
JSF Restore View: Provides before and after phase events for the Restore View phase.
You can create a listener and register it with them before or after the event of this phase,
45/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
and the application will behave as if the listener were registered with the Restore View phase.
The Initialize Context phase of the ADF Model page lifecycle listens for the after(JSF
Restore View) event and then executes. The ADF Controller uses listeners for the before
and after events of this phase to synchronize the server-side state with the request. For
example, it is in this phase that browser back button detection and bookmark references are
handled. After the before and after listeners are executed, the page flow scope is available.
Initialize Context: The page definition file is used to create
the bindingContainer object, which is the runtime representation of the page definition
file for the requested page. The LifecycleContext class used to persist information
throughout the ADF page lifecycle phases is instantiated and initialized with values for the
associated request, binding container, and lifecycle.
Prepare Model: The ADF page lifecycle enters the Prepare Model phase by calling
the BindingContainer.refresh(PREPARE_MODEL) method. During the Prepare Model
phase, BindingContainer page parameters are prepared and then evaluated. If
parameters for a task flow exist, they are passed into the flow. Next, any executables that
have their refresh attribute set to prepareModel are refreshed based on the order of entry
in the page definition file's <executables> section and on the evaluation of
their RefreshCondition properties (if present). When an executable leads to an iterator
binding refresh, the corresponding data control will be executed, and that leads to the
execution of one or more collections in the service objects. If an iterator binding fails to
refresh, a JBO exception will be thrown and the data will not be available to display. If the
incoming request contains no POST data or query parameters, then the lifecycle forwards
to the Render Response phase. If the page was created using a template, and that template
contains bindings using the ADF Model layer, the template's page definition file is used to
create the binding container for the template. The container is then added to the binding
context. If any task flow executable bindings exist (for example, if the page contains a
region), the task flow binding creates an ADF Controller ViewPortContext object for the
task flow, and any nested binding containers for pages in the flow are then executed.
Apply Request Values: Each component in the tree extracts new values from the
request parameters (using its decode method) and stores those values locally. Most
associated events are queued for later processing. If you have set a
component's immediate attribute to true, then the validation, conversion, and events
associated with the component are processed during this phase and the lifecycle skips the
Process Validations, Update Model Values, and Invoke Application phases. Additionally, any
associated iterators are invoked. For more information about ADF Faces validation and
conversion, see the "Validating and Converting Input" chapter in the Oracle Fusion
Middleware Web User Interface Developer's Guide for Oracle Application Development
Framework.
JSF Apply Request Values: Provides before and after phase events for the Apply Request
Values phase. You can create a listener and register it with them before or after the event
of this phase, and the application will behave as if the listener were registered with the Apply
Request Values phase.
Process Validations: Local values of components are converted and validated on the
client. If there are errors, the lifecycle jumps to the Render Response phase. At the end of
this phase, new component values are set, any validation or conversion error messages and
events are queued on FacesContext, and any value change events are delivered.
Exceptions are also caught by the binding container and cached.

46/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
JSF Process Validations: Provides before and after phase events for the Process
Validations phase. You can create a listener and register it with them before or after the
event of this phase, and the application will behave as if the listener were registered with
the Process Validations phase.
Update Model Values: The component's validated local values are moved to the model
and the local copies are discarded. For any updateable components (such as
an inputText component), corresponding iterators are refreshed, if the refresh condition
is set to the default (deferred) and the refresh condition (if any) evaluates to true. If you
are using a backing bean for a JSF page to manage your UI components, any UI attributes
bound to a backing bean property will also be refreshed in this phase.
JSF Update Model Values: Provides before and after phase events for the Update Model
Values phase. You can create a listener and register it with them before or after the event
of this phase, and the application will behave as if the listener were registered with the
Update Model Values phase.
Validate Model Updates: The updated model is now validated against any validation
routines set on the model. Exceptions are caught by the binding container and cached.
Invoke Application: Any action bindings for command components or events are invoked.
JSF Invoke Application: Provides before and after phase events for the Invoke Application
phase. You can create a listener and register it with them before or after the event of this
phase, and the application will behave as if the listener were registered with the Invoke
Application phase.
Metadata Commit: Changes to runtime metadata are committed. This phase stores any
runtime changes made to the application using the Metadata Service (MDS). For more
information about using MDS to persist runtime changes
Initialize Context (only if navigation occurred in the Invoke Application lifecycle): The
Initialize Context phase listens for the beforeJSFRenderResponse event to execute. The
page definition file for the next page is initialized.
Prepare Model (only if navigation occurred in the Invoke Application lifecycle): Any
page parameters contained in the next page's definition are set.
Prepare Render: The binding container is refreshed to allow for any changes that may
have occurred in the Apply Request Values or Validation phases. Any iterators that
correspond to read-only components (such as an outputText component) are refreshed.
Any dynamic regions are switched if needed. The prepareRender event is sent to all
registered listeners, as is the afterJSFRenderResponse event.
Render Response: The components in the tree are rendered as the Java EE web container
traverses the tags on the page. State information is saved for subsequent requests and the
Restore View phase. To lessen the wait time required to display both a page and any
associated data, certain ADF Faces components such as the table component, use data
streaming for their initial request. When a page contains one or more of these components,
the page goes through the normal lifecycle. However, instead of fetching the data during
that request, a special separate request is run. Because the page has just rendered, only the
Render Response phase executes for the components that use data streaming, and the
corresponding data is fetched and displayed. If the user's action (for example scrolling in a
table), causes a subsequent data to fetch another request is executed. Tables, trees, tree
tables, and data visualization components all use data streaming.
JSF Render Response: Provides before and after phase events for the Render Response
phase. You can create a listener and register it with them before or after the event of this
phase, and the application will behave as if the listener were registered with the Render
Response phase.
47/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

5. Complex usage of a managed bean


A managed bean is the place where the complex UI logic is added for an ADF web application.
Complex bean logic involves listener logic for the components, page load logic, component-
initialization logic, and so on. Some UI use cases involve other operations that have to be
performed in the managed bean. The following are some of the use cases, snippets, and
implementations that involve writing logic in a managed bean:

Getting the iterator information:


BindingContainer bindings = BindingContext.getCurrent()
.getCurrentBindingsEntry();
DCIteratorBinding dciterContainer =
(DCIteratorBinding)bindings.get(iteratorName);

Getting the current row from the iterator:


DCBindingContainer bc =
(DCBindingContainer)BindingContext.getCurrent()
.getCurrentBindingsEntry();
DCIteratorBinding iterator = bc.findIteratorBinding("VOIterator");
Row r = iterator.getCurrentRow();
String val = (String)r.getAttribute("fieldName");

Accessing scope variables:


AdfFacesContext context = AdfFacesContext.getCurrentInstance();
Map pfScope = context.getPageFlowScope();
pfScope.get("paramName");
FacesContext fctx = FacesContext.getCurrentInstance();
ExternalContext ectx = fctx.getExternalContext();
Map sessionScope = ectx.getSessionMap();
sessionScope.get("paramName");

Check if the transaction is "dirty":


BindingContext bctx = oracle.adf.controller.binding
.BindingUtils.getBindingContext();
if (bctx.findDataControlFrame (bctx.getCurrentDataControlFrame())
.isTransactionDirty())
{
//show the timestamp
}
else{
//don't show
}

Scroll to a specific row on the loading of a page:


this.tableBinding.setRowIndex(rowIndex);
RowKeySet ps = this.tableBinding.getSelectedRowKeys();
ps.clear();
ps.add(this.tableBinding.getRowKey());
AdfFacesContext.getCurrentInstance()
.addPartialTarget(this.tableBinding);

48/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Reset the value of InputText:
RichInputText input = (RichInputText) JSFUtils.findComponentInRoot(id);
input.setSubmittedValue(null);
input.resetValue();
AdfFacesContext.getCurrentInstance() .addPartialTarget(input);

Refresh the component:


AdfFacesContext.getCurrentInstance() .addPartialTarget(component);

Show the pop-up window:


RichPopup.PopupHints ph = new RichPopup.PopupHints();
myPop.show(ph);

Navigate programmatically among view activities:


ControllerContext.getInstance().getCurrentViewPort().setViewId("Employ
ee");

Add Javascript from Bean


FacesContext facesContext = FacesContext.getCurrentInstance();
org.apache.myfaces.trinidad.render.ExtendedRenderKitService service =
org.apache.myfaces.trinidad.util.Service.getRenderKitService(facesCont
ext, ExtendedRenderKitService.class);
service.addScript(facesContext, "alert('Hi');window.close();");

Find an UI Component in the page:


private UIComponent findComponentOnPage(String id){
String comp = id;
//see ADF Code Corner sample #58 to read about the code
//used in the search below
FacesContext fctx = FacesContext.getCurrentInstance();
UIViewRoot root = fctx.getViewRoot();
root.invokeOnComponent(fctx,comp,
new ContextCallback(){
public void invokeContextCallback(FacesContext
facesContext,UIComponent uiComponent) {
lookupComponent = uiComponent;
}
});
return lookupComponent;
}

In Bean class:
public List TableKey() {
List<Key> list= new ArrayList<Key>();
for(Object empKey:empsTable.getSelectedRowKeys())
empsTable.setRowKey(empKey);
JUCtrlHierNodeBinding data =
(JUCtrlHierNodeBinding)empsTable.getRowData();
list.add(data.getRow().getKey());
return list;
}

49/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

public void onCreate(ActionEvent actionEvent) {


// Add event code here...
DCBindingContainer bindings2 =
(DCBindingContainer)BindingContext
.getCurrent().getCurrentBindingsEntr
y();
JUCtrlHierBinding obj =
(JUCtrlHierBinding)bindings2.findCtrlBinding("EmpVO1");
ViewObject vo = obj.getViewObject();
ADFUtils.invokeEL("#{bindings.Create.execute}");
ViewObject vo1 = obj.getViewObject();
}

public void onCreateIns(ActionEvent actionEvent) {


// Add event code here...
DCBindingContainer bindings2 =
(DCBindingContainer)BindingContext
.getCurrent().getCurrentBindingsEntry
();
JUCtrlHierBinding obj = (JUCtrlHierBinding)bindings2
.findCtrlBinding("EmpVO1")
;
ViewObject vo = obj.getViewObject();
ADFUtils.invokeEL("#{bindings.CreateInsert.execute}");
ViewObject vo1 = obj.getViewObject();
}

To refresh Current Page:


FacesContext context = FacesContext.getCurrentInstance()
String viewId = context.getViewRoot().getViewId()
ViewHandler vh = context.getApplication().getViewHandler()
UIViewRoot page = vh.createView(context, viewId);
context.setViewRoot(page);

Logout in oracle ADF / expiring session in ADF-adf-faces-prog:


public String logout() throws IOException {
ExternalContext ectx = FacesContext.getCurrentInstance()
.getExternalContext();
HttpServletResponse resp =
(HttpServletResponse)ectx.getResponse();
HttpSession sess = (HttpSession)ectx.getSession(false);
sess.invalidate();
resp.sendRedirect("login.jspx");
return null;
}

To display a message, use code like the following:


FacesContext fctx = FacesContext.getCurrentInstance();
FacesMessage fm = new FacesMessage("Message text");
fm.setSeverity(FacesMessage.SEVERITY_WARN);
fctx.addMessage(null, fm);
50/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

51/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

18 Binding Model Layer with Business Services and Databound View


1. Clean ADF Table filter without Managed Bean:
When you have an ADF filterable table then you may have noticed that the text inside the filter
doesn't clear itself when you navigate to other pages. It remains there. There are two ways to
clear the filters as far as I know.
1. Setting One of the output text column header true
2. A button with managed bean
3. ADF table's column property RowHeader is set to true then this column renders as a non-
filterable column with a Clear All icon which clears all filters and reloads the table

2. The following are the attributes that the table uses:


femptyText – This attribute tells the table what to display in case there are no records.
frowSelection – This attribute represents the type of selection this table should have;
you have three options: None, Single, or Multiple.
fselectedRowKeys – This attribute indicates selected rows inside the collection model
that indicates the selected row(s) if rowSelection is either Single or Multiple.
fselectionListener – This attribute indicates an event that gets triggered every time
you select a new record from the table and the selection listener, which by default executes
a method called makeCurrent. This method changes the current row of the
collectionModel inside the iterator, which means if you have a form and a table that
point to the same iterator and select a record inside the table, the form should display the
same record.
ffetchSize – This attribute represents the number of rows in the data fetch block.
ffilterModel – This attribute is responsible for the inline filtering feature that you see
when you enable the filter. This is the query that gets executed when you enter some text
in the filter's textbox and hit Enter. This points to #{bindings.
EmployeesView1Query.queryDescriptor} in the Executables section in the Bindings
view.
fqueryListener – This attribute indicates an event such as selectionListener, but
the filter executes every time you hit Enter on your filter textboxes.
fscrollPolicy – This attribute indicates how the pagination in the table should work;
there are two policies, either Scroll or Page, and you have to have a non-stretchable parent
for page's scrollPolicy to work effectively.
fvarStatus – This attribute indicates the status of the var attribute which focuses on
getting the status of the current row and not the row data, that is, information such as index
number, count, and step.

3. Tuning RangeSize:
rows and fetchSize are set the same as RangeSize. autoHeightRows value cannot be
larger than fetchSize attribute. The best practice is to set RangeSize to be
autoHeightRows+1.
For additional information refer:
 https://vtkrishn.com/tag/fetchsize/
 http://adfwithejb.blogspot.in/2015/05/understanding-aftable-property.html

52/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

19 Querying Data with Search Components


1. JDev 12c: Change Label depending on Data in Field
https://tompeez.wordpress.com/tag/afquery/
Use case
Before going into detail on how this is implemented, let’s look at the use case in detail. Starting
with a normal af:query component showing a search form for locations

We want to change the label of the ‘State’ field depending on the selected Value of the
‘CountryId’ field. The page is simply created by dragging the named criteria ‘All Queryable
Attributes’ onto the page as ‘Query with Table’.
To make the UI more interesting we use an af:selectOneChoice to select the country.
Depending on the selected country we like to show different labels for the ‘State’ field. If we select
the ‘United States of America’ as a country, the label should show ‘US States’, if we select
‘Germany’ we want to see ‘Bundesland’ and for Switzerland, we want to show ‘Kanton’. For the
remaining countries, we show ‘State’.

53/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Here we see that the label changed to ‘Kanton’ for the country Switzerland. Selecting the USA will
change the label to ‘US State’

54/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

2. Implementation
To implement this we only need to add some groovy script to the model project. To be precise we
add groovy to the attribute label of the view which is used in the UI for the af:query.
Adding the groovy to the view will guarantee that the UI always shows the effect. In the sample
(download instructions below) you’ll find a second page where the view is dropped as a af:form.
Running this page you’ll see the same effect.
OK, let’s have a look at the groovy script
if (CountryId == 'US') {
return 'US State';
} else if (CountryId == 'DE') {
return 'Bundesland';
} else if (CountryId == 'CH') {
return 'Kanton';
} else if (CountryId != null) {
return CountryId + ' State';
} else {
return 'State';
}
The script checks for specific countries and depending on which country is currently selected it
return a special label. For country ‘DE’ it returns ‘Bundesland’, for country ‘CH’ it returns ‘Kanton’.
For other countries we return the country code we get from the country attribute and add ‘State’
to it. A special case we have to handle is if the country is null or empty. In this case, we return
‘State’.
Below we see that we add the script to the attributes ‘UI Hint’ tab as ‘Label’. This is only possible
in 12c, so if you are using an earlier version, you have to use java code to get the same result.

This is all we have to do. The sample which is build using JDev 12.2.1.2.0 can be downloaded
from BlogChangeQueryLabel. The sample uses the HR DB schema.
http://www.learnoracleadf.com/2013/05/programatic-handle-to-adf-query.html

55/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3. Programmatic handle to ADF Query Component - see Query Input values


You can create ADF Query search forms that will allow users to search based on some input fields.
The results of the query can be displayed as ADF Table, form or any other ADF UI Component. In
general search, forms are based on af:query and af:quickquery components.
ADF Search forms are based on view criteria defined at ADF VO level or implicit view criteria
defined by the framework. Once you define the View criteria, drag and drop it from the data
control palette on the page as ADF Query pane with the table. ADF will take care of the rest of
the things. Everything will be configured on its own ranging from search button binding to the
particular model and to the table which is being refreshed whenever results are being fetched.
Suppose we may want to modify the query values / see the current query values / validate the
user input. we will see how to get a handle to the ADF Query component to do this.
you will see the ADF:Query pane code in the page like this :
<af:query id="qryId1" headerText="Search" disclosed="true"
value="#{bindings.VOCriteriaQuery.queryDescriptor}"
model="#{bindings.VOCriteriaQuery.queryModel}"
queryListener="#{bindings.VOCriteriaQuery.processQuery}"
queryOperationListener="#{bindings.VOCriteriaQuery.processQuery
Operation}" resultComponentId="::resId1"/>
queryListener having an expression that deals with invoking of the corresponding binding
dynamically. To get a handle to this component we will write our custom method and bind it to
the queryListener.
After modifying, it looks like
queryListener="#{backingBeanScope.managedBean1.onSearch}"
The Below custom method will tell you everything in clear
public void onSearch(QueryEvent queryEvent) {
String EmployeeId = null;
// Query Event is delivered when a query action is triggered
QueryDescriptor qd = queryEvent.getDescriptor();

// This line will represent a group of criterion objects


ConjunctionCriterion conCrit = qd.getConjunctionCriterion();

//access the list of all search fields


List<Criterion> criterionList = conCrit.getCriterionList();

for (Criterion criterion : criterionList) {


AttributeDescriptor attrDescriptor =
((AttributeCriterion)criterion).getAttribute();

if (attrDescriptor.getName().equalsIgnoreCase("EmployeeId")) {
// EmployeeId is one of the query items in the search pane
EmployeeId =
(String)((AttributeCriterion)criterion).getValues().get(0);

//This is how we will access the query field


System.out.println("EmployeeId :" + EmployeeId );

}
}
DCBindingContainer bc =
56/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
(DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
ViewCriteria vc = getViewCriteria(bc, qd);

System.out.println("View Object"+ vc.getViewObject);

//Execute the query Listener using EL. This will execute the query
component. If u see the exp, this was initially applied to QueryListener..
Later we assigned QueryListener to our custom method.

invokeMethodExpression("#{bindings.VOCriteriaQuery.processQuery}",
queryEvent);

//helper method to execute the QueryListener EL

private void invokeMethodExpression(String expr, QueryEvent queryEvent)


{
FacesContext fctx = FacesContext.getCurrentInstance();
ELContext elContext = fctx.getELContext();
ExpressionFactory eFactory =
fctx.getApplication().getExpressionFactory();
MethodExpression mexpr =
eFactory.createMethodExpression(elContext, expr, Object.class,
new Class[] { QueryEvent.class});
mexpr.invoke(elContext, new Object[] { queryEvent });
}

private ViewCriteria getViewCriteria(DCBindingContainer bc,


QueryDescriptor qd) {

Object execBinding = bc.findExecutableBinding("VOCriteriaQuery");


// This will be seen in the page executable section as we have
dropped for af:query
ViewCriteria vc =
JUSearchBindingCustomizer.getViewCriteria((DCBindingContainer)execBinding,
qd.getName());
return vc;
}

57/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

20 Implementing Transactions
1. ADF TaskFlow Transaction Basics
<http://suneesh-adf.blogspot.com/2013/10/adf-taskflow-transaction-basics.html >
The transaction is a collection of works either committed or rollback. Create a calling and called
task flow to go through some of the transaction basics of task flow.

Calling Task flow:

Called Task flow:

From the behavior section of the called task flow, you can see the following options

58/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
No Controller transaction is the default option means the called task flow does not
participate in any transaction management.
Always begin New Transaction - Transaction is created when entering to the task flow and
completes the task flow when exists the task flow
Always Use Existing transaction - Called task flow participates the existing transaction
User Existing transaction if possible - Participate the existing transaction if available or start
a new transaction if not available
restore-save-option

Use restore-save-option =true if you want to discard the changes the end-user makes with in a
called bounded task flow when the called bounded task flow exits. This option applies only if the
bounded task flow is entered by joining the existing transaction and a save point created on entry

No save point on task flow entry if selected prevent the creation of ADF model save point on task
flow entry if taskflow participate in 'Always Use existing transaction ' or 'User existing transaction
if Possible'. In this case, overhead associated with a save point is not created for the transaction.
End the transaction from task flow return activity by selecting the End transaction property to
commit or rollback.

59/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Shared Data control behavior and transaction:


Share data controls with calling task flow have the options Shared and Isolated
Shared Data Control
Transaction setting Isolated Data Control scope
scope

No controller txn DataControlFrame shared New DataControlFrame is


without open txn created without an open
transaction

Always begin new txn Begin new if one is not open Always begin new one

Always Use existing txn Throws an exception if txn is Invalid. The checkbox cannot
already open be deselected

Use Existing txn if Begin a new txn if one is not Always begin a new txn
possible already open

2. ADF Taskflow Transactions Management and Datacontrol scope - Part 1


<http://satishbathala.blogspot.com/2016/05/adf-taskflow-transactions-management.html >
There are quite a few excellent articles over the internet about taskflow transactions and
Datacontrol instances, but i felt it would be great to explain the full cycle with diagramatic
examples and scenarios where these features would be of great use. So lets start..

How Transaction and Application Module are related?


Each Application module holds one transaction at a time, the below diagram gives you a better
picture of how it works with App Module.

60/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

61/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
What is a DataControl Frame?
A DC Frame is a container that holds the state of all associated Data controls. It may be confusing
now, but you will get more clarity once we see an example. E.g. : Let’s take 2 different taskflows
"Employees" and "Departments", Both these Taskflows use the same Application Module(this is
very important), default settings and are used on the same page.
This is how it works internally.

62/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
A Commit/RollBack anywhere in the DCFrame would update all DC changes to
DataBase i.e. Commit/Rollback in Employees taskflow will Commit/Rollback changes in
Departments taskflow too.
Check out the below example with sample data. As you can see, Both the taskflows have the same
DC Frames.

63/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
What is Data Control Scopes?
Now that we have a good understanding of how Datacontrol Frames work, let's discuss Data
Control Scopes.
There are 2 different kinds of DC Scopes –
 Shared (Default, It is what we saw in the previous example).
 Isolated.
Now, what if we want to separate the transactions i.e. if a commit in Departments taskflow should
not affect Employees Taskflow?
We have an option in Taskflow level to separate the DataControl Frames,
Go to Taskflow behavior> Set the Transaction as "Isolated".

So let’s see how it works internally

64/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Here is the example with sample data -

Note: the DC frame, it is different for both taskflows. A similar example can be explained for
parent and child taskflows too. A solid understanding of datacontrol scopes will help understand
the next post in this series.

65/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3. ADF Taskflow Transactions Management and Datacontrol scope - Part 2


<http://satishbathala.blogspot.com/2016/05/adf-taskflow-transactions-management_16.html>
In the previous post, we discussed in detail about basics Datacontrol scopes, Transactions and
Application Module using single AppModule.
Now let’s take it to the next level and make it a little complex.
The below picture depicts how to sample Parent and Child sample taskflows used in this post are
configured.

As you can see we have 2 iterators from 2 different Application modules in the parent as well as
child taskflow.

66/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Case 1 (Default Taskflow Settings) -
Parent Taskflow
Transaction - No Controller Transaction
Data Control Scope - SHARED
Child Taskflow
Transaction - No Controller Transaction
Data Control Scope - SHARED
This is how it will work internally-

Key Observations
Since Datacontrol Scope is set to Shared, Both the Taskflows will share the same DC Frame.
Both AppModule1 and AppModule2 will create the Root Application Module which eventually
means 2 Connections, 2 Separate Commit/RollBack per transaction, etc.
In Parent/Child Taskflows, Commit in Employee Iterator 1 will not reflect changes in Employee
Iterator 2 and vice versa until a new control state is created.
A Commit/RollBack in Child Taskflow's Employee Iterator1 will update changes in Employee
Iterator1 of Parent Taskflow and vice versa because they share the same Transaction.
A Real Example - Notice the Transaction and AppModule

67/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

68/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Case 2 -
Parent Taskflow
Transaction - No Controller Transaction
Data Control Scope - SHARED
Child Taskflow
Transaction - No Controller Transaction
Data Control Scope - ISOLATED

This is how it will work internally-

Key Observations
Since Datacontrol Scope of the child is set to Isolated, Both the Taskflows will have separate
DC Frames.
Since DC Frames are separate each of iterators will have Transactions of its own so
2 Taskflows * 2 AppModules = 4 Transactions, 4 Connections (Not good right?)
Commit/RollBack in any of the iterator will not affect any other.
A Real Example

69/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

70/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

4. ADF Taskflow Transactions Management and Datacontrol scope - Part 3


<http://satishbathala.blogspot.com/2016/05/adf-taskflow-transactions-management_17.html>
In our previous post, we had discussions about how DataControl Scopes and multiple Application
Module Transactions interact with each other.

Let’s use the same application used in the previous post and discuss more about Taskflow
Transactions Management
What is Transaction management in taskflow?
Transactions are managed by the Application Modules, as an application grows we might want to
use multiple data controls from different application modules in a single view.

Eg: If we use datacontrol from 3 different application modules (Assuming they are not nested in
Data Model) in one taskflow view, then we end up with 3 Root App Modules = 3 Database
connections and the important part is we need 3 separate commits to post all changes to DB.

ADF taskflows offer an elegant solution to such problems, which is to manage Transactions at
taskflow level.

Let’s see how it works -

Case 3:
Parent Taskflow
Transaction - Always Begin New Transaction
Data Control Scope - ISOLATED

Child Taskflow
Transaction - Use Existing Transaction if possible
Data Control Scope - SHARED

As we saw in Case 1 and 2, each Application module is created as Root with separate Transactions.
In Case 3 let’s make the Parent Taskflow begin new Transaction and Child to Use the Existing
Transaction.

This is how it works internally -

71/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Observations
Parent Taskflow begins a new Transaction at Taskflow level and Child taskflow uses the
same.
Only Root Application Module (App module 1) is created and App module 2 is nested inside
App Module 1. Hence overall only 1 Transaction and 1 DB Connection is used across different
application modules and taskflows.
Only one DCFrame is used.
A commit/rollback in any iterator will commit the changes to DB since they use one
Transaction.
There is also a better way to do it using taskflow return, which we can discuss later in a different
post.

Check out the flow in a real example,


Notice that only one Transaction is used in all 4 iterators.

72/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Similarly, we can create multiple cases based on different Transaction management and
Datacontrol scope options, but with the above examples, you will be able to figure out those
combinations pretty easily.
E.g.:

Case 4:
Parent Taskflow
Transaction - No Controller Transaction
Data Control Scope - ISOLATED

Child Taskflow
Transaction - Always Begin New Transaction
73/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Data Control Scope - ISOLATED

Parent taskflow will use 2 Transactions and Child will use 1.

Case 5:
Parent Taskflow
Transaction - No Controller Transaction
Data Control Scope - ISOLATED

Child Taskflow
Transaction - Use Existing Transaction if possible
Data Control Scope - ISOLATED

Parent taskflow will use 2 Transactions and Child creates a new Transaction since no new
transaction already exists in the taskflow layer.

We can go on and on.

In my opinion, Don't use Transaction management options unless you are sure of its use.
In most cases, you needn't use it.

In simple terms -
Data Control Scope - To manage DC Frames.
Transaction management options - To manage DB Transactions in the taskflow layer instead
of in the model layer using Application Modules.

You can check out the application used in these blog posts from
https://github.com/bsatishinbox/FusionSamples/tree/master/TransactionFlows

74/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

21 Understanding Data Controls and Bindings


1. Oracle ADF BindingContext and BindingContainer
The Oracle ADF binding context is a runtime map (accessible through the EL expression
#{data}) of all data controls and page definitions within the application. The binding
context does not contain real live instances of these objects. Instead, the map contains
references that become data control or binding container objects on demand. The ADF
lifecycle creates the binding context from the application module, DataBindings.cpx, and
page definition files.
In Oracle ADF, the group of bindings supporting the UI components on a page are described
in a page-specific XML file called the page definition file. The ADF Model layer uses this file
at runtime to instantiate the page’s bindings. These bindings are held in a request-scoped
map called the binding container, accessible during each page request using the EL
expression: #{bindings}
This expression always evaluates to the binding container for the current page. For example,
to access the collectionModel of binding object named MyShoppingCart, you use the
EL expression: #{bindings.MyShoppingCart.collectionModel}
BindingContext: The binding context lives in the HttpSession for each end user. It
holds references to lightweight application module data control objects that manage
acquiring an application module instance from the pool during the request (when the data
control is accessed) and releasing it to the pool at the end of each request. The data control
holds a reference to the ADF session cookie that identifies the user session. The binding
context also holds references to binding containers. The binding context might contain many
data controls and many binding containers. There are three options to access the binding
context at runtime by Fusion Web Applications:
a. BindingContext.getCurrent()
b. BindingUtils.getBindingContext()
c. JsfUtils.resolveExpression("#{data}")
For option a and b, they are implemented in the same way internally:
import oracle.adf.model.BindingContext;
(BindingContext)ADFContext.getCurrent().getSessionScope().get("
data");
However, option c is different and resolveExpression() is defined to be:
public static Object resolveExpression(String expression) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp=elFactory.createValueExpression(
elContext, expression, Object.class);
return valueExp.getValue(elContext);
}
As you can see it, the third approach is more expensive because it involves extra
expression parsing and syntactic validation of the expression. BindingContext is an
object that implements the Map interface and exposes generic methods to access the
binding layer. For example, to find a data control, you could use the
findDataControl() method on BindingContext findDataControl(dc_name)
BindingContainer: To access binding container, you first retrieve binding context as
described above; then you use binding context's getCurrentBindingsEntry method to
retrieve binding container object:
75/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
import oracle.binding.BindingContainer;
BindingContainer bc = bindingContext.getCurrentBindingsEntry();
Internally, getCurrentBindingsEntry() is implemented as follows:
(BindingContainer)ADFContext.getCurrent().getRequestScope().get
("bindings");
If you use option 3 as described above, you can retrieve binding container in a more
straightforward way (although it's still more expensive):
FacesContext facesCxt = FacesContext.getCurrentInstance();
ExpressionFactory exp =
facesContext.getApplication().getExpressionFactory();
DCBindingContainer bindingContainer =
(DCBindingContainer)exp.createValueExpression(facesCxt.getELCon
text(),
"#{bindings}",DCBindingContainer.class).getValue(facesCxt.getEL
Context());
Fusion application developers who prefer working with type-safe methods can cast the
bindings instance (i.e., BindingContainer) to DCBindingContainer:
DCBindingContainer object exposes more methods than the its super class object
BindingContainer. For example, you can access the application module's client interface
from this DCBindingContainer by naming an ADF action binding or an ADF iterator
binding as shown below:
// 1. Access the binding container
DCBindingContainer bc = (DCBindingContainer)getBindings();
// 2. Find a named action binding
JUCtrlActionBinding action =
(JUCtrlActionBinding)bc.findCtrlBinding("SomeActionBinding");
// 3. Get the data control from the iterator binding (or method
binding)
DCDataControl dc = action.getDataControl();
// 4. Access the data control's application module data provider
ApplicationModule am = (ApplicationModule)dc.getDataProvider();
// 5. Cast the AM to call methods on the custom client interface
StoreServiceAM service = (StoreServiceAM)am;
// 6. Call a method on the client interface
service.doSomethingInteresting();

2. ADF Bindings
Oracle Application Development Framework (Oracle ADF) provides several types of binding objects
to support the attributes and operations exposed by the Oracle ADF data controls for a particular
business object:
Iterator binding, one per accessor attribute that your page or panel displays. Iterates over
the business objects of the data collection and maintain the row currency and state.
Value bindings, one for each databound UI component. It provides access to data.
Action binding, specifically defined for a button component. It provides access to
operations defined by the business object.
 You create these bindings in JDeveloper through your interaction with the Data Control
Palette, a visual editor, the Structure window, and the Property Inspector. You can
view the binding in your application in any one of several ways:

76/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
 In the source code view of a web page, where binding references appear in expressions
that get evaluated at runtime using the expression language (EL) features. In the code
view, the expression looks like this:
<c:forEach var="rv"
items="${bindings.DataBindingObject.theCollectionProperty}"
 The data binding object accesses the Oracle ADF binding container through the
bindings variable, which is a variable that specifies the namespace for the binding
containers in the ADF binding context. The binding container is initialized for Model
2&ndashstyle web applications in the Oracle ADF class
oracle.adf.controller.struts.actions.DataAction.
 In the code view of a JClient panel or form, where the setModel() method call on the
UI component initializes the data binding object and accesses the binding container
through the ADF binding context (specified by the setBindingContext() method
call on the data panel).
 The binding container is initialized from the PanelName UIModel.xml file in the JClient
project when the panel binding is created (by the JUPanelBinding panelBinding
constructor).
 In the Structure window for either client type (web page or JClient panel), where the
data binding objects defined for each UI component in your view document appear in
the UI Model tab icon (UI Model) tab. To edit the declarative properties of the binding
definitions, right-click and choose Edit. To understand what values you can set for
runtime-only properties, select the binding node and press F1.

The following sections describe the various bindings.


About the Iterator Binding: The oracle.jbo.uicli.binding.JUIteratorBinding
class implements the iterator binding. The iterator binding is a runtime object that your
application creates to access the Oracle ADF binding context. The iterator binding holds
references to the bound data collection, accesses it, and iterates over its data objects. The
iterator binding notifies value bindings of row currency and row state. Then, value bindings
that you define allow UI components to display or update the current data object of the
collection being iterated over. In this way, the iterator binding provides uniform access to
various collection types from different business services. In the case of an ADF Business
Components view object, the ADF bindings for the UI components may be able to display a
row currency indicator. In a table, for example, the current row is identified at runtime by
an asterisk (*) symbol displayed in the first column of that row. The currency indicator is
available only through the iterator binding when the bound view object has a key attribute
defined. When no key attribute is defined for the bound view object, each row of the table
will display the asterisk. In this case, you can edit the UI component in the visual editor to
prevent the asterisks from displaying at runtime. The iterator binding defines its own set of
runtime properties.
About the Value Bindings:
 Attribute Value Binding
 The oracle.jbo.uicli.binding.JUCtrlValueBinding class implements
the attribute value binding.
 The attribute value binding permits the databound UI component to obtain the
attribute value of the specified collection's data object. Depending on the type of
UI component, users may view and, in some cases, edit the value of the attribute.
 The attribute value binding defines its own set of runtime properties.
 Boolean Value Binding
77/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
 The oracle.jbo.uicli.binding.JUCtrlBoolBinding class implements
the boolean binding.
 The boolean binding obtains the attribute value of the specified collection's data
object based on the control's selection state.
 The boolean value binding defines its own set of runtime properties.
 List Value Binding
 The oracle.jbo.uicli.binding.JUCtrlListBinding class implements
the list binding.
 Depending on the type of UI component, the list binding may:
 Update an attribute of a data object in the bound collection.
 Traverse the data objects of the bound collection.
 Update a target data object in one collection using the value from another
collection's data object.
 The list value binding defines its own set of runtime properties.
 Range Value Binding
 The oracle.jbo.uicli.binding.JUCtrlRangeBinding class implements
the range binding.
 The range binding permits the databound UI component to obtain a range of
attribute values from the specified collection's data objects and to display the
position of the current data object relative to that range.
 The range value binding defines its own set of runtime properties.
 Scroll Value Binding
 The oracle.jbo.uicli.binding.JUCtrlScrollBinding class implements
the scroll binding.
 The scroll binding permits the databound UI component to display the current
position of the data object in the selected collection. When the user scrolls the UI
component, the scroll binding maintains the current position in the collection.
 The scroll value binding defines its own set of runtime properties.
About the Action Binding: The oracle.jbo.uicli.binding.JUCtrlActionBinding
class implements the action binding. The action binding is a type of binding object defined
by Oracle ADF that performs actions on the bound data collection & request row set iterator.
At runtime, when the user initiates the action, using a button control, the action binding
accesses the Oracle ADF binding context and initiates the specified action on the data objects
of the selected collection. The action binding supports many predefined actions. The action
binding defines its own set of runtime properties. For information about how the ADF binding
context provides access to these bindings’ objects at runtime

3. Model Layer
“DataBindings.cpx” will be created implicitly, when a data bound component (pagedef.xml)
was created.

4. Get Iterator of a table


public static DCIteratorBinding getDciteratorFromTable(RichTable
table) {
CollectionModel model = (CollectionModel)table.getValue();
JUCtrlHierBinding treeBinding =
JUCtrlHierBinding)model.getWrappedData();
return treeBinding.getDCIteratorBinding();
}
78/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

5. Execute Binding operations


BindingContext bindingCtx = BindingContext.getCurrent();
BdiningContext bindings = bindingCtx.getCurrentBindingsEntry();
OperationBinding setCurrentRowWithKey =
bindings.getOperationBinding("setCurrentRowWithKey");
setCurrentRowWithKey.getParamsMap().put("rowKey",rowKey);
setCurrentRowWithKey.execute();

6. Expression Language
Expression Language is used for adding additional logic to the runtime customization of page
components.
The examples provided in this document serve the following basic customization needs, and
whilst more advanced logic is possible venturing into great complexity may take your
customization beyond the scope that page composer is designed to support.
 Dynamically set a field to default a specific value
 Dynamically set the display properties of a specific field
 Conditionally hide or disable a field or region
Generally, EL statements return either a value such as ‘Richard’, or a Boolean such as TRUE
if the test is a success. These are then used in setting ADF page component properties, such
as Value, Required, or Visible. The examples in this document include a mixture of return
values used for setting various properties. In ADF a partial page refresh is used to fire the
EL logic, and careful testing in a safe environment is needed to ensure your EL executes at
the expected places. An example might be properly defaulting values for fields upon actions
such as create, edit, and re-edit.
Expression Language (EL) is widely used in ADF Binding to reference items in the Binding
Context. In some scenarios, direct use of EL reference isn't enough and manipulation of
several EL references needed to accomplish the task. While you can always manipulate the
logics in a managed bean, if you want to go with "declarative", here is why I am saying
about.
Varchar2 type in SQL format (database) is converted to String automatically, but Number
type in SQL is converted to oracle.jbo.domain.Number format. EL inherit generic Java
API and can only recognize java.lang.Number type.
Therefore, if you have two EL binding references to two database Number attributes:
#{bindings.NumberAtt1.inputValue} and
#{bindings.NumberAtt2.inputValue}. If you want to evaluate if the first number
greater than the second number, you cannot use compareTo() method which belongs to
oracle.jbo.domain.Number and you cannot use #{A > B} because A or B is not
java.lang.Number
A simple conversion is to attach ".value" at the end of EL binding reference and it will convert
it to a java.lang.Double format type.
In JSF pages, a typical ADF data binding EL expression uses the following syntax to reference
any of the different types of binding objects in the binding container:
#{bindingVariable.BindingObject.propertyName}
where:
 bindingVariable is a variable that identifies where to find the binding object being
referenced by the expression. The bindings variable is the most common variable used
in ADF binding expressions. It references the binding container of the current page. By

79/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
default, all components created from the Data Control Palette use the bindings variable
in the binding expressions.
 BindingObject is the name of the binding object as it is defined in the page definition
file. The binding object name appears in the id attribute of the binding object definition
in the page definition and is unique to that page definition. An EL expression can
reference any binding object in the page definition file, including parameters,
executables, or value bindings. When you use the Data Control Palette to create a
component, JDeveloper assigns the names to the binding objects based on the names
of the items in the data control.
 propertyName is a variable that determines the default display characteristics of each
databound UI component and sets properties for the binding object at runtime. There
are different binding properties for each type of binding object. For example, in the
following expression: #{bindings.SvrId.inputValue}
JSP 2.1 and JSF 1.2 - both of them use a unified Expression language. One major and the
most obvious difference is between $ and #. JSP 2.1 uses $ and JSF 1.2 uses # in an EL.
 $ - immediate evaluation.
$ syntax executes expressions eagerly/immediately, which means that the result is
returned immediately when the page renders.
 # - deferred evaluation.
# syntax defers the expression evaluation to a point defined by the implementing
technology. In general, JSF uses deferred EL evaluation because of its multiple
lifecycle phases in which events are handled. To ensure the model is prepared before
the values are accessed by EL, it must defer EL evaluation until the appropriate point
in the life cycle.

7. Browsing through the page definition file:


Parameters
The <parameters> section in the page definition file allows you to define parameter binding objects
that other bindings or UI components can refer to. In real life, you may use this section to define
parameters whose value is referenced from multiple places in a page definition file.
Executables
The <executables> section defines executable items that get executed during the ADF page
lifecycle. Note that the data collections used in the page are refreshed through appropriate
executable binding entries. The following are the executable binding objects supported by the
framework:
Iterator: The <iterator> section binds to an iterator object that iterates over the data
collection exposed through data control. An example of a data collection is a view object instance
in the data control panel. The iterator binding definition decides how and when to refresh the
attached data collection during a page lifecycle.
Method iterator: The <methodIterator> section binds to an iterator object that iterates
over the data collection returned from a custom method exposed through data control.
Variable iterator: The <variableIterator> section binds to an iterator object that
exposes all the variables in the page definition, which other bindings can reference. Variable
iterators include method parameters and scalar return values of custom methods exposed
through data control.
Invoke action: The <invokeAction> section binds to a built-in action or method action
binding present in the binding section of the page definition file. This is useful if you want
to execute a method action during the lifecycle of a page for each request from the browser.

80/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
You should keep the following points in mind while using this binding in the application:
invokeAction is executed for each request from the web client. Use the appropriate Refresh
property for the invokeAction binding to decide the lifecycle phase at which the binding is
refreshed.
If the method contains page initialization logic and it is supposed to be executed only once during
the page load, check the feasibility of using a method call activity in the navigation flow definition
(bounded or unbounded task flow XML file), before the page renders, to invoke the method instead
of using invokeAction. If method call activity is not a viable option for you, make sure that the
framework is not triggering the invokeAction executable multiple times during the page
lifecycle by adding the appropriate refreshCondition.
Page: The <page> binding is used to refresh the data binding for the page template. This entry
will appear only if the current page is built by choosing a data-bound page template. The page
binding executable is refreshed during the Prepare Model phase. During this phase, the binding
container for the template is created based on the template's page definition file, and it is added
to the binding context.
Search region: <searchRegion> defines the executable binding definition for the query
component and Query By Example (QBE) criteria that appear on a UI table. This binds the
named view criteria to the iterator for data collection.
Task flow: <taskFlow> defines the binding for the task flow that is embedded in a region.
During the page lifecycle, the framework instantiates the binding container for a region's task
flow.
Multitask flow: <multiTaskFlow> defines the binding for an unknown number of task flows
whose IDs are decided at runtime. This is useful when you have a page that contains an unknown
number of regions. An example is the dynamic panelTabbed component where each tab is a
region, whose contents are decided at runtime.

8. Bindings
The bindings section in a page definition file defines value bindings as well as action bindings for
a web page. Value bindings bind the UI with the attribute value returned by an iterator, and action
bindings bind component actions (events) with operations from the underlying data model
exposed through data control. ADF supports the following binding types:
Action: The <action> binding defines bindings for built-in operations on the row iterator
object as well as on data control.
Method action: The <methodAction> binding defines bindings for custom methods
exposed through data control.
Attribute value: The <attributeValues> binding defines the binding for accessing
attribute values of the currently selected row in a data collection. Note that attribute binding
is accessed through the iterator executable.
Boolean value: The <button> binding (also known as Boolean binding) defines the
bindings for attribute types whose value takes the form of checked or unchecked states.
Data visualization components bindings: ADF provides data-binding supports for the
following graph types: Map
 Gantt
 Gauge
 Graph
 PivotTable
List: The <list> binding defines the bindings for a list of items. The list binding definition
can refer to the model-driven list, static list, or dynamic list. ADF also supports a variant of
81/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
list binding, the <listOfValues> binding, which offers more options on the UI such as
lazy loading, search and select, and range fetching.
Binding Business Services with User Interface
Tree bindings: The <tree> binding defines the binding for nested data collections that
are used for populating hierarchical UI components such as trees and hierarchy viewer
components. The tree binding even works for single-level collections as well. When you drag-
and-drop a collection as a table, JDeveloper generates tree binding although the data
collection is not hierarchical.
Table binding: The <table> binding defines the binding for a single-level collection of
data.

82/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

22 Programmatically Customizing Business Services


1. Methods
lock() and doDML(): Data Manipulation Methods: Generate methods to override DML
methods.
Create(): Select to override the create() method to modify or add initialization features to
create logic.
Remove(): Select to override the remove() method to modify or add clean-up code to the
remove logic.
doDML() method: This method fires after all the attribute and entity validation is complete.
You can add code that is beyond validation logic here. For example, you could add code that
records audit information in another entity.
beforeCommit() method: This method is used for rules that involve more than one
instance of the same entity or more than one entity. Because any of the instances could
have changed in the current transaction, it is important to delay validation until all of the
instances have been posted.
remove() method: It is used for rules that are triggered by a delete action.
createRowSetIterator(java.lang.String name): Creates an iterator for the row
set
executeQuery(): Executes the view object’s query
getApplicationModule(): Gets the row set’s Application Module
getEstimatedRowCount(): Counts the number of rows in the collection defined by the
view object’s query
getMasterRowSetIterators(): Returns all controlling masters of this row set
getName(): Gets the row set’s name
getViewObject(): Gets the view object that contains the row set
getWhereClauseParams(): Gets the bind-variable values to be used with the view object’s
query condition
setWhereClauseParam(int index, java.lang.Object value): Specifies a single
bind-variable value to use with the view object’s query condition, and executes the query
setWhereClauseParams(java.lang.Object[] values): Specifies the bind-variable
values to use with the view object’s query condition, and executes the query The RowSet
interface implements the RowIterator interface, which enables access to the row set.
Some of its methods include the following:
createRow(): Creates a new Row object, but does not insert it into the row set
findByEntity(int eRowHandle, int maxNumOfRows): Finds and returns view rows
that use the entity row, identified by the entity row handle, eRowHandle
findByKey(Key key, int maxNumOfRows): Finds and returns view rows that match
the specified key
first(): Designates the first row of the row set as the current row
getRow(Key key): Accesses a row through a unique key
hasNext(): Tests for the existence of a row after the current row
hasPrevious(): Tests for the existence of a row before the current row
insertRow(Row row): Adds a row to the row set, before the current row
last(): Designates the last row of the row set as the current row
next(): Steps forward, designating the next row as the current row
removeCurrentRow(): Removes the current Row object from the row set

83/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
previous(): Steps backward, designating the previous row as the current row
reset(): Clears the “current row” designation and places the iterator in the slot before the
first row
setCurrentRow(Row row): Designates a given row as the current row In addition to the
RowSet and RowIterator interfaces, ViewObjectImpl implements the ViewObject
interface, containing the following methods:
applyViewCriteria(ViewCriteria criteria): Applies the view criteria to this view
object
createRowSet(java.lang.String name): Creates and names a row set for the view
object
createViewCriteria(): Creates a “Query by Example” view criteria object
findViewLinkAccessor(ViewLink vl): Finds the view link accessor attribute
getOrderByClause(): Retrieves the current ORDER BY clause of the view object’s query
statement
getQuery(): Retrieves the view object’s query statement
getViewCriteria(): Gets this view object’s view criteria
getViewLinkNames(): Retrieves the names of the view object’s View Links
getWhereClause(): Retrieves the current WHERE clause of the view object’s query
statement
isReadOnly(): Tests if the view object is read-only
setOrderByClause(java.lang.String expr): Sets the ORDER BY clause of the view
object’s query statement
setWhereClause(java.lang.String cond): Sets the WHERE clause of the view
object’s query statement

2. Code to set Default value from another EO:


public void setDepartmentId(Integer value) {
setAttributeInternal(DEPARTMENTID, value);
if (value!= null) {
DepartmentsEOImpl departmentsEOImpl =
this.getDepartmentsEO1();
if (departmentsEOImpl != null) {
setManagerId(departmentsEOImpl.getManagerId());
} else {
//user enter invalid data in DepartmentId
setManagerId(null);
}
} else {
//user don't enter data in DepartmentId
setManagerId(null);
}
}

3. Dynamic VO:
84/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
public void changeDynamicVoQuery(String sqlStatement) {
ViewObject dynamicVO = this.findViewObject("DynamicVO1");
dynamicVO.remove();
dynamicVO = this.createViewObjectFromQueryStmt("DynamicVO1",
sqlStatement);
dynamicVO.executeQuery();
}

4. Add the Attribute programmatically:


ViewObject vo = this.findViewObject("ViewObjectName");
if (vo != null) {
try {
String transientAttr =
vo.findAttributeDef("XXAttr").toString();
} catch (Exception e) {
vo.addDynamicAttribute("XXAttr");
}
}

5. Programmatically apply view criteria:


public void searchEmployee(Number employeeId) {
ViewObjectImpl vo = getEmployeesView1();
ViewCriteria vc = vo.getViewCriteria("findEmployeeVC");
vo.applyViewCriteria(vc);
vo.setNamedWhereClauseParam("pEmployeeId", employeeId);
vo.executeQuery();
}

6. Programmatically create view criteria:


public void searchByEmployeeIdEmail(Number employeeId, String
email) {
ViewObjectImpl vo = getEmployeesView2();
ViewCriteria vc = vo.createViewCriteria();
ViewCriteriaRow vcRow = vc.createViewCriteriaRow();
vcRow.setAttribute("EmployeeId", employeeId);
vc.addRow(vcRow);
vcRow.setAttribute("Email", email);
vc.addRow(vcRow);
vo.applyViewCriteria(vc);
vo.executeQuery();
}

7. Set ViewCriteria columns as visible/hide:


public void setQuerable(String attributeName, Boolean isQuerable)
{
int indx = this.getAttributeIndexOf(attributeName);
ViewAttributeDefImpl attr =
(ViewAttributeDefImpl)this.getAttributeDef(indx);
attr.setQueriable(isQuerable);
}
8. Delete Selected records from a table, In vo impl class:
85/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
public void deleteEmps(List <Key> empKeys ) {
if(empKeys!= null) {
for(Key k: empKeys) {
Row[] row = this.findByKey(k, 1);
if(row!= null && row.length==1) {
EmployeeVoRowImpl r = (EmployeeVoRowImpl)row[0];
r.remove(); // EmployeeVoRowImpl class that we have
created earlier
}
}
}
}

9. Lifecycle of an entity object


The following diagram depicts the entity row status at various stages of a business transaction:

86/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

10. Lifecycle callback methods of a view object


The following diagram depicts the sequence of the lifecycle callback for a view object.

The following sequence diagram illustrates the sequence of actions and collaboration between
various framework components when an application module is checked out from the pool to serve
a new client when a client tries to grab an application module instance:

87/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

11. Programmatic passivation and activation of custom data


The following example illustrates programmatic approach to passivate and activate custom data
present in an application module. This example overrides the passivatesState(Document,
Element) and activatesState(Element) methods in an application module to make the
regionId data available for the client even after the passivation and activation cycle of the
application module.
//In application module implementation class
/**
* Overridden framework method to passivate user data
* in XML format by appending to the parent node
*/
@Override
public void passivateState(Document doc, Element parent) {
//This code snippet stores the data in USERDATA node
Element nodeUserData = doc.createElement("USERDATA");
nodeUserData.setAttribute("KEY", USER_REGION);
nodeUserData.setAttribute("VALUE",
getRegionId().toString());
parent.appendChild(nodeUserData);
super.passivateState(doc, parent);
}
/**
* Overridden framework method to activate user data from
* XML snapshot, stored during passivation
*/
@Override
public void activateState(Element parent) {
//This code snippet reads the data stored in USERDATA node
if (parent != null) {

88/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
NodeList nl = parent.getElementsByTagName("USERDATA");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
String key = e.getAttribute("KEY");
String value = e.getAttribute("VALUE");
setRegionId(new Integer(value));
break;
}
}

super.activateState(parent);
}

// regionId is made activation safe in this e.g


private Integer regionId = null;
private Integer getRegionId() {
return regionId;
}
private void setRegionId(Integer regionId) {
this.regionId = regionId;
}

89/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

23 Deploying ADF Applications


1. Overview
Deploying an application is as important as developing the application. There is an option for us
to deploy the application to a different application server provided that the server contains all
runtime libraries to support the ADF application. The ADF runtime libraries, which are called Java
Resource Files (JRF), are provided by default for the WebLogic Server, WebSphere, and GlassFish.
The ADF application is deployed to the server as a packaged enterprise archive which contains
the required web content and related resource files. All the deployment library properties are
configured from the Deployment option in the Project properties and Application properties
options. The different archives that are helpful at different stages of the ADF web application
deployments are as follows:
Java Archive (JAR): Java archive is a Java specific archive that is used to package all the
Java class files related to the project. For example, we can bundle all the utility class files as
a Java archive file and then use it in any other project. JAR files are used as libraries in the
Model and Viewcontroller projects. The file structure includes a class file and a META-
INF folder that contains the MANIFEST.MF file.
Web Application Archive (WAR): Web archive is a package of all the web-related files.
The Web Archive option is available from the Viewcontroller project that contains web
resources. All files such as .html .jspx, .jsff, and .jsf are packaged as WAR files. The file
structure contains a WEB-INF folder that contains adfc-config.xml, web.xml,
weblogic.xml, faces-config.xml, trinidad-config.xml, and so on. The classes
folder contains the Java classes such as backing or managed bean added in the UI project.
The lib folder will include all the dependent libraries that are required to compile the web
archive file.
ADF library (JAR): The ADF library is an archive that is specific to the ADF framework. The
ADF library is different from a Java archive file because the ADF library will pull all related
libraries referenced by the files and add it to the manifest file. The dependent libraries are
pulled by JDeveloper and added as a secondary import. The ADF library will expose the ADF
task flows and other ADF-specific metadata files that are not exposed by a normal Java
archive file. ADF libraries may contain task flows but are also used for declarative
components and page templates. Using the ADF library, we can drag-and-drop the task flow
onto the page as a region. The structure includes the META-INF folder containing the
manifest file along with the jar-connection.xml and jar-adf-config.xml files specific to the
ADF library. The ADF library can contain configuration files for the ADF application.
Enterprise Archive (EAR): Most of the web applications which involve model data
interaction will be packaged using the enterprise archive. The business logic which interacts
with the data layer and the presentation layer is collectively bundled into a single archive.
The presentation layer information is bundled internally using the web archive and then it is
added to the enterprise archive.
Metadata Archive (MAR): This archive will package all the metadata files needed for the
customization of the web pages. Customization includes a few XML files that will have the
delta details for different users. The metadata archive will package the XML files along with
the configuration files to support user customization.

90/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

2. Deployment Overview Flow Diagram:

91/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

3. Preparing the Application for Deployment Flow Diagram:

92/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

4. Application Deployment Flow Diagram:

93/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

24 Securing ADF Applications


1. Get Current Logged User name
ADFContext adfCtx = ADFContext.getCurrent();
SecurityContext secCntx = adfCtx.getSecurityContext();
String user = secCntx.getUserPrincipal().getName();
String _user = secCntx.getUserName();

94/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

25 Debugging and Troubleshooting ADF Applications


1. Configuration Options for Optimizing ADF Faces Troubleshooting
Configuration
Description
Recommendation
Enable debug output by setting the following in the trinidad-config.xml file:

<adf-faces-config xmlns=
"http://xmlns.oracle.com/adf/view/faces/config">
<debug-output>true</debug-output>
<skin-family>oracle</skin-family>
</adf-faces-config>
Enable debug Improves the readability of HTML markup in the web browser:
output.
 Line wraps and indents the output.
 Detects and highlights unbalanced elements and other common HTML
errors, such as unbalanced elements.
 Adds comments that help you to identify which ADF Faces component
generated each block of HTML in the browser page.

Disable content compression by setting the following in the web.xml file:


<context-param>
<param-name>
rg.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION
</param-name>
Disable content <param-value>true</param-value>
compression. </context-param>
Improves readability by forcing the use of original uncompressed styles.

Unless content compression is disabled, CSS style names and styles will appear
compressed and may be more difficult to read.
Disable JavaScript compression by setting the following in the web.xml file:
<context-param>
<param-name>
Disable
org.apache.myfaces.trinidad.DEBUG_JAVA_SCRIPT
JavaScript </param-name>
compression. <param-value>true</param-value>
</context-param>
Allows normally obfuscated JavaScript to appear uncompressed as the source.
Enable client side asserts by setting the following in the web.xml file:
<context-param>
<param-name>
Enable client side oracle.adf.view.rich.ASSERT_ENABLED
asserts. </param-name>
<param-value>true</param-value>
</context-param>
Allows warnings of unexpected conditions to be output to the browser console.
Enable clientside Enable clientside logging by setting the following in the web.xml file:
logging.
95/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Configuration
Description
Recommendation
<context-param>
<param-name>
oracle.adf.view.rich.ASSERT_ENABLED
</param-name>
<param-value>true</param-value>
</context-param>

Allows log messages to be output to the browser console.

Unless client side logging is enabled, log messages will not be reported in the
client.
Enable more detailed server side logging shut down the application server,
enter the following setting in the logging.xml file, and restart the server:

<logger name="oracle.adf.faces” level=”CONFIG"/>

or

Use the WLST command:

setLogLevel(logger="oracle.adf” level=”CONFIG”,
addLogger=1)
Enable more
detailed server or
side logging.
In Oracle Enterprise Manager Fusion Middleware Control, use the Configuration
page to set oracle.adf, oracle.adfinternal, and oracle.jbo to level CONFIG.

Allows more detailed log messages to be output to the browser console.

Unless server side logging is configured with a log level of CONFIG or higher,
useful diagnostic messages may go unreported.

Allowed log level settings are: SEVERE, WARNING, INFO, CONFIG, FINE,
FINER, FINEST, ALL. Oracle recommends CONFIG level or higher; the default is
SEVERE.
Disable HTTP cache headers by setting the following in the web.xml file:

<context-param>
Disable HTTP <param-name>
cache headers. org.apache.myfaces.trinidad.resource.DEBUG
</param-name>
<param-value>true</param-value>
</context-param>

96/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

Configuration
Description
Recommendation

Forces reloading of patched resources.

Unless HTTP cache headers are disabled, the browser will cache resources to
ensure fast access to resources.

After changing the setting, clear the browser cache to force it to reload
resources.

97/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

26 ADF Best Practices


1. Oracle ADF – Best Practices
1. Do not use invokeAction in pageDef because it will be executed several times. Use
instead of a task flow with a method call in front. Also, using this approach, we can reuse
the page in other task flows.
2. Do not create view criteria containing the name of the view since the name of the view could
be changed and then also, the criteria name should be changed.
3. Use unbounded tasks only for pages or bounded task flows available as bookmarks.
4. Do not use unbounded task flows for the following operations: create, update and delete. It
should be used only for read operations.
5. Do not add service methods in the application model that are dependent on the view iterators
(default iterators). Use instead of standard operations like CreateWithParams,
ExecuteWithParams, etc.
6. Create secondary iterators for views in the service methods. Do not use default iterators
because they are the same used in the view layer.
7. Do not add HTML in JSF. Use instead styles and/or CSS for available ADF components.
8. Try to not use the view’s attributes in the WHERE clause for filtering. Use instead default
criteria for each view instance from the application model.
9. Do not use two services layers separately with different database connections to the same
database if is not needed. Use instead of nested application models.
10. Always use the scope prefix for any accessed memory variables (requestScope,
backingBeanScope, viewScope, pageFlowScope, sessionScope,
applicationScope, backingBeanScope).
11. Put the Cancel operation in af:subform and with immediate=true, in order to ignore the
validations of other input fields which have immediate=true.
12. In the context of fragment based task flows, use viewScope in preference to request scope
for a more predictable behavior within the context of the sub-flow that contains the
fragments
13. Task flows should always contain an activity marked as an exception handler. This activity
does not have to be a view activity it can be a method or router (our preferred approach)
with control flow rules to subsequent activities.
14. Use SetPropertyListener instead of SetActionListener (was deprecated in 11g).
15. Do not combine view accessors with data model master-detail because accessor attributes
create distinct row sets based on an internal view object other than that from detail.
16. When view criteria are applied programmatically in a business method from the application
model later the view criteria must be removed.
17. Try to use a data model master-detail only for composite relations.
18. For a performance increase, you can tune the view instance from the application model to
get from DB more than one row once. By default, it is 1.

98/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

27 Miscellaneous
1. Miscellaneo9us
Iterative development lets you make changes to your Framework application while it is running
on the Integrated WebLogic Server and immediately see the effect of those
changes simply by refreshing the current page in your browser.

Iterative Development lets you see changes to these components almost


instantly upon a browser refresh:
page definitions
navigation model
page hierarchy
existing JSPX files
page templates
resource catalog
addition of task flows to pages
addition of portlets to pages

No browser refresh for new jspx files, web.xml and adfc-config.xml.


The MDS Cache size is set to 0. This setting causes all metadata files to be re-loaded on
each request.
The Navigation Model cache is invalidated on each request.

99/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

28 Advance ADF
1. Managed bean interface and event handler method:

2. Contextual event callback handler in action:

100/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

29 Integrating ADF with Web Service


1. Web Services Architecture:

101/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

102/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

30 Integrating ADF with EJB


1. EJB Architecture:

103/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

31 Integrating ADF with SOA


1. SOA Architecture:

104/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

32 Integrating ADF with Mobile Application Framework (MAF)


1. MAF Architecture:

105/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

33 Integrating ADF with Cloud Service


1. Cloud Architecture:

106/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

34 Integrating ADF with WebCenter


1. WebCenter
WebCenter is the enterprise Web 2.0 extensional framework, build on top of ADF to develop
a complete portfolio of Sites, Portal and Content Management
WebCenter Pillars:
 WebCenter Sites
 WebCenter Portal Cloud
 WebCenter Content

107/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes

35 Tools
1. Junit
JUnit is an open-source framework to write and run test cases for java programs. In the case of
web applications, JUnit is used to test the application without a server. This framework builds a
relationship between the development and testing process.

Problems that we are facing in testing the applications


If we want to test any application, In standalone, we need to call the respective method’s main()
method but there are so many problems in testing the flow using main() method.
In a web application, to test the flow we need to deploy it in the server so if there is a change
then again we need to restart the server. Here also facing problems while testing the application.
Writing main method checks is convenient because all Java IDEs provide the ability to
compile and run the class in the current buffer, and certainly have their place for exercising
an object’s capability. There are, however, some issues with this approach that make it
ineffective as a comprehensive test framework:
There is no explicit concept of a test passing or failing. Typically, the program outputs
messages simply with System.out.println; the user has to look at this and decide if it
is correct.
main has access to protected and private members and methods. While you may want to
test the inner workings of a class may be desired, many tests are really about testing an
object’s interface to the outside world.
There is no mechanism to collect results in a structured fashion.
There is no replicability. After each test run, a person has to examine and interpret the
results.
The JUnit framework addresses these issues, and more

Advantages of JUnit
JUnit addresses the above issues; It’s used to test an existing class. Suppose, if we have a
Calculation class then, we need to write CalculationTest to test the Calculation class.
Using JUnit we can save testing time.
In real-time, in the web application development, we implement JUnit test cases in the DAO
classes. DAO classes can be tested without a server.
With JUnit, we can also test Struts / Spring applications but most of the time we test only
DAO classes. Even some times service classes also tested using JUnit.
Using JUnit, if we want to test the application (for web applications) then a server is not
required so the testing becomes fast.

2. ANT
Ant is an abbreviation for Another Neat Tool. Ant is a Java-based build tool created as part of the
Apache open-source project. You can think of it as a Java version of make. Ant scripts have a
structure and are written in XML. Similar to make, Ant targets can depend on other targets.

Configuring Apache Ant


A Java build process typically includes:
the compilation of the Java source code into Java bytecode
creation of the .jar file for the distribution of the code
creation of the Javadoc documentation

108/109
ADF Essentials Training by Deepak Bhagat
Oracle Application Development Framework (ADF) Assorted Notes
Ant uses an XML file for its configuration. The default file name is build.xml. Ant builds are based
on three blocks: tasks, targets and extension points.
A task is a unit of work that should be performed and is small, atomic steps, for example, compile
source code or create Javadoc. Tasks can be grouped into targets.
A target can be directly invoked via Ant. Targets can specify their dependencies. Ant will
automatically execute all dependent targets.
For example, if target A depends on B and Ant is instructed to run A, it first runs B before running
A. In your build.xml file you can specify the default target. Ant executes this target if no explicit
target is specified.

109/109
ADF Essentials Training by Deepak Bhagat

You might also like